- Panel: changing a role or disabling an account always failed (db.transaction doesn't exist on node:sqlite); it uses tx() now - Feeds and link previews are scanned with indexOf, not whole-document regexes, so a hostile feed or page can't freeze the server; entity decoding can't throw; escaped-HTML descriptions make clean excerpts - Feed reads share one fetch per feed and serve the stale copy while a refresh runs - Deliberate HTTP errors (the CSRF 403) keep their status instead of becoming logged 500s; a JSON null body is handled - url columns read the scheme the way the URL parser does, so control characters can't hide javascript: - Google sign-in state cookie is __Host- and its return page is checked again; more reserved ranges blocked for previews and feeds, and a 15 s cap on each whole fetch - Log lines from visitor text are made single-line and short; list limits can't go negative; entity names can't hit object prototypes - A clip title can't point the clip tool at another file - Uploads over 60 MP are refused before decoding; the Keep original help says a photo's location stays in it - admin-cli add defaults to the editor role Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
294 lines
9.5 KiB
JavaScript
294 lines
9.5 KiB
JavaScript
#!/usr/bin/env node
|
|
/* ═══════════════════════════════════════════════════════════════
|
|
ADMIN ACCOUNT CLI
|
|
|
|
The only way an account comes into existence. Run it on the box,
|
|
against the live database:
|
|
|
|
cd /srv/ngu-api
|
|
DB_PATH=/var/lib/ngu/ngu.db node src/admin-cli.js add you@ngu.org
|
|
DB_PATH=/var/lib/ngu/ngu.db node src/admin-cli.js list
|
|
DB_PATH=/var/lib/ngu/ngu.db node src/admin-cli.js passwd you@ngu.org
|
|
DB_PATH=/var/lib/ngu/ngu.db node src/admin-cli.js role them@ngu.org editor
|
|
DB_PATH=/var/lib/ngu/ngu.db node src/admin-cli.js disable them@ngu.org
|
|
DB_PATH=/var/lib/ngu/ngu.db node src/admin-cli.js enable them@ngu.org
|
|
|
|
Roles, low to high. Each one can do everything the one above it
|
|
in this list can:
|
|
|
|
viewer read the CMS, change nothing
|
|
editor + create and update records
|
|
admin + delete records
|
|
superadmin + accounts, roles and sessions, via /admin/panel
|
|
|
|
add takes --role=admin, --name="Full Name". It defaults to
|
|
editor, the least that can change content; raise it on purpose. Press enter at the password prompt and it generates one
|
|
and prints it once.
|
|
|
|
The list comes from auth.js rather than being repeated here, so
|
|
the CLI can't drift from what requireRole will actually accept.
|
|
|
|
This is also how the first superadmin is made, there's no
|
|
bootstrap path in the web interface, on purpose:
|
|
|
|
node src/admin-cli.js role you@ngu.org superadmin
|
|
|
|
Changing a password, a role, or disabling an account drops that
|
|
person's live sessions, so it takes effect now rather than in
|
|
30 days.
|
|
|
|
Nothing here refuses to demote or disable the last superadmin.
|
|
The panel does, because a misclick there locks everyone out;
|
|
here you're already root on the box holding the database, and a
|
|
recovery tool that argues with you isn't one.
|
|
═══════════════════════════════════════════════════════════════ */
|
|
|
|
import { createInterface } from "node:readline";
|
|
import { randomBytes } from "node:crypto";
|
|
|
|
import { openDatabase, migrate } from "./db.js";
|
|
import { hashPassword, destroyAllSessionsFor, ROLES } from "./auth.js";
|
|
|
|
const MIN_PASSWORD = 12;
|
|
|
|
/* ── Prompt, with echo suppressed for secrets ────────────────── */
|
|
|
|
function ask(question, { hidden = false } = {}) {
|
|
return new Promise((resolve) => {
|
|
const rl = createInterface({
|
|
input: process.stdin,
|
|
output: process.stdout,
|
|
terminal: true,
|
|
});
|
|
|
|
rl.muted = false;
|
|
rl._writeToOutput = function (text) {
|
|
if (!rl.muted) rl.output.write(text);
|
|
};
|
|
|
|
rl.question(question, (answer) => {
|
|
if (hidden) rl.output.write("\n");
|
|
rl.close();
|
|
resolve(answer);
|
|
});
|
|
|
|
rl.muted = hidden;
|
|
});
|
|
}
|
|
|
|
async function readPassword() {
|
|
const first = await ask("Password (enter to generate): ", { hidden: true });
|
|
|
|
if (first === "") {
|
|
const generated = randomBytes(12).toString("base64url");
|
|
console.log(`\nGenerated password: ${generated}`);
|
|
console.log("Copy it now, it isn't stored anywhere readable.\n");
|
|
return generated;
|
|
}
|
|
|
|
if (first.length < MIN_PASSWORD) {
|
|
fail(`Password must be at least ${MIN_PASSWORD} characters.`);
|
|
}
|
|
|
|
const second = await ask("Again: ", { hidden: true });
|
|
if (first !== second) fail("Passwords didn't match.");
|
|
|
|
return first;
|
|
}
|
|
|
|
function fail(message) {
|
|
console.error(`✗ ${message}`);
|
|
process.exit(1);
|
|
}
|
|
|
|
/* ── Commands ────────────────────────────────────────────────── */
|
|
|
|
function findUser(db, email) {
|
|
return db
|
|
.prepare("SELECT id, email, name, role, is_active FROM admin_users WHERE email = ?")
|
|
.get(email);
|
|
}
|
|
|
|
function checkRole(role) {
|
|
if (!ROLES.includes(role)) {
|
|
fail(`Role must be one of: ${ROLES.join(", ")}.`);
|
|
}
|
|
return role;
|
|
}
|
|
|
|
/* Printed, never enforced, see the note at the top of the file.
|
|
Worth saying out loud, because the person doing it is usually
|
|
tidying up accounts rather than thinking about lockouts. */
|
|
function warnIfLastSuper(db, user) {
|
|
if (user.role !== "superadmin" || user.is_active !== 1) return;
|
|
|
|
const { n } = db
|
|
.prepare(
|
|
"SELECT COUNT(*) AS n FROM admin_users WHERE role = 'superadmin' AND is_active = 1",
|
|
)
|
|
.get();
|
|
|
|
if (n <= 1) {
|
|
console.warn(
|
|
"⚠ That's the last active superadmin. Nobody will be able to manage\n" +
|
|
" accounts from /admin/panel until you promote someone here.",
|
|
);
|
|
}
|
|
}
|
|
|
|
async function add(db, email, flags) {
|
|
if (findUser(db, email)) fail(`${email} already exists. Use passwd to change it.`);
|
|
|
|
const role = checkRole(flags.role ?? "editor");
|
|
|
|
const password = await readPassword();
|
|
|
|
db.prepare(
|
|
`INSERT INTO admin_users (email, name, password_hash, role)
|
|
VALUES (?, ?, ?, ?)`,
|
|
).run(email, flags.name ?? null, hashPassword(password), role);
|
|
|
|
console.log(`✓ ${email} created as ${role}`);
|
|
}
|
|
|
|
async function passwd(db, email) {
|
|
const user = findUser(db, email);
|
|
if (!user) fail(`No account for ${email}.`);
|
|
|
|
const password = await readPassword();
|
|
|
|
db.prepare("UPDATE admin_users SET password_hash = ? WHERE id = ?").run(
|
|
hashPassword(password),
|
|
user.id,
|
|
);
|
|
destroyAllSessionsFor(db, user.id);
|
|
|
|
console.log(`✓ password changed for ${email}, existing sessions ended`);
|
|
}
|
|
|
|
function setRole(db, email, role) {
|
|
const user = findUser(db, email);
|
|
if (!user) fail(`No account for ${email}.`);
|
|
|
|
checkRole(role);
|
|
|
|
if (user.role === role) {
|
|
console.log(`· ${email} is already ${role}, nothing to do`);
|
|
return;
|
|
}
|
|
|
|
// Only a demotion can strand the account list.
|
|
if (role !== "superadmin") warnIfLastSuper(db, user);
|
|
|
|
db.prepare("UPDATE admin_users SET role = ? WHERE id = ?").run(role, user.id);
|
|
|
|
// The session they're holding was issued against the old role.
|
|
// Every check reads the row fresh, so it isn't a security hole,
|
|
// but their open tab would keep drawing buttons that now 403.
|
|
destroyAllSessionsFor(db, user.id);
|
|
|
|
console.log(`✓ ${email} is now ${role} (was ${user.role}), sessions ended`);
|
|
}
|
|
|
|
function setActive(db, email, active) {
|
|
const user = findUser(db, email);
|
|
if (!user) fail(`No account for ${email}.`);
|
|
|
|
if (!active) warnIfLastSuper(db, user);
|
|
|
|
db.prepare("UPDATE admin_users SET is_active = ? WHERE id = ?").run(
|
|
active ? 1 : 0,
|
|
user.id,
|
|
);
|
|
if (!active) destroyAllSessionsFor(db, user.id);
|
|
|
|
console.log(`✓ ${email} ${active ? "enabled" : "disabled"}`);
|
|
}
|
|
|
|
function list(db) {
|
|
const rows = db
|
|
.prepare(
|
|
`SELECT u.email, u.name, u.role, u.is_active, u.last_login_at,
|
|
u.google_sub IS NOT NULL AS google,
|
|
(SELECT COUNT(*) FROM sessions s
|
|
WHERE s.user_id = u.id AND s.expires_at > datetime('now')) AS sessions
|
|
FROM admin_users u
|
|
ORDER BY u.email`,
|
|
)
|
|
.all();
|
|
|
|
if (rows.length === 0) {
|
|
console.log("No accounts yet. Create one with: admin-cli.js add you@ngu.org");
|
|
return;
|
|
}
|
|
|
|
for (const r of rows) {
|
|
// Role and state are separate facts now. The old single column
|
|
// printed "disabled" over the top of the role, which hid what
|
|
// the account would go back to on enable.
|
|
const state = r.is_active ? r.role : `${r.role} (disabled)`;
|
|
const seen = r.last_login_at ?? "never";
|
|
console.log(
|
|
`${r.email.padEnd(32)} ${state.padEnd(22)} last login ${seen.padEnd(20)} ${r.sessions} session(s)` +
|
|
(r.google ? " google linked" : ""),
|
|
);
|
|
}
|
|
}
|
|
|
|
/* ── Entry ───────────────────────────────────────────────────── */
|
|
|
|
const [command, ...rest] = process.argv.slice(2);
|
|
|
|
const flags = {};
|
|
const positional = [];
|
|
for (const arg of rest) {
|
|
const match = /^--([^=]+)=(.*)$/.exec(arg);
|
|
if (match) flags[match[1]] = match[2];
|
|
else positional.push(arg);
|
|
}
|
|
|
|
const email = positional[0]?.trim().toLowerCase();
|
|
|
|
const db = await openDatabase(process.env.DB_PATH ?? "./ngu.db");
|
|
migrate(db); // so a fresh database gets the tables before we use them
|
|
|
|
try {
|
|
switch (command) {
|
|
case "add":
|
|
if (!email) fail("Usage: admin-cli.js add email@example.com [--role=editor]");
|
|
await add(db, email, flags);
|
|
break;
|
|
case "passwd":
|
|
if (!email) fail("Usage: admin-cli.js passwd email@example.com");
|
|
await passwd(db, email);
|
|
break;
|
|
case "role": {
|
|
// Positional reads better for a two-argument command, but
|
|
// --role= is what `add` takes, so accept both rather than
|
|
// making people remember which is which.
|
|
const role = positional[1]?.trim().toLowerCase() ?? flags.role;
|
|
if (!email || !role) {
|
|
fail(`Usage: admin-cli.js role email@example.com <${ROLES.join("|")}>`);
|
|
}
|
|
setRole(db, email, role);
|
|
break;
|
|
}
|
|
case "disable":
|
|
if (!email) fail("Usage: admin-cli.js disable email@example.com");
|
|
setActive(db, email, false);
|
|
break;
|
|
case "enable":
|
|
if (!email) fail("Usage: admin-cli.js enable email@example.com");
|
|
setActive(db, email, true);
|
|
break;
|
|
case "list":
|
|
list(db);
|
|
break;
|
|
default:
|
|
console.log("Commands: add, passwd, role, disable, enable, list");
|
|
console.log(`Roles: ${ROLES.join(", ")}`);
|
|
process.exit(command ? 1 : 0);
|
|
}
|
|
} finally {
|
|
db.close();
|
|
}
|