修复安全和请求策略问题

This commit is contained in:
CN-JS-HuiBai
2026-04-14 16:56:46 +08:00
parent 5e9dac6197
commit 44843475c8
4 changed files with 110 additions and 30 deletions

View File

@@ -1,6 +1,7 @@
const axios = require('axios');
const http = require('http');
const https = require('https');
const cache = require('./cache'); // <-- ADD
const QUERY_TIMEOUT = 10000;
@@ -10,7 +11,11 @@ const httpAgent = new http.Agent({ keepAlive: true });
const httpsAgent = new https.Agent({ keepAlive: true });
const serverIdMap = new Map(); // token -> { instance, job, source, lastSeen }
const SECRET = process.env.APP_SECRET || crypto.randomBytes(32).toString('hex');
function getSecret() {
// Use the env variable populated by index.js initialization
return process.env.APP_SECRET || 'fallback-secret-for-safety';
}
// Periodic cleanup of serverIdMap to prevent infinite growth
setInterval(() => {
@@ -24,7 +29,7 @@ setInterval(() => {
}, 3600000); // Once per hour
function getServerToken(instance, job, source) {
const hash = crypto.createHmac('sha256', SECRET)
const hash = crypto.createHmac('sha256', getSecret())
.update(`${instance}:${job}:${source}`)
.digest('hex')
.substring(0, 16);
@@ -245,6 +250,9 @@ async function getOverviewMetrics(url, sourceName) {
// Store mapping for detail queries
serverIdMap.set(token, { instance: originalInstance, source: sourceName, job, lastSeen: Date.now() });
// Also store in Valkey for resilience across restarts
cache.set(`server_token:${token}`, originalInstance, 86400).catch(()=>{});
if (!instances.has(token)) {
instances.set(token, {
@@ -559,10 +567,13 @@ function mergeCpuHistories(histories) {
}
function resolveToken(token) {
async function resolveToken(token) {
if (serverIdMap.has(token)) {
return serverIdMap.get(token).instance;
}
const cachedInstance = await cache.get(`server_token:${token}`);
if (cachedInstance) return cachedInstance;
return token;
}
@@ -571,7 +582,7 @@ function resolveToken(token) {
*/
async function getServerDetails(baseUrl, instance, job, settings = {}) {
const url = normalizeUrl(baseUrl);
const node = resolveToken(instance);
const node = await resolveToken(instance);
// Queries based on the requested dashboard structure
const queries = {
@@ -735,7 +746,7 @@ async function getServerDetails(baseUrl, instance, job, settings = {}) {
*/
async function getServerHistory(baseUrl, instance, job, metric, range = '1h', start = null, end = null, p95Type = 'tx') {
const url = normalizeUrl(baseUrl);
const node = resolveToken(instance);
const node = await resolveToken(instance);
// CPU Busy history: 100 - idle
if (metric === 'cpuBusy') {