Initial upload to Gitea
This commit is contained in:
1 parent
78193254ad
commit
8478998cae
1485 files changed
+461025
-42348
No files matched your search
@@ -0,0 +1,146 @@
|
||||
"use strict";
|
||||
|
||||
const { Router } = require("express");
|
||||
const { AgentRpcError } = require("../AgentWorker/private-rpc");
|
||||
const { LIVE_SOURCE, parseLiveAgentSubmission } = require("../AgentWorker/admission");
|
||||
const { cancelOwnedAgentJob } = require("../AgentWorker/job-store");
|
||||
const { reviewProjection, REVIEW_SOURCE_REF_PREFIX } = require("../AgentWorker/action-proposal");
|
||||
const { isValidServerAgentChatCursor } = require("../services/server-agent-chat-ownership");
|
||||
|
||||
const ERRORS = {
|
||||
agent_unavailable: "ADPanel Agent is temporarily unavailable. Try again shortly.",
|
||||
agent_discovery_busy: "Model discovery is busy or rate-limited. Wait a moment and try again.",
|
||||
agent_discovery_failed: "Could not load models from the provider. Check the configuration and try again.",
|
||||
agent_discovery_auth: "The provider rejected the API key or denied access. Check the key and its permissions.",
|
||||
agent_discovery_account: "The provider requires account or billing attention.",
|
||||
agent_discovery_empty: "The provider returned no usable models. Check model access or enter a model ID for a custom provider.",
|
||||
agent_discovery_invalid_response: "The models endpoint did not return a model catalog. Check the API base URL or enter a model ID.",
|
||||
agent_discovery_unsupported: "The provider does not expose a models endpoint at that API URL. Check the URL or enter a model ID.",
|
||||
agent_discovery_model_unavailable: "The provider could not use that model ID. Check the ID, API base URL, and model access.",
|
||||
agent_discovery_redirect: "The provider redirected the request. Enter its final API base URL. Redirects are not followed.",
|
||||
agent_discovery_timeout: "The provider did not respond in time. Try again shortly.",
|
||||
agent_discovery_unreachable: "Could not reach the provider from the panel. Check DNS, TLS, and network access.",
|
||||
agent_discovery_upstream: "The provider returned a service error. Try again shortly.",
|
||||
agent_discovery_response_too_large: "The provider returned a model catalog larger than the discovery limit.",
|
||||
agent_invalid_proposal: "The Agent could not read the provider setup request. Try Save & Connect again.",
|
||||
agent_invalid_manual_model: "Enter up to 32 model IDs, one per line. Each ID must be at most 255 characters, with no control characters, and the list must fit within 4 KB.",
|
||||
agent_client_refresh_required: "Refresh the server page before sending an Agent message.",
|
||||
agent_invalid_chat: "Invalid chat ID.",
|
||||
agent_invalid_server: "A server is required.",
|
||||
agent_invalid_prompt: "A prompt below the size limit is required.",
|
||||
agent_invalid_image: "Use one supported image below the size limit.",
|
||||
agent_invalid_access_mode: "Select General access or Read only.",
|
||||
agent_chat_not_found: "Chat not found.",
|
||||
agent_chat_busy: "Finish or stop the current reply in this chat first.",
|
||||
agent_request_conflict: "This submission ID was already used for a different message.",
|
||||
agent_authority_revoked: "You no longer have permission for that Agent action.",
|
||||
agent_review_not_found: "This action is no longer available for review.",
|
||||
agent_review_used: "This action has already been reviewed.",
|
||||
agent_review_target_changed: "The reviewed server is no longer available.",
|
||||
agent_review_file_unavailable: "This file could not be reviewed as text.",
|
||||
agent_review_invalid_command: "The proposed console command is not valid.",
|
||||
agent_review_invalid: "Invalid action review.",
|
||||
};
|
||||
|
||||
function sendAgentError(res, error) {
|
||||
const status = Number(error?.status);
|
||||
if (!Number.isInteger(status) || status < 400 || status > 599) return res.status(500).json({ error: "Agent request failed." });
|
||||
if (status === 429 || status === 503) res.set("Retry-After", "3");
|
||||
if (Object.hasOwn(ERRORS, error.code)) return res.status(status).json({ error: ERRORS[error.code], code: error.code });
|
||||
const code = error instanceof AgentRpcError ? error.code : status === 503 ? "agent_unavailable" : undefined;
|
||||
return res.status(status).json({ error: ERRORS[code] || (status < 500 ? error.message : ERRORS.agent_unavailable), code });
|
||||
}
|
||||
|
||||
function createAgentLiveRouter({ db, isAuthenticated, hasAgentAccess, getLoggedInUser, cancelLimiter, statusLimiter, insertAiAgentChatJob, saveSelection, worker, ensureAiChatTablesReady, review, reviewLimiter, getRequestIp }) {
|
||||
const router = Router();
|
||||
|
||||
async function authorize(req, res, next) {
|
||||
try {
|
||||
res.set("Cache-Control", "no-store");
|
||||
if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" });
|
||||
if (!(await hasAgentAccess(req))) return res.status(403).json({ error: "no agent access" });
|
||||
const user = await getLoggedInUser(req);
|
||||
if (!user?.id || user.suspended) return res.status(403).json({ error: "no agent access" });
|
||||
req.agentAccount = user;
|
||||
return next();
|
||||
} catch (error) {
|
||||
return sendAgentError(res, error);
|
||||
}
|
||||
}
|
||||
|
||||
router.post("/chat", authorize, async (req, res) => {
|
||||
try {
|
||||
const live = parseLiveAgentSubmission(req.body);
|
||||
const { provider, model } = req.body;
|
||||
if (typeof provider !== "string" || typeof model !== "string" || model.length > 255) {
|
||||
return res.status(400).json({ error: "provider and model are required" });
|
||||
}
|
||||
const user = req.agentAccount;
|
||||
const job = await insertAiAgentChatJob({ user, serverName: live.server, prompt: live.prompt, provider, model, source: LIVE_SOURCE, live });
|
||||
await saveSelection(user.id, job.provider, job.model).catch(() => {});
|
||||
return res.status(202).json({ ok: true, chatId: job.chatId, jobId: job.jobId, status: job.status });
|
||||
} catch (error) {
|
||||
return sendAgentError(res, error);
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/jobs/:id", statusLimiter, authorize, async (req, res) => {
|
||||
try {
|
||||
if (!isValidServerAgentChatCursor(req.params.id)) return res.status(400).json({ error: "invalid job id" });
|
||||
await ensureAiChatTablesReady();
|
||||
const [job] = await db.query(`SELECT job.id, job.chat_id, job.status, job.error, job.created_at, job.started_at,
|
||||
job.completed_at, reply.content, reply.agent_actions, reply.thinking_time_ms, reply.thinking_content, reply.model, ${reviewProjection},
|
||||
(SELECT CAST(conclusion.id AS CHAR) FROM ai_agent_jobs conclusion WHERE conclusion.chat_id = job.chat_id
|
||||
AND conclusion.user_id = job.user_id AND conclusion.source = job.source
|
||||
AND conclusion.source_ref = CONCAT('${REVIEW_SOURCE_REF_PREFIX}', job.id) AND conclusion.status IN ('queued','running')
|
||||
AND conclusion.feature_generation = job.feature_generation LIMIT 1) AS review_conclusion_job_id
|
||||
FROM ai_agent_jobs job LEFT JOIN ai_chats chat ON chat.id = job.chat_id AND chat.created_by = job.user_id
|
||||
LEFT JOIN ai_messages reply ON reply.id = job.result_message_id AND reply.chat_id = chat.id
|
||||
WHERE job.id = ? AND job.user_id = ? LIMIT 1`, [req.params.id, req.agentAccount.id]);
|
||||
if (!job) return res.status(404).json({ error: "job not found" });
|
||||
return res.json({ ok: true, job });
|
||||
} catch (error) {
|
||||
return sendAgentError(res, error);
|
||||
}
|
||||
});
|
||||
|
||||
router.post("/jobs/:id/cancel", cancelLimiter, authorize, async (req, res) => {
|
||||
try {
|
||||
if (!isValidServerAgentChatCursor(req.params.id)) return res.status(400).json({ error: "invalid job id" });
|
||||
const id = req.params.id;
|
||||
const userId = req.agentAccount.id;
|
||||
await ensureAiChatTablesReady();
|
||||
const [job] = await db.query("SELECT claim_token FROM ai_agent_jobs WHERE id = ? AND user_id = ? LIMIT 1", [id, userId]);
|
||||
if (!job) return res.status(404).json({ error: "job not found" });
|
||||
const cancelled = await cancelOwnedAgentJob(db, userId, id);
|
||||
if (cancelled && job.claim_token) {
|
||||
try { void worker.request("cancel", { id, token: job.claim_token }, AbortSignal.timeout(500)).catch(() => {}); } catch { }
|
||||
}
|
||||
return res.json({ ok: true, cancelled });
|
||||
} catch (error) {
|
||||
return sendAgentError(res, error);
|
||||
}
|
||||
});
|
||||
|
||||
if (review) {
|
||||
router.get("/jobs/:id/review", statusLimiter, authorize, async (req, res) => {
|
||||
try {
|
||||
if (!isValidServerAgentChatCursor(req.params.id) || typeof req.query.server !== "string") {
|
||||
throw new AgentRpcError(400, "agent_review_invalid");
|
||||
}
|
||||
return res.json(await review.preview(req, req.params.id, req.query.server));
|
||||
} catch (error) { return sendAgentError(res, error); }
|
||||
});
|
||||
router.post("/jobs/:id/review", reviewLimiter, authorize, async (req, res) => {
|
||||
try {
|
||||
if (!isValidServerAgentChatCursor(req.params.id)) throw new AgentRpcError(400, "agent_review_invalid");
|
||||
const result = await review.submit(req, res, req.params.id, getRequestIp(req));
|
||||
if (result) return res.json(result);
|
||||
} catch (error) { return sendAgentError(res, error); }
|
||||
});
|
||||
}
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
module.exports = { createAgentLiveRouter, sendAgentError };
|
||||
+519
-62
@@ -2,19 +2,93 @@
|
||||
|
||||
const express = require("express");
|
||||
const multer = require("multer");
|
||||
const { createDashboardAssistantService } = require("../utils/dashboard-assistant-service");
|
||||
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;
|
||||
if (message.includes("not configured")) return 503;
|
||||
// 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")
|
||||
) {
|
||||
@@ -23,15 +97,50 @@ function inferStatusCode(error) {
|
||||
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(),
|
||||
limits: { fileSize: AUDIO_UPLOAD_LIMIT_BYTES, files: 1 },
|
||||
fileFilter: acceptAudioUploadsOnly,
|
||||
limits: {
|
||||
fileSize: AUDIO_UPLOAD_LIMIT_BYTES,
|
||||
files: 1,
|
||||
fields: 10,
|
||||
parts: 12,
|
||||
},
|
||||
});
|
||||
const service = createDashboardAssistantService(deps);
|
||||
|
||||
@@ -66,22 +175,59 @@ module.exports = function createDashboardAssistantRouter(deps) {
|
||||
return true;
|
||||
}
|
||||
|
||||
router.get("/bootstrap", async (req, res) => {
|
||||
// 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 state = await service.getBootstrap(req);
|
||||
return res.json({ ok: true, ...state });
|
||||
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] bootstrap failed:", error);
|
||||
return res.status(500).json({ error: "failed to load assistant" });
|
||||
console.error("[dashboard-assistant] fetch models failed:", error);
|
||||
return res.status(500).json({ error: "failed to fetch models" });
|
||||
}
|
||||
});
|
||||
|
||||
router.post("/token", async (req, res) => {
|
||||
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 = deps.requireActionTokenOr403(req, res, "POST /api/dashboard-assistant/token");
|
||||
const ok = await deps.requireActionTokenOr403(req, res, "POST /api/dashboard-assistant/token");
|
||||
if (!ok) return;
|
||||
}
|
||||
|
||||
@@ -89,46 +235,92 @@ module.exports = function createDashboardAssistantRouter(deps) {
|
||||
const saved = await service.saveProviderToken({ provider, token });
|
||||
return res.json({ ok: true, provider: saved });
|
||||
} catch (error) {
|
||||
const statusCode = inferStatusCode(error);
|
||||
return res.status(statusCode).json({ error: error?.message || "failed to save provider token" });
|
||||
return respondWithError(res, error, "failed to save provider token");
|
||||
}
|
||||
});
|
||||
|
||||
router.post("/access", async (req, res) => {
|
||||
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 = deps.requireActionTokenOr403(req, res, "POST /api/dashboard-assistant/access");
|
||||
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());
|
||||
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" });
|
||||
// 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,
|
||||
};
|
||||
|
||||
return res.json({ ok: true, allowNormalUsers: nextConfig.allowNormalUsers });
|
||||
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) {
|
||||
const statusCode = inferStatusCode(error);
|
||||
return res.status(statusCode).json({ error: error?.message || "failed to save assistant access" });
|
||||
return respondWithError(res, error, "failed to save assistant access");
|
||||
}
|
||||
});
|
||||
|
||||
router.post("/reset", async (req, res) => {
|
||||
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();
|
||||
const chat = await service.createFreshChat(userEmail);
|
||||
// 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);
|
||||
@@ -136,17 +328,49 @@ module.exports = function createDashboardAssistantRouter(deps) {
|
||||
}
|
||||
});
|
||||
|
||||
router.post("/transcribe", (req, res, next) => {
|
||||
// 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) {
|
||||
const statusCode = error.code === "LIMIT_FILE_SIZE" ? 400 : 500;
|
||||
return res.status(statusCode).json({ error: error.code === "LIMIT_FILE_SIZE" ? "The recording is too large." : "Audio upload failed." });
|
||||
// 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 (!(await requireAssistantAccess(req, res))) return;
|
||||
if (!req.file?.buffer) {
|
||||
return res.status(400).json({ error: "No audio was uploaded." });
|
||||
}
|
||||
@@ -161,71 +385,304 @@ module.exports = function createDashboardAssistantRouter(deps) {
|
||||
|
||||
return res.json({ ok: true, ...transcript });
|
||||
} catch (error) {
|
||||
const statusCode = inferStatusCode(error);
|
||||
return res.status(statusCode).json({ error: error?.message || "Transcription failed." });
|
||||
return respondWithError(res, error, "Transcription failed.");
|
||||
}
|
||||
});
|
||||
|
||||
router.post("/chat", async (req, res) => {
|
||||
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: req.body?.message,
|
||||
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) {
|
||||
const statusCode = inferStatusCode(error);
|
||||
console.error("[dashboard-assistant] chat failed:", error);
|
||||
return res.status(statusCode).json({ error: error?.message || "Assistant request failed." });
|
||||
return respondWithError(res, error, "Assistant request failed.");
|
||||
}
|
||||
});
|
||||
|
||||
router.post("/client-follow-up", async (req, res) => {
|
||||
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: req.body?.summary,
|
||||
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) {
|
||||
const statusCode = inferStatusCode(error);
|
||||
console.error("[dashboard-assistant] client-follow-up failed:", error);
|
||||
return res.status(statusCode).json({ error: error?.message || "Assistant follow-up failed." });
|
||||
return respondWithError(res, error, "Assistant follow-up failed.");
|
||||
}
|
||||
});
|
||||
|
||||
router.post("/confirm-delete", async (req, res) => {
|
||||
try {
|
||||
if (!(await requireAssistantAccess(req, res))) return;
|
||||
// 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 result = await service.confirmDeleteServer({
|
||||
userEmail,
|
||||
chatId: req.body?.chatId,
|
||||
serverName: req.body?.server,
|
||||
userIp: req.ip || req.connection?.remoteAddress || "unknown",
|
||||
});
|
||||
return res.json({ ok: true, ...result });
|
||||
} catch (error) {
|
||||
const statusCode = inferStatusCode(error);
|
||||
console.error("[dashboard-assistant] confirm-delete failed:", error);
|
||||
return res.status(statusCode).json({ error: error?.message || "Server deletion failed." });
|
||||
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;
|
||||
};
|
||||
@@ -1,300 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
const express = require("express");
|
||||
const dns = require("dns").promises;
|
||||
const db = require("../db");
|
||||
const nodes = require("../nodes");
|
||||
const { getTechnicalServerName } = require("../utils/server-name");
|
||||
const router = express.Router();
|
||||
|
||||
|
||||
async function resolveServer(req, res, next) {
|
||||
const serverName = req.params.serverName;
|
||||
if (!serverName) return res.status(400).json({ error: "missing server name" });
|
||||
|
||||
try {
|
||||
const lowered = String(serverName).trim().toLowerCase();
|
||||
const rows = await db.query(
|
||||
`SELECT *
|
||||
FROM servers
|
||||
WHERE LOWER(name) = ? OR LOWER(bot) = ?
|
||||
ORDER BY
|
||||
CASE
|
||||
WHEN LOWER(name) = ? THEN 0
|
||||
WHEN LOWER(bot) = ? THEN 1
|
||||
ELSE 2
|
||||
END,
|
||||
id DESC
|
||||
LIMIT 1`,
|
||||
[lowered, lowered, lowered, lowered]
|
||||
);
|
||||
if (!rows.length) return res.status(404).json({ error: "server not found" });
|
||||
req.server = rows[0];
|
||||
next();
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.status(500).json({ error: "internal error" });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
async function checkPerms(req, perm) {
|
||||
if (!req.session.user) return false;
|
||||
|
||||
|
||||
const userEmail = req.session.user;
|
||||
let user = null;
|
||||
|
||||
try {
|
||||
const userRows = await db.query("SELECT * FROM users WHERE email = ? LIMIT 1", [userEmail]);
|
||||
if (userRows.length > 0) user = userRows[0];
|
||||
} catch (e) {
|
||||
console.error("Error resolving user:", e);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!user) return false;
|
||||
if (user.admin) return true;
|
||||
|
||||
|
||||
const access = await db.query(
|
||||
"SELECT * FROM user_access WHERE user_id = ? AND server_name = ?",
|
||||
[user.id, req.server.name]
|
||||
);
|
||||
if (!access.length) return false;
|
||||
|
||||
let acl = {};
|
||||
try {
|
||||
acl = typeof req.server.acl === 'string' ? JSON.parse(req.server.acl) : (req.server.acl || {});
|
||||
} catch (e) { acl = {}; }
|
||||
|
||||
const userPerms = acl[userEmail] || {};
|
||||
return !!userPerms[perm];
|
||||
}
|
||||
|
||||
router.get("/:serverName", resolveServer, async (req, res) => {
|
||||
|
||||
if (!await checkPerms(req, 'subdomain_show')) {
|
||||
return res.status(403).json({ error: "permission denied" });
|
||||
}
|
||||
|
||||
try {
|
||||
const subs = await db.query("SELECT * FROM subdomains WHERE server_id = ?", [req.server.id]);
|
||||
res.json({ subdomains: subs });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.status(500).json({ error: "db error" });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
router.post("/:serverName", resolveServer, async (req, res) => {
|
||||
|
||||
if (!await checkPerms(req, 'subdomain_add')) {
|
||||
return res.status(403).json({ error: "permission denied" });
|
||||
}
|
||||
|
||||
const domain = String(req.body.domain || "").trim().toLowerCase();
|
||||
if (!domain || domain.length > 253) return res.status(400).json({ error: "invalid domain" });
|
||||
|
||||
|
||||
const hostnameRegex = /^(?!-)[a-z0-9-]{1,63}(?<!-)(\.[a-z0-9-]{1,63})*\.[a-z]{2,}$/;
|
||||
if (!hostnameRegex.test(domain)) {
|
||||
return res.status(400).json({ error: "invalid domain format" });
|
||||
}
|
||||
|
||||
|
||||
let expectedIp = req.server.ip;
|
||||
if (!expectedIp && req.server.node_id) {
|
||||
try {
|
||||
const nodeRows = await db.query("SELECT address FROM nodes WHERE id = ?", [req.server.node_id]);
|
||||
if (nodeRows.length) expectedIp = nodeRows[0].address;
|
||||
} catch (e) {
|
||||
console.error("Node IP lookup failed:", e);
|
||||
return res.status(500).json({ error: "internal error" });
|
||||
}
|
||||
}
|
||||
|
||||
if (!expectedIp) {
|
||||
return res.status(500).json({ error: "cannot determine node ip" });
|
||||
}
|
||||
|
||||
|
||||
let targetIps = [];
|
||||
if (/^(\d{1,3}\.){3}\d{1,3}$/.test(expectedIp)) {
|
||||
targetIps = [expectedIp];
|
||||
} else {
|
||||
try {
|
||||
targetIps = await dns.resolve4(expectedIp);
|
||||
} catch (e) {
|
||||
console.error("Failed to resolve node address:", expectedIp, e);
|
||||
return res.status(500).json({ error: "failed to resolve node address" });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
try {
|
||||
const addresses = await dns.resolve4(domain);
|
||||
|
||||
const matched = addresses.some(addr => targetIps.includes(addr));
|
||||
|
||||
if (!matched) {
|
||||
return res.status(400).json({
|
||||
error: "DNS verification failed",
|
||||
details: "Domain does not point to the expected server address"
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
|
||||
return res.status(400).json({ error: "DNS lookup failed: record not found" });
|
||||
}
|
||||
|
||||
|
||||
let subId;
|
||||
try {
|
||||
const result = await db.query("INSERT INTO subdomains (server_id, domain, status) VALUES (?, ?, 'approved')", [req.server.id, domain]);
|
||||
subId = result.insertId;
|
||||
} catch (err) {
|
||||
if (err.code === 'ER_DUP_ENTRY') {
|
||||
return res.status(400).json({ error: "domain already registered" });
|
||||
}
|
||||
console.error(err);
|
||||
res.status(500).json({ error: "db error" });
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
try {
|
||||
const { node } = await nodes.remoteContext(req.server.name);
|
||||
if (node) {
|
||||
const base = nodes.nodeUrl(node);
|
||||
const url = `${base}/v1/servers/${encodeURIComponent(getTechnicalServerName(req.server, req.server.name))}/subdomains`;
|
||||
await nodes.httpJson(url, {
|
||||
method: 'POST',
|
||||
headers: nodes.nodeHeaders(node),
|
||||
body: JSON.stringify({ domain: domain, action: 'create' })
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Agent call failed:", err);
|
||||
|
||||
await db.query("DELETE FROM subdomains WHERE id = ?", [subId]);
|
||||
return res.status(500).json({ error: "agent communication failed" });
|
||||
}
|
||||
|
||||
res.json({ ok: true, id: subId });
|
||||
});
|
||||
|
||||
router.post("/:serverName/:id/verify", resolveServer, async (req, res) => {
|
||||
|
||||
if (!await checkPerms(req, 'subdomain_add')) {
|
||||
return res.status(403).json({ error: "permission denied" });
|
||||
}
|
||||
|
||||
const subId = req.params.id;
|
||||
|
||||
let sub, expectedIp;
|
||||
try {
|
||||
const rows = await db.query("SELECT * FROM subdomains WHERE id = ? AND server_id = ?", [subId, req.server.id]);
|
||||
if (!rows.length) return res.status(404).json({ error: "subdomain not found" });
|
||||
sub = rows[0];
|
||||
|
||||
expectedIp = req.server.ip;
|
||||
if (!expectedIp && req.server.node_id) {
|
||||
const nodeRows = await db.query("SELECT address FROM nodes WHERE id = ?", [req.server.node_id]);
|
||||
if (nodeRows.length) expectedIp = nodeRows[0].address;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
return res.status(500).json({ error: "internal error" });
|
||||
}
|
||||
|
||||
if (!expectedIp) {
|
||||
return res.status(500).json({ error: "cannot determine node ip" });
|
||||
}
|
||||
|
||||
|
||||
let targetIps = [];
|
||||
if (/^(\d{1,3}\.){3}\d{1,3}$/.test(expectedIp)) {
|
||||
targetIps = [expectedIp];
|
||||
} else {
|
||||
try {
|
||||
targetIps = await dns.resolve4(expectedIp);
|
||||
} catch (e) {
|
||||
console.error("Failed to resolve node address:", expectedIp, e);
|
||||
return res.status(500).json({ error: "failed to resolve node address" });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
try {
|
||||
const addresses = await dns.resolve4(sub.domain);
|
||||
|
||||
const matched = addresses.some(addr => targetIps.includes(addr));
|
||||
|
||||
const newStatus = matched ? 'approved' : 'canceled';
|
||||
await db.query("UPDATE subdomains SET status = ? WHERE id = ?", [newStatus, subId]);
|
||||
|
||||
|
||||
if (matched) {
|
||||
const { node } = await nodes.remoteContext(req.server.name);
|
||||
if (node) {
|
||||
const base = nodes.nodeUrl(node);
|
||||
const url = `${base}/v1/servers/${encodeURIComponent(getTechnicalServerName(req.server, req.server.name))}/subdomains`;
|
||||
await nodes.httpJson(url, {
|
||||
method: 'POST',
|
||||
headers: nodes.nodeHeaders(node),
|
||||
body: JSON.stringify({ domain: sub.domain, action: 'create' })
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
res.json({ ok: true, status: newStatus, expected: expectedIp, found: addresses });
|
||||
} catch (err) {
|
||||
console.error("DNS error:", err.message);
|
||||
|
||||
await db.query("UPDATE subdomains SET status = 'canceled' WHERE id = ?", [subId]);
|
||||
res.json({ ok: true, status: 'canceled', error: "dns lookup failed" });
|
||||
}
|
||||
});
|
||||
|
||||
router.delete("/:serverName/:id", resolveServer, async (req, res) => {
|
||||
|
||||
if (!await checkPerms(req, 'subdomain_add')) {
|
||||
return res.status(403).json({ error: "permission denied" });
|
||||
}
|
||||
|
||||
let domain;
|
||||
try {
|
||||
const rows = await db.query("SELECT domain FROM subdomains WHERE id = ? AND server_id = ?", [req.params.id, req.server.id]);
|
||||
if (!rows.length) return res.status(404).json({ error: "subdomain not found" });
|
||||
domain = rows[0].domain;
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
return res.status(500).json({ error: "internal error" });
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
const { node } = await nodes.remoteContext(req.server.name);
|
||||
if (node) {
|
||||
const base = nodes.nodeUrl(node);
|
||||
const url = `${base}/v1/servers/${encodeURIComponent(getTechnicalServerName(req.server, req.server.name))}/subdomains`;
|
||||
|
||||
await nodes.httpJson(url, {
|
||||
method: 'POST',
|
||||
headers: nodes.nodeHeaders(node),
|
||||
body: JSON.stringify({ domain: domain, action: 'delete' })
|
||||
});
|
||||
}
|
||||
|
||||
await db.query("DELETE FROM subdomains WHERE id = ? AND server_id = ?", [req.params.id, req.server.id]);
|
||||
res.json({ ok: true });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.status(500).json({ error: "db/agent error" });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
Reference in new issue
Block a user