Initial upload to Gitea
This commit is contained in:
1 parent
78193254ad
commit
8478998cae
1485 files changed
+461025
-42348
No files matched your search
+322
-57
@@ -1,5 +1,6 @@
|
||||
"use strict";
|
||||
|
||||
const crypto = require("crypto");
|
||||
const path = require("path");
|
||||
|
||||
require("dotenv").config({
|
||||
@@ -9,19 +10,34 @@ require("dotenv").config({
|
||||
|
||||
const speakeasy = require("speakeasy");
|
||||
const db = require("../db");
|
||||
const totpSecretCrypto = require("../utils/totp-secret-crypto");
|
||||
const { deleteAccountAssistantHistory } = require("../services/dashboard-assistant-history");
|
||||
const { deleteAccountServerAgentChats } = require("../services/server-agent-chat-ownership");
|
||||
const { preferBundledMediaUrl } = require("../utils/branding");
|
||||
// adpanel:bcrypt-cost-parity — shared with index.js; required AFTER dotenv
|
||||
// config above so BCRYPT_ROUNDS resolves against the loaded .env.
|
||||
const { resolveBcryptRounds, loadBcrypt, bcryptHashInputError } = require("../utils/bcrypt-rounds");
|
||||
// adpanel:credential-generation — the ONE shared session-epoch generator
|
||||
// (same module index.js requires): the panel and this CLI must mint epoch
|
||||
// values from the same CSPRNG range, never 0, never a predictable increment.
|
||||
const { newSessionEpoch, newSessionEpochDifferentFrom } = require("../utils/session-epoch");
|
||||
|
||||
let bcrypt;
|
||||
try {
|
||||
bcrypt = require("bcrypt");
|
||||
} catch {
|
||||
bcrypt = require("bcryptjs");
|
||||
}
|
||||
const bcrypt = loadBcrypt();
|
||||
|
||||
const ADMIN_AVATAR_URL = "https://cdn.jsdelivr.net/gh/antonndev/ADCDn/admin-avatar.webp";
|
||||
// adpanel:bcrypt-cost-parity — every hash this script writes (passwords AND
|
||||
// recovery codes) must cost the SAME bcrypt work the running panel's dummy
|
||||
// hash costs, or accounts created here answer login compares measurably
|
||||
// faster and login latency becomes an account-existence oracle. The rounds
|
||||
// resolve through the ONE shared resolver (utils/bcrypt-rounds.js) — never a
|
||||
// hardcoded literal. Rows already written at a stale cost self-heal through
|
||||
// rehash-on-login in POST /login.
|
||||
const BCRYPT_ROUNDS = resolveBcryptRounds();
|
||||
|
||||
const ADMIN_AVATAR_URL = "/images/admin-avatar.webp";
|
||||
const DEFAULT_USER_AVATAR_URLS = [
|
||||
"https://cdn.jsdelivr.net/gh/antonndev/ADCDn/normal-1.webp",
|
||||
"https://cdn.jsdelivr.net/gh/antonndev/ADCDn/normal-2.webp",
|
||||
"https://cdn.jsdelivr.net/gh/antonndev/ADCDn/normal-3.webp",
|
||||
"/images/normal-1.webp",
|
||||
"/images/normal-2.webp",
|
||||
"/images/normal-3.webp",
|
||||
];
|
||||
const MANAGED_AVATAR_URLS = new Set([ADMIN_AVATAR_URL, ...DEFAULT_USER_AVATAR_URLS]);
|
||||
|
||||
@@ -47,19 +63,61 @@ async function ensureUsersColumn(columnName, definition) {
|
||||
}
|
||||
}
|
||||
|
||||
// Session-epoch discriminator: the running panel revokes browser sessions
|
||||
// whose stored epoch no longer matches users.session_epoch. Generation lives
|
||||
// in the ONE shared module (adpanel:credential-generation — utils/session-
|
||||
// epoch.js, required below): fresh and unpredictable per mutation (never a
|
||||
// predictable increment, never the 0 column default), CSPRNG in the
|
||||
// established [1, 2147483647] range, and it must never be printed: it is
|
||||
// security-relevant discriminator material, not operation detail.
|
||||
|
||||
// Queue a session-revocation request for the running panel. The PRIMARY KEY
|
||||
// on email is the cross-process claim mechanism (a worker claims a row by
|
||||
// DELETEing it), so this must stay an insert-or-update keyed by email only.
|
||||
// Pass a transaction connection as executor to keep the insert inside the
|
||||
// caller's transaction; pass db for standalone calls.
|
||||
async function requestSessionRevocation(executor, email, reason) {
|
||||
await executor.query(
|
||||
`INSERT INTO pending_session_revocations (email, requested_at, reason, attempts) VALUES (?, ?, ?, 0)
|
||||
ON DUPLICATE KEY UPDATE requested_at = VALUES(requested_at), reason = VALUES(reason), attempts = 0`,
|
||||
[email, Date.now(), reason]
|
||||
);
|
||||
}
|
||||
|
||||
function usage() {
|
||||
return [
|
||||
"Usage:",
|
||||
" sudo node scripts/create-user.js --email user@example.com --password \"pass\" [--admin] [--secret BASE32] [--avatar-url URL]",
|
||||
" sudo node scripts/create-user.js --email user@example.com --password-hash \"$2b$...\" [--admin] [--secret BASE32] [--avatar-url URL]",
|
||||
" sudo node scripts/create-user.js --update-password --email user@example.com --password \"newpass\" [--current-password \"oldpass\"]",
|
||||
" sudo node scripts/create-user.js --update-password --email user@example.com --password-hash \"$2b$...\" [--current-password \"oldpass\"]",
|
||||
" sudo node scripts/create-user.js --email user@example.com [--admin] [--avatar-url URL]",
|
||||
" password via the ADPANEL_USER_PASSWORD environment variable, or",
|
||||
" sudo node scripts/create-user.js --email user@example.com --password-hash \"$2b$...\" [--admin] [--avatar-url URL]",
|
||||
" sudo node scripts/create-user.js --update-password --email user@example.com --password-hash \"$2b$...\"",
|
||||
" previous password (for verification) via ADPANEL_USER_CURRENT_PASSWORD env",
|
||||
" sudo node scripts/create-user.js --delete --email user@example.com",
|
||||
"",
|
||||
"Plaintext credentials must not be command arguments, including assignments",
|
||||
"after sudo or env. Use the inherited ADPANEL_USER_PASSWORD,",
|
||||
"ADPANEL_USER_CURRENT_PASSWORD, or ADPANEL_USER_TOTP_SECRET environment",
|
||||
"variables, or the initializer's --credentials-stdin option.",
|
||||
"--credentials-stdin reads a NUL-terminated password hash then a",
|
||||
"NUL-terminated TOTP seed (creation) or current password (update).",
|
||||
"",
|
||||
"TOTP seeds are sealed at rest. The sealing key comes from",
|
||||
"TOTP_SEALING_KEY when that env override is set, else it is derived from",
|
||||
"SESSION_SECRET — the panel and this script must share the same inputs,",
|
||||
"and a TOTP_SEALING_KEY override shorter than 32 chars is rejected here",
|
||||
"exactly as the panel rejects it at boot.",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
function parseArgs(argv) {
|
||||
const out = { admin: false, delete: false, updatePassword: false };
|
||||
const out = {
|
||||
admin: false,
|
||||
delete: false,
|
||||
updatePassword: false,
|
||||
password: process.env.ADPANEL_USER_PASSWORD || null,
|
||||
currentPassword: process.env.ADPANEL_USER_CURRENT_PASSWORD || null,
|
||||
secret: process.env.ADPANEL_USER_TOTP_SECRET || null,
|
||||
};
|
||||
for (let i = 0; i < argv.length; i += 1) {
|
||||
const arg = argv[i];
|
||||
if (arg === "--help" || arg === "-h") {
|
||||
@@ -78,31 +136,25 @@ function parseArgs(argv) {
|
||||
out.updatePassword = true;
|
||||
continue;
|
||||
}
|
||||
if (arg === "--credentials-stdin") {
|
||||
out.credentialsFromStdin = true;
|
||||
continue;
|
||||
}
|
||||
if (arg === "--email") {
|
||||
out.email = argv[i + 1];
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg === "--password") {
|
||||
out.password = argv[i + 1];
|
||||
i += 1;
|
||||
continue;
|
||||
if (arg === "--password" || arg === "--secret" || arg === "--current-password") {
|
||||
console.error(`error: ${arg} places a credential on this process's argv, which any local user can read via /proc/<pid>/cmdline.`);
|
||||
console.error(" pass it through inherited environment variables or use the initializer's --credentials-stdin option.");
|
||||
process.exit(2);
|
||||
}
|
||||
if (arg === "--password-hash") {
|
||||
out.passwordHash = argv[i + 1];
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg === "--current-password") {
|
||||
out.currentPassword = argv[i + 1];
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg === "--secret") {
|
||||
out.secret = argv[i + 1];
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg === "--avatar-url") {
|
||||
out.avatarUrl = argv[i + 1];
|
||||
i += 1;
|
||||
@@ -112,6 +164,19 @@ function parseArgs(argv) {
|
||||
return out;
|
||||
}
|
||||
|
||||
function readStdinCredentials(args) {
|
||||
if (args.delete || args.passwordHash || process.stdin.isTTY) return false;
|
||||
const fields = require("node:fs").readFileSync(0, "utf8").split("\0");
|
||||
if (fields.length !== 3 || !fields[0] || fields[2] !== "") return false;
|
||||
|
||||
const [passwordHash, credential] = fields;
|
||||
args.password = null;
|
||||
args.passwordHash = passwordHash;
|
||||
if (args.updatePassword) args.currentPassword = credential || null;
|
||||
else args.secret = credential || null;
|
||||
return true;
|
||||
}
|
||||
|
||||
function requireSudo() {
|
||||
if (typeof process.getuid === "function" && process.getuid() !== 0) {
|
||||
console.error("This script must be run with sudo.");
|
||||
@@ -151,6 +216,11 @@ async function main() {
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (args.credentialsFromStdin && !args.help && args.email && !readStdinCredentials(args)) {
|
||||
console.error("Invalid credential input on standard input.");
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (args.help || !args.email || (!args.delete && !args.updatePassword && !args.password && !args.passwordHash)) {
|
||||
console.log(usage());
|
||||
return 1;
|
||||
@@ -162,41 +232,184 @@ async function main() {
|
||||
return 1;
|
||||
}
|
||||
|
||||
// users.email is VARCHAR(255) and MySQL strict mode raises error 1406 on
|
||||
// longer values, so cap at 254 to match normalizeProvisionedEmail in
|
||||
// index.js and the self-service email-change handler. The cap is safe to
|
||||
// apply to every operation (create/delete/updatePassword): no email longer
|
||||
// than 254 characters can exist in the table, so a lookup could never match
|
||||
// anyway.
|
||||
if (email.length > 254) {
|
||||
console.error("Email must be 254 characters or fewer.");
|
||||
return 1;
|
||||
}
|
||||
if (/[\x00-\x1f\x7f]/.test(email)) {
|
||||
console.error("Email contains invalid control characters.");
|
||||
return 1;
|
||||
}
|
||||
|
||||
await db.ensureSchema();
|
||||
await ensureUsersColumn("recovery_codes", "TEXT NULL");
|
||||
await ensureUsersColumn("avatar_url", "VARCHAR(2048) NULL");
|
||||
await ensureUsersColumn("session_epoch", "BIGINT UNSIGNED NOT NULL DEFAULT 0");
|
||||
|
||||
// adpanel:planner-job-retract — the retract UPDATE inside the --delete path
|
||||
// writes status = 'cancelled', a member that only exists once the panel
|
||||
// boot's widening ALTER (index.js initAiChatTables) or mysql-schema.sql has
|
||||
// defined it: db.ensureSchema()'s CREATE TABLE IF NOT EXISTS above never
|
||||
// widens an existing table, so on a pre-retract install that UPDATE raises
|
||||
// error 1265 under STRICT_TRANS_TABLES and the delete transaction's catch
|
||||
// rolls back the ENTIRE delete — the account becomes undeletable via the
|
||||
// CLI. Replay the panel's ALTER here, byte-identical: the ENUM member list
|
||||
// MUST stay in lockstep with the panel's boot ALTER (same drift rule as the
|
||||
// mysql-schema.sql copy). Redefining the same column is idempotent — a
|
||||
// repeat simply succeeds, so unlike the panel's ADD COLUMN migration there
|
||||
// is no benign-error case to swallow — and mirroring the panel's error
|
||||
// posture, a real failure (insufficient rights, ...) is warned and NOT
|
||||
// fatal: the script proceeds and the retract keeps its transactional
|
||||
// fail-closed behavior. It runs HERE, in the setup phase and only for the
|
||||
// delete path (the only writer of 'cancelled'), never inside the delete
|
||||
// transaction: MySQL DDL causes an implicit commit, so this must never sit
|
||||
// between the delete's beginTransaction and commit.
|
||||
if (args.delete) {
|
||||
try {
|
||||
await db.query(`ALTER TABLE ai_agent_jobs MODIFY COLUMN status ENUM('queued','running','completed','failed','cancelled') NOT NULL DEFAULT 'queued'`);
|
||||
} catch (alterErr) {
|
||||
console.warn("[create-user] Could not widen ai_agent_jobs.status for the cancelled state (the delete will fail closed if the ENUM is still narrow):", alterErr.message);
|
||||
}
|
||||
}
|
||||
|
||||
if (args.delete) {
|
||||
let existing = null;
|
||||
if (args.currentPassword) {
|
||||
const found = await db.query(
|
||||
"SELECT id, password FROM users WHERE LOWER(email) = LOWER(?) LIMIT 1",
|
||||
// Delete the account and its access rows in one transaction so a crash
|
||||
// between the statements cannot leave orphaned user_access rows behind
|
||||
// (installs whose user_access table predates the CASCADE foreign key).
|
||||
// Remaining user-owned rows follow the schema's CASCADE constraints, and
|
||||
// the panel's startup sweep removes any leftovers deterministically.
|
||||
const conn = await db.pool.getConnection();
|
||||
try {
|
||||
await conn.beginTransaction();
|
||||
const [rows] = await conn.execute(
|
||||
"SELECT id, password FROM users WHERE LOWER(email) = LOWER(?) LIMIT 1 FOR UPDATE",
|
||||
[email]
|
||||
);
|
||||
existing = Array.isArray(found) ? found[0] : null;
|
||||
const existing = Array.isArray(rows) ? rows[0] : null;
|
||||
if (!existing) {
|
||||
await conn.rollback();
|
||||
console.error("User not found.");
|
||||
return 2;
|
||||
}
|
||||
if (!bcrypt.compareSync(String(args.currentPassword || ""), String(existing.password || ""))) {
|
||||
if (args.currentPassword && !bcrypt.compareSync(String(args.currentPassword || ""), String(existing.password || ""))) {
|
||||
await conn.rollback();
|
||||
console.error("Current password is incorrect.");
|
||||
return 3;
|
||||
}
|
||||
}
|
||||
|
||||
const result = await db.query("DELETE FROM users WHERE LOWER(email) = LOWER(?)", [email]);
|
||||
const affected = result && typeof result.affectedRows === "number" ? result.affectedRows : 0;
|
||||
if (!affected) {
|
||||
console.error("User not found.");
|
||||
return 2;
|
||||
await conn.execute("DELETE FROM user_access WHERE user_id = ?", [existing.id]);
|
||||
// adpanel:planner-item-cascade-retract — a queued planner job must never
|
||||
// outlive its item: a co-user may hold a queued ai_agent_jobs row (source
|
||||
// planner_send / scheduler_planner_next, source_ref = the item id) for
|
||||
// this account's planner item. That row no longer runs the enqueue-time
|
||||
// prompt once the item is gone (planner-source rows fail terminally at
|
||||
// processAiAgentJob's item-existence gate), but the retract — not a
|
||||
// fire-time 404 — is what keeps the jobs table consistent with the
|
||||
// items and frees the queued slot immediately instead of leaving it
|
||||
// queued only to die at fire time. The retract is
|
||||
// inlined on this transaction connection mirroring the panel's shape
|
||||
// (deleteUserAccountAtomically), lock direction included: the
|
||||
// queued-jobs FOR UPDATE pins only status = 'queued' rows against the
|
||||
// claim gate, so a RUNNING job keeps its enqueue-time authorization and
|
||||
// can never be marked cancelled here, and the survivor-chat read below
|
||||
// is a locking SELECT ... FOR UPDATE too (adpanel:retract-note-chat-toctou
|
||||
// — a chat deleted concurrently between a plain SELECT and the note
|
||||
// INSERT would FK-abort the whole delete on schema installs or orphan
|
||||
// the note on FK-less installs; FOR UPDATE pins the surviving rows so
|
||||
// the concurrent delete blocks until this transaction commits). All of
|
||||
// it sits BEFORE the ai_messages/ai_chats deletes below so the lock
|
||||
// direction (ai_agent_jobs row locks FIRST, then the ai_chats read and
|
||||
// the ai_messages write — jobs -> chats) matches the panel retract
|
||||
// (cancelQueuedPlannerAgentJobs) instead of inverting against it. The
|
||||
// doomed chats still exist at this point, so the note write excludes
|
||||
// them by account ID — a note may only land on a chat this transaction
|
||||
// does NOT delete.
|
||||
const [authoredPlannerItems] = await conn.execute(
|
||||
"SELECT id, server_name FROM server_planner_items WHERE prompt_author_id = ? OR (prompt_author_id IS NULL AND created_by_email = ?)",
|
||||
[existing.id, email]
|
||||
);
|
||||
if (authoredPlannerItems.length > 0) {
|
||||
// adpanel:planner-item-cascade-retract — the doomed items pair to
|
||||
// their queued jobs through a JOIN over the items table instead of
|
||||
// an OR clause per item: the OR-chain scaled 2 placeholders per
|
||||
// authored item toward mysql2's 65,535-placeholder ceiling, past
|
||||
// which this SELECT throws inside the transaction and rolls back
|
||||
// the WHOLE account delete. Mirrors the panel's
|
||||
// deleteUserAccountAtomically JOIN exactly (adpanel:source-ref-string-bind
|
||||
// keys the same rows: server_name + CAST(source_ref AS CHAR)) with a
|
||||
// constant placeholder count. The retract UPDATE and survivor-chat
|
||||
// read below keep their id IN (...) lists, which stay bounded:
|
||||
// enqueue-time dedupe allows at most one queued/running job per item
|
||||
// and insertAiAgentChatJob's AI_AGENT_MAX_PENDING_JOBS cap bounds the
|
||||
// whole pending queue, far under the ceiling. source/status are
|
||||
// unambiguous (server_planner_items carries neither column) and stay
|
||||
// unqualified to match the shared retract shape this block mirrors.
|
||||
const [queuedPlannerJobs] = await conn.execute(
|
||||
`SELECT j.id, j.chat_id, j.model
|
||||
FROM ai_agent_jobs j
|
||||
JOIN server_planner_items i
|
||||
ON j.server_name = i.server_name
|
||||
AND j.source_ref = CAST(i.id AS CHAR)
|
||||
WHERE (i.prompt_author_id = ? OR (i.prompt_author_id IS NULL AND i.created_by_email = ?))
|
||||
AND source IN ('planner_send','scheduler_planner_next')
|
||||
AND status = 'queued'
|
||||
FOR UPDATE`,
|
||||
[existing.id, email]
|
||||
);
|
||||
if (queuedPlannerJobs.length > 0) {
|
||||
const retractPlaceholders = queuedPlannerJobs.map(() => "?").join(",");
|
||||
await conn.execute(
|
||||
`UPDATE ai_agent_jobs SET status = 'cancelled', completed_at = NOW(), error = ? WHERE id IN (${retractPlaceholders})`,
|
||||
["planner_item_deleted", ...queuedPlannerJobs.map((jobRow) => jobRow.id)]
|
||||
);
|
||||
const survivingChatIds = new Set();
|
||||
const jobChatIds = [...new Set(queuedPlannerJobs.map((jobRow) => Number(jobRow.chat_id)).filter((n) => Number.isFinite(n)))];
|
||||
if (jobChatIds.length > 0) {
|
||||
const chatPlaceholders = jobChatIds.map(() => "?").join(",");
|
||||
const [survivingChatRows] = await conn.execute(
|
||||
`SELECT id FROM ai_chats WHERE id IN (${chatPlaceholders}) AND created_by <> ? FOR UPDATE`,
|
||||
[...jobChatIds, existing.id]
|
||||
);
|
||||
for (const chatRow of survivingChatRows) survivingChatIds.add(Number(chatRow.id));
|
||||
}
|
||||
for (const jobRow of queuedPlannerJobs) {
|
||||
if (!survivingChatIds.has(Number(jobRow.chat_id))) continue;
|
||||
await conn.execute(
|
||||
"INSERT INTO ai_messages (chat_id, role, content, image_data, thinking_time_ms, thinking_content, model) VALUES (?, 'assistant', ?, NULL, NULL, NULL, ?)",
|
||||
[jobRow.chat_id, "Planner task retracted before the agent ran it: the item was deleted, modified, or completed.", jobRow.model || null]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
// adpanel:user-delete-email-keyed-cleanup - retract planner work before deleting its items.
|
||||
await deleteAccountServerAgentChats(conn, existing.id);
|
||||
await conn.execute("DELETE FROM server_planner_items WHERE prompt_author_id = ? OR (prompt_author_id IS NULL AND created_by_email = ?)", [existing.id, email]);
|
||||
await deleteAccountAssistantHistory(conn, existing.id, email);
|
||||
await conn.execute("DELETE FROM users WHERE id = ?", [existing.id]);
|
||||
// Browser sessions are keyed by email, so the row deletion alone leaves
|
||||
// live sessions authenticated. Queue the revocation inside this
|
||||
// transaction: a committed delete must never skip the request.
|
||||
await requestSessionRevocation(conn, email, "cli-delete");
|
||||
await conn.commit();
|
||||
} catch (err) {
|
||||
try { await conn.rollback(); } catch { }
|
||||
throw err;
|
||||
} finally {
|
||||
conn.release();
|
||||
}
|
||||
console.log(`User deleted: ${email}`);
|
||||
console.log(`Session revocation requested: the running panel will revoke browser sessions for ${email} within a few seconds.`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (args.updatePassword) {
|
||||
const found = await db.query(
|
||||
"SELECT id, password FROM users WHERE LOWER(email) = LOWER(?) LIMIT 1",
|
||||
"SELECT id, password, session_epoch FROM users WHERE LOWER(email) = LOWER(?) LIMIT 1",
|
||||
[email]
|
||||
);
|
||||
const existing = Array.isArray(found) ? found[0] : null;
|
||||
@@ -214,8 +427,9 @@ async function main() {
|
||||
|
||||
let newHash = args.passwordHash ? String(args.passwordHash).trim() : "";
|
||||
if (newHash) {
|
||||
if (!/^\$2[aby]\$/.test(newHash)) {
|
||||
console.error("Password hash must be a bcrypt hash.");
|
||||
const hashError = bcryptHashInputError(newHash);
|
||||
if (hashError) {
|
||||
console.error(hashError);
|
||||
return 1;
|
||||
}
|
||||
} else {
|
||||
@@ -224,18 +438,29 @@ async function main() {
|
||||
console.error("Password is required.");
|
||||
return 1;
|
||||
}
|
||||
newHash = bcrypt.hashSync(rawPassword, 10);
|
||||
newHash = bcrypt.hashSync(rawPassword, BCRYPT_ROUNDS);
|
||||
}
|
||||
|
||||
await db.query("UPDATE users SET password = ? WHERE id = ?", [newHash, existing.id]);
|
||||
// Fresh unpredictable epoch on every password change: the running panel
|
||||
// revokes any browser session carrying a stale one, so the replaced
|
||||
// credential cannot keep an authenticated session alive. It must differ
|
||||
// from the current value for the revocation to be observable — the shared
|
||||
// generator's bounded retry keeps that guarantee (the CLI's former inline
|
||||
// while-loop, same semantics).
|
||||
const sessionEpoch = newSessionEpochDifferentFrom(Number(existing.session_epoch || 0));
|
||||
|
||||
await db.query("UPDATE users SET password = ?, session_epoch = ? WHERE id = ?", [newHash, sessionEpoch, existing.id]);
|
||||
await requestSessionRevocation(db, email, "cli-password");
|
||||
console.log(`Password updated: ${email}`);
|
||||
console.log(`Session revocation requested: the running panel will revoke browser sessions for ${email} within a few seconds.`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
let passwordHash = args.passwordHash ? String(args.passwordHash).trim() : "";
|
||||
if (passwordHash) {
|
||||
if (!/^\$2[aby]\$/.test(passwordHash)) {
|
||||
console.error("Password hash must be a bcrypt hash.");
|
||||
const hashError = bcryptHashInputError(passwordHash);
|
||||
if (hashError) {
|
||||
console.error(hashError);
|
||||
return 1;
|
||||
}
|
||||
} else {
|
||||
@@ -244,21 +469,50 @@ async function main() {
|
||||
console.error("Password is required.");
|
||||
return 1;
|
||||
}
|
||||
passwordHash = bcrypt.hashSync(rawPassword, 10);
|
||||
passwordHash = bcrypt.hashSync(rawPassword, BCRYPT_ROUNDS);
|
||||
}
|
||||
|
||||
const secret = args.secret
|
||||
? String(args.secret).trim()
|
||||
: speakeasy.generateSecret({ length: 20 }).base32;
|
||||
|
||||
// adpanel:totp-sealing-key-override — standalone mirror of index.js's boot
|
||||
// guard (requireStrongSecretOverride). This script seals with whatever
|
||||
// override the environment carries: a set-but-short (< 32 chars)
|
||||
// TOTP_SEALING_KEY would seal the seed under a key the panel refuses to
|
||||
// boot with, so the account's 2FA would fail closed until re-enrollment.
|
||||
// Fail here instead — before the seal and before any write.
|
||||
const totpSealingKeyOverride = process.env.TOTP_SEALING_KEY;
|
||||
if (totpSealingKeyOverride !== undefined && totpSealingKeyOverride !== "" && totpSealingKeyOverride.length < 32) {
|
||||
console.error("[config] TOTP_SEALING_KEY is set but too short. Set a random 32+ chars secret in env.TOTP_SEALING_KEY, or leave it unset to derive one from SESSION_SECRET.");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// M1: the seed is stored sealed (AES-256-GCM), matching the panel's own
|
||||
// write path. Sealing here fails hard rather than downgrading the row to
|
||||
// plaintext — the sealing key input is the TOTP_SEALING_KEY override when
|
||||
// set, else the SESSION_SECRET the panel runs with (both inputs are
|
||||
// strength-checked the same way: index.js exits at boot on a short
|
||||
// override, the guard above exits before this script writes anything).
|
||||
const sealedSecret = totpSecretCrypto.encryptTotpSecret(secret);
|
||||
if (!sealedSecret) {
|
||||
console.error("Could not seal the TOTP secret (sealing inputs are SESSION_SECRET, or the TOTP_SEALING_KEY override when set — unset or sealing failed); aborting so no plaintext seed is written.");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const RECOVERY_CODE_COUNT = 7;
|
||||
const RECOVERY_CODE_LENGTH = 8;
|
||||
const RECOVERY_CODE_CHARS = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
|
||||
|
||||
// Recovery codes are account credentials, so every character must come from
|
||||
// the OS CSPRNG. crypto.randomInt is rejection-sampled internally and stays
|
||||
// uniformly distributed over the alphabet even if its size ever stops being
|
||||
// a power of two — Math.random is a seeded PRNG and must never generate
|
||||
// secret material (CWE-338).
|
||||
function generateRecoveryCode() {
|
||||
let code = '';
|
||||
for (let i = 0; i < RECOVERY_CODE_LENGTH; i++) {
|
||||
code += RECOVERY_CODE_CHARS.charAt(Math.floor(Math.random() * RECOVERY_CODE_CHARS.length));
|
||||
code += RECOVERY_CODE_CHARS.charAt(crypto.randomInt(RECOVERY_CODE_CHARS.length));
|
||||
}
|
||||
return code;
|
||||
}
|
||||
@@ -268,11 +522,11 @@ async function main() {
|
||||
for (let i = 0; i < RECOVERY_CODE_COUNT; i++) {
|
||||
const code = generateRecoveryCode();
|
||||
plainRecoveryCodes.push(code);
|
||||
hashedRecoveryCodes.push(bcrypt.hashSync(code, 10));
|
||||
hashedRecoveryCodes.push(bcrypt.hashSync(code, BCRYPT_ROUNDS));
|
||||
}
|
||||
|
||||
const recoveryCodesJson = JSON.stringify(hashedRecoveryCodes);
|
||||
const explicitAvatarUrl = normalizeAvatarUrl(args.avatarUrl);
|
||||
const explicitAvatarUrl = preferBundledMediaUrl(normalizeAvatarUrl(args.avatarUrl));
|
||||
const desiredAvatarUrl = explicitAvatarUrl || pickDefaultAvatar(args.admin);
|
||||
const existingRows = await db.query(
|
||||
"SELECT id, avatar_url, admin FROM users WHERE LOWER(email) = LOWER(?) LIMIT 1",
|
||||
@@ -282,7 +536,7 @@ async function main() {
|
||||
|
||||
let avatarUrlToStore = desiredAvatarUrl;
|
||||
if (!explicitAvatarUrl && existingUser?.avatar_url) {
|
||||
const currentAvatar = String(existingUser.avatar_url).trim();
|
||||
const currentAvatar = preferBundledMediaUrl(String(existingUser.avatar_url).trim());
|
||||
if (currentAvatar && !MANAGED_AVATAR_URLS.has(currentAvatar)) {
|
||||
avatarUrlToStore = currentAvatar;
|
||||
} else if (args.admin) {
|
||||
@@ -294,17 +548,28 @@ async function main() {
|
||||
}
|
||||
}
|
||||
|
||||
// Fresh epoch on every create: a re-seeded existing account gets a new
|
||||
// discriminator, so its pre-mutation browser sessions stop authenticating.
|
||||
const sessionEpoch = newSessionEpoch();
|
||||
|
||||
try {
|
||||
await db.query(
|
||||
`INSERT INTO users (email, password, secret, admin, recovery_codes, avatar_url) VALUES (?, ?, ?, ?, ?, ?)
|
||||
ON DUPLICATE KEY UPDATE password = VALUES(password), secret = VALUES(secret), admin = VALUES(admin), recovery_codes = VALUES(recovery_codes), avatar_url = VALUES(avatar_url)`,
|
||||
[email, passwordHash, secret, args.admin ? 1 : 0, recoveryCodesJson, avatarUrlToStore]
|
||||
`INSERT INTO users (email, password, secret, admin, recovery_codes, avatar_url, session_epoch) VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
ON DUPLICATE KEY UPDATE password = VALUES(password), secret = VALUES(secret), admin = VALUES(admin), recovery_codes = VALUES(recovery_codes), avatar_url = VALUES(avatar_url), session_epoch = VALUES(session_epoch)`,
|
||||
[email, passwordHash, sealedSecret, args.admin ? 1 : 0, recoveryCodesJson, avatarUrlToStore, sessionEpoch]
|
||||
);
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
await requestSessionRevocation(
|
||||
db,
|
||||
email,
|
||||
existingUser ? "cli-create-existing" : "cli-create"
|
||||
);
|
||||
|
||||
console.log(`User created/updated: ${email}`);
|
||||
console.log(`Session revocation requested: the running panel will revoke browser sessions for ${email} within a few seconds.`);
|
||||
console.log(`2FA secret: ${secret}`);
|
||||
console.log(`Avatar URL: ${avatarUrlToStore}`);
|
||||
console.log('');
|
||||
|
||||
Reference in new issue
Block a user