689 lines
31 KiB
JavaScript
689 lines
31 KiB
JavaScript
"use strict";
|
|
|
|
const express = require("express");
|
|
const multer = require("multer");
|
|
const {
|
|
createDashboardAssistantService,
|
|
ASSISTANT_DELETE_CONFIRM_ACTION,
|
|
ASSISTANT_USER_MESSAGE_MAX_CHARS,
|
|
ASSISTANT_FOLLOWUP_SUMMARY_MAX_CHARS,
|
|
} = require("../utils/dashboard-assistant-service");
|
|
// Shared cross-site read guard (same implementation the panel's file routes
|
|
// and the nodes.js relays mount): /bootstrap is a session-facing read that
|
|
// embeds action tokens, so it rejects exactly what they reject.
|
|
const { rejectCrossSiteRead } = require("../utils/cross-site-read-guard");
|
|
|
|
const AUDIO_UPLOAD_LIMIT_BYTES = parseInt(process.env.DASHBOARD_ASSISTANT_AUDIO_LIMIT_BYTES || "", 10) || 15 * 1024 * 1024;
|
|
const DELETE_INTENT_ID_PATTERN = /^[a-f0-9]{32}$/;
|
|
// Re-mint budget for the confirm-delete step-up failure courtesy (see the
|
|
// /confirm-delete handler): 5-minute window, aligned in spirit with the
|
|
// delete-intent limiter (5 min / 10 mints), but capped lower — the courtesy
|
|
// must never outgrow the metered /delete-intent entrance.
|
|
const DELETE_INTENT_REMINT_WINDOW_MS = 5 * 60 * 1000;
|
|
const DELETE_INTENT_REMINT_MAX_PER_WINDOW = 5;
|
|
// Client-caused multer rejections for the /transcribe audio upload, mapped to
|
|
// their user-facing messages. Every code below is scriptable from a plain
|
|
// multipart body (wrong or missing field names, extra files/fields/parts,
|
|
// oversized field keys/values), so each is answered 400 WITHOUT console.error — logging them
|
|
// would read like a system fault and falsify error monitoring. Messages never
|
|
// reflect error.field/error.filename (attacker-controlled strings); they name
|
|
// at most the server's own "audio" field. Codes verified against the
|
|
// installed multer (node_modules/multer/lib/multer-error.js): the 2.x-only
|
|
// LIMIT_FIELD_NESTING / LIMIT_FIELD_ARRAY_INDEX are unreachable here because
|
|
// this route's limits config never sets fieldNestingDepth/fieldArrayIndexLimit.
|
|
// Anything unmapped — multer internals, storage-engine faults, non-multer
|
|
// errors — keeps the handler's 500 plus its server-side fault log.
|
|
const AUDIO_UPLOAD_CLIENT_ERROR_MESSAGES = {
|
|
LIMIT_AUDIO_TYPE: "Only audio uploads are supported.",
|
|
LIMIT_FILE_SIZE: "The recording is too large.",
|
|
LIMIT_UNEXPECTED_FILE: "Unexpected upload field. Send one file in the 'audio' field.",
|
|
LIMIT_FILE_COUNT: "Too many files. Send one audio file in the 'audio' field.",
|
|
LIMIT_FIELD_COUNT: "Too many form fields.",
|
|
LIMIT_PART_COUNT: "Too many form parts.",
|
|
LIMIT_FIELD_KEY: "A form field name is too long.",
|
|
LIMIT_FIELD_VALUE: "A form field value is too long.",
|
|
// A multipart part with no `name` parameter (busboy emits fieldname null)
|
|
// aborts the upload with this code (make-middleware's fieldname == null).
|
|
MISSING_FIELD_NAME: "A form field name is missing.",
|
|
};
|
|
|
|
function inferStatusCode(error) {
|
|
const message = String(error?.message || "").toLowerCase();
|
|
if (message.includes("not authenticated")) return 401;
|
|
if (message.includes("admin required") || message.includes("permission") || message.includes("access disabled")) return 403;
|
|
// Provider quota/rate-limit text and the curated tool-loop guards are
|
|
// legitimate, user-actionable conditions: their exact message is the only
|
|
// feedback the chat client shows, so they must not fall through to 500.
|
|
if (message.includes("rate limit") || message.includes("too many requests") || message.includes("quota")) return 429;
|
|
if (
|
|
message.includes("not configured") ||
|
|
message.includes("tool limit") ||
|
|
message.includes("returned an empty response") ||
|
|
// Curated, secret-free configuration error from the provider-key crypto
|
|
// ("neither encryption secret is set"). Falling to 500 would hide the
|
|
// operator guidance behind the generic fallback, and /token is
|
|
// admin-gated, so the message is safe to show as-is.
|
|
message.includes("encryption secret is unavailable") ||
|
|
// The fail-closed legacy guard's curated error: the stored provider key
|
|
// still wears the legacy enc-v1 envelope while its automatic re-encryption
|
|
// is pending. The message is secret-free and admin-actionable (re-save the
|
|
// key, or restore .env write access). Admin-gated by default; when
|
|
// allowNormalUsers is enabled, a normal user's chat can also surface it —
|
|
// the same precedent as the existing "not configured" and "encryption
|
|
// secret is unavailable" members of this curated 503 group — so it joins
|
|
// them instead of the 500 fallback: the condition is operator-fixable,
|
|
// not an internal fault, and the message stays secret-free either way.
|
|
message.includes("legacy encryption envelope")
|
|
) {
|
|
return 503;
|
|
}
|
|
if (message.includes("not found") || message.includes("could not be found")) return 404;
|
|
// Magic-byte sniffing rejects transcription uploads whose bytes match no
|
|
// recognized audio container: a client-actionable rejection (generic
|
|
// message, no provider call, no billing), not a system fault.
|
|
if (message.includes("audio format is not supported")) return 415;
|
|
if (
|
|
message.includes("required") ||
|
|
message.includes("valid") ||
|
|
message.includes("too large") ||
|
|
// Chat input length caps (service-side defense in depth) are legitimate
|
|
// user-actionable rejections, not faults.
|
|
message.includes("too long") ||
|
|
message.includes("could not be transcribed") ||
|
|
message.includes("no audio")
|
|
) {
|
|
return 400;
|
|
}
|
|
return 500;
|
|
}
|
|
|
|
// Assistant/provider errors are deliberately user-facing: inferStatusCode
|
|
// recognizes them by their curated message text and the chat client renders
|
|
// them as-is. Everything the classifier falls back to 500 for is an
|
|
// unexpected system fault whose raw message can disclose internal topology
|
|
// (e.g. "connect ECONNREFUSED 10.0.0.12:3306") — log it server-side and send
|
|
// only the route's generic fallback message to the user.
|
|
function respondWithError(res, error, fallbackMessage) {
|
|
const statusCode = inferStatusCode(error);
|
|
if (statusCode === 500) {
|
|
console.error("[dashboard-assistant] unexpected failure:", error);
|
|
return res.status(500).json({ error: fallbackMessage || "Internal error. Please try again later." });
|
|
}
|
|
return res.status(statusCode).json({ error: error?.message || fallbackMessage });
|
|
}
|
|
|
|
module.exports = function createDashboardAssistantRouter(deps) {
|
|
if (!deps || typeof deps !== "object") {
|
|
throw new Error("Dashboard assistant router dependencies are required.");
|
|
}
|
|
|
|
const router = express.Router();
|
|
// Accept only audio/* uploads (the voice client records audio/wav,
|
|
// audio/webm and audio/mp4 — parameterized types included, the prefix
|
|
// check covers "audio/webm;codecs=opus" and friends). Rejected parts are
|
|
// never buffered into memoryStorage.
|
|
function acceptAudioUploadsOnly(req, file, callback) {
|
|
const mimeType = String(file?.mimetype || "").trim().toLowerCase();
|
|
if (mimeType.startsWith("audio/")) {
|
|
return callback(null, true);
|
|
}
|
|
const error = new Error("Only audio uploads are supported.");
|
|
error.code = "LIMIT_AUDIO_TYPE";
|
|
return callback(error);
|
|
}
|
|
|
|
const upload = multer({
|
|
storage: multer.memoryStorage(),
|
|
fileFilter: acceptAudioUploadsOnly,
|
|
limits: {
|
|
fileSize: AUDIO_UPLOAD_LIMIT_BYTES,
|
|
files: 1,
|
|
fields: 10,
|
|
parts: 12,
|
|
},
|
|
});
|
|
const service = createDashboardAssistantService(deps);
|
|
|
|
async function requireAuth(req, res) {
|
|
if (!(await deps.isAuthenticated(req))) {
|
|
res.status(401).json({ error: "not authenticated" });
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
async function requireAssistantAccess(req, res) {
|
|
if (!(await requireAuth(req, res))) return false;
|
|
if (await deps.isAdmin(req)) return true;
|
|
|
|
const allowNormalUsers = typeof deps.isDashboardAssistantEnabledForNormalUsers === "function"
|
|
? !!(await deps.isDashboardAssistantEnabledForNormalUsers())
|
|
: false;
|
|
if (!allowNormalUsers) {
|
|
res.status(403).json({ error: "assistant access disabled" });
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
async function requireAssistantAdmin(req, res) {
|
|
if (!(await requireAssistantAccess(req, res))) return false;
|
|
if (!(await deps.isAdmin(req))) {
|
|
res.status(403).json({ error: "admin required" });
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
// Mounted ahead of the handler's auth check (matching /models and
|
|
// /transcribe) so an authenticated flood is counted and rejected before
|
|
// the bootstrap's first DB query; unauthenticated requests skip the
|
|
// limiter and are rejected by requireAssistantAccess below.
|
|
// Cross-site read guard runs ahead of the limiter: requests the guard
|
|
// rejects (cross-site, or cookie-bearing with no initiator evidence) are
|
|
// answered 403 without consuming limiter budget. The guard targets
|
|
// /bootstrap specifically because the admin bootstrap embeds action
|
|
// tokens — a hostile page must not be able to drive repeated mints through
|
|
// the victim's browser (same rationale as /api/servers/:name/permissions).
|
|
router.get("/bootstrap",
|
|
rejectCrossSiteRead,
|
|
typeof deps.dashboardAssistantBootstrapRateLimiter === "function"
|
|
? deps.dashboardAssistantBootstrapRateLimiter
|
|
: (req, res, next) => next(),
|
|
async (req, res) => {
|
|
try {
|
|
if (!(await requireAssistantAccess(req, res))) return;
|
|
// Admin bootstrap embeds action tokens for token/access management.
|
|
res.set("Cache-Control", "no-store");
|
|
const state = await service.getBootstrap(req);
|
|
return res.json({ ok: true, ...state });
|
|
} catch (error) {
|
|
console.error("[dashboard-assistant] bootstrap failed:", error);
|
|
return res.status(500).json({ error: "failed to load assistant" });
|
|
}
|
|
});
|
|
|
|
router.get("/models",
|
|
typeof deps.dashboardAssistantModelsRateLimiter === "function"
|
|
? deps.dashboardAssistantModelsRateLimiter
|
|
: (req, res, next) => next(),
|
|
async (req, res) => {
|
|
try {
|
|
if (!(await requireAssistantAccess(req, res))) return;
|
|
const provider = String(req.query.provider || "groq").toLowerCase();
|
|
const models = await service.getModelsForProvider({ provider });
|
|
return res.json({ ok: true, models: models || [] });
|
|
} catch (error) {
|
|
console.error("[dashboard-assistant] fetch models failed:", error);
|
|
return res.status(500).json({ error: "failed to fetch models" });
|
|
}
|
|
});
|
|
|
|
router.post("/token",
|
|
typeof deps.dashboardAssistantTokenRateLimiter === "function"
|
|
? deps.dashboardAssistantTokenRateLimiter
|
|
: (req, res, next) => next(),
|
|
async (req, res) => {
|
|
try {
|
|
if (!(await requireAssistantAdmin(req, res))) return;
|
|
if (typeof deps.requireActionTokenOr403 === "function") {
|
|
const ok = await deps.requireActionTokenOr403(req, res, "POST /api/dashboard-assistant/token");
|
|
if (!ok) return;
|
|
}
|
|
|
|
const { provider, token } = req.body || {};
|
|
const saved = await service.saveProviderToken({ provider, token });
|
|
return res.json({ ok: true, provider: saved });
|
|
} catch (error) {
|
|
return respondWithError(res, error, "failed to save provider token");
|
|
}
|
|
});
|
|
|
|
router.post("/access",
|
|
typeof deps.dashboardAssistantAccessRateLimiter === "function"
|
|
? deps.dashboardAssistantAccessRateLimiter
|
|
: (req, res, next) => next(),
|
|
async (req, res) => {
|
|
try {
|
|
if (!(await requireAssistantAdmin(req, res))) return;
|
|
if (!req.is("application/json")) {
|
|
return res.status(415).json({ error: "JSON body required" });
|
|
}
|
|
// Fail closed on the access flag: a JSON string "false" is truthy, so
|
|
// the previous !! coercion turned a "disable normal users" request into
|
|
// an enable — coercion errored toward over-permission. Only a real
|
|
// boolean is accepted (the admin client sends JSON.stringify of a
|
|
// boolean); anything else is a client bug, not something to guess.
|
|
// Checked before the action-token gate so a malformed body never burns
|
|
// the single-use nonce (same ordering principle as /confirm-delete).
|
|
if (typeof req.body?.allowNormalUsers !== "boolean") {
|
|
return res.status(400).json({ error: "allowNormalUsers must be a boolean" });
|
|
}
|
|
if (typeof deps.requireActionTokenOr403 === "function") {
|
|
const ok = await deps.requireActionTokenOr403(req, res, "POST /api/dashboard-assistant/access");
|
|
if (!ok) return;
|
|
}
|
|
|
|
const currentUser = await deps.findUserByEmail(String(req.session?.user || "").trim().toLowerCase());
|
|
|
|
// Cross-process save lock: everything below is a config read-modify-write
|
|
// (load → spread → save), and two pm2 cluster workers running it
|
|
// concurrently would each start from their own snapshot — the last
|
|
// rename silently reverts the other's toggle (a revoked allowNormalUsers
|
|
// re-enabled). Fail-fast tryAcquire, matching the other config mutexes:
|
|
// concurrent admins get a retriable 429 instead of a lost update. The
|
|
// critical section is fully synchronous (acquired after the awaited auth
|
|
// and user lookups), so no heartbeat dependence and no steal window.
|
|
// Optional dep: when the mutex is absent (tests, minimal wiring) the
|
|
// handler still saves unlocked — the readback verification inside
|
|
// saveDashboardAssistantConfig already prevents the stale-pin failure
|
|
// mode; only the lost-update race remains possible.
|
|
const accessMutex = deps.dashboardAssistantConfigMutex && typeof deps.dashboardAssistantConfigMutex.tryAcquire === "function"
|
|
? deps.dashboardAssistantConfigMutex
|
|
: null;
|
|
const releaseAccessLock = accessMutex ? accessMutex.tryAcquire() : null;
|
|
if (accessMutex && !releaseAccessLock) {
|
|
return res.status(429).json({ error: "Another assistant access update is in progress. Please wait." });
|
|
}
|
|
try {
|
|
const currentConfig = typeof deps.getDashboardAssistantConfig === "function"
|
|
? deps.getDashboardAssistantConfig()
|
|
: { allowNormalUsers: false };
|
|
const nextConfig = {
|
|
...currentConfig,
|
|
allowNormalUsers: !!req.body?.allowNormalUsers,
|
|
updatedAt: new Date().toISOString(),
|
|
updatedBy: currentUser?.email || String(req.session?.user || "").trim().toLowerCase() || null,
|
|
};
|
|
|
|
if (typeof deps.saveDashboardAssistantConfig !== "function" || !deps.saveDashboardAssistantConfig(nextConfig)) {
|
|
return res.status(500).json({ error: "failed to save assistant access" });
|
|
}
|
|
|
|
return res.json({ ok: true, allowNormalUsers: nextConfig.allowNormalUsers });
|
|
} finally {
|
|
if (releaseAccessLock) releaseAccessLock();
|
|
}
|
|
} catch (error) {
|
|
return respondWithError(res, error, "failed to save assistant access");
|
|
}
|
|
});
|
|
|
|
router.post("/reset",
|
|
typeof deps.dashboardAssistantResetRateLimiter === "function"
|
|
? deps.dashboardAssistantResetRateLimiter
|
|
: (req, res, next) => next(),
|
|
async (req, res) => {
|
|
try {
|
|
if (!(await requireAssistantAccess(req, res))) return;
|
|
const userEmail = String(req.session?.user || "").trim().toLowerCase();
|
|
// resetChat (not createFreshChat): repeated resets must not insert a
|
|
// new chat row per call — empty chats are reused/pruned, chats with
|
|
// real history are kept.
|
|
const chat = await service.resetChat(userEmail, req.currentUser?.id || req.session?.accountId);
|
|
return res.json({ ok: true, chat, messages: [] });
|
|
} catch (error) {
|
|
console.error("[dashboard-assistant] reset failed:", error);
|
|
return res.status(500).json({ error: "failed to reset assistant chat" });
|
|
}
|
|
});
|
|
|
|
// Auth gates BEFORE multer: the session check reads no multipart fields,
|
|
// so authenticating first keeps unauthenticated requests from buffering
|
|
// upload bytes into memoryStorage. Multer just runs after the gate now;
|
|
// its client-error classification is the map above.
|
|
router.post("/transcribe",
|
|
typeof deps.dashboardAssistantTranscribeRateLimiter === "function"
|
|
? deps.dashboardAssistantTranscribeRateLimiter
|
|
: (req, res, next) => next(),
|
|
async (req, res, next) => {
|
|
try {
|
|
if (!(await requireAssistantAccess(req, res))) return;
|
|
next();
|
|
} catch (error) {
|
|
return respondWithError(res, error, "Transcription failed.");
|
|
}
|
|
},
|
|
// In-flight concurrency gate: AFTER the auth gate (it keys on the session
|
|
// identity the gate above guarantees) and BEFORE multer (a rejected request
|
|
// must not buffer 15 MB of audio into memoryStorage first).
|
|
typeof deps.dashboardAssistantTranscribeConcurrencyGate === "function"
|
|
? deps.dashboardAssistantTranscribeConcurrencyGate
|
|
: (req, res, next) => next(),
|
|
(req, res, next) => {
|
|
upload.single("audio")(req, res, (error) => {
|
|
if (error) {
|
|
// Known client-caused multer rejections are answered 400 with the
|
|
// mapped message and never logged server-side (see the map above):
|
|
// they are attacker-scriptable, not faults. The typeof guard keeps
|
|
// prototype-chain lookups ("constructor", "toString") out of the 400
|
|
// branch, so they fall through to the genuine-fault path below.
|
|
const clientMessage = AUDIO_UPLOAD_CLIENT_ERROR_MESSAGES[error.code];
|
|
if (typeof clientMessage === "string") {
|
|
return res.status(400).json({ error: clientMessage });
|
|
}
|
|
// Unexpected multer/storage fault: never reflected, but log it
|
|
// server-side — this is the real system-fault signal.
|
|
console.error("[dashboard-assistant] audio upload failed:", error);
|
|
return res.status(500).json({ error: "Audio upload failed." });
|
|
}
|
|
next();
|
|
});
|
|
}, async (req, res) => {
|
|
try {
|
|
if (!req.file?.buffer) {
|
|
return res.status(400).json({ error: "No audio was uploaded." });
|
|
}
|
|
|
|
const transcript = await service.transcribeAudio({
|
|
buffer: req.file.buffer,
|
|
mimeType: req.file.mimetype,
|
|
filename: req.file.originalname,
|
|
language: req.body?.language,
|
|
prompt: req.body?.prompt,
|
|
});
|
|
|
|
return res.json({ ok: true, ...transcript });
|
|
} catch (error) {
|
|
return respondWithError(res, error, "Transcription failed.");
|
|
}
|
|
});
|
|
|
|
router.post("/chat",
|
|
typeof deps.dashboardAssistantCompletionRateLimiter === "function"
|
|
? deps.dashboardAssistantCompletionRateLimiter
|
|
: (req, res, next) => next(),
|
|
async (req, res) => {
|
|
try {
|
|
if (!(await requireAssistantAccess(req, res))) return;
|
|
|
|
const userEmail = String(req.session?.user || "").trim().toLowerCase();
|
|
// Fast reject before the service: measure exactly the text the service
|
|
// will store (String + trim), mirroring ASSISTANT_USER_MESSAGE_MAX_CHARS.
|
|
const chatMessage = String(req.body?.message || "").trim();
|
|
if (chatMessage.length > ASSISTANT_USER_MESSAGE_MAX_CHARS) {
|
|
return res.status(400).json({ error: `Your message is too long (max ${ASSISTANT_USER_MESSAGE_MAX_CHARS} characters).` });
|
|
}
|
|
const result = await service.completeChat({
|
|
userEmail,
|
|
userId: req.currentUser?.id || req.session?.accountId,
|
|
chatId: req.body?.chatId,
|
|
userMessage: chatMessage,
|
|
// Client-owned pick: the service validates and allowlists it against
|
|
// the provider's live model list before any provider call.
|
|
requestedModel: req.body?.model,
|
|
userIp: req.ip || req.connection?.remoteAddress || "unknown",
|
|
});
|
|
|
|
return res.json({ ok: true, ...result });
|
|
} catch (error) {
|
|
return respondWithError(res, error, "Assistant request failed.");
|
|
}
|
|
});
|
|
|
|
router.post("/client-follow-up",
|
|
typeof deps.dashboardAssistantCompletionRateLimiter === "function"
|
|
? deps.dashboardAssistantCompletionRateLimiter
|
|
: (req, res, next) => next(),
|
|
async (req, res) => {
|
|
try {
|
|
if (!(await requireAssistantAccess(req, res))) return;
|
|
|
|
const userEmail = String(req.session?.user || "").trim().toLowerCase();
|
|
// Fast reject before the service: measure exactly the text the service
|
|
// will persist, mirroring ASSISTANT_FOLLOWUP_SUMMARY_MAX_CHARS.
|
|
const followUpSummary = String(req.body?.summary || "").trim();
|
|
if (followUpSummary.length > ASSISTANT_FOLLOWUP_SUMMARY_MAX_CHARS) {
|
|
return res.status(400).json({ error: `Your follow-up summary is too long (max ${ASSISTANT_FOLLOWUP_SUMMARY_MAX_CHARS} characters).` });
|
|
}
|
|
const result = await service.completeClientFollowUp({
|
|
userEmail,
|
|
userId: req.currentUser?.id || req.session?.accountId,
|
|
chatId: req.body?.chatId,
|
|
summary: followUpSummary,
|
|
sourceType: req.body?.sourceType,
|
|
context: req.body?.context,
|
|
// Same client-owned pick as /chat; validated by the service.
|
|
requestedModel: req.body?.model,
|
|
skipAi: !!req.body?.skipAi,
|
|
});
|
|
|
|
return res.json({ ok: true, ...result });
|
|
} catch (error) {
|
|
return respondWithError(res, error, "Assistant follow-up failed.");
|
|
}
|
|
});
|
|
|
|
// Pending delete intent mint. This endpoint creates the server-side intent
|
|
// state the confirm endpoint demands: an admin-validated, chat-bound,
|
|
// canonical-server-bound record in the admin's session plus a matching
|
|
// short-TTL single-use action token. Minting carries no capability by
|
|
// itself — the confirm endpoint still requires the token, the live intent
|
|
// and the destructive-action credential step-up.
|
|
router.post("/delete-intent",
|
|
typeof deps.dashboardAssistantDeleteIntentRateLimiter === "function"
|
|
? deps.dashboardAssistantDeleteIntentRateLimiter
|
|
: (req, res, next) => next(),
|
|
async (req, res) => {
|
|
try {
|
|
if (!(await requireAssistantAdmin(req, res))) return;
|
|
if (!req.is("application/json")) {
|
|
return res.status(415).json({ error: "JSON body required" });
|
|
}
|
|
res.set("Cache-Control", "no-store");
|
|
|
|
const userEmail = String(req.session?.user || "").trim().toLowerCase();
|
|
const intent = await service.createDeleteIntent({
|
|
req,
|
|
userEmail,
|
|
chatId: req.body?.chatId,
|
|
serverName: req.body?.server,
|
|
});
|
|
return res.json({ ok: true, intent });
|
|
} catch (error) {
|
|
return respondWithError(res, error, "Failed to prepare the delete request.");
|
|
}
|
|
});
|
|
|
|
// Session-scoped re-mint budget backing the confirm-delete step-up failure
|
|
// courtesy. The counter is two numbers in the session blob — never
|
|
// per-mint keys — so Redis store pressure stays bounded. The window resets
|
|
// lazily on first use after expiry; an absent or malformed field simply
|
|
// starts a fresh window.
|
|
function deleteIntentRemintBudgetAvailable(req) {
|
|
const state = req.session.assistantDeleteIntentRemints;
|
|
if (!state || typeof state !== "object"
|
|
|| typeof state.count !== "number"
|
|
|| typeof state.windowStart !== "number") {
|
|
req.session.assistantDeleteIntentRemints = { count: 0, windowStart: Date.now() };
|
|
return true;
|
|
}
|
|
if (Date.now() - state.windowStart >= DELETE_INTENT_REMINT_WINDOW_MS) {
|
|
state.count = 0;
|
|
state.windowStart = Date.now();
|
|
return true;
|
|
}
|
|
return state.count < DELETE_INTENT_REMINT_MAX_PER_WINDOW;
|
|
}
|
|
|
|
// Consumes budget only after a successful mint: a failed mint (throw or
|
|
// falsy result) must not spend the courtesy.
|
|
function recordDeleteIntentRemint(req) {
|
|
const state = req.session.assistantDeleteIntentRemints;
|
|
if (state && typeof state === "object" && typeof state.count === "number") {
|
|
state.count += 1;
|
|
}
|
|
}
|
|
|
|
// Assistant-driven server delete — gated identically to
|
|
// DELETE /api/settings/servers/:name:
|
|
// 1. always-on confirm-loop budget (counts every confirm attempt, with
|
|
// or without credentials) + shared step-up credential limiter
|
|
// (bounds password/2FA guessing on the credential-bearing ones),
|
|
// 2. admin + JSON-only + no-store,
|
|
// 3. the pending intent from the admin's session (server-side state —
|
|
// there is no standing "delete anything" capability),
|
|
// 4. the intent's single-use, session-, action- and resource-bound action
|
|
// token (CSRF-hardening: unforgeable, untransferable, replay-proof),
|
|
// 5. the destructive-action step-up: fresh password/2FA or a grant scoped
|
|
// to server:<name>, with failureResponseExtras re-minting a fresh
|
|
// intent so a mistyped credential does not force re-asking the
|
|
// assistant,
|
|
// 6. full audit parity (per-server + _system records, deletedBy, step-up
|
|
// method, trusted-proxy IP).
|
|
router.post("/confirm-delete",
|
|
typeof deps.dashboardAssistantConfirmDeleteRateLimiter === "function"
|
|
? deps.dashboardAssistantConfirmDeleteRateLimiter
|
|
: (req, res, next) => next(),
|
|
typeof deps.sessionRevoke2faRateLimiter === "function"
|
|
? deps.sessionRevoke2faRateLimiter
|
|
: (req, res, next) => next(),
|
|
async (req, res) => {
|
|
try {
|
|
if (!(await requireAssistantAdmin(req, res))) return;
|
|
if (!req.is("application/json")) {
|
|
return res.status(415).json({ error: "JSON body required" });
|
|
}
|
|
res.set("Cache-Control", "no-store");
|
|
|
|
const userEmail = String(req.session?.user || "").trim().toLowerCase();
|
|
const intentId = String(req.body?.intentId || "").trim();
|
|
const requestedServer = String(req.body?.server || "").trim();
|
|
const requestedChatId = req.body?.chatId;
|
|
|
|
if (!DELETE_INTENT_ID_PATTERN.test(intentId)) {
|
|
return res.status(403).json({
|
|
error: "This delete request is no longer pending. Ask the assistant to delete the server again.",
|
|
code: "intent-invalid",
|
|
});
|
|
}
|
|
if (!requestedServer) {
|
|
return res.status(400).json({ error: "A server name is required." });
|
|
}
|
|
|
|
// The session's pending intent is the authority for what this confirm
|
|
// may target. Validate the request against it BEFORE burning the
|
|
// single-use artifacts, so a stale or mismatched body costs neither
|
|
// the token nonce nor a grace use.
|
|
const store = req.session.assistantDeleteIntents && typeof req.session.assistantDeleteIntents === "object"
|
|
? req.session.assistantDeleteIntents
|
|
: null;
|
|
const pendingIntent = (store && store[intentId]) || null;
|
|
if (!pendingIntent || Number(pendingIntent.expiresAt || 0) <= Date.now()) {
|
|
if (store) delete store[intentId];
|
|
return res.status(403).json({
|
|
error: "This delete request is no longer pending. Ask the assistant to delete the server again.",
|
|
code: "intent-invalid",
|
|
});
|
|
}
|
|
if (requestedServer !== String(pendingIntent.serverName || "")) {
|
|
return res.status(400).json({
|
|
error: "This confirmation does not match the requested server.",
|
|
code: "intent-mismatch",
|
|
});
|
|
}
|
|
if (Number(pendingIntent.chatId) !== Number(requestedChatId)) {
|
|
return res.status(400).json({
|
|
error: "This confirmation does not match the requesting chat.",
|
|
code: "intent-mismatch",
|
|
});
|
|
}
|
|
|
|
// One-time token minted only by delete-intent for this exact
|
|
// intent/chat/server triple. Consumed on first verification (nonce
|
|
// burn) regardless of the outcome below — fail closed. The verifier
|
|
// is a hard dep: a missing gate must abort the delete, never skip it.
|
|
if (typeof deps.requireActionTokenOr403 !== "function") {
|
|
throw new Error("The delete action-token gate is not available.");
|
|
}
|
|
const tokenOk = await deps.requireActionTokenOr403(req, res, ASSISTANT_DELETE_CONFIRM_ACTION, {
|
|
intentId,
|
|
chatId: pendingIntent.chatId,
|
|
serverName: pendingIntent.serverName,
|
|
});
|
|
if (!tokenOk) return;
|
|
|
|
// Consume the pending intent: exactly one confirm attempt per mint.
|
|
delete store[intentId];
|
|
|
|
const currentUser = await deps.findUserByEmail(userEmail);
|
|
if (!(currentUser && currentUser.admin)) {
|
|
return res.status(403).json({ error: "admin required" });
|
|
}
|
|
|
|
// Same credential step-up as DELETE /api/settings/servers/:name: a
|
|
// fresh password/2FA proof, or a grant scoped to server:<name>.
|
|
// failureResponseExtras re-mints a fresh pending intent so a mistyped
|
|
// credential does not force re-asking the assistant. That re-mint is
|
|
// a UX courtesy, not a second minting entrance: the credential-bearing
|
|
// limiter mounted on this route counts only requests carrying a
|
|
// password/2FA payload, so without a budget a hijacked session could
|
|
// loop confirm attempts and churn crypto.randomBytes intents plus
|
|
// one-time token nonces into the shared Redis session store
|
|
// unmetered. deleteIntentRemintBudgetAvailable caps the courtesy at a
|
|
// per-session window budget (consumed only by successful mints), the
|
|
// rate-limited /delete-intent endpoint remains the metered main mint
|
|
// path, and the step-up below still gates the destructive action.
|
|
// Hard dep: a missing step-up must abort the delete, never skip it.
|
|
if (typeof deps.requireDestructiveActionStepUp !== "function") {
|
|
throw new Error("The destructive-action step-up gate is not available.");
|
|
}
|
|
const stepUp = await deps.requireDestructiveActionStepUp(
|
|
req,
|
|
res,
|
|
currentUser,
|
|
`Assistant server delete "${pendingIntent.serverName}"`,
|
|
{
|
|
scopeKey: `server:${pendingIntent.serverName}`,
|
|
failureResponseExtras: () => {
|
|
try {
|
|
// Over budget: no mint — the 403 still carries its error and
|
|
// the admin re-asks via /delete-intent (the metered path).
|
|
if (!deleteIntentRemintBudgetAvailable(req)) return {};
|
|
const minted = service.mintDeleteIntent({
|
|
req,
|
|
chatId: pendingIntent.chatId,
|
|
serverName: pendingIntent.serverName,
|
|
displayName: pendingIntent.displayName,
|
|
});
|
|
if (!minted) return {};
|
|
recordDeleteIntentRemint(req);
|
|
return { intent: minted };
|
|
} catch {
|
|
return {};
|
|
}
|
|
},
|
|
}
|
|
);
|
|
if (!stepUp.ok) return;
|
|
|
|
const userIp = typeof deps.getRequestIp === "function"
|
|
? deps.getRequestIp(req)
|
|
: (req.ip || req.connection?.remoteAddress || "unknown");
|
|
const result = await service.confirmDeleteServer({
|
|
userEmail,
|
|
userId: req.currentUser?.id || req.session?.accountId,
|
|
chatId: pendingIntent.chatId,
|
|
serverName: pendingIntent.serverName,
|
|
userIp,
|
|
authMethod: stepUp.usedFreshVerification ? "fresh-credential" : "grace-grant",
|
|
});
|
|
|
|
const graceState = typeof deps.getVerifiedSessionRevokeGraceState === "function"
|
|
? await deps.getVerifiedSessionRevokeGraceState(req, currentUser)
|
|
: null;
|
|
const graceExpiresAt = stepUp.graceExpiresAt || graceState?.expiresAt || 0;
|
|
|
|
return res.status(result.deleting ? 202 : 200).json({
|
|
ok: true,
|
|
...result,
|
|
graceExpiresAt,
|
|
});
|
|
} catch (error) {
|
|
return respondWithError(res, error, "Server deletion failed.");
|
|
}
|
|
});
|
|
|
|
return router;
|
|
};
|