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
+43
View File
@@ -0,0 +1,43 @@
// server/fork.mjs — fork: a run copied whole, the owner replaced.
//
// Runs are entirely independent: no lineage is recorded, and the only
// mark a fork bears is `forked: unixtime` in run.json (its `created`
// carries over unchanged — the story's start date is a fact of the
// contents). No inconsistent state on disk at any point: the copy
// lands staged under a dot-name and is swapped in by a same-volume
// rename, which is atomic — no reader ever sees a half-run. The
// caller holds the source run's activity lock, so the copy is never
// taken mid-turn; a copied open window reopens honestly in the fork
// (the log is the truth, same as boot-rebuild).
import fs from 'node:fs';
import path from 'node:path';
import { randomBytes } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import { requireRun } from './bundle.mjs';
import { latestSession, lastHousekept, loadSession } from './session.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const RUNS_DIR = path.join(ROOT, 'runs');
export function forkRun(ctx, srcId, user) {
requireRun(srcId);
let id;
for (;;) {
id = randomBytes(4).toString('hex'); // anonymous, same alphabet as create
if (!fs.existsSync(path.join(RUNS_DIR, id)) && !fs.existsSync(path.join(RUNS_DIR, `.staging-${id}`))) break;
}
const staging = path.join(RUNS_DIR, `.staging-${id}`);
fs.cpSync(path.join(RUNS_DIR, srcId), staging, { recursive: true }); // sync: atomic wrt the event loop
const metaPath = path.join(staging, 'run.json');
const meta = JSON.parse(fs.readFileSync(metaPath, 'utf8'));
meta.owner = user.id;
meta.forked = Math.floor(Date.now() / 1000); // unixtime, UTC by definition
fs.writeFileSync(metaPath, JSON.stringify(meta, null, 2) + '\n');
fs.renameSync(staging, path.join(RUNS_DIR, id)); // same-volume rename: the atomic swap-in
// an open, unhousekept window in the source is an open window in the
// fork — its transcript reaches the fork's rings only after the fork
// housekeeps it, same rule as the original
const latest = latestSession(id);
if (latest && latest !== lastHousekept(id)) ctx.sessions.set(id, loadSession(id, latest));
return { run: id };
}
+9 -5
View File
@@ -96,7 +96,7 @@ export function parseManifest(text) {
// --- the job -----------------------------------------------------------------
export function trigger(ctx, runId) {
export function trigger(ctx, runId, user) {
requireRun(runId);
const s = ctx.sessions.get(runId);
if (!s) throw new HttpError(409, `no open window for '${runId}' — housekeeping is the window-close ritual`);
@@ -104,16 +104,18 @@ export function trigger(ctx, runId) {
ctx.sessions.delete(runId); // the window is closed from here on
const job = { state: 'running', session: s.stamp, started: new Date().toISOString() };
ctx.jobs.set(runId, job);
runJob(ctx, runId, s.stamp, s.lines); // async; catches its own errors
// the whole async chain holds the run's activity lock — a fork
// enqueued behind it copies the post-wrap state, never a half-apply
ctx.enqueue(runId, () => runJob(ctx, runId, s.stamp, s.lines, user));
return job;
}
async function runJob(ctx, runId, stamp, lines) {
async function runJob(ctx, runId, stamp, lines, user) {
const job = ctx.jobs.get(runId);
try {
const text = ctx.mock
? mockManifest(stamp)
: await callHousekeeper(ctx, runId, buildMessages(runId, lines, stamp));
: await callHousekeeper(ctx, runId, buildMessages(runId, lines, stamp), user);
const dir = path.join(runDir(runId), 'manifests');
fs.mkdirSync(dir, { recursive: true });
let mf;
@@ -136,9 +138,11 @@ async function runJob(ctx, runId, stamp, lines) {
}
}
async function callHousekeeper(ctx, runId, messages) {
async function callHousekeeper(ctx, runId, messages, user) {
const model = ctx.cfg.models?.housekeeper ?? ctx.cfg.models?.player ?? null;
if (!model) throw new Error('no housekeeper model configured (server.json models.housekeeper)');
// attribution (#22): every LLM call names the acting user
console.log(`${new Date().toISOString().slice(11, 19)} llm ${model} u:${user?.id ?? '?'}`);
const data = await ctx.provider.chat(model, messages, undefined, ctx.cfg.params ?? {});
return data.choices[0].message.content ?? '';
}
+10 -8
View File
@@ -27,7 +27,7 @@ function needSession(ctx, runId) {
return s;
}
export async function gmTurn(ctx, runId, line) {
export async function gmTurn(ctx, runId, line, user) {
const s = needSession(ctx, runId);
if (s.pendingAsk) throw new HttpError(409, 'a question is pending — answer it first (POST /ask)');
const paper = clerkJson(runId, 'paper'); // fresh per turn
@@ -37,7 +37,7 @@ export async function gmTurn(ctx, runId, line) {
s.conflict = null;
}
s.append({ t: 'msg', m: { role: 'user', content } });
return runLoop(ctx, runId);
return runLoop(ctx, runId, user);
}
// the opening beat: turn-0 sent as the first GM turn, separate from
@@ -45,7 +45,7 @@ export async function gmTurn(ctx, runId, line) {
// block was ingested as her opening paper at window-open — stripped
// here, since the normal ride carries the current paper on every GM
// turn, the beat included.
export async function turn0(ctx, runId) {
export async function turn0(ctx, runId, user) {
const s = needSession(ctx, runId);
if (s.pendingAsk) throw new HttpError(409, 'a question is pending — answer it first (POST /ask)');
if (!s.fresh) throw new HttpError(409, 'turn-0 opens a fresh run only');
@@ -57,10 +57,10 @@ export async function turn0(ctx, runId) {
let text = expandVars(runId, fs.readFileSync(file, 'utf8')); // $NAME tokens resolve like every bundle file
const sm = text.match(/<status>[\s\S]*?<\/status>/);
if (sm) text = text.replace(sm[0], '');
return gmTurn(ctx, runId, text.trim());
return gmTurn(ctx, runId, text.trim(), user);
}
export async function answerAsk(ctx, runId, answer) {
export async function answerAsk(ctx, runId, answer, user) {
const s = needSession(ctx, runId);
if (!s.pendingAsk) throw new HttpError(409, 'no pending question');
// execute the paused batch: the ask gets the answer, its siblings
@@ -73,13 +73,12 @@ export async function answerAsk(ctx, runId, answer) {
}
}
s.pendingAsk = null;
return runLoop(ctx, runId);
return runLoop(ctx, runId, user);
}
async function runLoop(ctx, runId) {
async function runLoop(ctx, runId, user) {
const s = ctx.sessions.get(runId);
const tools = toolList(runId);
const model = s.pendingAsk ? null : resolveModel(ctx, runId);
const out = { tools: [] };
for (;;) {
const view = renderView(s);
@@ -87,6 +86,9 @@ async function runLoop(ctx, runId) {
if (ctx.mock) {
msg = mockModel(s, view);
} else {
const model = resolveModel(ctx, runId);
// attribution (#22): every LLM call names the acting user
console.log(`${new Date().toISOString().slice(11, 19)} llm ${model} u:${user?.id ?? '?'}`);
const data = await ctx.provider.chat(model, view, tools, ctx.cfg.params ?? {});
msg = data.choices[0].message;
s.usage = data.usage
+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}`);
+159
View File
@@ -0,0 +1,159 @@
// server/users.mjs — the deployment's people: users, invites, tokens.
//
// Identity is a token, nothing else: no usernames, no passwords, no
// external IDPs. A single-use invite code is exchanged at claim time
// for a persistent token; the server stores hashes only, the client
// keeps the token. Spent invites stay recorded forever — claiming
// with a spent code is rejected loudly, never silently dropped. The
// first claim on a fresh deployment creates the superuser; recovery
// for a lost superuser token is filesystem access (it is their
// deployment). Revocation deletes the row — the token dies with it,
// and the person returns (if invited again) as a new identity.
//
// All times are UTC (house rule). Never model-facing: nothing here
// ever enters a bundle or a prompt.
import { DatabaseSync } from 'node:sqlite';
import { createHash, randomBytes } from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const STATE_DIR = path.join(ROOT, 'state');
const DB_PATH = path.join(STATE_DIR, 'deployment.db');
const BOOTSTRAP_FILE = path.join(STATE_DIR, 'bootstrap-invite.txt');
const SCHEMA = `
CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY,
token_hash TEXT NOT NULL UNIQUE,
name TEXT NOT NULL,
superuser INTEGER NOT NULL DEFAULT 0,
created TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS invites (
id INTEGER PRIMARY KEY AUTOINCREMENT,
code_hash TEXT NOT NULL UNIQUE,
kind TEXT NOT NULL CHECK (kind IN ('invite', 'bootstrap')),
created_by TEXT NOT NULL,
created_at TEXT NOT NULL,
claimed_by TEXT,
claimed_at TEXT
);
`;
fs.mkdirSync(STATE_DIR, { recursive: true });
const db = new DatabaseSync(DB_PATH);
db.exec(SCHEMA);
const now = () => new Date().toISOString();
const sha = (s) => createHash('sha256').update(String(s)).digest('hex');
const hex = (n) => randomBytes(n).toString('hex');
// --- users ---------------------------------------------------------------------
export function userCount() {
return db.prepare('SELECT COUNT(*) AS n FROM users').get().n;
}
// does this identity exist? A revoked user's id resolves to absent —
// dead ids are ownerless by resolution, never by rewriting history
export function exists(uid) {
if (uid == null) return false;
return !!db.prepare('SELECT 1 FROM users WHERE id = ?').get(uid);
}
export function getUserByToken(token) {
const t = String(token ?? '').trim();
if (!t) return null;
const row = db.prepare('SELECT * FROM users WHERE token_hash = ?').get(sha(t));
return row ?? null;
}
export function userName(uid) {
if (uid == null) return null;
const row = db.prepare('SELECT name FROM users WHERE id = ?').get(uid);
return row ? row.name : null;
}
export function listUsers() {
return db.prepare('SELECT id, name, superuser, created FROM users ORDER BY created').all()
.map((u) => ({ ...u, superuser: u.superuser === 1 }));
}
// revocation destroys the identity: no suspend, no restore. Their runs
// and packages stay — ownerless, readable, forkable.
export function revokeUser(id) {
return db.prepare('DELETE FROM users WHERE id = ?').run(id).changes > 0;
}
// --- invites ---------------------------------------------------------------------
export function mintInvite(byUid, kind = 'invite') {
const code = hex(12); // 24 hex chars — shown once, stored hashed
const res = db.prepare(
'INSERT INTO invites (code_hash, kind, created_by, created_at) VALUES (?, ?, ?, ?)'
).run(sha(code), kind, byUid, now());
return { id: Number(res.lastInsertRowid), code };
}
export function listInvites() {
return db.prepare(
'SELECT id, kind, created_by, created_at, claimed_by, claimed_at FROM invites ORDER BY id'
).all();
}
// only unclaimed invites can be revoked; spent ones are a permanent record
export function revokeInvite(id) {
return db.prepare('DELETE FROM invites WHERE id = ? AND claimed_by IS NULL').run(id).changes > 0;
}
// exchange a single-use invite code for a persistent token. Unknown,
// spent, and dead-bootstrap codes are each named explicitly.
export function claimInvite(code, name) {
const c = String(code ?? '').trim();
const n = String(name ?? '').trim();
const fail = (msg) => { const e = new Error(msg); e.status = 400; throw e; };
if (!c) fail('the invite code is required');
if (!n) fail('a display name is required');
const row = db.prepare('SELECT * FROM invites WHERE code_hash = ?').get(sha(c));
if (!row) fail('unknown invite code');
if (row.claimed_by != null) fail('this invite was already used — ask for a fresh one');
if (row.kind === 'bootstrap' && userCount() > 0) {
fail('the bootstrap invite expired when this deployment got its superuser — ask the operator for an invite');
}
const uid = hex(4);
const token = hex(16); // 32 hex chars — returned once, never again
const su = userCount() === 0 ? 1 : 0;
db.exec('BEGIN');
try {
db.prepare('INSERT INTO users (id, token_hash, name, superuser, created) VALUES (?, ?, ?, ?, ?)')
.run(uid, sha(token), n, su, now());
db.prepare('UPDATE invites SET claimed_by = ?, claimed_at = ? WHERE id = ?').run(uid, now(), row.id);
db.exec('COMMIT');
} catch (e) {
db.exec('ROLLBACK');
throw e;
}
return { token, user: { id: uid, name: n, superuser: su === 1 } };
}
// --- bootstrap -------------------------------------------------------------------
//
// On the fresh-deployment condition (no users yet) the server mints
// the superuser's invite itself and places it on disk for the op.
// Exactly one bootstrap invite exists until claimed: reused across
// restarts so a restart never invalidates what the op already saw;
// never generated again once any user exists; rejected at claim time
// if somehow presented after that.
export function bootstrap() {
if (userCount() > 0) return null;
const open = db.prepare("SELECT id FROM invites WHERE kind = 'bootstrap' AND claimed_by IS NULL").get();
if (open) return { reused: true };
const { code } = mintInvite('bootstrap', 'bootstrap');
fs.writeFileSync(BOOTSTRAP_FILE, `${code}\n`);
return { code };
}
export const bootstrapFile = BOOTSTRAP_FILE;