multiuser: token identity, invites + bootstrap, owner-gated runs, fork, user packages; spectator spa; utc house rule

This commit is contained in:
2026-11-14 20:01:15 +00:00
parent 9f85adc3c6
commit 711634cc38
15 changed files with 1134 additions and 105 deletions
+213 -31
View File
@@ -1,9 +1,11 @@
// server/main.mjs — entry + REST spine.
//
// Loopback, single-human, synchronous JSON. The SPA and curl are both
// just clients. Boot-rebuild: every run whose latest session was not
// housekept gets its open window back from the jsonl — the log is the
// truth, the context is a view.
// Synchronous JSON over HTTP; the SPA and curl are both just clients.
// Multiuser: bearer-token identity (users.mjs), ownership gating on
// every mutation and model call, fork for everyone else. Boot-rebuild:
// every run whose latest session was not housekept gets its open
// window back from the jsonl — the log is the truth, the context is a
// view.
//
// usage: node server/main.mjs [--mock]
import fs from 'node:fs';
@@ -11,11 +13,13 @@ import path from 'node:path';
import http from 'node:http';
import { fileURLToPath } from 'node:url';
import { makeProvider } from './provider.mjs';
import { clerkRaw, clerkRawJson, clerkJson } from './clerk.mjs';
import { clerkRaw, clerkRawJson, clerkJson, clerk } from './clerk.mjs';
import * as bundle from './bundle.mjs';
import * as session from './session.mjs';
import * as housekeeping from './housekeeping.mjs';
import { gmTurn, answerAsk, turn0, HttpError } from './loop.mjs';
import * as users from './users.mjs';
import { forkRun } from './fork.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const MOCK = process.argv.includes('--mock');
@@ -29,11 +33,36 @@ const cfg = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));
const provider = makeProvider(cfg.endpoint ?? {});
const ctx = { mock: MOCK, cfg, provider, sessions: new Map(), jobs: new Map(), runMeta: bundle.runMeta };
// --- the per-run activity lock ---------------------------------------------------
//
// Serializes every async mutation span (turn, ask, turn0, the
// housekeeping job, fork) so a fork can never torn-copy mid-turn and
// two concurrent turns can never interleave across their awaits.
// Sync-only handlers (paper-set, file writes) need no lock: they
// block the event loop and are atomic by construction.
ctx.locks = new Map();
ctx.enqueue = (runId, fn) => {
const prev = ctx.locks.get(runId) ?? Promise.resolve();
const next = prev.then(fn, fn); // run regardless of a prior failure
ctx.locks.set(runId, next.catch(() => {}));
return next;
};
// --- bootstrap: the fresh-deployment superuser invite ---------------------------
const boot = users.bootstrap();
if (boot?.code) {
console.log(`fresh deployment — the superuser invite (also at ${path.relative(ROOT, users.bootstrapFile)}):`);
console.log(` ${boot.code}`);
} else if (boot?.reused) {
console.log(`fresh deployment — the superuser invite waits at ${path.relative(ROOT, users.bootstrapFile)}`);
}
// --- boot-rebuild ------------------------------------------------------------
if (fs.existsSync(path.join(ROOT, 'runs'))) {
for (const d of fs.readdirSync(path.join(ROOT, 'runs'), { withFileTypes: true })) {
if (!d.isDirectory()) continue;
if (!d.isDirectory() || d.name.startsWith('.')) continue; // .staging-* is never a run
if (!fs.existsSync(path.join(ROOT, 'runs', d.name, 'run.json'))) continue;
const latest = session.latestSession(d.name);
if (latest && latest !== session.lastHousekept(d.name)) {
@@ -67,7 +96,8 @@ const readBody = (req) => new Promise((resolve, reject) => {
});
const routes = [];
const route = (method, pattern, handler) => routes.push({ method, segs: pattern.split('/').filter(Boolean), handler });
const route = (method, pattern, handler, opts = {}) =>
routes.push({ method, segs: pattern.split('/').filter(Boolean), handler, publicRoute: opts.public === true });
const match = (method, pathname) => {
const segs = pathname.split('/').filter(Boolean);
@@ -78,7 +108,7 @@ const match = (method, pathname) => {
if (r.segs[i].startsWith(':')) params[r.segs[i].slice(1)] = decodeURIComponent(segs[i]);
else if (r.segs[i] !== segs[i]) continue outer;
}
return { handler: r.handler, params };
return { handler: r.handler, params, publicRoute: r.publicRoute };
}
return null;
};
@@ -115,6 +145,92 @@ function serveStatic(pathname, res) {
res.end(data);
}
// --- identity: session, claim, invites, users ---------------------------------
//
// Identity is a bearer token (server/users.mjs). Two routes are
// public: reading your own session (null when signed out) and
// claiming an invite. Everything else — reads included — requires a
// signed-in user: the runs and packages of this deployment are shared
// among invitees, not with the world.
route('GET', '/api/session', async ({ user }) => ({
user, // null when signed out or the token is stale
fresh: users.userCount() === 0,
}), { public: true });
route('POST', '/api/claim', async ({ body }) => {
const r = users.claimInvite(body.code, body.name);
return { token: r.token, user: r.user };
}, { public: true });
// superuser: mint an invite — the code is returned once, never stored
route('POST', '/api/invites', async ({ user }) => {
requireSuperuser(user);
return users.mintInvite(user.id);
});
// superuser: the invite ledger, hashes only — codes are never listed
route('GET', '/api/invites', async ({ user }) => {
requireSuperuser(user);
const list = users.listInvites().map((i) => ({
id: i.id,
kind: i.kind,
created_at: i.created_at,
state: i.claimed_by == null ? 'unclaimed' : `claimed by ${users.userName(i.claimed_by) ?? i.claimed_by}`,
}));
return { invites: list };
});
// superuser: revoke an unclaimed invite (handed to the wrong chat)
route('DELETE', '/api/invites/:id', async ({ params, user }) => {
requireSuperuser(user);
if (!users.revokeInvite(Number(params.id))) throw new HttpError(409, 'no such unclaimed invite');
return { ok: true };
});
route('GET', '/api/users', async ({ user }) => {
requireSuperuser(user);
return { users: users.listUsers() };
});
// revocation destroys the identity: the token dies with the row. Their
// runs and packages stay on disk untouched — the record of ownership
// keeps its dead id, which resolves to ownerless everywhere it is
// read. Only the live map is reconciled: their open windows close.
route('POST', '/api/users/:id/revoke', async ({ params, user }) => {
requireSuperuser(user);
if (params.id === user.id) throw new HttpError(409, 'revoking yourself would lock the deployment out of its superuser');
if (!users.revokeUser(params.id)) throw new HttpError(404, `no such user: ${params.id}`);
for (const id of [...ctx.sessions.keys()]) {
if (bundle.runMeta(id)?.owner === params.id) ctx.sessions.delete(id);
}
return { ok: true };
});
function requireSuperuser(user) {
if (!user?.superuser) throw new HttpError(403, 'superuser only');
}
// ownership is resolved, never maintained: run.json keeps the record
// of who owned a run, and a dead owner id (revocation) resolves to
// absent. The API never exposes a dangling id.
const resolveOwner = (owner) => (owner != null && users.exists(owner) ? owner : null);
// ownership: every GM action — every mutation, every model call — is
// the owner's alone. Ownerless runs (pre-user or revoked owner) are
// one uniform state: readable by all, forkable, never re-claimed.
function requireOwner(user, runId) {
bundle.requireRun(runId); // 404 when it doesn't exist
const meta = bundle.runMeta(runId) ?? {};
if (resolveOwner(meta.owner) == null) {
throw new HttpError(403, `run '${runId}' is ownerless — fork it to make it yours`);
}
if (meta.owner !== user.id) {
throw new HttpError(403, `run '${runId}' is ${users.userName(meta.owner) ?? 'another user'}'s — fork it to continue as yours`);
}
return meta;
}
// --- routes -------------------------------------------------------------------
route('GET', '/api', async () => ({
@@ -125,7 +241,30 @@ route('GET', '/api', async () => ({
route('GET', '/api/models', async () => (MOCK ? ['mock'] : await provider.models()));
route('GET', '/api/packages', async () => clerkRawJson('packages'));
route('GET', '/api/packages', async () => {
const pkgs = clerkRawJson('packages');
for (const p of pkgs) {
if (p.origin === 'user') {
p.owner = resolveOwner(p.owner);
p.ownerName = p.owner == null ? null : users.userName(p.owner);
}
}
return pkgs;
});
// save a run's craft as a new user package, published to every user
// (gm.md included — saving is the act of publishing). The pc never
// rides: the next create asks for one.
route('POST', '/api/packages', async ({ body, user }) => {
const from = String(body.from ?? '').trim();
const name = String(body.name ?? '').trim();
if (!from) throw new HttpError(400, 'from (a run id) is required');
if (!name) throw new HttpError(400, 'name (the new package\'s display name) is required');
requireOwner(user, from);
const r = clerk(from, '--json', '--owner', user.id, 'save-package', name);
if (r.code !== 0) throw new HttpError(400, r.err || r.out || 'save-package failed');
return { package: JSON.parse(r.out) };
});
// the repo-fed prompts, read-only: per-project opening + guards and
// substrate invariants — never copied into a run, so the editor shows
@@ -148,6 +287,8 @@ route('GET', '/api/runs', async () => {
r.pendingAsk = s?.pendingAsk?.question ?? null;
r.lastSession = session.latestSession(r.id);
r.lastHousekept = session.lastHousekept(r.id);
r.owner = resolveOwner(r.owner);
r.ownerName = r.owner == null ? null : users.userName(r.owner);
}
return runs;
});
@@ -155,13 +296,13 @@ route('GET', '/api/runs', async () => {
// create: the pc's name is required (unique per package); the
// package display name defaults to the package's own. The id is
// anonymous, generated by the clerk.
route('POST', '/api/runs', async ({ body }) => {
route('POST', '/api/runs', async ({ body, user }) => {
const pkg = String(body.package ?? '').trim();
const pc = String(body.pc ?? '').trim();
if (!/^[a-z0-9-]+$/.test(pkg)) throw new HttpError(400, 'package must be a slug — see GET /api/packages');
if (!pc) throw new HttpError(400, 'pc is required — the main character\'s name, distinct per package');
const name = body.name === undefined ? undefined : String(body.name);
const r = clerkRaw('--json', 'create', pkg, pc, ...(name !== undefined ? [name] : []), ...(body.model ? [String(body.model)] : []));
const r = clerkRaw('--json', '--owner', user.id, 'create', pkg, pc, ...(name !== undefined ? [name] : []), ...(body.model ? [String(body.model)] : []));
if (r.code !== 0) throw new HttpError(400, r.err || r.out || 'create failed');
const run = JSON.parse(r.out);
return { run, dir: `runs/${run.id}` };
@@ -182,8 +323,17 @@ route('GET', '/api/runs/:id', async ({ params }) => {
const st = clerkJson(id, '--json', 'status');
const s = ctx.sessions.get(id);
const meta = bundle.runMeta(id);
const owner = resolveOwner(meta?.owner);
return {
run: { id, package: meta?.package ?? null, created: meta?.created ?? null, model: meta?.model ?? null },
run: {
id,
package: meta?.package ?? null,
created: meta?.created ?? null,
forked: meta?.forked ?? null,
owner,
ownerName: owner == null ? null : users.userName(owner),
model: meta?.model ?? null,
},
display: bundle.runDisplay(id),
open: !!s,
draft: session.latestSession(id) === null,
@@ -235,8 +385,9 @@ route('GET', '/api/runs/:id/files', async ({ params }) => {
return { files };
});
route('PUT', '/api/runs/:id/files/:path', async ({ params, body }) => {
route('PUT', '/api/runs/:id/files/:path', async ({ params, body, user }) => {
const dir = bundle.requireRun(params.id);
requireOwner(user, params.id);
const f = params.path;
const mode = RUN_FILES[f];
if (!mode) throw new HttpError(404, `no such run file in the API surface: ${f}`);
@@ -251,8 +402,9 @@ route('PUT', '/api/runs/:id/files/:path', async ({ params, body }) => {
// prompt vars: the inputs the prompts themselves declare ($TOKENS
// found in any prompt file). Values live in the run's settings vars.
route('POST', '/api/runs/:id/vars', async ({ params, body }) => {
route('POST', '/api/runs/:id/vars', async ({ params, body, user }) => {
const dir = bundle.requireRun(params.id);
requireOwner(user, params.id);
const vars = body.vars;
if (typeof vars !== 'object' || vars === null || Array.isArray(vars)) throw new HttpError(400, 'vars (an object of token -> value) is required');
for (const [k, v] of Object.entries(vars)) {
@@ -274,8 +426,9 @@ route('GET', '/api/runs/:id/notes', async ({ params }) => {
return { content: fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '' };
});
route('PUT', '/api/runs/:id/notes', async ({ params, body }) => {
route('PUT', '/api/runs/:id/notes', async ({ params, body, user }) => {
const dir = bundle.requireRun(params.id);
requireOwner(user, params.id); // spectators read the pad, the owner writes it
if (typeof body.content !== 'string') throw new HttpError(400, 'content (a string) is required — empty clears the pad');
fs.writeFileSync(path.join(dir, 'gm.md'), body.content);
return { ok: true };
@@ -285,8 +438,9 @@ route('PUT', '/api/runs/:id/notes', async ({ params, body }) => {
// so the directory is the whole run and removal is complete. A played
// run is a story — deleting one is a deliberate act that stays by
// hand (Remove-Item runs/<id>), not a button.
route('DELETE', '/api/runs/:id', async ({ params }) => {
route('DELETE', '/api/runs/:id', async ({ params, user }) => {
const dir = bundle.requireRun(params.id);
requireOwner(user, params.id);
if (session.latestSession(params.id) !== null) {
throw new HttpError(409, `this run has been played — its sessions and memory stay until deleted by hand: Remove-Item -Recurse ${path.join('runs', params.id)}`);
}
@@ -294,8 +448,9 @@ route('DELETE', '/api/runs/:id', async ({ params }) => {
return { ok: true, deleted: params.id };
});
route('POST', '/api/runs/:id/windows', async ({ params, body }) => {
route('POST', '/api/runs/:id/windows', async ({ params, body, user }) => {
const id = params.id;
requireOwner(user, id);
if (ctx.sessions.has(id)) throw new HttpError(409, `a window is already open for '${id}' — one active window per run`);
const s = session.openWindow(id, body.override === true);
ctx.sessions.set(id, s);
@@ -318,20 +473,33 @@ route('GET', '/api/runs/:id/session', async ({ params }) => {
};
});
route('POST', '/api/runs/:id/turn', async ({ params, body }) => {
route('POST', '/api/runs/:id/turn', async ({ params, body, user }) => {
const line = String(body.line ?? '').trim();
if (!line) throw new HttpError(400, 'line is required');
return { ok: true, ...(await gmTurn(ctx, params.id, line)) };
requireOwner(user, params.id);
return { ok: true, ...(await ctx.enqueue(params.id, () => gmTurn(ctx, params.id, line, user))) };
});
// the opening beat as its own action: sent as the first GM turn on a
// fresh window — "start" is this right after window-open
route('POST', '/api/runs/:id/turn0', async ({ params }) => ({ ok: true, ...(await turn0(ctx, params.id)) }));
route('POST', '/api/runs/:id/turn0', async ({ params, user }) => {
requireOwner(user, params.id);
return { ok: true, ...(await ctx.enqueue(params.id, () => turn0(ctx, params.id, user))) };
});
route('POST', '/api/runs/:id/ask', async ({ params, body }) => {
route('POST', '/api/runs/:id/ask', async ({ params, body, user }) => {
const answer = String(body.answer ?? '').trim();
if (!answer) throw new HttpError(400, 'answer is required');
return { ok: true, ...(await answerAsk(ctx, params.id, answer)) };
requireOwner(user, params.id);
return { ok: true, ...(await ctx.enqueue(params.id, () => answerAsk(ctx, params.id, answer, user))) };
});
// fork: any user, any run — a mechanical atomic copy with the owner
// replaced (server/fork.mjs). The source's activity lock is held, so
// the copy is never taken mid-turn.
route('POST', '/api/runs/:id/fork', async ({ params, user }) => {
bundle.requireRun(params.id);
return ctx.enqueue(params.id, () => forkRun(ctx, params.id, user));
});
route('GET', '/api/runs/:id/status', async ({ params }) => {
@@ -344,9 +512,10 @@ route('GET', '/api/runs/:id/status', async ({ params }) => {
// clerk (which journals the prior state). Descriptions never contain
// commas — the transport is comma-separated — so a comma inside an
// item is a 400, not a silent corruption later.
route('POST', '/api/runs/:id/paper', async ({ params, body }) => {
route('POST', '/api/runs/:id/paper', async ({ params, body, user }) => {
const id = params.id;
bundle.requireRun(id);
requireOwner(user, id);
const items = body.items;
if (!Array.isArray(items)) throw new HttpError(400, 'items (an array of descriptions) is required — an empty array clears the paper');
for (const it of items) {
@@ -357,9 +526,10 @@ route('POST', '/api/runs/:id/paper', async ({ params, body }) => {
return { ok: true, paper };
});
route('POST', '/api/runs/:id/housekeeping', async ({ params }) => {
route('POST', '/api/runs/:id/housekeeping', async ({ params, user }) => {
// ends the window and kicks the async chain; poll GET for the outcome
const job = housekeeping.trigger(ctx, params.id);
requireOwner(user, params.id);
const job = housekeeping.trigger(ctx, params.id, user);
return { state: job.state, session: job.session };
});
@@ -368,9 +538,10 @@ route('POST', '/api/runs/:id/housekeeping', async ({ params }) => {
// saved for review — but nothing applied, no window ended, no state
// touched. The way to iterate on housekeeper.md against real data
// without playing more; works on the open window too.
route('POST', '/api/runs/:id/housekeeping/replay', async ({ params, body }) => {
route('POST', '/api/runs/:id/housekeeping/replay', async ({ params, body, user }) => {
const id = params.id;
bundle.requireRun(id);
requireOwner(user, id); // a replay spends a model call on the shared key
const stamp = String(body?.session ?? '').trim() || session.latestSession(id);
if (!stamp) throw new HttpError(409, 'no session to replay — this run has none');
let lines;
@@ -384,7 +555,7 @@ route('POST', '/api/runs/:id/housekeeping/replay', async ({ params, body }) => {
fs.mkdirSync(dir, { recursive: true });
const text = ctx.mock
? housekeeping.mockManifest(stamp)
: await housekeeping.callHousekeeper(ctx, id, housekeeping.buildMessages(id, lines, stamp));
: await housekeeping.callHousekeeper(ctx, id, housekeeping.buildMessages(id, lines, stamp), user);
let mf;
try {
mf = housekeeping.parseManifest(text);
@@ -402,11 +573,12 @@ route('GET', '/api/runs/:id/housekeeping', async ({ params }) => housekeeping.jo
route('GET', '/api/runs/:id/housekeeping/log', async ({ params }) => housekeeping.latestLog(params.id));
route('POST', '/api/runs/:id/housekeeping/apply', async ({ params, body }) => {
route('POST', '/api/runs/:id/housekeeping/apply', async ({ params, body, user }) => {
// the recovery path: apply a (hand-edited) manifest directly — closes
// any open window, marks the latest session housekept, autorestarts
const id = params.id;
bundle.requireRun(id);
requireOwner(user, id);
const file = String(body.file ?? '').trim();
if (!file) throw new HttpError(400, 'file is required — a manifest path relative to the run dir, e.g. manifests/<window>.json');
const manifestPath = path.resolve(path.join(ROOT, 'runs', id), file);
@@ -427,15 +599,23 @@ route('POST', '/api/runs/:id/housekeeping/apply', async ({ params, body }) => {
// --- dispatch -------------------------------------------------------------------
// bearer-token identity (users.mjs); null when absent or unknown
function authenticate(req) {
const m = /^Bearer\s+(.+)$/i.exec(req.headers.authorization ?? '');
return m ? users.getUserByToken(m[1].trim()) : null;
}
const server = http.createServer(async (req, res) => {
const started = Date.now();
let user = null;
try {
const url = new URL(req.url, 'http://localhost');
// the request log: one line per API call — reconstruct any session
// from the console output after the fact
// from the console output after the fact; the acting user rides
// every line (attribution, #22)
res.on('finish', () => {
if (url.pathname.startsWith('/api')) {
console.log(`${new Date().toISOString().slice(11, 19)} ${req.method} ${url.pathname} ${res.statusCode} ${Date.now() - started}ms`);
console.log(`${new Date().toISOString().slice(11, 19)} ${req.method} ${url.pathname} ${res.statusCode} ${Date.now() - started}ms${user ? ` u:${user.id}` : ''}`);
}
});
if (!url.pathname.startsWith('/api')) {
@@ -446,7 +626,9 @@ const server = http.createServer(async (req, res) => {
const m = match(req.method, url.pathname);
if (!m) throw new HttpError(404, `no such route: ${req.method} ${url.pathname}`);
const body = (req.method === 'POST' || req.method === 'PUT') ? await readBody(req) : {};
send(res, 200, await m.handler({ params: m.params, body, req }));
user = authenticate(req);
if (!m.publicRoute && !user) throw new HttpError(401, 'not signed in — claim an invite first (POST /api/claim)');
send(res, 200, await m.handler({ params: m.params, body, req, user }));
} catch (e) {
const status = e.status ?? 500;
if (status >= 500) console.error(`server: ${e.stack ?? e.message}`);