Compare commits

..

10 Commits

Author SHA1 Message Date
copilot-swe-agent[bot] 23f21d7448 Fix code review issues: div-by-zero, duplicate logic, cron_name fallback
Agent-Logs-Url: https://github.com/whyour/qinglong/sessions/3db54913-03d2-4721-b720-8ccbf8d0f00e

Co-authored-by: whyour <22700758+whyour@users.noreply.github.com>
2026-04-25 06:53:27 +00:00
copilot-swe-agent[bot] 34bc18cb25 Add statistics panel: backend models, services, APIs and frontend page
Agent-Logs-Url: https://github.com/whyour/qinglong/sessions/3db54913-03d2-4721-b720-8ccbf8d0f00e

Co-authored-by: whyour <22700758+whyour@users.noreply.github.com>
2026-04-25 06:51:31 +00:00
copilot-swe-agent[bot] 0995808309 Initial plan 2026-04-25 06:42:15 +00:00
Copilot 07bf0c705b fix: respect QlPort env var in Docker health check (#2963)
* Initial plan

* fix: use QlPort env variable in health check with fallback to default 5700

Co-authored-by: whyour <22700758+whyour@users.noreply.github.com>
2026-03-11 20:43:56 +08:00
whyour fd516977e3 chore: upgrade nodemailer 2026-03-07 22:35:18 +08:00
whyour c39f4ef846 chore: 更新 multer,解决 cve 漏洞 2026-03-07 21:31:24 +08:00
whyour 275d8af4e2 更新版本 v2.20.2 2026-03-01 20:35:25 +08:00
whyour 544c432f49 修复 PATH 环境变量 2026-03-01 20:35:19 +08:00
Copilot 6bec52dca1 Fix /open/user/init auth bypass allowing credential reset on initialized systems (#2941)
* Initial plan

* fix: add /open/user/init paths to init guard to prevent auth bypass

Co-authored-by: whyour <22700758+whyour@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: whyour <22700758+whyour@users.noreply.github.com>
Co-authored-by: whyour <imwhyour@gmail.com>
2026-03-01 18:02:21 +08:00
rockymelody ce599d306f 青龙面板鉴权绕过漏洞已修复 (#2935)
已实施的安全加固措施
第一层防御:启用Express严格路由(第17-18行)
app.set('case sensitive routing', true);  // 路由大小写敏感
app.set('strict routing', true);           // 严格路由匹配
第二层防御:路径标准化检查中间件(第23-37行)
app.use((req, res, next) => {
  const originalPath = req.path;
  const normalizedPath = originalPath.toLowerCase();

  // 检测并拦截大小写混淆攻击
  if (originalPath !== normalizedPath &&
      (normalizedPath.startsWith('/api/') || normalizedPath.startsWith('/open/'))) {
    return res.status(400).json({
      code: 400,
      message: 'Invalid path format'
    });
  }

  next();
});
作用:主动检测并拒绝含有大小写变体的恶意请求
第三层防御:JWT中间件正则表达式修复(第59行)
// 修复前:
path: [...config.apiWhiteList, /^\/(?!api\/).*/],

// 修复后:添加大小写不敏感标志 'i'
path: [...config.apiWhiteList, /^(\/(?!api\/).*)$/i],
作用:防御正则匹配层面的绕过
第四层防御:自定义Token中间件路径标准化(第74-87行)
// 修复前:
if (!['/open/', '/api/'].some((x) => req.path.startsWith(x))) {

// 修复后:统一转小写比较
const pathLower = req.path.toLowerCase();
if (!['/open/', '/api/'].some((x) => pathLower.startsWith(x))) {
}
作用:确保Token验证逻辑对所有路径变体生效

第五层防御:初始化接口路径检查修复(第122-123行)
// 修复前:
if (!['/api/user/init', '/api/user/notification/init'].includes(req.path)) {

// 修复后:
const pathLower = req.path.toLowerCase();
if (!['/api/user/init', '/api/user/notification/init'].includes(pathLower)) {
2026-03-01 17:44:03 +08:00
22 changed files with 1326 additions and 440 deletions
+53
View File
@@ -3,6 +3,7 @@ import { Container } from 'typedi';
import { Logger } from 'winston';
import CronService from '../services/cron';
import CronViewService from '../services/cronView';
import CronStatsService from '../services/cronStats';
import { celebrate, Joi } from 'celebrate';
import { commonCronSchema } from '../validation/schedule';
@@ -141,6 +142,58 @@ export default (app: Router) => {
},
);
route.get(
'/stats',
async (req: Request, res: Response, next: NextFunction) => {
try {
const cronStatsService = Container.get(CronStatsService);
const data = await cronStatsService.stats();
return res.send({ code: 200, data });
} catch (e) {
return next(e);
}
},
);
route.get(
'/stats/trend',
async (req: Request, res: Response, next: NextFunction) => {
try {
const cronStatsService = Container.get(CronStatsService);
const data = await cronStatsService.trend();
return res.send({ code: 200, data });
} catch (e) {
return next(e);
}
},
);
route.get(
'/stats/top-duration',
async (req: Request, res: Response, next: NextFunction) => {
try {
const cronStatsService = Container.get(CronStatsService);
const data = await cronStatsService.topDuration();
return res.send({ code: 200, data });
} catch (e) {
return next(e);
}
},
);
route.get(
'/stats/top-count',
async (req: Request, res: Response, next: NextFunction) => {
try {
const cronStatsService = Container.get(CronStatsService);
const data = await cronStatsService.topCount();
return res.send({ code: 200, data });
} catch (e) {
return next(e);
}
},
);
route.get('/', async (req: Request, res: Response, next: NextFunction) => {
const logger: Logger = Container.get('logger');
try {
+4 -61
View File
@@ -535,43 +535,12 @@ export async function setSystemTimezone(timezone: string): Promise<boolean> {
}
}
// Helper function to check if a name is a GitHub URL
function isGitHubUrl(name: string): boolean {
// Support git+https://, git+http://, https://, and http:// URLs
// This covers GitHub URLs and other git-compatible repositories
return !!name.match(/^(git\+https?:\/\/|https?:\/\/)/i);
}
// Helper function to check if a name is a requirements file
function isRequirementsFile(name: string): boolean {
return !!name.match(/requirements.*\.(txt|in)$/i);
}
// Helper function to check if a name is a pyproject.toml file
function isPyprojectToml(name: string): boolean {
return name.endsWith('pyproject.toml');
}
export function getGetCommand(type: DependenceTypes, name: string): string {
const trimmedName = name.trim();
// For Python dependencies installed from GitHub or requirements files,
// we can't reliably check if they're installed, so skip the check
if (type === DependenceTypes.python3) {
if (isGitHubUrl(trimmedName) ||
isRequirementsFile(trimmedName) ||
isPyprojectToml(trimmedName)) {
// Return a command that will always indicate not installed
// This ensures GitHub URLs and requirements files are always installed
return 'echo ""';
}
}
const baseCommands = {
[DependenceTypes.nodejs]: `pnpm ls -g | grep "${trimmedName}" | head -1`,
[DependenceTypes.nodejs]: `pnpm ls -g | grep "${name}" | head -1`,
[DependenceTypes.python3]: `
python3 -c "exec('''
name='${trimmedName}'
name='${name}'
try:
from importlib.metadata import version
print(version(name))
@@ -581,7 +550,7 @@ except:
spec=u.find_spec(name)
print(name if spec else '')
''')"`,
[DependenceTypes.linux]: `apk info -es ${trimmedName}`,
[DependenceTypes.linux]: `apk info -es ${name}`,
};
return baseCommands[type];
@@ -601,33 +570,7 @@ export function getInstallCommand(type: DependenceTypes, name: string): string {
command = `${command} --prefix=${PYTHON_INSTALL_DIR}`;
}
const trimmedName = name.trim();
// Handle different installation methods for Python
if (type === DependenceTypes.python3) {
// Check if it's a GitHub URL (support both git+ and direct URLs)
if (isGitHubUrl(trimmedName)) {
return `${command} ${trimmedName}`;
}
// Check if it's a requirements file path
if (isRequirementsFile(trimmedName)) {
return `${command} -r ${trimmedName}`;
}
// Check if it's a pyproject.toml file
if (isPyprojectToml(trimmedName)) {
// For pyproject.toml, install from the directory containing it
const pathMatch = trimmedName.match(/^(.+)\/pyproject\.toml$/);
if (pathMatch) {
// Has a path prefix, use the directory
return `${command} ${pathMatch[1]}`;
} else {
// Just "pyproject.toml", install current directory
return `${command} .`;
}
}
}
return `${command} ${trimmedName}`;
return `${command} ${name.trim()}`;
}
export function getUninstallCommand(
+31
View File
@@ -0,0 +1,31 @@
import { sequelize } from '.';
import { DataTypes, Model } from 'sequelize';
export class CronLog {
id?: number;
cron_id: number;
cron_name: string;
start_time: number;
duration: number;
constructor(options: CronLog) {
this.cron_id = options.cron_id;
this.cron_name = options.cron_name;
this.start_time = options.start_time;
this.duration = options.duration;
}
}
export interface CronLogInstance extends Model<CronLog, CronLog>, CronLog {}
export const CronLogModel = sequelize.define<CronLogInstance>(
'CronLog',
{
cron_id: DataTypes.NUMBER,
cron_name: DataTypes.STRING,
start_time: DataTypes.NUMBER,
duration: DataTypes.NUMBER,
},
{
indexes: [{ fields: ['cron_id'] }, { fields: ['start_time'] }],
},
);
+2
View File
@@ -6,6 +6,7 @@ import { AppModel } from '../data/open';
import { SystemModel } from '../data/system';
import { SubscriptionModel } from '../data/subscription';
import { CrontabViewModel } from '../data/cronView';
import { CronLogModel } from '../data/cronLog';
import { sequelize } from '../data';
export default async () => {
@@ -17,6 +18,7 @@ export default async () => {
await EnvModel.sync();
await SubscriptionModel.sync();
await CrontabViewModel.sync();
await CronLogModel.sync();
// 初始化新增字段
const migrations = [
+34 -5
View File
@@ -13,9 +13,29 @@ import { isValidToken } from '../shared/auth';
import path from 'path';
export default ({ app }: { app: Application }) => {
// Security: Enable strict routing to prevent case-insensitive path bypass
app.set('case sensitive routing', true);
app.set('strict routing', true);
app.set('trust proxy', 'loopback');
app.use(cors());
// Security: Path normalization middleware to prevent case variation attacks
app.use((req, res, next) => {
const originalPath = req.path;
const normalizedPath = originalPath.toLowerCase();
// Block requests with case variations on protected paths
if (originalPath !== normalizedPath &&
(normalizedPath.startsWith('/api/') || normalizedPath.startsWith('/open/'))) {
return res.status(400).json({
code: 400,
message: 'Invalid path format'
});
}
next();
});
// Rewrite URLs to strip baseUrl prefix if configured
// This allows the rest of the app to work without baseUrl awareness
if (config.baseUrl) {
@@ -36,7 +56,7 @@ export default ({ app }: { app: Application }) => {
secret: config.jwt.secret,
algorithms: ['HS384'],
}).unless({
path: [...config.apiWhiteList, /^\/(?!api\/).*/],
path: [...config.apiWhiteList, /^(\/(?!api\/).*)$/i],
}),
);
@@ -51,19 +71,20 @@ export default ({ app }: { app: Application }) => {
});
app.use(async (req: Request, res, next) => {
if (!['/open/', '/api/'].some((x) => req.path.startsWith(x))) {
const pathLower = req.path.toLowerCase();
if (!['/open/', '/api/'].some((x) => pathLower.startsWith(x))) {
return next();
}
const headerToken = getToken(req);
if (req.path.startsWith('/open/')) {
if (pathLower.startsWith('/open/')) {
const apps = await shareStore.getApps();
const doc = apps?.filter((x) =>
x.tokens?.find((y) => y.value === headerToken),
)?.[0];
if (doc && doc.tokens && doc.tokens.length > 0) {
const currentToken = doc.tokens.find((x) => x.value === headerToken);
const keyMatch = req.path.match(/\/open\/([a-z]+)\/*/);
const keyMatch = pathLower.match(/\/open\/([a-z]+)\/*/);
const key = keyMatch && keyMatch[1];
if (
doc.scopes.includes(key as any) &&
@@ -98,7 +119,15 @@ export default ({ app }: { app: Application }) => {
});
app.use(async (req, res, next) => {
if (!['/api/user/init', '/api/user/notification/init'].includes(req.path)) {
const pathLower = req.path.toLowerCase();
if (
![
'/api/user/init',
'/api/user/notification/init',
'/open/user/init',
'/open/user/notification/init',
].includes(req.path)
) {
return next();
}
const authInfo =
+2 -2
View File
@@ -13,7 +13,7 @@ import { AuthDataType, SystemModel } from '../data/system';
import SystemService from '../services/system';
import UserService from '../services/user';
import { writeFile, readFile } from 'fs/promises';
import { createRandomString, fileExist, safeJSONParse } from '../config/util';
import { createRandomString, fileExist, isDemoEnv, safeJSONParse } from '../config/util';
import OpenService from '../services/open';
import { shareStore } from '../shared/store';
import Logger from './logger';
@@ -50,7 +50,7 @@ export default async () => {
const [authConfig] = await SystemModel.findOrCreate({
where: { type: AuthDataType.authConfig },
});
if (!authConfig?.info) {
if (!authConfig?.info || isDemoEnv()) {
let authInfo = {
username: 'admin',
password: 'admin',
+13
View File
@@ -2,6 +2,7 @@ import { Service, Inject } from 'typedi';
import winston from 'winston';
import config from '../config';
import { Crontab, CrontabModel, CrontabStatus } from '../data/cron';
import { CronLog, CronLogModel } from '../data/cronLog';
import { exec, execSync } from 'child_process';
import fs from 'fs/promises';
import CronExpressionParser from 'cron-parser';
@@ -176,6 +177,18 @@ export default class CronService {
{ ...pickBy(options, (v) => v === 0 || !!v) },
{ where: { id } },
);
if (status === CrontabStatus.idle && last_running_time > 0) {
const cronName = (cron.name || cron.command || '').substring(0, 255);
await CronLogModel.create(
new CronLog({
cron_id: id,
cron_name: cronName,
start_time: last_execution_time,
duration: last_running_time,
}),
);
}
}
}
+137
View File
@@ -0,0 +1,137 @@
import { Service, Inject } from 'typedi';
import winston from 'winston';
import { CrontabModel } from '../data/cron';
import { CronLog, CronLogModel } from '../data/cronLog';
import { Op } from 'sequelize';
import dayjs from 'dayjs';
type GroupedLog = {
cron_id: number;
cron_name: string;
durations: number[];
};
@Service()
export default class CronStatsService {
constructor(@Inject('logger') private logger: winston.Logger) {}
private groupLogsByCronId(logs: CronLog[]): Record<number, GroupedLog> {
const grouped: Record<number, GroupedLog> = {};
for (const log of logs) {
if (!grouped[log.cron_id]) {
grouped[log.cron_id] = {
cron_id: log.cron_id,
cron_name: log.cron_name,
durations: [],
};
}
grouped[log.cron_id].durations.push(log.duration);
}
return grouped;
}
private avgOf(nums: number[]): number {
if (nums.length === 0) return 0;
return Math.round(nums.reduce((a, b) => a + b, 0) / nums.length);
}
private getTodayRange() {
return {
start: dayjs().startOf('day').unix(),
end: dayjs().endOf('day').unix(),
};
}
public async stats() {
const { start, end } = this.getTodayRange();
const [allCrons, todayLogs] = await Promise.all([
CrontabModel.findAll({ where: {} }),
CronLogModel.findAll({
where: { start_time: { [Op.between]: [start, end] } },
}),
]);
const total = allCrons.length;
const enabled = allCrons.filter((c: any) => c.isDisabled !== 1).length;
const disabled = allCrons.filter((c: any) => c.isDisabled === 1).length;
const todayCount = todayLogs.length;
const todayTotalDuration = todayLogs.reduce(
(sum: number, l: any) => sum + (l.duration || 0),
0,
);
const todayAvgDuration =
todayCount > 0 ? Math.round(todayTotalDuration / todayCount) : 0;
return {
total,
enabled,
disabled,
today: {
count: todayCount,
avgDuration: todayAvgDuration,
},
};
}
public async trend() {
const days = 7;
const result: Array<{ date: string; count: number }> = [];
for (let i = days - 1; i >= 0; i--) {
const dayStart = dayjs().subtract(i, 'day').startOf('day').unix();
const dayEnd = dayjs().subtract(i, 'day').endOf('day').unix();
const date = dayjs().subtract(i, 'day').format('MM-DD');
const logs = await CronLogModel.findAll({
where: { start_time: { [Op.between]: [dayStart, dayEnd] } },
});
result.push({ date, count: logs.length });
}
return result;
}
public async topDuration(limit = 5) {
const { start, end } = this.getTodayRange();
const logs = await CronLogModel.findAll({
where: { start_time: { [Op.between]: [start, end] } },
});
const grouped = this.groupLogsByCronId(logs as any);
return Object.values(grouped)
.map((g) => ({
cron_id: g.cron_id,
cron_name: g.cron_name,
count: g.durations.length,
avgDuration: this.avgOf(g.durations),
maxDuration: Math.max(...g.durations),
}))
.sort((a, b) => b.avgDuration - a.avgDuration)
.slice(0, limit);
}
public async topCount(limit = 5) {
const { start, end } = this.getTodayRange();
const logs = await CronLogModel.findAll({
where: { start_time: { [Op.between]: [start, end] } },
});
const grouped = this.groupLogsByCronId(logs as any);
return Object.values(grouped)
.map((g) => ({
cron_id: g.cron_id,
cron_name: g.cron_name,
count: g.durations.length,
avgDuration: this.avgOf(g.durations),
}))
.sort((a, b) => b.count - a.count)
.slice(0, limit);
}
}
+4 -3
View File
@@ -69,9 +69,10 @@ RUN git clone --depth=1 -b ${QL_BRANCH} ${QL_URL} ${QL_DIR} \
ENV PNPM_HOME=${QL_DIR}/data/dep_cache/node \
PYTHON_HOME=${QL_DIR}/data/dep_cache/python3 \
PYTHONUSERBASE=${QL_DIR}/data/dep_cache/python3
PYTHONUSERBASE=${QL_DIR}/data/dep_cache/python3 \
HOME=/root
ENV PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${PNPM_HOME}:${PYTHON_HOME}/bin \
ENV PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${PNPM_HOME}:${PYTHON_HOME}/bin:${HOME}/bin \
NODE_PATH=/usr/local/bin:/usr/local/lib/node_modules:${PNPM_HOME}/global/5/node_modules \
PIP_CACHE_DIR=${PYTHON_HOME}/pip \
PYTHONPATH=${PYTHON_HOME}:${PYTHON_HOME}/lib/python${PYTHON_SHORT_VERSION}:${PYTHON_HOME}/lib/python${PYTHON_SHORT_VERSION}/site-packages
@@ -83,6 +84,6 @@ COPY --from=builder /tmp/build/node_modules/. /ql/node_modules/
WORKDIR ${QL_DIR}
HEALTHCHECK --interval=5s --timeout=2s --retries=20 \
CMD curl -sf --noproxy '*' http://127.0.0.1:5700/api/health || exit 1
CMD curl -sf --noproxy '*' http://127.0.0.1:${QlPort:-5700}/api/health || exit 1
ENTRYPOINT ["./docker/docker-entrypoint.sh"]
+4 -3
View File
@@ -69,9 +69,10 @@ RUN git clone --depth=1 -b ${QL_BRANCH} ${QL_URL} ${QL_DIR} \
ENV PNPM_HOME=${QL_DIR}/data/dep_cache/node \
PYTHON_HOME=${QL_DIR}/data/dep_cache/python3 \
PYTHONUSERBASE=${QL_DIR}/data/dep_cache/python3
PYTHONUSERBASE=${QL_DIR}/data/dep_cache/python3 \
HOME=/root
ENV PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${PNPM_HOME}:${PYTHON_HOME}/bin \
ENV PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${PNPM_HOME}:${PYTHON_HOME}/bin:${HOME}/bin \
NODE_PATH=/usr/local/bin:/usr/local/lib/node_modules:${PNPM_HOME}/global/5/node_modules \
PIP_CACHE_DIR=${PYTHON_HOME}/pip \
PYTHONPATH=${PYTHON_HOME}:${PYTHON_HOME}/lib/python${PYTHON_SHORT_VERSION}:${PYTHON_HOME}/lib/python${PYTHON_SHORT_VERSION}/site-packages
@@ -83,6 +84,6 @@ COPY --from=builder /tmp/build/node_modules/. /ql/node_modules/
WORKDIR ${QL_DIR}
HEALTHCHECK --interval=5s --timeout=2s --retries=20 \
CMD curl -sf --noproxy '*' http://127.0.0.1:5700/api/health || exit 1
CMD curl -sf --noproxy '*' http://127.0.0.1:${QlPort:-5700}/api/health || exit 1
ENTRYPOINT ["./docker/docker-entrypoint.sh"]
-2
View File
@@ -1,7 +1,5 @@
#!/bin/bash
export PATH="$HOME/bin:$PATH"
dir_shell=/ql/shell
. $dir_shell/share.sh
+2 -2
View File
@@ -77,9 +77,9 @@
"js-yaml": "^4.1.0",
"jsonwebtoken": "^9.0.2",
"lodash": "^4.17.21",
"multer": "1.4.5-lts.1",
"multer": "2.1.1",
"node-schedule": "^2.1.0",
"nodemailer": "^6.9.16",
"nodemailer": "^8.0.1",
"p-queue-cjs": "7.3.4",
"@bufbuild/protobuf": "^2.10.0",
"ps-tree": "^1.2.0",
+568 -259
View File
File diff suppressed because it is too large Load Diff
-74
View File
@@ -111,76 +111,6 @@ add_cron() {
notify_api "$path 新增任务" "$detail"
}
## 自动安装订阅仓库中的Python依赖
auto_install_python_deps() {
local repo_path="$1"
local uniq_path="$2"
echo -e "\n检测订阅仓库中的Python依赖文件...\n"
get_token
# 检查 requirements.txt
if [[ -f "${repo_path}/requirements.txt" ]]; then
echo -e "发现 requirements.txt,开始自动安装依赖...\n"
local req_file="${dir_scripts}/${uniq_path}/requirements.txt"
# 确保目标目录存在
make_dir "${dir_scripts}/${uniq_path}"
# 复制文件并检查结果
if cp -f "${repo_path}/requirements.txt" "${req_file}" 2>/dev/null; then
# 调用API添加依赖安装任务
local dep_name="${uniq_path}/requirements.txt"
local currentTimeStamp=$(date +%s)
local result=$(curl -s --noproxy "*" "http://127.0.0.1:${ql_port}/open/dependencies?t=$currentTimeStamp" \
-X POST \
-H "Content-Type: application/json;charset=UTF-8" \
-H "Authorization: Bearer ${__ql_token__}" \
--data-raw "[{\"name\":\"${dep_name}\",\"type\":1,\"remark\":\"自动检测:${uniq_path} 订阅依赖\"}]" 2>/dev/null)
local code=$(echo "$result" | jq -r '.code' 2>/dev/null)
if [[ "$code" == "200" ]]; then
echo -e "已添加 requirements.txt 依赖安装任务\n"
else
echo -e "添加 requirements.txt 依赖失败,请手动添加\n"
fi
else
echo -e "复制 requirements.txt 失败,跳过自动安装\n"
fi
fi
# 检查 pyproject.toml
if [[ -f "${repo_path}/pyproject.toml" ]]; then
echo -e "发现 pyproject.toml,开始自动安装依赖...\n"
local pyproject_file="${dir_scripts}/${uniq_path}/pyproject.toml"
# 确保目标目录存在
make_dir "${dir_scripts}/${uniq_path}"
# 复制文件并检查结果
if cp -f "${repo_path}/pyproject.toml" "${pyproject_file}" 2>/dev/null; then
# 调用API添加依赖安装任务
local dep_name="${uniq_path}/pyproject.toml"
local currentTimeStamp=$(date +%s)
local result=$(curl -s --noproxy "*" "http://127.0.0.1:${ql_port}/open/dependencies?t=$currentTimeStamp" \
-X POST \
-H "Content-Type: application/json;charset=UTF-8" \
-H "Authorization: Bearer ${__ql_token__}" \
--data-raw "[{\"name\":\"${dep_name}\",\"type\":1,\"remark\":\"自动检测:${uniq_path} 订阅依赖\"}]" 2>/dev/null)
local code=$(echo "$result" | jq -r '.code' 2>/dev/null)
if [[ "$code" == "200" ]]; then
echo -e "已添加 pyproject.toml 依赖安装任务\n"
else
echo -e "添加 pyproject.toml 依赖失败,请手动添加\n"
fi
else
echo -e "复制 pyproject.toml 失败,跳过自动安装\n"
fi
fi
}
## 更新仓库
update_repo() {
local url="$1"
@@ -207,10 +137,6 @@ update_repo() {
if [[ $exit_status -eq 0 ]]; then
echo -e "拉取 ${uniq_path} 成功...\n"
# 自动检测并安装Python依赖
auto_install_python_deps "${repo_path}" "${uniq_path}"
diff_scripts "$repo_path" "$author" "$path" "$blackword" "$dependence" "$extensions" "$autoAddCron" "$autoDelCron"
else
echo -e "拉取 ${uniq_path} 失败,请检查日志...\n"
+7 -1
View File
@@ -1,5 +1,5 @@
import intl from 'react-intl-universal';
import { SettingOutlined } from '@ant-design/icons';
import { BarChartOutlined, SettingOutlined } from '@ant-design/icons';
import IconFont from '@/components/iconfont';
import { BasicLayoutProps } from '@ant-design/pro-layout';
@@ -30,6 +30,12 @@ export default {
icon: <IconFont type="ql-icon-crontab" />,
component: '@/pages/crontab/index',
},
{
path: '/statistics',
name: intl.get('统计面板'),
icon: <BarChartOutlined />,
component: '@/pages/statistics/index',
},
{
path: '/subscription',
name: intl.get('订阅管理'),
+19
View File
@@ -18,6 +18,25 @@
"青龙": "Qinglong",
"返回首页": "Return to Home",
"保存": "Save",
"统计面板": "Statistics",
"总体概览": "Overview",
"总任务数量": "Total Tasks",
"启用任务数": "Enabled Tasks",
"禁用任务数": "Disabled Tasks",
"今日总执行次数": "Today's Executions",
"今日平均耗时(秒)": "Today's Avg Duration (s)",
"近7日执行趋势": "7-Day Execution Trend",
"今日平均耗时 Top 5": "Top 5 Slowest Today",
"今日执行次数 Top 5": "Top 5 Most Frequent Today",
"排名": "Rank",
"任务名称": "Task Name",
"平均耗时(秒)": "Avg Duration (s)",
"最长单次(秒)": "Max Duration (s)",
"今日执行次数": "Today's Count",
"今日暂无执行记录": "No execution records today",
"暂无数据": "No data",
"次": "times",
"刷新": "Refresh",
"日志": "Log",
"脚本": "Script",
"确认保存文件": "Confirm to Save File",
+19
View File
@@ -18,6 +18,25 @@
"青龙": "青龙",
"返回首页": "返回首页",
"保存": "保存",
"统计面板": "统计面板",
"总体概览": "总体概览",
"总任务数量": "总任务数量",
"启用任务数": "启用任务数",
"禁用任务数": "禁用任务数",
"今日总执行次数": "今日总执行次数",
"今日平均耗时(秒)": "今日平均耗时(秒)",
"近7日执行趋势": "近7日执行趋势",
"今日平均耗时 Top 5": "今日平均耗时 Top 5",
"今日执行次数 Top 5": "今日执行次数 Top 5",
"排名": "排名",
"任务名称": "任务名称",
"平均耗时(秒)": "平均耗时(秒)",
"最长单次(秒)": "最长单次(秒)",
"今日执行次数": "今日执行次数",
"今日暂无执行记录": "今日暂无执行记录",
"暂无数据": "暂无数据",
"次": "次",
"刷新": "刷新",
"日志": "日志",
"脚本": "脚本",
"确认保存文件": "确认保存文件",
+2 -18
View File
@@ -22,9 +22,6 @@ const DependenceModal = ({
}) => {
const [form] = Form.useForm();
const [loading, setLoading] = useState(false);
const [selectedType, setSelectedType] = useState(
DependenceTypes[defaultType as any],
);
const handleOk = async (values: any) => {
setLoading(true);
@@ -93,7 +90,7 @@ const DependenceModal = ({
label={intl.get('依赖类型')}
initialValue={DependenceTypes[defaultType as any]}
>
<Select onChange={(value) => setSelectedType(value)}>
<Select>
{config.dependenceTypes.map((x, i) => (
<Option key={i} value={i}>
{x}
@@ -124,24 +121,11 @@ const DependenceModal = ({
whitespace: true,
},
]}
tooltip={
selectedType === DependenceTypes.python3
? intl.get(
'Python支持多种安装方式:\n1. 包名(如:requests\n2. GitHub链接(如:git+https://github.com/user/repo.git\n3. requirements文件路径(如:path/to/requirements.txt\n4. pyproject.toml文件路径',
)
: undefined
}
>
<Input.TextArea
rows={4}
autoSize={{ minRows: 1, maxRows: 5 }}
placeholder={
selectedType === DependenceTypes.python3
? intl.get(
'支持包名、GitHub链接、requirements.txt或pyproject.toml路径',
)
: intl.get('请输入依赖名称')
}
placeholder={intl.get('请输入依赖名称')}
/>
</Form.Item>
<Form.Item name="remark" label={intl.get('备注')}>
+17
View File
@@ -0,0 +1,17 @@
.stats-section {
margin-bottom: 16px;
}
.trend-chart-wrapper {
width: 100%;
overflow: hidden;
}
.trend-chart-empty {
display: flex;
align-items: center;
justify-content: center;
height: 200px;
color: #999;
font-size: 14px;
}
+402
View File
@@ -0,0 +1,402 @@
import { SharedContext } from '@/layouts';
import config from '@/utils/config';
import { request } from '@/utils/http';
import { BarChartOutlined, ReloadOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-layout';
import { useOutletContext } from '@umijs/max';
import {
Button,
Card,
Col,
Row,
Statistic,
Table,
Tooltip,
Typography,
} from 'antd';
import { ColumnProps } from 'antd/lib/table';
import React, { useEffect, useState } from 'react';
import intl from 'react-intl-universal';
import './index.less';
const { Title } = Typography;
interface StatsData {
total: number;
enabled: number;
disabled: number;
today: {
count: number;
avgDuration: number;
};
}
interface TrendItem {
date: string;
count: number;
}
interface TopDurationItem {
cron_id: number;
cron_name: string;
count: number;
avgDuration: number;
maxDuration: number;
}
interface TopCountItem {
cron_id: number;
cron_name: string;
count: number;
avgDuration: number;
}
const TrendChart = ({ data }: { data: TrendItem[] }) => {
if (!data || data.length === 0) {
return (
<div className="trend-chart-empty">
{intl.get('暂无数据')}
</div>
);
}
const width = 600;
const height = 200;
const paddingLeft = 40;
const paddingRight = 20;
const paddingTop = 20;
const paddingBottom = 40;
const chartWidth = width - paddingLeft - paddingRight;
const chartHeight = height - paddingTop - paddingBottom;
const maxCount = Math.max(...data.map((d) => d.count), 1);
const points = data.map((d, i) => ({
x: paddingLeft + (i / Math.max(data.length - 1, 1)) * chartWidth,
y: paddingTop + chartHeight - (d.count / maxCount) * chartHeight,
...d,
}));
const pathD = points
.map((p, i) => `${i === 0 ? 'M' : 'L'} ${p.x.toFixed(1)} ${p.y.toFixed(1)}`)
.join(' ');
const areaD =
pathD +
` L ${points[points.length - 1].x.toFixed(1)} ${(paddingTop + chartHeight).toFixed(1)}` +
` L ${points[0].x.toFixed(1)} ${(paddingTop + chartHeight).toFixed(1)} Z`;
const yTicks = [0, Math.ceil(maxCount / 2), maxCount];
return (
<div className="trend-chart-wrapper">
<svg
viewBox={`0 0 ${width} ${height}`}
preserveAspectRatio="xMidYMid meet"
style={{ width: '100%', height: 200 }}
>
{/* Grid lines */}
{yTicks.map((tick) => {
const y =
paddingTop + chartHeight - (tick / maxCount) * chartHeight;
return (
<g key={tick}>
<line
x1={paddingLeft}
y1={y}
x2={paddingLeft + chartWidth}
y2={y}
stroke="#f0f0f0"
strokeWidth={1}
/>
<text
x={paddingLeft - 6}
y={y + 4}
textAnchor="end"
fontSize={10}
fill="#999"
>
{tick}
</text>
</g>
);
})}
{/* Area fill */}
<path d={areaD} fill="rgba(24, 144, 255, 0.1)" />
{/* Line */}
<path
d={pathD}
fill="none"
stroke="#1890ff"
strokeWidth={2}
strokeLinejoin="round"
strokeLinecap="round"
/>
{/* Points */}
{points.map((p, i) => (
<Tooltip
key={i}
title={`${p.date}: ${p.count} ${intl.get('次')}`}
>
<circle
cx={p.x}
cy={p.y}
r={4}
fill="#1890ff"
stroke="#fff"
strokeWidth={2}
style={{ cursor: 'pointer' }}
/>
</Tooltip>
))}
{/* X axis labels */}
{points.map((p, i) => (
<text
key={i}
x={p.x}
y={height - 8}
textAnchor="middle"
fontSize={10}
fill="#999"
>
{p.date}
</text>
))}
{/* Axes */}
<line
x1={paddingLeft}
y1={paddingTop}
x2={paddingLeft}
y2={paddingTop + chartHeight}
stroke="#e8e8e8"
strokeWidth={1}
/>
<line
x1={paddingLeft}
y1={paddingTop + chartHeight}
x2={paddingLeft + chartWidth}
y2={paddingTop + chartHeight}
stroke="#e8e8e8"
strokeWidth={1}
/>
</svg>
</div>
);
};
const Statistics = () => {
const { headerStyle, isPhone } = useOutletContext<SharedContext>();
const [stats, setStats] = useState<StatsData | null>(null);
const [trend, setTrend] = useState<TrendItem[]>([]);
const [topDuration, setTopDuration] = useState<TopDurationItem[]>([]);
const [topCount, setTopCount] = useState<TopCountItem[]>([]);
const [loading, setLoading] = useState(true);
const loadAll = async () => {
setLoading(true);
try {
const [
statsRes,
trendRes,
topDurationRes,
topCountRes,
] = await Promise.all([
request.get(`${config.apiPrefix}crons/stats`),
request.get(`${config.apiPrefix}crons/stats/trend`),
request.get(`${config.apiPrefix}crons/stats/top-duration`),
request.get(`${config.apiPrefix}crons/stats/top-count`),
]);
if (statsRes.code === 200) setStats(statsRes.data);
if (trendRes.code === 200) setTrend(trendRes.data);
if (topDurationRes.code === 200) setTopDuration(topDurationRes.data);
if (topCountRes.code === 200) setTopCount(topCountRes.data);
} catch (e) {
console.error(e);
} finally {
setLoading(false);
}
};
useEffect(() => {
loadAll();
}, []);
const topDurationColumns: ColumnProps<TopDurationItem>[] = [
{
title: intl.get('排名'),
key: 'rank',
width: 60,
render: (_: any, __: any, index: number) => index + 1,
},
{
title: intl.get('任务名称'),
dataIndex: 'cron_name',
key: 'cron_name',
ellipsis: true,
},
{
title: intl.get('平均耗时(秒)'),
dataIndex: 'avgDuration',
key: 'avgDuration',
width: 120,
render: (v: number) => `${v}s`,
},
{
title: intl.get('最长单次(秒)'),
dataIndex: 'maxDuration',
key: 'maxDuration',
width: 120,
render: (v: number) => `${v}s`,
},
];
const topCountColumns: ColumnProps<TopCountItem>[] = [
{
title: intl.get('排名'),
key: 'rank',
width: 60,
render: (_: any, __: any, index: number) => index + 1,
},
{
title: intl.get('任务名称'),
dataIndex: 'cron_name',
key: 'cron_name',
ellipsis: true,
},
{
title: intl.get('今日执行次数'),
dataIndex: 'count',
key: 'count',
width: 120,
},
{
title: intl.get('平均耗时(秒)'),
dataIndex: 'avgDuration',
key: 'avgDuration',
width: 120,
render: (v: number) => `${v}s`,
},
];
return (
<PageContainer
header={{
style: headerStyle,
}}
title={
<span>
<BarChartOutlined style={{ marginRight: 8 }} />
{intl.get('统计面板')}
</span>
}
extra={[
<Button
key="refresh"
icon={<ReloadOutlined />}
loading={loading}
onClick={loadAll}
>
{intl.get('刷新')}
</Button>,
]}
>
{/* Section 1: Overview Cards */}
<Card
className="stats-section"
title={intl.get('总体概览')}
loading={loading}
>
<Row gutter={[16, 16]}>
<Col xs={12} sm={8} md={6} lg={4}>
<Statistic
title={intl.get('总任务数量')}
value={stats?.total ?? '-'}
/>
</Col>
<Col xs={12} sm={8} md={6} lg={4}>
<Statistic
title={intl.get('启用任务数')}
value={stats?.enabled ?? '-'}
valueStyle={{ color: '#52c41a' }}
/>
</Col>
<Col xs={12} sm={8} md={6} lg={4}>
<Statistic
title={intl.get('禁用任务数')}
value={stats?.disabled ?? '-'}
valueStyle={{ color: '#d9d9d9' }}
/>
</Col>
<Col xs={12} sm={8} md={6} lg={4}>
<Statistic
title={intl.get('今日总执行次数')}
value={stats?.today?.count ?? '-'}
valueStyle={{ color: '#1890ff' }}
/>
</Col>
<Col xs={12} sm={8} md={6} lg={4}>
<Statistic
title={intl.get('今日平均耗时(秒)')}
value={stats?.today?.avgDuration ?? '-'}
suffix="s"
valueStyle={{ color: '#faad14' }}
/>
</Col>
</Row>
</Card>
{/* Section 2: 7-day Trend */}
<Card
className="stats-section"
title={intl.get('近7日执行趋势')}
loading={loading}
>
<TrendChart data={trend} />
</Card>
{/* Section 3 & 4: Top Tables */}
<Row gutter={[16, 16]}>
<Col xs={24} lg={12}>
<Card
className="stats-section"
title={intl.get('今日平均耗时 Top 5')}
loading={loading}
>
<Table
dataSource={topDuration}
columns={topDurationColumns}
rowKey="cron_id"
pagination={false}
size="small"
locale={{ emptyText: intl.get('今日暂无执行记录') }}
/>
</Card>
</Col>
<Col xs={24} lg={12}>
<Card
className="stats-section"
title={intl.get('今日执行次数 Top 5')}
loading={loading}
>
<Table
dataSource={topCount}
columns={topCountColumns}
rowKey="cron_id"
pagination={false}
size="small"
locale={{ emptyText: intl.get('今日暂无执行记录') }}
/>
</Card>
</Col>
</Row>
</PageContainer>
);
};
export default Statistics;
+1
View File
@@ -504,6 +504,7 @@ export default {
'/login': intl.get('登录'),
'/initialization': intl.get('初始化'),
'/crontab': intl.get('定时任务'),
'/statistics': intl.get('统计面板'),
'/env': intl.get('环境变量'),
'/subscription': intl.get('订阅管理'),
'/config': intl.get('配置文件'),
+5 -10
View File
@@ -1,11 +1,6 @@
version: 2.20.1
changeLogLink: https://t.me/jiao_long/433
publishTime: 2025-12-26 22:00
version: 2.20.2
changeLogLink: https://t.me/jiao_long/434
publishTime: 2026-03-01 1800
changeLog: |
1. 修复获取依赖管理列表
2. notify.js 修复 TG_PROXY_AUTH 参数拼接
3. QLAPI.notify larkSecret 参数
4. 修复 cron parser 定时规则校验
5. 修复设置 baseUrl 后无法访问
6. 修复环境变量排序
7. 修复定时任务无法停止
1. 修复 path 安全漏洞(重要)