Initial upload to Gitea

This commit is contained in:
antonn committed 2026-11-30 16:32:37 +00:00
1 parent 78193254ad
commit 8478998cae
1485 files changed
+461025 -42348

No files matched your search

+182
View File
@@ -0,0 +1,182 @@
"use strict";
// adpanel:admin-2fa-reset-preflight — ONE shared implementation of the admin
// 2FA reset pipeline. Express 4 cannot catch rejected handler promises: an
// `await` that is not lexically enclosed by a try-with-catch turns any
// transient rejection (DB hiccup, Redis timeout, session-store reset) into a
// request that is never answered — the process-level unhandledRejection
// handler only logs, and the client hangs. The ENTIRE awaited pipeline of
// this handler — admin gate, action-token gate, target/acting-admin lookups,
// self-reset refusal, destructive step-up, the secret-clearing write, the
// session/socket evictions, the audit entry and the response — sits inside
// ONE guard try whose catch logs its own bracketed marker and answers the
// headersSent-guarded 500 (ending an already-answered response exactly once
// instead of writing a second body). HARD CONTRACT: the exported handler
// NEVER REJECTS — this is what makes the thin expression-bodied arrow
// adapters in index.js safe under Express 4.
//
// Every capability arrives through the injected `deps` object (the
// dependency-injection pattern of services/server-create.js): this module
// must never require index.js. index.js constructs the service once next to
// the two route registrations and keeps only auth-adjacent wiring there.
// adpanel:credential-generation — the ONE shared session-epoch generator
// (one-way dependency: services -> utils). The secret-clearing write below
// bumps the epoch in the SAME statement as the credential.
const { resetAccountTwoFactor } = require("./account-credentials");
const { accountActionScope, requireAccountActionTarget } = require("./account-actions");
// adpanel:session-inventory-error-propagation — the ONE shared renderer for
// the response's sessionInvalidationWarnings: a degraded inventory scan
// (scanIncomplete) surfaces as a truthful warning even when it produced no
// per-session error strings. The note is true here: the epoch rode the
// secret-clearing write below, so any session the sweep missed fails the
// binding check on its next request.
const { renderSessionInvalidationWarnings } = require("../utils/session-invalidation-warnings");
// adpanel:admin-reset-target-pinning — the ONE stale-target wire string,
// byte-identical to the credential CAS 409 that index.js carries as exactly
// three inline literals (pinned by tests/credential-change-atomic-guard.test.js
// — this constant must never be re-inlined into index.js, which would add a
// fourth occurrence). index.js imports it, injects it back into this service
// for the reset flow and reuses it for the admin recovery-code reset route, so
// every admin reset surface answers a stale target with the same wire string.
const STALE_TARGET_409_MESSAGE = "Your credentials were just changed in another session or by an administrator. Re-verify and try again.";
// Shared implementation for POST /api/admin/user/reset-2fa (canonical) and
// POST /api/admin/user/confirm-2fa-reset (backward-compatibility alias for
// older clients). One implementation prevents the privileged flow from
// drifting between copies (the alias had already lost its audit trail once).
// The routes stay separately registered because action tokens are bound to
// the exact action string, so a token minted for one route must not
// authorize the other.
//
// Security model: the admin must NEVER learn the target user's TOTP seed,
// otherwise the admin could generate valid codes for that account and
// non-repudiation is broken. The old confirm-2fa-reset flow generated a TOTP
// seed on the admin's behalf and saved it here, which exposed the seed to the
// admin. Instead of generating a new secret on the admin's behalf, this
// handler clears the user's 2FA. The user re-enrolls their own authenticator
// from account settings after their next login.
function createAdminTwoFactorResetService(deps) {
const {
isAdmin,
requireActionTokenOr403,
findUserByEmail,
requireDestructiveActionStepUp,
db,
destroyBrowserSessionsForUser,
disconnectSocketsForUser,
recordActivity,
getRequestIp,
normalizeAdminTargetEmail,
stripLogControlChars,
// adpanel:admin-reset-target-pinning — injectable so a variant surface can
// reword the stale 409; the default keeps the ONE shared wire string.
staleTarget409Message = STALE_TARGET_409_MESSAGE,
logger = console,
} = deps || {};
// Fail closed: a miswired construction site must die at boot, not silently
// answer every request 500 (or worse, half-run the pipeline).
for (const [name, value] of [
["isAdmin", isAdmin],
["requireActionTokenOr403", requireActionTokenOr403],
["findUserByEmail", findUserByEmail],
["requireDestructiveActionStepUp", requireDestructiveActionStepUp],
["destroyBrowserSessionsForUser", destroyBrowserSessionsForUser],
["disconnectSocketsForUser", disconnectSocketsForUser],
["recordActivity", recordActivity],
["getRequestIp", getRequestIp],
["normalizeAdminTargetEmail", normalizeAdminTargetEmail],
["stripLogControlChars", stripLogControlChars],
]) {
if (typeof value !== "function") {
throw new Error(`[admin-2fa-reset] missing required dep: ${name}`);
}
}
if (!db || typeof db.query !== "function") {
throw new Error("[admin-2fa-reset] missing required dep: db.query");
}
async function handleAdmin2faReset(req, res, { action, proofLabel, logSuffix }) {
try {
if (!(await isAdmin(req))) {
return res.status(403).json({ error: "Admin access required" });
}
if (!await requireActionTokenOr403(req, res, action)) return;
const { email } = req.body || {};
const targetEmail = normalizeAdminTargetEmail(email);
if (!targetEmail) {
return res.status(400).json({ error: "invalid email" });
}
const targetEmailLower = targetEmail.toLowerCase();
const targetUser = await findUserByEmail(targetEmail);
if (!targetUser) {
return res.status(404).json({ error: "User not found" });
}
if (!requireAccountActionTarget(req, res, targetUser)) return;
if (targetUser.email.toLowerCase() === req.session.user.toLowerCase()) {
return res.status(400).json({ error: "Cannot reset your own 2FA through admin panel. Use account settings." });
}
// Step-up authentication: the acting admin must re-verify with their own
// password or 2FA before this destructive action is allowed. This mirrors
// the protection used by other destructive admin actions (maintenance,
// session revoke) and prevents abuse via a hijacked admin session.
const actingAdmin = req.currentUser || await findUserByEmail(req.session.user);
if (!actingAdmin || !actingAdmin.admin) {
return res.status(403).json({ error: "Admin access required" });
}
const stepUp = await requireDestructiveActionStepUp(req, res, actingAdmin, "Admin 2FA reset", { scopeKey: accountActionScope(targetUser), credentialFlow: "password-then-totp" });
if (!stepUp.ok) return;
// adpanel:account-actor-commit - the shared transaction pins both the
// admitted actor generation and the target ID before clearing 2FA.
if (!await resetAccountTwoFactor(db, targetUser, actingAdmin)) {
logger.log(`[SECURITY] Admin 2FA reset hit a stale target (row deleted/recreated between lookup and write) | Requested for: ${stripLogControlChars(targetUser.email)} by admin ${stripLogControlChars(req.session.user)} | IP: ${getRequestIp(req)}`);
return res.status(409).json({ error: staleTarget409Message });
}
logger.log(`[admin] 2FA cleared${logSuffix} for user ${stripLogControlChars(targetUser.email)} by admin ${stripLogControlChars(req.session.user)} | IP: ${getRequestIp(req)}`);
// Evict the target's sessions and remember-me tokens: clearing 2FA is a
// remediation action, so a stolen session must not outlive it. The acting
// admin's own session is never the target (self-reset is rejected above).
const sessionInvalidation = await destroyBrowserSessionsForUser(targetUser);
const socketsDisconnected = disconnectSocketsForUser(targetUser.email, "2fa-reset-by-admin", { accountId: targetUser.id });
logger.log(`[SECURITY] Admin 2FA reset evictions | Target: ${stripLogControlChars(targetUser.email)} | Sessions destroyed: ${sessionInvalidation.destroyed} | Sockets disconnected: ${socketsDisconnected}`);
try {
recordActivity("_system", "admin_reset_2fa", `Reset (cleared) 2FA for ${targetUser.email}`, req.session.user, getRequestIp(req));
} catch (_) { }
return res.json({
ok: true,
email: targetUser.email,
cleared: true,
sessionsDestroyed: sessionInvalidation.destroyed,
socketsDisconnected,
rememberLoginsRevoked: sessionInvalidation.rememberLoginsRevoked,
sessionInvalidationWarnings: renderSessionInvalidationWarnings(sessionInvalidation),
message: "2FA has been reset. The user must set up 2FA again from their account settings.",
});
} catch (err) {
// adpanel:admin-2fa-reset-preflight — the whole awaited pipeline is
// lexically inside the guard try above, so a rejection lands here
// instead of escaping into the Express-4 void. A gate that already
// answered (403 action-token/step-up challenge) must not be written
// again: end that response exactly once, never a second body.
logger.error("[admin-2fa-reset] pre-flight failed:", err);
if (!res.headersSent) return res.status(500).json({ error: "internal error" });
res.end();
}
}
return { handleAdmin2faReset };
}
module.exports = { createAdminTwoFactorResetService, STALE_TARGET_409_MESSAGE };