Files
interactive-story/backend/app/main.py
T
JesseMarkowitzandClaude Opus 5 44edece67e M9: a campaign you can actually get back
A campaign could already be exported and imported. What could not survive the
trip was everything that explains it: the state events behind the authoritative
document, the prompt each turn was actually given, the passages it was shown,
the summaries that carry long-story continuity, and which take belonged to which
turn. An imported campaign could be read and could no longer say why it was what
it was — and a manual correction, the one state change no narration explains,
was indistinguishable from something the story had established.

The bundle is now `ai-dnd-adventure-v3`, and the version is the design rather
than a side effect. Everything added here could have been another optional key,
the way persona, Save Points, narrative state and imported knowledge each were.
That mechanism stops working at exactly this addition: a v2 file with no prompt
provenance is ambiguous between "written before M9" and "written by M9 from a
campaign that has none", and those are different facts about a campaign. A
version number is how a recovery file states what it was capable of recording.
v1 and v2 still import, and every seam from pre-active-head onward is tested for
the rule that an older file is never reinterpreted under a newer assumption.

Two categories became three. "Chosen travels, derived is recomputed" was enough
until stored prompts had to be decided: they are derived, and they must travel
anyway. The test that separates evidence from cache is not "could this be
recomputed" but "would a recomputation answer the same question" — a rebuilt
search index answers the same question, a rebuilt prompt says what the turn
would be told *now*, which is the opposite of what the inspector is for.

Also here: a real SQLite backup, through the online backup API rather than a
file copy, taken while the application is running and verified before it is
kept; story cards settled as compatibility-only legacy data and taken out of the
narrator's prompt, because they were the untracked path around knowledge
authority that IMPORTED-KNOWLEDGE-DESIGN §73 already forbade; and no schema
change at all, proved against a database M8's own code wrote.

Three defects, found by running the milestone's own tests rather than by reading
them. Deleting a campaign leaked its FTS index rows, and SQLite then handed the
freed ids to the next source imported into any campaign, which failed with an
integrity error that Reindex could not repair — both ends are closed, and a
database already carrying the damage now repairs itself. An imported node with
no state snapshot was being stamped with the campaign's head state, so an Undo
to turn 2 showed what the story knew at turn 20. And the snapshot relink did not
persist at all, because it mutated a dict in place on a column SQLAlchemy tracks
by assignment: it looked correct in memory and wrote the wrong ids to disk.

Carrying per-turn prompts looked like it would halve the length of campaign that
can be restored. Measured — and after compressing them inside the file —
everything M9 added costs 12% of it: the import ceiling moves from about 318
turns to about 279, against a 100-turn certification target. The dominant cost
is not M9's at all. The per-position narrative state document is 74% of a
bundle, and v2 already carried it.

Backend 1,102 passed / 14 skipped / 0 failed. Frontend 145 passed. Lint,
production build and Docker build clean. Verified across two server processes
with two data directories, and in a real browser against a real narrator.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Qyn3oRd4D6pi72nKBG725B
2026-09-07 01:55:45 -04:00

165 lines
5.9 KiB
Python

