Files
tiny-worlds/server/users.mjs
T

182 lines
7.6 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.
/** @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;