4b8fbd7471
The rulings (developer, 2026-11-19, in conversation): a deployment basically always needs a fronting proxy, so the listen address is code -- loopback, no override (an op who wants otherwise owns their own socat); the port rides the RP_PORT env var (the RP_BASE twin the test scripts use, default 7350, garbage refused loud); server.json is deleted entirely, file and reader both, because it held no meaningful configuration once the bind died -- only the dead bind and the declared contwin; and contwin is provider/model dependent, never a deployment global, so the meter must DISCOVER it, not read a declaration.
The meter: the run detail's context block now derives its window from the registry -- modelState's resolved player spec, findModel, the model's input ceiling -- null when the provider states none or no pick stands, pct computed against that. A dividend named in review: pct is uncapped, so a mid-run re-pick onto a smaller model shows the meter over 100% BEFORE the first send refuses (the endpoint's own context-length 400 is the designed refusal -- no pre-request check, nothing truncates, the failed call lands its req event, the composer keeps the line per the standing rule).
Debug mode reworked around its real purpose (skip the invite dance on a fresh server, mocks in particular): the old shape -- every request the superuser, no auth at all -- left any debug server that somehow reached a network fully open. Now one fixed superuser behind a real bearer token: minted into state/debug-token.txt (the bootstrap-invite precedent -- a raw secret on disk so a restart never invalidates what the tester already pasted; the developer ruled persist), printed at every boot, and the claim screen gains the paste path ("or paste a token": store it, verify through the public /session, land or banner). The paste path is generic surface, not debug-only: tokens are returned once and never listed, so a pasted saved token is the only browser-migration path that existed to build. The public /session carries a debug flag so the claim hint says "paste the token the server printed at boot" instead of pointing at the bootstrap file debug never mints. Debug browser passes now exercise the real auth path (the 401, the u: attribution line) instead of bypassing it.
En-route mock fidelity fix the smoke earned: the mock path never set s.usage (no provider call happens), so every usage and context surface was null under the smoke -- the first cut of the new gauge assertion failed on exactly that. The mock now carries a synthetic usage (the assembled view's chars over 4), riding the msg events like the real path's, so the detail's usage and the context gauge are smoke-assertable: contwin 524288 straight from the mock's registry input ceiling, pct computed.
Verified: typecheck green both programs; smoke ALL PASS (+1, the discovered-gauge assertion); restart + reminder checks green (5 runs again); a browser pass on --mock --debug end to end -- the wrong token banners "token rejected" and stays on claim, the printed token lands as Debug the op, the stored token survives a server restart (the persistence proof), zero console errors; check-repo clean (it caught the round's own "window" in the new README passage -- contwin is the word); the dev machine's server.json deleted and the debug server restarted on the real state (Chloe and Irene rebuilt, the token minted into the real state/). Docs: README's deployment and debug passages, the config passage, and the layout tree (the server.example.json lines gone with the file); DICTIONARY's meter and contwin entries (the config key died with the file -- the dated rename record keeps its day's words); AGENTS's server entry and the two server.json gotchas; HANDOFF's round record and the push-queue count (now eight). The developer's operator-queue line ("revisit the debug mode, hardcode loopback") is struck by them in the same commit. packages/detention stays untracked WIP, untouched.
202 lines
8.5 KiB
JavaScript
202 lines
8.5 KiB
JavaScript
// 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.
|
|
/** @typedef {import('./shapes.mjs').User} User */
|
|
/** A users table row (token hashes never leave this module). */
|
|
/** @typedef {{ id: string, token_hash: string, name: string, superuser: number, created: string }} UserRow */
|
|
/** An invites table row. */
|
|
/** @typedef {{ id: number, code_hash: string, kind: 'invite'|'bootstrap', created_by: string, created_at: string, claimed_by: ?string, claimed_at: ?string }} InviteRow */
|
|
/** @typedef {{ id: number, kind: 'invite'|'bootstrap', created_by: string, created_at: string, claimed_by: ?string, claimed_at: ?string }} InviteListed */
|
|
|
|
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();
|
|
/** @param {string} s @returns {string} */
|
|
const sha = (s) => createHash('sha256').update(String(s)).digest('hex');
|
|
/** @param {number} n @returns {string} */
|
|
const hex = (n) => randomBytes(n).toString('hex');
|
|
|
|
// --- users ---------------------------------------------------------------------
|
|
|
|
/** @returns {number} */
|
|
export function userCount() {
|
|
return Number(db.prepare('SELECT COUNT(*) AS n FROM users').get()?.n ?? 0);
|
|
}
|
|
|
|
// does this identity exist? A revoked user's id resolves to absent --
|
|
// dead ids are ownerless by resolution, never by rewriting history
|
|
/** @param {?string} uid @returns {boolean} */
|
|
export function exists(uid) {
|
|
if (uid == null) return false;
|
|
return !!db.prepare('SELECT 1 FROM users WHERE id = ?').get(uid);
|
|
}
|
|
|
|
/** @param {?string} token @returns {?UserRow} */
|
|
export function getUserByToken(token) {
|
|
const t = String(token ?? '').trim();
|
|
if (!t) return null;
|
|
const row = /** @type {?UserRow} */ (db.prepare('SELECT * FROM users WHERE token_hash = ?').get(sha(t)));
|
|
return row ?? null;
|
|
}
|
|
|
|
/** @param {?string|undefined} uid @returns {?string} */
|
|
export function userName(uid) {
|
|
if (uid == null) return null;
|
|
const row = db.prepare('SELECT name FROM users WHERE id = ?').get(uid);
|
|
return row ? String(row.name) : null;
|
|
}
|
|
|
|
/** @returns {User[]} */
|
|
export function listUsers() {
|
|
return /** @type {{ id: string, name: string, superuser: number, created: string }[]} */ (
|
|
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.
|
|
/** @param {string} id @returns {boolean} */
|
|
export function revokeUser(id) {
|
|
return db.prepare('DELETE FROM users WHERE id = ?').run(id).changes > 0;
|
|
}
|
|
|
|
// --- invites ---------------------------------------------------------------------
|
|
|
|
/** @param {string} byUid @param {'invite'|'bootstrap'} [kind] @returns {{ id: number, code: string }} */
|
|
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 };
|
|
}
|
|
|
|
/** @returns {InviteListed[]} */
|
|
export function listInvites() {
|
|
return /** @type {InviteListed[]} */ (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
|
|
/** @param {number} id @returns {boolean} */
|
|
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.
|
|
/** @param {?string} code @param {?string} name @returns {{ token: string, user: User }} */
|
|
export function claimInvite(code, name) {
|
|
const c = String(code ?? '').trim();
|
|
const n = String(name ?? '').trim();
|
|
/** @param {string} msg @returns {never} */
|
|
const fail = (msg) => { const e = /** @type {import('./shapes.mjs').HttpError} */ (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 = /** @type {?InviteRow} */ (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.
|
|
|
|
/** @returns {?{ reused?: boolean, code?: string }} */
|
|
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;
|
|
|
|
// --- the debug token -------------------------------------------------------------
|
|
//
|
|
// Debug mode's sign-in (developer, 2026-11-19): one bearer token,
|
|
// minted into state/debug-token.txt and printed by the server at
|
|
// every boot. The bootstrap-invite precedent -- a raw secret on disk
|
|
// so a restart never invalidates what the tester already pasted.
|
|
// Never a db row: the debug user stays out of the deployment's
|
|
// people, the token dies with the file.
|
|
|
|
const DEBUG_TOKEN_FILE = path.join(STATE_DIR, 'debug-token.txt');
|
|
|
|
/** @returns {string} */
|
|
export function debugToken() {
|
|
const existing = fs.existsSync(DEBUG_TOKEN_FILE) ? fs.readFileSync(DEBUG_TOKEN_FILE, 'utf8').trim() : '';
|
|
if (existing) return existing;
|
|
const t = hex(16); // 32 hex chars -- the user-token shape
|
|
fs.writeFileSync(DEBUG_TOKEN_FILE, `${t}\n`);
|
|
return t;
|
|
}
|