Case Study
Sword of Truth Publishing Platform - A Full-Stack Book Production System
Independent publishers run on a patchwork of disconnected tools: word processors for manuscripts, design software for covers, spreadsheets for royalties, email threads for author communications, and third-party services for distribution; each owned by someone else, each a liability. Sword of Truth Publishing replaced that fragmented stack with a single purpose-built platform: a FastAPI backend with 65+ route modules covering every publishing function, a Next.js 16 web frontend, and a Tauri 2 desktop app for fully offline use. The result is a platform that manages the complete book lifecycle, from manuscript intake and cover generation to EPUB/PDF production and multi-retailer distribution, without dependency on external SaaS for core operations.

Background & Context
Sword of Truth Publishing is an independent publishing house that produces both digital and print titles. Like most small publishers, the operation grew organically: each new capability was solved by adopting a new tool, a new subscription, or a new manual process. Over time, the accumulated weight of these decisions created a fragile, expensive, and difficult-to-maintain publishing operation, one where changing any single tool risked breaking several adjacent workflows.
The stakes were also higher than for a typical content business. Publishing has strict technical requirements: print files must meet specific bleed, trim, and ICC color specifications; EPUBs must pass accessibility validation; ISBNs must be registered and tracked; royalty calculations must be auditable. Getting these wrong doesn't produce bad user experience — it produces unsellable books.
Problem Statement
The Question: How do you build a publishing operation that produces professional-quality digital and print books without renting the infrastructure from someone else?
The Problem: Cover assets lived in scattered folders with no version control or spec enforcement. Distribution to retailers was a manual multi-step process prone to error and impossible to audit after the fact. Author communications were untracked email threads. Book and ebook production required exporting files through multiple third-party tools; any one of which could change its pricing, drop a format, or shut down.
The Challenge: Publishing is a domain with genuine technical depth. A platform for it must handle CSS-driven composition, print-specification-aware cover generation, EPUB accessibility compliance, multi-connector distribution, real-time collaborative editing, font licensing, and screenplay format support — all in a single coherent system. The complexity budget is high, and shortcuts produce books that can't be sold.
Methodology / Approach
The platform was designed domain-first, with a clear separation between domain logic, persistence, and API routing. Each major publishing function — composition, cover, distribution, collaboration, billing, validation — was modeled as an isolated domain with its own models, validators, and service layer before any routes were written.
Stack rationale:
- FastAPI (Python) for the backend - performant async routing, native Pydantic validation, and clean dependency injection; well-suited to the document-heavy domain.
- Alembic + PostgreSQL for schema versioning across 9 migration phases, each aligned to a feature domain.
- Celery for async job processing — distribution submissions, webhook ingestion, stalled-submission monitoring.
- Next.js 16 + React 19 + Tailwind v4 for the web frontend with dark/light theme support.
- Tauri 2 + SQLite for the desktop edition — offline-first, one-time purchase, no cloud dependency at runtime.
- Security-first posture from the start — rate limiting, auth, webhook secret management, and path traversal hardening were built into the backend before public routes were exposed.
The 9-phase database schema evolution was the architectural backbone of the project — each migration corresponded to a working system capability, not a speculative future need.
Analysis and Findings
Three patterns surfaced repeatedly during development:
Publishing has more domain concepts than most software. The route module count, 65+ distinct API surfaces, reflects publishing reality: annotations, track changes, scene metadata, cross-references, footnotes, table of contents, index entries, print marks, ICC color profiles, copy fitting, ornaments, galley proofs, proof orders, condition text. These aren't speculative features; each maps to a real production workflow that independent publishers currently handle manually or by paying for a specialist tool.
Offline capability is a genuine requirement, not a nice-to-have. Publishers frequently work without reliable internet — at writing retreats, in rural areas, traveling to print houses. A cloud-only platform is a liability in these contexts. The Tauri desktop edition addresses this directly: SQLite-backed local storage, a bundled FastAPI sidecar, and no network dependency at runtime. The offline edition is purchased once and runs indefinitely.
Quality gates must be automated, not aspirational. EPUB accessibility failures, missing print bleed, unregistered ISBNs, and incorrect ICC profiles are discovered at submission time if not caught earlier — at which point they block publication. Automating these checks inside the platform (via dedicated validation, EPUB a11y, PDF preflight, and manifest generation modules) moves failures from the distribution queue to the development cycle, where they're cheap to fix.
Solutions and Implementation
The platform shipped across 17 phases, grouped into six functional layers:
Book & Content Management
Structured models for books, series, collections, and templates. Character databases, scene metadata, and arc tracking for narrative projects. Screenplay format support via Fountain parsing. A scratchpad and research workspace integrated directly into the editing environment.
Manuscript Composition
A CSS-driven composition engine that converts manuscript content into typeset layouts. Front matter generation, composition profiles, and a CSS generator that outputs print-ready stylesheets. Copy fit controls, ornament placement, footnote and cross-reference resolution, and table of contents and index generation.
Cover Generation
A spec-driven cover engine that calculates dimensions from trim size, page count, and paper weight. A cover validator that enforces bleed, resolution, and color space requirements before assets leave the platform. Cover assets are versioned and stored with full audit history.
Quality & Validation
An EPUB validator with accessibility compliance checking (epub_a11y). PDF preflight for print files. A quality report and issue diagnostics system that surfaces failures with structured remediation guidance. A manifest generator for distribution metadata. Font license tracking to prevent inadvertent use of restricted typefaces.
Distribution
A connector framework supporting multiple retailer integrations with a unified submission pipeline. Async job processing via Celery for long-running distribution tasks. Webhook ingestion for retailer callbacks. Stalled-submission detection and reconciliation. Distribution reconciliation to audit what was submitted versus what was received.
Collaboration, Communication & Operations
Real-time presence, document locking, and track changes for multi-author workflows. Assignment management and scene-level collaboration. Author notifications via a structured email service with configurable templates. Royalty calculation and billing with auditable records. ISBN registration and proof order management. Launch coordination and landing page tooling for new releases. A backup system, snapshot management, and an autosave pipeline for in-progress work.
Security Hardening
Following a 16-vulnerability audit (SEC-001 through SEC-016), the backend received systematic hardening across phases 1–4d: path traversal validation on all file operations, upload content-type enforcement, ZIP import size caps and resource limits, rate limiting on public endpoints, webhook secret management, and a temporary directory cleanup system.
Conclusion and Lessons Learned
The platform now manages the full publishing lifecycle for Sword of Truth Publishing, from manuscript intake through cover production, composition, validation, and multi-retailer distribution, in a single owned codebase with no runtime dependency on external SaaS for core functions. The 1,750+ test suite spans unit, integration, and database layers, enforcing correctness across all 65+ API surfaces. The Tauri desktop edition provides a fully offline alternative for environments where cloud access isn't reliable.
The platform accomplishes its meta-goal: it gives an independent publisher the same production capabilities as a larger house; spec-driven covers, accessibility-validated EPUBs, auditable distribution, real-time collaboration, without the cost or fragility of assembling those capabilities from third-party subscriptions.
Three lessons that transfer beyond this project:
Model the domain before building the API. Publishing has genuine domain depth, more than a typical content app. Writing isolated domain models first, before any routing logic, meant that the 65+ route modules could be added incrementally without creating coupling between unrelated publishing functions. Each new module dropped into a working system rather than requiring rewrites of existing code.
Offline capability requires an architecture decision, not a feature flag. Adding offline support to a cloud-native app is expensive. Building the Tauri desktop edition as a first-class target from the start, with a bundled FastAPI sidecar and SQLite persistence, meant offline and cloud share the same domain logic and API contract. The desktop edition is a deployment target, not a fork.
Automate quality gates at the creation layer, not the submission layer. Finding an ICC color profile mismatch or an EPUB accessibility failure at distribution time blocks publication and creates pressure to ship anyway. Embedding preflight checks, EPUB validation, and manifest verification into the normal composition and cover workflows moves failures to a moment when fixing them is routine.
Project README
Sword of Truth Publishing
A full-stack publishing platform covering the entire author lifecycle: drafting → production → packaging → distribution. Authors submit a manuscript once — it is composed, validated against every channel's requirements, and routed to KDP, IngramSpark, and Draft2Digital from a single pipeline.
Status: Phases 0–17 complete. UI/UX Modernization complete (design system, author-first nav, desktop startup UX, accessibility, analytics instrumentation, feature flags). 1750+ backend tests passing. Frontend complete. Desktop Edition shipped — see desktop/README.md. Phase 17 plan documented at docs/plans/DESKTOP_COMPLETION_PLAN.md. UI/UX plan at docs/plans/ui-ux-modernization-plan.md.
Editions
Sword of Truth Publishing ships in two editions, sharing one codebase.
| SaaS (web) | Desktop | |
|---|---|---|
| Hosting | Cloud-hosted | Local install (Win/macOS/Linux) |
| Pricing | Subscription | One-time purchase |
| Connectivity | Always online | Offline-first authoring & packaging; online only for Distribution submit, Billing, cloud AI assist, Collaboration |
| Persistence | PostgreSQL (cloud) | SQLite (local) |
| Multi-device | Yes | Single machine (optional cloud sync — see desktop/CLOUD_SYNC_DESIGN.md) |
| Collaboration | Yes (workspaces, presence, real-time) | Single user (live collaboration is online-only) |
| Tech shell | Next.js 16 in browser | Tauri 2 wrapping Next.js static export + FastAPI sidecar |
| Build | CI / Vercel | desktop/ — npm run desktop:build:{win,mac,linux} |
What This Is
Sword of Truth Publishing is a publishing platform for independent authors, with emphasis on non-fiction and personal development. The platform handles:
- Authoring — manuscript structure, outline, scene/chapter hierarchy, characters, world-building, snapshots & diff, annotations, track changes, footnotes, cross-references, index, ToC, Fountain screenplay mode, redline change bars
- Editorial — assignments, review cycles, spellcheck, ARC/beta reader flows, rule-based AI style analysis, AI assist, DOCX export, copy-fit
- Layout & typography — composition profiles, paged preview, font storage & licensing, ICC profiles, print marks, ornaments, conditions, compile filters, style libraries
- Packaging — EPUB3 generation (stdlib, EPUBCheck-conformant), PDF generation (6×9 trade paperback via fpdf2), build orchestration, channel validation, quality gates, issue diagnostics, EPUB accessibility compliance, galley proofs
- Production bridges — submission package, build manifest, royalty estimator, ISBN procurement, cover spec & builder, series management, proof orders
- Distribution — single-submission routing to KDP, IngramSpark, Draft2Digital via connector framework; sync, retry, withdraw; sales reporting; webhook ingest
- Author platform — landing page builder, launch checklist, reader list, newsletter integrations
- Auth & ops — JWT-based auth, OWASP middleware, GDPR compliance, incident runbooks, backup/restore (DR), launch readiness gates, rollout cohorts
- Notifications — transactional email (Resend), in-app notifications, presence, real-time collaboration over WebSocket + SSE fallback, font storage events, scene collab
Tech Stack
Backend
| Layer | Technology | Version | Edition |
|---|---|---|---|
| API framework | FastAPI | 0.104.1 | Both |
| Server | Uvicorn (ASGI) | 0.24.0 | Both |
| Validation | Pydantic v2 | 2.9.2 | Both |
| ORM | SQLAlchemy 2.0 (async) | 2.0.35 | Both |
| Database (SaaS) | PostgreSQL + psycopg | 16 / 3.3.4 | SaaS |
| Database (Desktop) | SQLite + aiosqlite | — | Desktop |
| Migrations | Alembic | 1.13.1 | Both |
| Job queue | Celery + Redis | 5.3.4 / 7 | SaaS only |
| In-process scheduler | APScheduler | — | Desktop only |
| Auth | python-jose (JWT) | 3.3.0 | Both |
| fpdf2 | 2.8.7 | Both | |
| Resend (optional) | — | SaaS (no-op on Desktop) | |
| Language | Python | 3.13 | Both |
Frontend
| Layer | Technology | Version |
|---|---|---|
| Framework | Next.js (App Router) | 16.1.6 |
| UI | React | 19.2.3 |
| Styling | Tailwind CSS | v4 |
| Editor | TipTap | latest |
| Fonts | Cormorant Garamond + Inter | Google Fonts |
| Analytics | Vercel Analytics | 2.x (SaaS only) |
| Language | TypeScript | — |
Desktop
| Layer | Technology |
|---|---|
| Shell | Tauri 2 (Rust) |
| Frontend | Next.js static export (output: "export") |
| Backend sidecar | FastAPI packaged via PyInstaller |
| Persistence | SQLite via aiosqlite |
| Credential vault | OS keychain (Windows Credential Manager / macOS Keychain / libsecret) via keyring crate |
| Licensing | HMAC-SHA256, offline-verified, machine-fingerprint-bound |
| OS integration | File associations (.sotp, .msk), deep links (sotp://), single-instance, drag-and-drop |
| CI/CD | GitHub Actions matrix (windows-latest, macos-14, ubuntu-22.04) |
| Docs | desktop/README.md, desktop/SMOKE_TESTS.md, desktop/CLOUD_SYNC_DESIGN.md |
Architecture
Repository layout
sword-of-truth-publishing/
├── backend/ # FastAPI application (primary codebase)
│ ├── app/ # 70+ routers, middleware, app factory
│ ├── domain/ # Business logic (framework-agnostic)
│ ├── persistence/ # SQLAlchemy ORM + adapters
│ ├── composition/ # Manuscript rendering engine
│ ├── cover/ # Cover spec and generation
│ ├── distribution/ # KDP / IngramSpark / D2D connectors
│ ├── notifications/ # Transactional email (Resend SDK wrapper)
│ ├── validation/ # Content validation rules
│ ├── workers/ # Celery worker configuration (SaaS)
│ ├── alembic/versions/ # Migrations 0001–0011
│ └── tests/ # 1750+ tests across ~125 files
├── frontend/ # Next.js 16 web UI (and desktop static export target)
│ └── src/
│ ├── app/(app)/ # Authenticated shell, 50+ pages
│ ├── components/ui/ # Shared UI primitives (PageHeader, Button, Card, …)
│ └── lib/ # Auth context, API client, hooks, analytics, feature-flags
├── docs/
│ ├── brand-identity/ # BRAND-BIBLE.md (24 sections), creative brief, color tokens
│ └── plans/
│ ├── DOCUMENT_CREATION_PLAN.md # Phases 0–16 roadmap (complete)
│ ├── DESKTOP_COMPLETION_PLAN.md # Phase 17 — desktop edition
│ ├── ui-ux-modernization-plan.md # UI/UX modernization — 8-phase author-first redesign
│ ├── ARCHITECTURE.md
│ ├── DECISIONS.md
│ ├── GAP_ANALYSIS.md
│ ├── PACKAGING_PIPELINE.md
│ ├── ROADMAP.md
│ ├── VERIFICATION_GATES.md
│ ├── brand-identity-plan.md
│ └── rebrand-implementation-plan.md
├── icons/SwordOfTruth/ # Branded source assets (SVG)
├── sample-projects/ # Templates bundled with Desktop edition (planned)
├── manuskript/ # Legacy PyQt5 fork (DEPRECATED — see docs/plans/DESKTOP_COMPLETION_PLAN.md §17.9)
├── docker-compose.yml
└── README.md
Frontend route map (high level)
/ landing page
/login, /sign-up auth
/dashboard authenticated shell
/projects project list
/projects/[projectId]/ project home
/projects/[projectId]/{characters, history, research, search, series,
readers, landing-page, launch, backup,
collections, annotations, footnotes, xrefs,
index, toc, styles, ornaments, conditions,
compile-filters, fountain, scratchpad,
scene-metadata, spellcheck, dictionary,
style-analysis, font-licenses, font-storage,
icc-profiles, locks, assignments,
review-cycles, track-changes, galley, export}
/projects/[projectId]/books/[bookId]/{compose, quality, artifacts,
distribution, cover, royalty, isbn, sales,
accessibility, paged-preview, print-marks,
arc, copy-fit, proof-orders}
/tools/{names, templates}
/settings
Prerequisites
- Python 3.13+
- Node.js 20+
- Docker and Docker Compose (for SaaS dev with Postgres + Redis)
Setup (SaaS / dev)
Backend
cd backend
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install -r requirements.txt
pip install -r requirements-dev.txt
Configure:
cp .env.example .env
Edit backend/.env:
DATABASE_URL=postgresql+psycopg://sotpub:password@localhost:5432/sword_of_truth_publishing
REDIS_URL=redis://localhost:6379/0
SECRET_KEY=<generate a strong random string>
JWT_ALGORITHM=HS256
JWT_EXPIRE_MINUTES=60
EMAIL_ENABLED=true
RESEND_API_KEY=
[email protected]
Start infra and migrate:
docker-compose up -d postgres redis
cd backend && alembic upgrade head
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
API: http://localhost:8000 · Swagger: http://localhost:8000/docs
Frontend
cd frontend
npm install
npm run dev # http://localhost:3000
Full stack via Docker
docker-compose up
Setup (Desktop)
See desktop/README.md for prerequisites, dev loop, and per-OS build instructions.
Quick start:
# Install deps
cd frontend && npm ci && cd ..
cd desktop && npm ci && cd ..
pip install -r backend/requirements.txt pyinstaller
# Build sidecar + launch in dev mode
node desktop/scripts/build-sidecar.mjs
cd desktop && npm run tauri:dev
Legacy Manuskript client
The legacy PyQt5/Qt5 Manuskript client in manuskript/ has been superseded by
the Tauri Desktop Edition. The legacy entry point (bin/manuskript) will print
a deprecation message and exit. Build scripts in package/ and snap/ are
preserved for historical reference only.
To import existing .msk projects into the Desktop Edition, use
Settings → Migration → Import from Manuskript (.msk).
API
Base URL: /api/v1. Auth is JWT. All responses include X-Process-Time-Ms. Errors return {"detail": "message"}.
| Route group | Base path | Operations |
|---|---|---|
| Auth | /auth |
Register, login, logout, me |
| Projects | /projects |
CRUD, word count |
| Books | /projects/{id}/books |
CRUD |
| Composition | /projects/{id}/compose |
Manuscript rendering, paged preview, profiles |
| Authoring | /projects/{id}/{characters, world, snapshots, annotations, footnotes, xrefs, index, toc, scratchpad, scene-metadata, search, series, ornaments, conditions, compile-filters, fountain, change-bars, track-changes, style-analysis, name-generator, templates, research, dictionary, collections, locks, assignments} |
CRUD per feature |
| Editorial | /projects/{id}/{review-cycles, assignments, spellcheck, docx, ai-assist, copy-fit, galley} |
Editorial workflow |
| Layout & typography | /projects/{id}/{styles, font-licenses, font-storage, icc-profiles, print-marks} |
Layout/typography engine |
| Packaging | /projects/{id}/books/{id}/packaging |
EPUB3, PDF, build, validate, quality, gates, diagnostics, export, A11y |
| Cover | /projects/{id}/cover |
Spec, generate, validate, builder |
| Distribution | /projects/{id}/books/{id}/publish |
Submit, sync, withdraw, sales, reconcile |
| Sales | /projects/{id}/books/{id}/sales |
Records, by-channel, by-format |
| Royalty | /projects/{id}/books/{id}/royalty |
Print-cost model, margin |
| ISBN | /projects/{id}/books/{id}/isbn |
Validate, register per-format, remove |
| Proof orders | /projects/{id}/books/{id}/proof-orders |
Proof copy workflow |
| ARC / readers | /projects/{id}/{arc, readers} |
Beta readers, public ARC, feedback |
| Landing & launch | /projects/{id}/{landing-page, launch} |
Author landing builder, launch checklist |
| Collaboration | /workspaces |
Workspace, members, invites, presence, scene-collab |
| Realtime | /realtime/projects/{id}/books/{id} |
WebSocket + SSE fallback |
| Notifications | /workspaces/{id}/notifications |
In-app + email preferences |
| Webhooks | /webhooks/distribution/{channel}/events |
Inbound distribution events |
| Storage | /projects/{id}/books/{id}/storage |
Presigned upload/download |
| Backup | /projects/{id}/backup |
DR snapshot/restore |
| Billing | /billing |
Subscriptions, usage |
| Admin | /admin |
Users, system stats |
| Ops | /ops |
Health, backups, incidents, GDPR, rollout, launch gate |
| Migration | /api/v1/migration |
Export to .sotp bundle, import .sotp, import .msk |
| Telemetry | /api/v1/telemetry |
Opt-in anonymous usage events (Desktop only) |
| Licensing | /api/v1/license |
Activate, status, deactivate (Desktop only) |
| Diagnostics | /api/v1/diagnostics |
Logs, sidecar status (Desktop only) |
| Autosave | /api/v1/autosave |
Draft save + pending recovery (Desktop + SaaS) |
Testing
cd backend
pytest tests/ -v
pytest tests/ --cov=app --cov=domain --cov=persistence --cov-report=html
Current baseline: 1750+ tests across ~125 test files.
Coverage target: ≥85% on domain/, app/, persistence/.
Frontend e2e (Playwright):
cd frontend
npx playwright test
Development Status
| Phase | Scope | Status |
|---|---|---|
| 0–9 | Foundation, domain, project/book CRUD, composition, cover, validation, collab, billing, auth, admin, ops, EPUB3/PDF generation, build orchestrator, channel validation, quality, gates, diagnostics, submission export | ✅ Complete |
| 10 | Authoring enhancement layer — snapshots, annotations, scratchpad, scene metadata, search, series, ornaments, conditions, compile filters, Fountain, change bars, track changes, AI assist, spellcheck, DOCX, project templates | ✅ Complete |
| 11 | Editorial workflow — assignments, review cycles, ARC/beta readers, redline, spellcheck/grammar | ✅ Complete |
| 12 | Layout & typography engine — styles, footnotes, xrefs, index, ToC, paged preview, print marks, ornaments, ICC profiles, A11y compliance, font licenses | ✅ Complete |
| 12.5 | Infrastructure foundations — DB migration, object storage, realtime transport, notifications, font storage, i18n, DR backup, security hardening, performance budgets | ✅ Complete |
| 13 | Authoring → Production bridge — onboarding, scene collab, presence, offline (PWA), series management | ✅ Complete |
| 14 | Production → Packaging bridge — composition, quality gate, artifact, distribution, cover builder, royalty estimator, ISBN procurement | ✅ Complete |
| 15 | Packaging → Distribution bridge — live connectors, sales reporting, webhook secret management, proof orders | ✅ Complete |
| 16 | Author platform & launch — landing page builder, launch checklist, newsletter/reader-list integrations | ✅ Complete |
| 17 | Desktop edition — Tauri 2 + FastAPI sidecar + SQLite + license activation + offline-first | ✅ Complete |
| UX | UI/UX Modernization — design system tokens, author-first nav, PageHeader primitive, desktop startup UX, offline banner, skip-to-content, analytics funnel, feature flags | ✅ Complete |
Deferred (non-blocking): e2e browser tests for editor keyboard workflows, e2e outline reorder regression tests, production S3 credential rollout.
Brand
Brand identity documentation is in docs/brand-identity/. The full brand system (positioning, color, typography, voice, SEO strategy, competitive analysis) is in BRAND-BIBLE.md.
Color palette: Espresso #1E1206 · Parchment #F5EDD8 · Amber Gold #C8963E · Burnished Oak #7A5C3A
Typography: Cormorant Garamond (display/headings) + Inter (UI/body)
Voice archetype: The Illuminator — "From manuscript to reader, with nothing lost."
Legacy: Manuskript (deprecated)
The manuskript/ directory contains the original open-source Manuskript desktop application (Python 3 + PyQt5, v0.17.0) from which this project was forked. It is preserved for .msk file format compatibility and reference. It is being retired as part of Phase 17 (docs/plans/DESKTOP_COMPLETION_PLAN.md §17.9). New users should use the SaaS web edition (now) or the Tauri desktop edition (Phase 17). Legacy .msk files import cleanly into both editions.
Project Gallery
This album acts as the portfolio gallery for the hybrid desktop/SaaS self-publishing application, "Sword of Truth Publisher", and the screenshot taken from this project.