import mimetypes
import os
from pathlib import Path
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from starlette.exceptions import HTTPException as StarletteHTTPException
from .database import engine
from .limits import BodySizeLimitMiddleware
from .migrations import bootstrap
from .routers import (
adventures, backups, chat, debug, scenarios, settings, story_cards,
)
from .seed import seed_public_scenarios
bootstrap(engine)
seed_public_scenarios(engine)
# Production serves the SPA same-origin, so CORS only matters for the Vite dev
# server; AIDND_CORS_ORIGINS overrides for any other cross-origin setup.
#
# A wildcard is refused rather than honoured. This API is unauthenticated by
# design and bound to loopback, so its only protection from a page the user
# happens to have open in another tab is the same-origin policy. `*` would hand
# every site on the Internet a write handle on the local campaign database. If the
# value is wrong the app refuses to start, because a permissive CORS policy that
# nobody notices is worse than one that fails loudly.
CORS_ORIGINS = [
o.strip()
for o in os.environ.get("AIDND_CORS_ORIGINS", "").split(",")
if o.strip()
] or ["http://localhost:5173", "http://127.0.0.1:5173"]
if any(o == "*" or o.strip() == "*" for o in CORS_ORIGINS):
raise RuntimeError(
"AIDND_CORS_ORIGINS must not contain '*'. The storyteller API is "
"unauthenticated and loopback-bound; a wildcard origin would let any "
"web page read and rewrite every campaign. List the exact origins "
"instead."
)
app = FastAPI(
title="Adventure Storyteller",
docs_url="/docs",
redoc_url=None,
openapi_url="/openapi.json",
)
app.add_middleware(
CORSMiddleware,
allow_origins=CORS_ORIGINS,
allow_methods=["*"],
allow_headers=["*"],
)
app.add_middleware(BodySizeLimitMiddleware)
class SecurityHeadersMiddleware:
"""Standard hardening headers on every response. Pure ASGI (wraps `send`)
so SSE streams pass through unbuffered.
The CSP allows exactly what the SPA uses, and that is now same-origin and
nothing else: scripts, styles, fonts, images and XHR/SSE all resolve to the
app itself. The fonts used to come from Google, which made an Internet
request on every page load; they are self-hosted under /fonts/ instead
(frontend/tools/vendor_fonts.py), so `font-src 'self'` covers them and the
two remote hosts are gone from the policy.
`'unsafe-inline'` stays on `style-src` because React writes inline `style`
attributes. It is deliberately absent from `script-src`.
"""
_HEADERS = [
(b"x-content-type-options", b"nosniff"),
(b"referrer-policy", b"same-origin"),
(b"x-frame-options", b"DENY"),
(
b"content-security-policy",
b"default-src 'self'; "
b"script-src 'self'; "
b"style-src 'self' 'unsafe-inline'; "
b"font-src 'self'; "
b"img-src 'self' data:; "
b"connect-src 'self'; "
b"object-src 'none'; "
b"base-uri 'none'; "
b"form-action 'self'; "
b"frame-ancestors 'none'",
),
]
def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
if scope["type"] != "http":
return await self.app(scope, receive, send)
async def send_with_headers(message):
if message["type"] == "http.response.start":
message.setdefault("headers", [])
message["headers"] = list(message["headers"]) + self._HEADERS
await send(message)
await self.app(scope, receive, send_with_headers)
app.add_middleware(SecurityHeadersMiddleware)
app.include_router(scenarios.router)
app.include_router(adventures.router)
app.include_router(story_cards.router)
app.include_router(settings.router)
# M9: a verified copy of the whole database, taken while the app is running.
app.include_router(backups.router)
app.include_router(chat.router)
app.include_router(debug.router)
@app.get("/api/health")
def health():
return {"ok": True}
# In production, serve the built frontend (frontend/dist) as static files.
class SPAStaticFiles(StaticFiles):
"""Serve index.html for unknown paths so client-side routes (/play/3)
survive a page reload. API routes are matched before this mount, and an
unmatched one 404s rather than falling through to the page."""
async def get_response(self, path, scope):
try:
response = await super().get_response(path, scope)
except StarletteHTTPException as exc:
if exc.status_code != 404:
raise
return await self._fallback(path, scope)
if response.status_code == 404:
return await self._fallback(path, scope)
return response
async def _fallback(self, path, scope):
# The mount is a catch-all, so an /api path no router claims — a typo,
# or an endpoint this build removed — used to come back as the SPA's
# HTML with status 200, and a client asking for JSON parsed a web page
# instead of seeing that the route is not there.
if path == "api" or path.startswith("api/"):
raise StarletteHTTPException(status_code=404)
return await super().get_response("index.html", scope)
# Python's mimetypes table has no entry for woff2 on a slim Debian image, so
# StaticFiles served the self-hosted fonts as application/octet-stream. Browsers
# take them anyway — a @font-face src carries its own format() hint — but the
# honest type costs one line.
mimetypes.add_type("font/woff2", ".woff2")
mimetypes.add_type("font/woff", ".woff")
frontend_dist = Path(__file__).resolve().parent.parent.parent / "frontend" / "dist"
if frontend_dist.is_dir():
app.mount("/", SPAStaticFiles(directory=frontend_dist, html=True), name="frontend")