Files
tiny-worlds/server/users.mjs
T

160 lines
6.1 KiB
JavaScript
Raw Normal View History

// 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;