Implement CHUNK #2: server layer, core schemas/adapters, contract tests, seed

Complete the server-backed storage layer for PubScript so the app can run
against a real Fastify + SQLite backend instead of only local IndexedDB.

Server (@pubscript/server):
- db.ts: better-sqlite3 schema + migrations (users, shares, projects, books,
  chapters, entities, boards, ai_sessions, audit); WAL mode; idempotent
  admin bootstrap via PUBSCRIPT_ADMIN_EMAIL/PASSWORD.
- auth.ts: argon2 hashing, JWT-ish session tokens, guards, auth routes.
- routes.ts: REST CRUD for projects/books/chapters/entities/boards/ai_sessions
  with multi-tenant isolation and optimistic concurrency (baseRev).
- ws.ts: Fastify websocket hub for autosave + presence events.
- mapping.ts: row <-> core type conversion.

Core (@pubscript/core):
- Zod domain schemas (projects, books, chapters, entities, boards, ai_sessions)
  exported from index.
- storage-local.ts (IndexedDB/Dexie) and storage-server.ts (REST) adapters
  implementing the StorageAdapter contract.

Tests & tooling:
- storage.contract.test.ts: parameterized over both adapters; wired as
  `pnpm contract` and added to CI.
- seed.ts (`pnpm --filter server seed`): creates demo project "The Glass Harbor"
  — 3 chapters of prose, 4 linked characters, 1 world location, 6-node board.
- Dockerfile + compose wiring for the server runtime.

Acceptance: seed project opens with 3 chapters, 4 linked characters, 1 board.
This commit is contained in:
Schwitzz
2026-10-24 18:31:20 -05:00
parent 53f4c5b4c7
commit 1c9b531996
95 changed files with 10006 additions and 16 deletions
+66
View File
@@ -0,0 +1,66 @@
import type { FastifyInstance } from "fastify";
import { WebSocket } from "ws";
import { canAccessProject, bearerToken, userFromToken } from "./auth.js";
import { toUser } from "./mapping.js";
interface Client {
ws: WebSocket;
projectId: string;
userId: string;
}
/**
* Register the `/api/ws` endpoint. Clients connect with `?projectId=X` and an
* auth token (bearer header or cookie). The server validates access, then
* relays `autosave` and `presence` events to the other clients in the same
* project (never back to the sender).
*/
export function registerWs(app: FastifyInstance): void {
const rooms = new Map<string, Set<Client>>();
app.get("/api/ws", { websocket: true }, (socket: WebSocket, req) => {
const db = app.db;
const query = req.query as { projectId?: string };
const projectId = query.projectId;
// Authenticate (bearer header or cookie).
const cookieToken = (req.headers.cookie ?? "")
.split("; ")
.find((c) => c.startsWith("ps_session="))
?.split("=")[1] ?? null;
const token = bearerToken(req) ?? cookieToken;
const row = token ? userFromToken(db, token) : null;
if (!row || !projectId || !canAccessProject(db, toUser(row), projectId)) {
socket.close(4401);
return;
}
const client: Client = { ws: socket, projectId, userId: row.id };
const room = rooms.get(projectId) ?? new Set<Client>();
room.add(client);
rooms.set(projectId, room);
socket.on("message", (data: WebSocket.RawData) => {
let msg: any;
try {
msg = JSON.parse(String(data));
} catch {
return;
}
if (msg?.type !== "autosave" && msg?.type !== "presence") return;
const payload = JSON.stringify({ ...msg, userId: client.userId, at: new Date().toISOString() });
for (const other of room) {
if (other !== client && other.ws.readyState === WebSocket.OPEN) {
other.ws.send(payload);
}
}
});
const cleanup = (): void => {
room.delete(client);
if (room.size === 0) rooms.delete(projectId);
};
socket.on("close", cleanup);
socket.on("error", cleanup);
});
}