fix(users): enforce read-only ownership and revocable managed sessions

This commit is contained in:
whyour committed 2026-10-12 01:13:53 +08:00
commit aafd85cbcc
505 files changed
+59207 -6463

No files matched your search

+17 -49
View File
@@ -3,46 +3,34 @@ import Logger from '../loaders/logger';
import { performance } from 'perf_hooks';
import { metricsService } from '../services/metrics';
interface RequestMetrics {
method: string;
path: string;
duration: number;
statusCode: number;
timestamp: number;
platform?: string;
}
const requestMetrics: RequestMetrics[] = [];
const UNMONITORED_PATH_SUFFIXES = ['/api/health', '/open/health'];
const HTTP_METRIC_SAMPLE_INTERVAL = 10;
let requestSampleOffset = 0;
export const monitoringMiddleware = (
req: Request,
res: Response,
next: NextFunction,
) => {
if (UNMONITORED_PATH_SUFFIXES.some((path) => req.path.endsWith(path))) {
return next();
}
const start = performance.now();
const originalEnd = res.end;
res.end = function (chunk?: any, encoding?: any, cb?: any) {
const duration = performance.now() - start;
const metric: RequestMetrics = {
method: req.method,
path: req.path,
duration,
statusCode: res.statusCode,
timestamp: Date.now(),
platform: req.platform,
};
requestMetrics.push(metric);
metricsService.record('http_request', duration, {
method: req.method,
path: req.path,
statusCode: res.statusCode.toString(),
...(req.platform && { platform: req.platform }),
});
if (requestMetrics.length > 1000) {
requestMetrics.shift();
const shouldSample = requestSampleOffset === 0;
requestSampleOffset =
(requestSampleOffset + 1) % HTTP_METRIC_SAMPLE_INTERVAL;
if (shouldSample) {
metricsService.record('http_request', duration, {
method: req.method,
path: req.path,
statusCode: res.statusCode.toString(),
...(req.platform && { platform: req.platform }),
});
}
if (duration > 1000) {
@@ -58,23 +46,3 @@ export const monitoringMiddleware = (
next();
};
export const getMetrics = () => {
return {
totalRequests: requestMetrics.length,
averageDuration:
requestMetrics.reduce((acc, curr) => acc + curr.duration, 0) /
requestMetrics.length,
requestsByMethod: requestMetrics.reduce((acc, curr) => {
acc[curr.method] = (acc[curr.method] || 0) + 1;
return acc;
}, {} as Record<string, number>),
requestsByPlatform: requestMetrics.reduce((acc, curr) => {
if (curr.platform) {
acc[curr.platform] = (acc[curr.platform] || 0) + 1;
}
return acc;
}, {} as Record<string, number>),
recentRequests: requestMetrics.slice(-10),
};
};
+23
View File
@@ -0,0 +1,23 @@
import type { NextFunction, Request, Response } from 'express';
export default function protectedPathCase(
req: Request,
res: Response,
next: NextFunction,
) {
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',
});
}
return next();
}
+14
View File
@@ -0,0 +1,14 @@
import { ErrorRequestHandler } from 'express';
import { UniqueConstraintError } from 'sequelize';
import { t } from '../shared/i18n';
// Handle the database constraint itself so concurrent writes are covered too.
const uniqueConstraintError: ErrorRequestHandler = (err, req, res, next) => {
if (!(err instanceof UniqueConstraintError)) return next(err);
// Constraint details can contain environment values or application credentials.
res
.status(409)
.json({ code: 409, message: t('资源已存在,请检查重复的名称或值') });
};
export default uniqueConstraintError;
+68
View File
@@ -0,0 +1,68 @@
import { Request, Response, NextFunction } from 'express';
import { Op } from 'sequelize';
import { EnvModel } from '../data/env';
import { CrontabModel } from '../data/cron';
import { SubscriptionModel } from '../data/subscription';
// Ordinary users are read-only until task workers and shared files are isolated.
export async function userAccess(
req: Request,
res: Response,
next: NextFunction,
) {
if (!req.user || req.user.role === 0) return next();
const userId = req.user.userId;
if (!Number.isSafeInteger(userId) || userId! <= 0)
return res.status(403).json({ code: 403, message: '需要有效用户会话' });
const pathname = req.path.replace(/\/$/, '') || '/';
if (
(req.method === 'GET' &&
['/user', '/system', '/health'].includes(pathname)) ||
(req.method === 'POST' && pathname === '/user/logout')
)
return next();
if (req.method === 'GET' && pathname === '/crons/views')
return res.json({ code: 200, data: [] });
const match = pathname.match(
/^\/(envs|crons|subscriptions)(?:\/([1-9][0-9]*))?$/,
);
if (req.method !== 'GET' || !match)
return res
.status(403)
.json({
code: 403,
message: '普通用户只读自己的数据,执行和系统修改由管理员负责',
});
try {
const models: Record<string, any> = {
envs: EnvModel,
crons: CrontabModel,
subscriptions: SubscriptionModel,
};
const model = models[match[1]];
const where: any = { userId };
if (match[2]) {
const id = Number(match[2]);
if (!Number.isSafeInteger(id))
return res.status(400).json({ code: 400, message: '无效 ID' });
where.id = id;
const doc = await model.findOne({ where });
return doc
? res.json({ code: 200, data: doc.get({ plain: true }) })
: res.status(404).json({ code: 404, message: '数据不存在' });
}
const search =
typeof req.query.searchValue === 'string'
? req.query.searchValue.slice(0, 1024)
: '';
if (search) where.name = { [Op.like]: `%${search}%` };
const docs = await model.findAll({ where, order: [['createdAt', 'DESC']] });
const data = docs.map((doc: any) => doc.get({ plain: true }));
return res.json({
code: 200,
data: match[1] === 'crons' ? { data, total: data.length } : data,
});
} catch (error) {
return next(error);
}
}