variant round: roll retired, chance is variant literature (strict parse, crypto pick on reception, picked-only rendering, /story variance metric); entity round: /story the whole deliverable, /table the play projection, the slidwin carry (smart contwin cutoff, whole exchanges, housekeeper reads session-minus-tail); dormant-session rework: universal session lifecycle (dormant->live->finished, sessions/<n> storage), move-at-stop, start lint + auto-send rule, rebaseable housekeeping, turn-0 -> carryover.jsonl, seed -> memory.json, draft-only save-package; format house rules enforced by the nine-rule check-repo (ascii bytes, no text-mutating css); smoke 105/105 + restart + reminder + browser pass green, irene hand-migrated to the new layout
2026-11-15 14:35:00 +00:00
|
|
|
// server/users.mjs -- the deployment's people: users, invites, tokens.
|
2026-11-14 20:01:15 +00:00
|
|
|
//
|
|
|
|
|
// 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
|
variant round: roll retired, chance is variant literature (strict parse, crypto pick on reception, picked-only rendering, /story variance metric); entity round: /story the whole deliverable, /table the play projection, the slidwin carry (smart contwin cutoff, whole exchanges, housekeeper reads session-minus-tail); dormant-session rework: universal session lifecycle (dormant->live->finished, sessions/<n> storage), move-at-stop, start lint + auto-send rule, rebaseable housekeeping, turn-0 -> carryover.jsonl, seed -> memory.json, draft-only save-package; format house rules enforced by the nine-rule check-repo (ascii bytes, no text-mutating css); smoke 105/105 + restart + reminder + browser pass green, irene hand-migrated to the new layout
2026-11-15 14:35:00 +00:00
|
|
|
// keeps the token. Spent invites stay recorded forever -- claiming
|
2026-11-14 20:01:15 +00:00
|
|
|
// 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
|
variant round: roll retired, chance is variant literature (strict parse, crypto pick on reception, picked-only rendering, /story variance metric); entity round: /story the whole deliverable, /table the play projection, the slidwin carry (smart contwin cutoff, whole exchanges, housekeeper reads session-minus-tail); dormant-session rework: universal session lifecycle (dormant->live->finished, sessions/<n> storage), move-at-stop, start lint + auto-send rule, rebaseable housekeeping, turn-0 -> carryover.jsonl, seed -> memory.json, draft-only save-package; format house rules enforced by the nine-rule check-repo (ascii bytes, no text-mutating css); smoke 105/105 + restart + reminder + browser pass green, irene hand-migrated to the new layout
2026-11-15 14:35:00 +00:00
|
|
|
// deployment). Revocation deletes the row -- the token dies with it,
|
2026-11-14 20:01:15 +00:00
|
|
|
// 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.
|
jsdoc typing round, phases 1-2: tsc as a no-emit checker over plain mjs (checkJs, strict), the shared shapes in server/shapes.mjs (log events as a tagged union, wire messages, manifests, job state, the ctx), all 12 server modules annotated; requireOwner/requireSuperuser as JSDoc assertion functions so the router guarantee narrows without callsite churn; runtime stays zero-dependency (typescript + @types/node as pinned devDeps, node_modules gitignored, QUESTIONS #4 amended: dev tooling exempt); every non-annotation delta audited onto a small intended list (clerk status ?? 1, dead 401 guards, async wraps on enqueue callsites); smoke 105/105 + restart + repo checks green; the clerk and web/ are the next phases
2026-11-15 15:28:56 +00:00
|
|
|
/** @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 */
|
|
|
|
|
|
2026-11-14 20:01:15 +00:00
|
|
|
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();
|
jsdoc typing round, phases 1-2: tsc as a no-emit checker over plain mjs (checkJs, strict), the shared shapes in server/shapes.mjs (log events as a tagged union, wire messages, manifests, job state, the ctx), all 12 server modules annotated; requireOwner/requireSuperuser as JSDoc assertion functions so the router guarantee narrows without callsite churn; runtime stays zero-dependency (typescript + @types/node as pinned devDeps, node_modules gitignored, QUESTIONS #4 amended: dev tooling exempt); every non-annotation delta audited onto a small intended list (clerk status ?? 1, dead 401 guards, async wraps on enqueue callsites); smoke 105/105 + restart + repo checks green; the clerk and web/ are the next phases
2026-11-15 15:28:56 +00:00
|
|
|
/** @param {string} s @returns {string} */
|
2026-11-14 20:01:15 +00:00
|
|
|
const sha = (s) => createHash('sha256').update(String(s)).digest('hex');
|
jsdoc typing round, phases 1-2: tsc as a no-emit checker over plain mjs (checkJs, strict), the shared shapes in server/shapes.mjs (log events as a tagged union, wire messages, manifests, job state, the ctx), all 12 server modules annotated; requireOwner/requireSuperuser as JSDoc assertion functions so the router guarantee narrows without callsite churn; runtime stays zero-dependency (typescript + @types/node as pinned devDeps, node_modules gitignored, QUESTIONS #4 amended: dev tooling exempt); every non-annotation delta audited onto a small intended list (clerk status ?? 1, dead 401 guards, async wraps on enqueue callsites); smoke 105/105 + restart + repo checks green; the clerk and web/ are the next phases
2026-11-15 15:28:56 +00:00
|
|
|
/** @param {number} n @returns {string} */
|
2026-11-14 20:01:15 +00:00
|
|
|
const hex = (n) => randomBytes(n).toString('hex');
|
|
|
|
|
|
|
|
|
|
// --- users ---------------------------------------------------------------------
|
|
|
|
|
|
jsdoc typing round, phases 1-2: tsc as a no-emit checker over plain mjs (checkJs, strict), the shared shapes in server/shapes.mjs (log events as a tagged union, wire messages, manifests, job state, the ctx), all 12 server modules annotated; requireOwner/requireSuperuser as JSDoc assertion functions so the router guarantee narrows without callsite churn; runtime stays zero-dependency (typescript + @types/node as pinned devDeps, node_modules gitignored, QUESTIONS #4 amended: dev tooling exempt); every non-annotation delta audited onto a small intended list (clerk status ?? 1, dead 401 guards, async wraps on enqueue callsites); smoke 105/105 + restart + repo checks green; the clerk and web/ are the next phases
2026-11-15 15:28:56 +00:00
|
|
|
/** @returns {number} */
|
2026-11-14 20:01:15 +00:00
|
|
|
export function userCount() {
|
jsdoc typing round, phases 1-2: tsc as a no-emit checker over plain mjs (checkJs, strict), the shared shapes in server/shapes.mjs (log events as a tagged union, wire messages, manifests, job state, the ctx), all 12 server modules annotated; requireOwner/requireSuperuser as JSDoc assertion functions so the router guarantee narrows without callsite churn; runtime stays zero-dependency (typescript + @types/node as pinned devDeps, node_modules gitignored, QUESTIONS #4 amended: dev tooling exempt); every non-annotation delta audited onto a small intended list (clerk status ?? 1, dead 401 guards, async wraps on enqueue callsites); smoke 105/105 + restart + repo checks green; the clerk and web/ are the next phases
2026-11-15 15:28:56 +00:00
|
|
|
return Number(db.prepare('SELECT COUNT(*) AS n FROM users').get()?.n ?? 0);
|
2026-11-14 20:01:15 +00:00
|
|
|
}
|
|
|
|
|
|
variant round: roll retired, chance is variant literature (strict parse, crypto pick on reception, picked-only rendering, /story variance metric); entity round: /story the whole deliverable, /table the play projection, the slidwin carry (smart contwin cutoff, whole exchanges, housekeeper reads session-minus-tail); dormant-session rework: universal session lifecycle (dormant->live->finished, sessions/<n> storage), move-at-stop, start lint + auto-send rule, rebaseable housekeeping, turn-0 -> carryover.jsonl, seed -> memory.json, draft-only save-package; format house rules enforced by the nine-rule check-repo (ascii bytes, no text-mutating css); smoke 105/105 + restart + reminder + browser pass green, irene hand-migrated to the new layout
2026-11-15 14:35:00 +00:00
|
|
|
// does this identity exist? A revoked user's id resolves to absent --
|
2026-11-14 20:01:15 +00:00
|
|
|
// dead ids are ownerless by resolution, never by rewriting history
|
jsdoc typing round, phases 1-2: tsc as a no-emit checker over plain mjs (checkJs, strict), the shared shapes in server/shapes.mjs (log events as a tagged union, wire messages, manifests, job state, the ctx), all 12 server modules annotated; requireOwner/requireSuperuser as JSDoc assertion functions so the router guarantee narrows without callsite churn; runtime stays zero-dependency (typescript + @types/node as pinned devDeps, node_modules gitignored, QUESTIONS #4 amended: dev tooling exempt); every non-annotation delta audited onto a small intended list (clerk status ?? 1, dead 401 guards, async wraps on enqueue callsites); smoke 105/105 + restart + repo checks green; the clerk and web/ are the next phases
2026-11-15 15:28:56 +00:00
|
|
|
/** @param {?string} uid @returns {boolean} */
|
2026-11-14 20:01:15 +00:00
|
|
|
export function exists(uid) {
|
|
|
|
|
if (uid == null) return false;
|
|
|
|
|
return !!db.prepare('SELECT 1 FROM users WHERE id = ?').get(uid);
|
|
|
|
|
}
|
|
|
|
|
|
jsdoc typing round, phases 1-2: tsc as a no-emit checker over plain mjs (checkJs, strict), the shared shapes in server/shapes.mjs (log events as a tagged union, wire messages, manifests, job state, the ctx), all 12 server modules annotated; requireOwner/requireSuperuser as JSDoc assertion functions so the router guarantee narrows without callsite churn; runtime stays zero-dependency (typescript + @types/node as pinned devDeps, node_modules gitignored, QUESTIONS #4 amended: dev tooling exempt); every non-annotation delta audited onto a small intended list (clerk status ?? 1, dead 401 guards, async wraps on enqueue callsites); smoke 105/105 + restart + repo checks green; the clerk and web/ are the next phases
2026-11-15 15:28:56 +00:00
|
|
|
/** @param {?string} token @returns {?UserRow} */
|
2026-11-14 20:01:15 +00:00
|
|
|
export function getUserByToken(token) {
|
|
|
|
|
const t = String(token ?? '').trim();
|
|
|
|
|
if (!t) return null;
|
jsdoc typing round, phases 1-2: tsc as a no-emit checker over plain mjs (checkJs, strict), the shared shapes in server/shapes.mjs (log events as a tagged union, wire messages, manifests, job state, the ctx), all 12 server modules annotated; requireOwner/requireSuperuser as JSDoc assertion functions so the router guarantee narrows without callsite churn; runtime stays zero-dependency (typescript + @types/node as pinned devDeps, node_modules gitignored, QUESTIONS #4 amended: dev tooling exempt); every non-annotation delta audited onto a small intended list (clerk status ?? 1, dead 401 guards, async wraps on enqueue callsites); smoke 105/105 + restart + repo checks green; the clerk and web/ are the next phases
2026-11-15 15:28:56 +00:00
|
|
|
const row = /** @type {?UserRow} */ (db.prepare('SELECT * FROM users WHERE token_hash = ?').get(sha(t)));
|
2026-11-14 20:01:15 +00:00
|
|
|
return row ?? null;
|
|
|
|
|
}
|
|
|
|
|
|
jsdoc typing round, phases 1-2: tsc as a no-emit checker over plain mjs (checkJs, strict), the shared shapes in server/shapes.mjs (log events as a tagged union, wire messages, manifests, job state, the ctx), all 12 server modules annotated; requireOwner/requireSuperuser as JSDoc assertion functions so the router guarantee narrows without callsite churn; runtime stays zero-dependency (typescript + @types/node as pinned devDeps, node_modules gitignored, QUESTIONS #4 amended: dev tooling exempt); every non-annotation delta audited onto a small intended list (clerk status ?? 1, dead 401 guards, async wraps on enqueue callsites); smoke 105/105 + restart + repo checks green; the clerk and web/ are the next phases
2026-11-15 15:28:56 +00:00
|
|
|
/** @param {?string|undefined} uid @returns {?string} */
|
2026-11-14 20:01:15 +00:00
|
|
|
export function userName(uid) {
|
|
|
|
|
if (uid == null) return null;
|
|
|
|
|
const row = db.prepare('SELECT name FROM users WHERE id = ?').get(uid);
|
jsdoc typing round, phases 1-2: tsc as a no-emit checker over plain mjs (checkJs, strict), the shared shapes in server/shapes.mjs (log events as a tagged union, wire messages, manifests, job state, the ctx), all 12 server modules annotated; requireOwner/requireSuperuser as JSDoc assertion functions so the router guarantee narrows without callsite churn; runtime stays zero-dependency (typescript + @types/node as pinned devDeps, node_modules gitignored, QUESTIONS #4 amended: dev tooling exempt); every non-annotation delta audited onto a small intended list (clerk status ?? 1, dead 401 guards, async wraps on enqueue callsites); smoke 105/105 + restart + repo checks green; the clerk and web/ are the next phases
2026-11-15 15:28:56 +00:00
|
|
|
return row ? String(row.name) : null;
|
2026-11-14 20:01:15 +00:00
|
|
|
}
|
|
|
|
|
|
jsdoc typing round, phases 1-2: tsc as a no-emit checker over plain mjs (checkJs, strict), the shared shapes in server/shapes.mjs (log events as a tagged union, wire messages, manifests, job state, the ctx), all 12 server modules annotated; requireOwner/requireSuperuser as JSDoc assertion functions so the router guarantee narrows without callsite churn; runtime stays zero-dependency (typescript + @types/node as pinned devDeps, node_modules gitignored, QUESTIONS #4 amended: dev tooling exempt); every non-annotation delta audited onto a small intended list (clerk status ?? 1, dead 401 guards, async wraps on enqueue callsites); smoke 105/105 + restart + repo checks green; the clerk and web/ are the next phases
2026-11-15 15:28:56 +00:00
|
|
|
/** @returns {User[]} */
|
2026-11-14 20:01:15 +00:00
|
|
|
export function listUsers() {
|
jsdoc typing round, phases 1-2: tsc as a no-emit checker over plain mjs (checkJs, strict), the shared shapes in server/shapes.mjs (log events as a tagged union, wire messages, manifests, job state, the ctx), all 12 server modules annotated; requireOwner/requireSuperuser as JSDoc assertion functions so the router guarantee narrows without callsite churn; runtime stays zero-dependency (typescript + @types/node as pinned devDeps, node_modules gitignored, QUESTIONS #4 amended: dev tooling exempt); every non-annotation delta audited onto a small intended list (clerk status ?? 1, dead 401 guards, async wraps on enqueue callsites); smoke 105/105 + restart + repo checks green; the clerk and web/ are the next phases
2026-11-15 15:28:56 +00:00
|
|
|
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 }));
|
2026-11-14 20:01:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// revocation destroys the identity: no suspend, no restore. Their runs
|
variant round: roll retired, chance is variant literature (strict parse, crypto pick on reception, picked-only rendering, /story variance metric); entity round: /story the whole deliverable, /table the play projection, the slidwin carry (smart contwin cutoff, whole exchanges, housekeeper reads session-minus-tail); dormant-session rework: universal session lifecycle (dormant->live->finished, sessions/<n> storage), move-at-stop, start lint + auto-send rule, rebaseable housekeeping, turn-0 -> carryover.jsonl, seed -> memory.json, draft-only save-package; format house rules enforced by the nine-rule check-repo (ascii bytes, no text-mutating css); smoke 105/105 + restart + reminder + browser pass green, irene hand-migrated to the new layout
2026-11-15 14:35:00 +00:00
|
|
|
// and packages stay -- ownerless, readable, forkable.
|
jsdoc typing round, phases 1-2: tsc as a no-emit checker over plain mjs (checkJs, strict), the shared shapes in server/shapes.mjs (log events as a tagged union, wire messages, manifests, job state, the ctx), all 12 server modules annotated; requireOwner/requireSuperuser as JSDoc assertion functions so the router guarantee narrows without callsite churn; runtime stays zero-dependency (typescript + @types/node as pinned devDeps, node_modules gitignored, QUESTIONS #4 amended: dev tooling exempt); every non-annotation delta audited onto a small intended list (clerk status ?? 1, dead 401 guards, async wraps on enqueue callsites); smoke 105/105 + restart + repo checks green; the clerk and web/ are the next phases
2026-11-15 15:28:56 +00:00
|
|
|
/** @param {string} id @returns {boolean} */
|
2026-11-14 20:01:15 +00:00
|
|
|
export function revokeUser(id) {
|
|
|
|
|
return db.prepare('DELETE FROM users WHERE id = ?').run(id).changes > 0;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// --- invites ---------------------------------------------------------------------
|
|
|
|
|
|
jsdoc typing round, phases 1-2: tsc as a no-emit checker over plain mjs (checkJs, strict), the shared shapes in server/shapes.mjs (log events as a tagged union, wire messages, manifests, job state, the ctx), all 12 server modules annotated; requireOwner/requireSuperuser as JSDoc assertion functions so the router guarantee narrows without callsite churn; runtime stays zero-dependency (typescript + @types/node as pinned devDeps, node_modules gitignored, QUESTIONS #4 amended: dev tooling exempt); every non-annotation delta audited onto a small intended list (clerk status ?? 1, dead 401 guards, async wraps on enqueue callsites); smoke 105/105 + restart + repo checks green; the clerk and web/ are the next phases
2026-11-15 15:28:56 +00:00
|
|
|
/** @param {string} byUid @param {'invite'|'bootstrap'} [kind] @returns {{ id: number, code: string }} */
|
2026-11-14 20:01:15 +00:00
|
|
|
export function mintInvite(byUid, kind = 'invite') {
|
variant round: roll retired, chance is variant literature (strict parse, crypto pick on reception, picked-only rendering, /story variance metric); entity round: /story the whole deliverable, /table the play projection, the slidwin carry (smart contwin cutoff, whole exchanges, housekeeper reads session-minus-tail); dormant-session rework: universal session lifecycle (dormant->live->finished, sessions/<n> storage), move-at-stop, start lint + auto-send rule, rebaseable housekeeping, turn-0 -> carryover.jsonl, seed -> memory.json, draft-only save-package; format house rules enforced by the nine-rule check-repo (ascii bytes, no text-mutating css); smoke 105/105 + restart + reminder + browser pass green, irene hand-migrated to the new layout
2026-11-15 14:35:00 +00:00
|
|
|
const code = hex(12); // 24 hex chars -- shown once, stored hashed
|
2026-11-14 20:01:15 +00:00
|
|
|
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 };
|
|
|
|
|
}
|
|
|
|
|
|
jsdoc typing round, phases 1-2: tsc as a no-emit checker over plain mjs (checkJs, strict), the shared shapes in server/shapes.mjs (log events as a tagged union, wire messages, manifests, job state, the ctx), all 12 server modules annotated; requireOwner/requireSuperuser as JSDoc assertion functions so the router guarantee narrows without callsite churn; runtime stays zero-dependency (typescript + @types/node as pinned devDeps, node_modules gitignored, QUESTIONS #4 amended: dev tooling exempt); every non-annotation delta audited onto a small intended list (clerk status ?? 1, dead 401 guards, async wraps on enqueue callsites); smoke 105/105 + restart + repo checks green; the clerk and web/ are the next phases
2026-11-15 15:28:56 +00:00
|
|
|
/** @returns {InviteListed[]} */
|
2026-11-14 20:01:15 +00:00
|
|
|
export function listInvites() {
|
jsdoc typing round, phases 1-2: tsc as a no-emit checker over plain mjs (checkJs, strict), the shared shapes in server/shapes.mjs (log events as a tagged union, wire messages, manifests, job state, the ctx), all 12 server modules annotated; requireOwner/requireSuperuser as JSDoc assertion functions so the router guarantee narrows without callsite churn; runtime stays zero-dependency (typescript + @types/node as pinned devDeps, node_modules gitignored, QUESTIONS #4 amended: dev tooling exempt); every non-annotation delta audited onto a small intended list (clerk status ?? 1, dead 401 guards, async wraps on enqueue callsites); smoke 105/105 + restart + repo checks green; the clerk and web/ are the next phases
2026-11-15 15:28:56 +00:00
|
|
|
return /** @type {InviteListed[]} */ (db.prepare(
|
2026-11-14 20:01:15 +00:00
|
|
|
'SELECT id, kind, created_by, created_at, claimed_by, claimed_at FROM invites ORDER BY id'
|
jsdoc typing round, phases 1-2: tsc as a no-emit checker over plain mjs (checkJs, strict), the shared shapes in server/shapes.mjs (log events as a tagged union, wire messages, manifests, job state, the ctx), all 12 server modules annotated; requireOwner/requireSuperuser as JSDoc assertion functions so the router guarantee narrows without callsite churn; runtime stays zero-dependency (typescript + @types/node as pinned devDeps, node_modules gitignored, QUESTIONS #4 amended: dev tooling exempt); every non-annotation delta audited onto a small intended list (clerk status ?? 1, dead 401 guards, async wraps on enqueue callsites); smoke 105/105 + restart + repo checks green; the clerk and web/ are the next phases
2026-11-15 15:28:56 +00:00
|
|
|
).all());
|
2026-11-14 20:01:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// only unclaimed invites can be revoked; spent ones are a permanent record
|
jsdoc typing round, phases 1-2: tsc as a no-emit checker over plain mjs (checkJs, strict), the shared shapes in server/shapes.mjs (log events as a tagged union, wire messages, manifests, job state, the ctx), all 12 server modules annotated; requireOwner/requireSuperuser as JSDoc assertion functions so the router guarantee narrows without callsite churn; runtime stays zero-dependency (typescript + @types/node as pinned devDeps, node_modules gitignored, QUESTIONS #4 amended: dev tooling exempt); every non-annotation delta audited onto a small intended list (clerk status ?? 1, dead 401 guards, async wraps on enqueue callsites); smoke 105/105 + restart + repo checks green; the clerk and web/ are the next phases
2026-11-15 15:28:56 +00:00
|
|
|
/** @param {number} id @returns {boolean} */
|
2026-11-14 20:01:15 +00:00
|
|
|
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.
|
jsdoc typing round, phases 1-2: tsc as a no-emit checker over plain mjs (checkJs, strict), the shared shapes in server/shapes.mjs (log events as a tagged union, wire messages, manifests, job state, the ctx), all 12 server modules annotated; requireOwner/requireSuperuser as JSDoc assertion functions so the router guarantee narrows without callsite churn; runtime stays zero-dependency (typescript + @types/node as pinned devDeps, node_modules gitignored, QUESTIONS #4 amended: dev tooling exempt); every non-annotation delta audited onto a small intended list (clerk status ?? 1, dead 401 guards, async wraps on enqueue callsites); smoke 105/105 + restart + repo checks green; the clerk and web/ are the next phases
2026-11-15 15:28:56 +00:00
|
|
|
/** @param {?string} code @param {?string} name @returns {{ token: string, user: User }} */
|
2026-11-14 20:01:15 +00:00
|
|
|
export function claimInvite(code, name) {
|
|
|
|
|
const c = String(code ?? '').trim();
|
|
|
|
|
const n = String(name ?? '').trim();
|
jsdoc typing round, phases 1-2: tsc as a no-emit checker over plain mjs (checkJs, strict), the shared shapes in server/shapes.mjs (log events as a tagged union, wire messages, manifests, job state, the ctx), all 12 server modules annotated; requireOwner/requireSuperuser as JSDoc assertion functions so the router guarantee narrows without callsite churn; runtime stays zero-dependency (typescript + @types/node as pinned devDeps, node_modules gitignored, QUESTIONS #4 amended: dev tooling exempt); every non-annotation delta audited onto a small intended list (clerk status ?? 1, dead 401 guards, async wraps on enqueue callsites); smoke 105/105 + restart + repo checks green; the clerk and web/ are the next phases
2026-11-15 15:28:56 +00:00
|
|
|
/** @param {string} msg @returns {never} */
|
|
|
|
|
const fail = (msg) => { const e = /** @type {import('./shapes.mjs').HttpError} */ (new Error(msg)); e.status = 400; throw e; };
|
2026-11-14 20:01:15 +00:00
|
|
|
if (!c) fail('the invite code is required');
|
|
|
|
|
if (!n) fail('a display name is required');
|
jsdoc typing round, phases 1-2: tsc as a no-emit checker over plain mjs (checkJs, strict), the shared shapes in server/shapes.mjs (log events as a tagged union, wire messages, manifests, job state, the ctx), all 12 server modules annotated; requireOwner/requireSuperuser as JSDoc assertion functions so the router guarantee narrows without callsite churn; runtime stays zero-dependency (typescript + @types/node as pinned devDeps, node_modules gitignored, QUESTIONS #4 amended: dev tooling exempt); every non-annotation delta audited onto a small intended list (clerk status ?? 1, dead 401 guards, async wraps on enqueue callsites); smoke 105/105 + restart + repo checks green; the clerk and web/ are the next phases
2026-11-15 15:28:56 +00:00
|
|
|
const row = /** @type {?InviteRow} */ (db.prepare('SELECT * FROM invites WHERE code_hash = ?').get(sha(c)));
|
2026-11-14 20:01:15 +00:00
|
|
|
if (!row) fail('unknown invite code');
|
variant round: roll retired, chance is variant literature (strict parse, crypto pick on reception, picked-only rendering, /story variance metric); entity round: /story the whole deliverable, /table the play projection, the slidwin carry (smart contwin cutoff, whole exchanges, housekeeper reads session-minus-tail); dormant-session rework: universal session lifecycle (dormant->live->finished, sessions/<n> storage), move-at-stop, start lint + auto-send rule, rebaseable housekeeping, turn-0 -> carryover.jsonl, seed -> memory.json, draft-only save-package; format house rules enforced by the nine-rule check-repo (ascii bytes, no text-mutating css); smoke 105/105 + restart + reminder + browser pass green, irene hand-migrated to the new layout
2026-11-15 14:35:00 +00:00
|
|
|
if (row.claimed_by != null) fail('this invite was already used -- ask for a fresh one');
|
2026-11-14 20:01:15 +00:00
|
|
|
if (row.kind === 'bootstrap' && userCount() > 0) {
|
variant round: roll retired, chance is variant literature (strict parse, crypto pick on reception, picked-only rendering, /story variance metric); entity round: /story the whole deliverable, /table the play projection, the slidwin carry (smart contwin cutoff, whole exchanges, housekeeper reads session-minus-tail); dormant-session rework: universal session lifecycle (dormant->live->finished, sessions/<n> storage), move-at-stop, start lint + auto-send rule, rebaseable housekeeping, turn-0 -> carryover.jsonl, seed -> memory.json, draft-only save-package; format house rules enforced by the nine-rule check-repo (ascii bytes, no text-mutating css); smoke 105/105 + restart + reminder + browser pass green, irene hand-migrated to the new layout
2026-11-15 14:35:00 +00:00
|
|
|
fail('the bootstrap invite expired when this deployment got its superuser -- ask the operator for an invite');
|
2026-11-14 20:01:15 +00:00
|
|
|
}
|
|
|
|
|
const uid = hex(4);
|
variant round: roll retired, chance is variant literature (strict parse, crypto pick on reception, picked-only rendering, /story variance metric); entity round: /story the whole deliverable, /table the play projection, the slidwin carry (smart contwin cutoff, whole exchanges, housekeeper reads session-minus-tail); dormant-session rework: universal session lifecycle (dormant->live->finished, sessions/<n> storage), move-at-stop, start lint + auto-send rule, rebaseable housekeeping, turn-0 -> carryover.jsonl, seed -> memory.json, draft-only save-package; format house rules enforced by the nine-rule check-repo (ascii bytes, no text-mutating css); smoke 105/105 + restart + reminder + browser pass green, irene hand-migrated to the new layout
2026-11-15 14:35:00 +00:00
|
|
|
const token = hex(16); // 32 hex chars -- returned once, never again
|
2026-11-14 20:01:15 +00:00
|
|
|
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.
|
|
|
|
|
|
jsdoc typing round, phases 1-2: tsc as a no-emit checker over plain mjs (checkJs, strict), the shared shapes in server/shapes.mjs (log events as a tagged union, wire messages, manifests, job state, the ctx), all 12 server modules annotated; requireOwner/requireSuperuser as JSDoc assertion functions so the router guarantee narrows without callsite churn; runtime stays zero-dependency (typescript + @types/node as pinned devDeps, node_modules gitignored, QUESTIONS #4 amended: dev tooling exempt); every non-annotation delta audited onto a small intended list (clerk status ?? 1, dead 401 guards, async wraps on enqueue callsites); smoke 105/105 + restart + repo checks green; the clerk and web/ are the next phases
2026-11-15 15:28:56 +00:00
|
|
|
/** @returns {?{ reused?: boolean, code?: string }} */
|
2026-11-14 20:01:15 +00:00
|
|
|
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;
|
2026-11-19 10:31:03 +00:00
|
|
|
|
|
|
|
|
// --- 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;
|
|
|
|
|
}
|