fix: address dependency and code scanning vulnerabilities

Upgrade SQLite to 1.1.5 and tar to 7.5.23 without a tar override.
Update Umi, React Router, uuid, lint-staged and compatible transitive
security fixes while retaining the existing ProLayout version.

Constrain script file operations to checked paths, serialize Python
environment values safely, and keep resource-intensive API limits with
room for normal bulk use. Avoid dynamic child-process code in upgrade
tests and load offline installer scripts from a fixed working directory.

Cover dependency compatibility, rate limits, offline recovery and npm
packaging, including the decoder patch required by existing Umi consumers.
This commit is contained in:
whyour committed 2026-11-20 10:11:04 +08:00
1 parent 0902bc074d
commit 9023a654df
20 files changed
+3049 -2746

No files matched your search

+2
View File
@@ -9,6 +9,7 @@ import { t } from '../shared/i18n';
import ConfigService from '../services/config'; import ConfigService from '../services/config';
import { writeFileWithLock } from '../shared/utils'; import { writeFileWithLock } from '../shared/utils';
import { resolveFileAccess } from '../shared/fileAccess'; import { resolveFileAccess } from '../shared/fileAccess';
import { rateLimit } from 'express-rate-limit';
const route = Router(); const route = Router();
export default (app: Router) => { export default (app: Router) => {
@@ -30,6 +31,7 @@ export default (app: Router) => {
route.get( route.get(
'/files', '/files',
rateLimit({ windowMs: 60 * 1000, limit: 600 }),
async (req: Request, res: Response, next: NextFunction) => { async (req: Request, res: Response, next: NextFunction) => {
const logger: Logger = Container.get('logger'); const logger: Logger = Container.get('logger');
try { try {
+2
View File
@@ -13,6 +13,7 @@ import {
import LogService from '../services/log'; import LogService from '../services/log';
import { InstanceStatus, RunningInstanceModel } from '../data/runningInstance'; import { InstanceStatus, RunningInstanceModel } from '../data/runningInstance';
import { MAX_LOG_CHUNK_BYTES, readLogChunk } from '../shared/logReader'; import { MAX_LOG_CHUNK_BYTES, readLogChunk } from '../shared/logReader';
import { rateLimit } from 'express-rate-limit';
const route = Router(); const route = Router();
const blacklist = ['.tmp']; const blacklist = ['.tmp'];
@@ -138,6 +139,7 @@ export default (app: Router) => {
route.post( route.post(
'/download', '/download',
rateLimit({ windowMs: 60 * 1000, limit: 600 }),
celebrate({ celebrate({
body: Joi.object({ body: Joi.object({
filename: Joi.string().required(), filename: Joi.string().required(),
+63 -21
View File
@@ -1,4 +1,7 @@
import { directoryCheckHandler, directoryPageHandler } from '../shared/directoryPageRoute'; import {
directoryCheckHandler,
directoryPageHandler,
} from '../shared/directoryPageRoute';
import { randomUUID } from 'crypto'; import { randomUUID } from 'crypto';
import { resolveFileAccess } from '../shared/fileAccess'; import { resolveFileAccess } from '../shared/fileAccess';
import { fileExist, readDirs, readDir, rmPath, IFile } from '../config/util'; import { fileExist, readDirs, readDir, rmPath, IFile } from '../config/util';
@@ -14,6 +17,7 @@ import ScriptHistoryService from '../services/scriptHistory';
import { t } from '../shared/i18n'; import { t } from '../shared/i18n';
import multer from 'multer'; import multer from 'multer';
import { writeFileWithLock } from '../shared/utils'; import { writeFileWithLock } from '../shared/utils';
import { rateLimit } from 'express-rate-limit';
import { import {
ScriptHistoryError, ScriptHistoryError,
HistoryUnavailableError, HistoryUnavailableError,
@@ -26,7 +30,7 @@ const blacklist = [
'pnpm-lock.yaml', 'pnpm-lock.yaml',
'yarn.lock', 'yarn.lock',
'package-lock.json', 'package-lock.json',
]; ];
function isPathAllowed(targetPath: string): boolean { function isPathAllowed(targetPath: string): boolean {
const resolved = path.resolve(targetPath); const resolved = path.resolve(targetPath);
@@ -44,6 +48,26 @@ function isPathAllowed(targetPath: string): boolean {
); );
} }
// Return the checked, normalized value so filesystem calls never reuse the
// original request path. Keep the root boundary visible to static analysis.
function writablePath(targetPath: string): string {
const normalized = resolve(targetPath);
if (!isPathAllowed(normalized)) return '';
for (const writableRoot of config.writePathList) {
const root = resolve(writableRoot) + sep;
if (normalized.startsWith(root)) return normalized;
}
return '';
}
function uploadedPath(filePath: string): string {
const normalized = resolve(filePath);
const root = resolve(config.tmpPath) + sep;
if (!normalized.startsWith(root)) return '';
if (!resolveFileAccess(config.tmpPath, [normalized])) return '';
return normalized;
}
async function existingWritableRealPath(targetPath: string): Promise<string> { async function existingWritableRealPath(targetPath: string): Promise<string> {
if (!isPathAllowed(targetPath)) { if (!isPathAllowed(targetPath)) {
throw new ScriptHistoryError(403, '暂无权限'); throw new ScriptHistoryError(403, '暂无权限');
@@ -84,8 +108,14 @@ const upload = multer({ storage: storage });
export default (app: Router) => { export default (app: Router) => {
app.use('/scripts', route); app.use('/scripts', route);
route.get('/entries', ...directoryPageHandler(() => config.scriptPath, blacklist, false)); route.get(
route.post('/entries/check', ...directoryCheckHandler(() => config.scriptPath, blacklist)); '/entries',
...directoryPageHandler(() => config.scriptPath, blacklist, false),
);
route.post(
'/entries/check',
...directoryCheckHandler(() => config.scriptPath, blacklist),
);
route.get( route.get(
'/', '/',
@@ -244,7 +274,10 @@ export default (app: Router) => {
'/', '/',
(req: Request, res: Response, next: NextFunction) => { (req: Request, res: Response, next: NextFunction) => {
res.on('finish', () => { res.on('finish', () => {
if (req.file?.path) fs.unlink(req.file.path).catch(() => undefined); if (req.file?.path) {
const temporaryPath = uploadedPath(req.file.path);
if (temporaryPath) fs.unlink(temporaryPath).catch(() => undefined);
}
}); });
next(); next();
}, },
@@ -292,18 +325,19 @@ export default (app: Router) => {
} }
if (req.file) { if (req.file) {
const uploadPath = join(path, filename); const uploadPath = writablePath(join(path, filename));
if (!isPathAllowed(uploadPath)) { const temporaryPath = uploadedPath(req.file.path);
if (!uploadPath || !temporaryPath) {
return res.send({ code: 403, message: t('暂无权限') }); return res.send({ code: 403, message: t('暂无权限') });
} }
await fs.copyFile(req.file.path, uploadPath); await fs.copyFile(temporaryPath, uploadPath);
await fs.unlink(req.file.path); await fs.unlink(temporaryPath);
return res.send({ code: 200 }); return res.send({ code: 200 });
} }
if (directory) { if (directory) {
const dirPath = join(path, directory); const dirPath = writablePath(join(path, directory));
if (!isPathAllowed(dirPath)) { if (!dirPath) {
return res.send({ code: 403, message: t('暂无权限') }); return res.send({ code: 403, message: t('暂无权限') });
} }
await fs.mkdir(dirPath, { recursive: true }); await fs.mkdir(dirPath, { recursive: true });
@@ -313,9 +347,9 @@ export default (app: Router) => {
if (!originFilename) { if (!originFilename) {
originFilename = filename; originFilename = filename;
} }
const originFilePath = join(path, originFilename); const originFilePath = writablePath(join(path, originFilename));
const filePath = join(path, filename); const filePath = writablePath(join(path, filename));
if (!isPathAllowed(filePath) || !isPathAllowed(originFilePath)) { if (!filePath || !originFilePath) {
return res.send({ code: 403, message: t('暂无权限') }); return res.send({ code: 403, message: t('暂无权限') });
} }
// Check the canonical parent directly at the directory creation boundary. // Check the canonical parent directly at the directory creation boundary.
@@ -462,6 +496,7 @@ export default (app: Router) => {
route.post( route.post(
'/download', '/download',
rateLimit({ windowMs: 60 * 1000, limit: 600 }),
celebrate({ celebrate({
body: Joi.object({ body: Joi.object({
filename: Joi.string().required(), filename: Joi.string().required(),
@@ -513,8 +548,10 @@ export default (app: Router) => {
path = ''; path = '';
} }
const { name, ext } = parse(filename); const { name, ext } = parse(filename);
const filePath = join(config.scriptPath, path, `${name}.swap${ext}`); const filePath = writablePath(
if (!isPathAllowed(filePath)) { join(config.scriptPath, path, `${name}.swap${ext}`),
);
if (!filePath) {
return res.send({ code: 403, message: t('暂无权限') }); return res.send({ code: 403, message: t('暂无权限') });
} }
await writeFileWithLock(filePath, content || ''); await writeFileWithLock(filePath, content || '');
@@ -544,8 +581,10 @@ export default (app: Router) => {
path = ''; path = '';
} }
const { name, ext } = parse(filename); const { name, ext } = parse(filename);
const filePath = join(config.scriptPath, path, `${name}.swap${ext}`); const filePath = writablePath(
if (!isPathAllowed(filePath)) { join(config.scriptPath, path, `${name}.swap${ext}`),
);
if (!filePath) {
return res.send({ code: 403, message: t('暂无权限') }); return res.send({ code: 403, message: t('暂无权限') });
} }
const logPath = resolveFileAccess(config.logPath, [ const logPath = resolveFileAccess(config.logPath, [
@@ -573,6 +612,7 @@ export default (app: Router) => {
route.put( route.put(
'/rename', '/rename',
rateLimit({ windowMs: 60 * 1000, limit: 600 }),
celebrate({ celebrate({
body: Joi.object({ body: Joi.object({
filename: Joi.string().required(), filename: Joi.string().required(),
@@ -590,9 +630,11 @@ export default (app: Router) => {
if (!path) { if (!path) {
path = ''; path = '';
} }
const filePath = join(config.scriptPath, path, filename); const filePath = writablePath(join(config.scriptPath, path, filename));
const newPath = join(config.scriptPath, path, newFilename); const newPath = writablePath(
if (!isPathAllowed(filePath) || !isPathAllowed(newPath)) { join(config.scriptPath, path, newFilename),
);
if (!filePath || !newPath) {
return res.send({ code: 403, message: t('暂无权限') }); return res.send({ code: 403, message: t('暂无权限') });
} }
await fs.rename(filePath, newPath); await fs.rename(filePath, newPath);
+1
View File
@@ -424,6 +424,7 @@ export default (app: Router) => {
route.put( route.put(
'/auth/reset', '/auth/reset',
rateLimit({ windowMs: 15 * 60 * 1000, limit: 60 }),
celebrate({ celebrate({
body: Joi.object({ body: Joi.object({
retries: Joi.number().optional(), retries: Joi.number().optional(),
+5 -9
View File
@@ -264,7 +264,7 @@ export default class EnvService {
const groups = groupBy(envs, 'name'); const groups = groupBy(envs, 'name');
let env_string = ''; let env_string = '';
let js_env_string = ''; let js_env_string = '';
let py_env_string = 'import os\n'; let py_env_string = 'import os, json\n';
for (const key in groups) { for (const key in groups) {
if (Object.prototype.hasOwnProperty.call(groups, key)) { if (Object.prototype.hasOwnProperty.call(groups, key)) {
const group = groups[key]; const group = groups[key];
@@ -277,17 +277,13 @@ export default class EnvService {
.replace(/'/g, "'\\''") .replace(/'/g, "'\\''")
.trim(); .trim();
env_string += `export ${key}='${value}'\n`; env_string += `export ${key}='${value}'\n`;
const _env_value = `${group
.map((x) => x.value)
.join('&')
.replace(/\\/g, '\\\\')}`;
js_env_string += `process.env[${JSON.stringify(key)}]=${JSON.stringify( js_env_string += `process.env[${JSON.stringify(key)}]=${JSON.stringify(
group.map((x) => x.value).join('&'), group.map((x) => x.value).join('&'),
)};\n`; )};\n`;
py_env_string += `os.environ['${key}']='''${_env_value.replace( // Serialize data instead of constructing an escaped Python literal.
/\'/g, py_env_string += `os.environ['${key}']=json.loads(${JSON.stringify(
"\\'", JSON.stringify(group.map((x) => x.value).join('&')),
)}'''\n`; )})\n`;
} }
} }
} }
+4 -4
View File
@@ -15,7 +15,7 @@
"@types/node": "22.19.0", "@types/node": "22.19.0",
"commander": "15.0.0", "commander": "15.0.0",
"esbuild": "0.28.2", "esbuild": "0.28.2",
"tar": "7.5.20", "tar": "7.5.23",
"typescript": "5.2.2" "typescript": "5.2.2"
}, },
"engines": { "engines": {
@@ -573,9 +573,9 @@
} }
}, },
"node_modules/tar": { "node_modules/tar": {
"version": "7.5.20", "version": "7.5.23",
"resolved": "https://registry.npmjs.org/tar/-/tar-7.5.20.tgz", "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.23.tgz",
"integrity": "sha512-9FcyK4PA6+WbzlTM9WhQm6vB5W7cP7dUiPsv1g7YDwEQnQ1CGpK3MGlKk/ITVWMk05kHZuBhmVhiv8LZoy/PFQ==", "integrity": "sha512-lkukzdoGngZHJZXxW4S/E4Fp9ghTDlyZXrQGRNoJ/LXvDKcXUTq2sg5yQe74po7Voea6n/IN09+wE/QvJMiifA==",
"dev": true, "dev": true,
"license": "BlueOak-1.0.0", "license": "BlueOak-1.0.0",
"dependencies": { "dependencies": {
+1 -1
View File
@@ -27,7 +27,7 @@
"esbuild": "0.28.2", "esbuild": "0.28.2",
"typescript": "5.2.2", "typescript": "5.2.2",
"@types/node": "22.19.0", "@types/node": "22.19.0",
"tar": "7.5.20" "tar": "7.5.23"
}, },
"license": "Apache-2.0", "license": "Apache-2.0",
"repository": { "repository": {
+1
View File
@@ -8,6 +8,7 @@ ENV NPM_CONFIG_PREFIX=/opt/node-global
ENV PATH=/opt/node-global/bin:${PATH} ENV PATH=/opt/node-global/bin:${PATH}
COPY package.json .npmrc pnpm-lock.yaml /tmp/build/ COPY package.json .npmrc pnpm-lock.yaml /tmp/build/
COPY patches/ /tmp/build/patches/
RUN set -x \ RUN set -x \
&& apk add --no-cache git \ && apk add --no-cache git \
&& npm i -g pnpm@8.3.1 pm2 ts-node typescript@5 \ && npm i -g pnpm@8.3.1 pm2 ts-node typescript@5 \
+1
View File
@@ -8,6 +8,7 @@ ENV NPM_CONFIG_PREFIX=/opt/node-global
ENV PATH=/opt/node-global/bin:${PATH} ENV PATH=/opt/node-global/bin:${PATH}
COPY package.json .npmrc pnpm-lock.yaml /tmp/build/ COPY package.json .npmrc pnpm-lock.yaml /tmp/build/
COPY patches/ /tmp/build/patches/
RUN set -x \ RUN set -x \
&& apk add --no-cache git \ && apk add --no-cache git \
&& npm i -g pnpm@8.3.1 pm2 ts-node typescript@5 \ && npm i -g pnpm@8.3.1 pm2 ts-node typescript@5 \
+1
View File
@@ -8,6 +8,7 @@ RUN apt-get update && \
FROM python:3.11.14-slim-bookworm AS builder FROM python:3.11.14-slim-bookworm AS builder
COPY package.json .npmrc pnpm-lock.yaml /tmp/build/ COPY package.json .npmrc pnpm-lock.yaml /tmp/build/
COPY patches/ /tmp/build/patches/
COPY --from=nodebuilder /usr/local/bin/node /usr/local/bin/ COPY --from=nodebuilder /usr/local/bin/node /usr/local/bin/
COPY --from=nodebuilder /usr/local/lib/node_modules/. /usr/local/lib/node_modules/ COPY --from=nodebuilder /usr/local/lib/node_modules/. /usr/local/lib/node_modules/
RUN set -x && \ RUN set -x && \
+1
View File
@@ -10,6 +10,7 @@ RUN apt-get update && \
# The floating 3.10-slim-bookworm tag no longer includes s390x. # The floating 3.10-slim-bookworm tag no longer includes s390x.
FROM python:3.10.19-slim-bookworm@sha256:23f63358922e79a794f71be8f3723c84e5ccca9638af3f74456dc73d6184499e AS builder FROM python:3.10.19-slim-bookworm@sha256:23f63358922e79a794f71be8f3723c84e5ccca9638af3f74456dc73d6184499e AS builder
COPY package.json .npmrc pnpm-lock.yaml /tmp/build/ COPY package.json .npmrc pnpm-lock.yaml /tmp/build/
COPY patches/ /tmp/build/patches/
COPY --from=nodebuilder /usr/local/bin/node /usr/local/bin/ COPY --from=nodebuilder /usr/local/bin/node /usr/local/bin/
COPY --from=nodebuilder /usr/local/lib/node_modules/. /usr/local/lib/node_modules/ COPY --from=nodebuilder /usr/local/lib/node_modules/. /usr/local/lib/node_modules/
RUN set -x && \ RUN set -x && \
+27 -19
View File
@@ -17,6 +17,7 @@
"back/protos/api.proto", "back/protos/api.proto",
"cli/src/internal/maintenance/*.cjs", "cli/src/internal/maintenance/*.cjs",
"ecosystem.config.js", "ecosystem.config.js",
"patches/*.patch",
"README*.md", "README*.md",
"sample/*.sample.*", "sample/*.sample.*",
"sample/notify.js", "sample/notify.js",
@@ -115,13 +116,20 @@
} }
}, },
"overrides": { "overrides": {
"sqlite3": "npm:@whyour/sqlite3@1.1.4", "sqlite3": "npm:@whyour/sqlite3@1.1.5",
"@codemirror/state": "6.5.4", "@codemirror/state": "6.5.4",
"@codemirror/view": "6.39.16", "@codemirror/view": "6.39.16",
"proxy-addr": "2.0.8", "axios@0": "0.34.0",
"websocket-driver": "0.7.5", "immer@8": "9.0.21",
"brace-expansion@1": "1.1.21", "vite@7": "7.3.7",
"brace-expansion@2": "2.1.7" "decode-uri-component": "0.5.1",
"path-to-regexp@1": "1.9.0",
"path-to-regexp@2": "3.3.0",
"path-to-regexp@8": "8.4.0",
"celebrate>lodash": "4.18.0"
},
"patchedDependencies": {
"decode-uri-component@0.5.1": "patches/decode-uri-component@0.5.1.patch"
} }
}, },
"dependencies": { "dependencies": {
@@ -131,7 +139,7 @@
"@grpc/proto-loader": "^0.8.0", "@grpc/proto-loader": "^0.8.0",
"@keyv/sqlite": "^4.0.1", "@keyv/sqlite": "^4.0.1",
"@otplib/preset-default": "^12.0.1", "@otplib/preset-default": "^12.0.1",
"body-parser": "^1.20.3", "body-parser": "^1.20.9",
"celebrate": "^15.0.3", "celebrate": "^15.0.3",
"chokidar": "^4.0.1", "chokidar": "^4.0.1",
"compression": "1.8.2", "compression": "1.8.2",
@@ -140,7 +148,7 @@
"cross-spawn": "^7.0.6", "cross-spawn": "^7.0.6",
"dayjs": "^1.11.13", "dayjs": "^1.11.13",
"dotenv": "^16.4.6", "dotenv": "^16.4.6",
"express": "^4.21.2", "express": "^4.22.3",
"express-jwt": "^8.4.1", "express-jwt": "^8.4.1",
"express-rate-limit": "^7.4.1", "express-rate-limit": "^7.4.1",
"express-urlrewrite": "^2.0.3", "express-urlrewrite": "^2.0.3",
@@ -152,10 +160,10 @@
"js-yaml": "^4.1.0", "js-yaml": "^4.1.0",
"jsonwebtoken": "^9.0.2", "jsonwebtoken": "^9.0.2",
"keyv": "^5.2.3", "keyv": "^5.2.3",
"lodash": "^4.17.21", "lodash": "^4.18.0",
"multer": "2.4.0", "multer": "2.5.0",
"node-cron": "4.6.0", "node-cron": "4.6.0",
"nodemailer": "^10.0.9", "nodemailer": "^10.1.4",
"p-queue-cjs": "7.3.4", "p-queue-cjs": "7.3.4",
"proper-lockfile": "^4.1.2", "proper-lockfile": "^4.1.2",
"ps-tree": "^1.2.0", "ps-tree": "^1.2.0",
@@ -163,14 +171,14 @@
"request-ip": "3.3.0", "request-ip": "3.3.0",
"sequelize": "6.37.8", "sequelize": "6.37.8",
"sockjs": "^0.3.24", "sockjs": "^0.3.24",
"sqlite3": "npm:@whyour/sqlite3@1.1.4", "sqlite3": "npm:@whyour/sqlite3@1.1.5",
"tar": "7.5.23",
"toad-scheduler": "^3.0.1", "toad-scheduler": "^3.0.1",
"typedi": "^0.10.0", "typedi": "^0.10.0",
"undici": "^7.9.0", "undici": "^7.30.1",
"uuid": "^11.0.3", "uuid": "^11.1.1",
"winston": "^3.17.0", "winston": "^3.17.0",
"winston-daily-rotate-file": "^5.0.0", "winston-daily-rotate-file": "^5.0.0"
"tar": "7.5.20"
}, },
"devDependencies": { "devDependencies": {
"@ant-design/icons": "^5.0.1", "@ant-design/icons": "^5.0.1",
@@ -206,17 +214,17 @@
"@types/uuid": "^8.3.4", "@types/uuid": "^8.3.4",
"@uiw/codemirror-extensions-langs": "^4.21.9", "@uiw/codemirror-extensions-langs": "^4.21.9",
"@uiw/react-codemirror": "^4.21.9", "@uiw/react-codemirror": "^4.21.9",
"@umijs/max": "^4.7.33", "@umijs/max": "^4.7.34",
"@umijs/ssr-darkreader": "^4.9.45", "@umijs/ssr-darkreader": "^4.9.45",
"ahooks": "^3.7.8", "ahooks": "^3.7.8",
"ansi-to-react": "^6.1.6", "ansi-to-react": "^6.1.6",
"antd": "^4.24.16", "antd": "^4.24.16",
"antd-img-crop": "^4.23.0", "antd-img-crop": "^4.23.0",
"axios": "^1.4.0", "axios": "^1.4.0",
"compression-webpack-plugin": "9.2.0", "compression-webpack-plugin": "12.0.0",
"concurrently": "^7.0.0", "concurrently": "^7.0.0",
"file-saver": "2.0.2", "file-saver": "2.0.2",
"lint-staged": "^13.0.3", "lint-staged": "^15.5.2",
"moment": "2.31.0", "moment": "2.31.0",
"monaco-editor": "0.33.0", "monaco-editor": "0.33.0",
"nodemon": "^3.0.1", "nodemon": "^3.0.1",
@@ -235,7 +243,7 @@
"react-dom": "18.3.1", "react-dom": "18.3.1",
"react-hotkeys-hook": "^4.6.1", "react-hotkeys-hook": "^4.6.1",
"react-intl-universal": "^2.12.0", "react-intl-universal": "^2.12.0",
"react-router-dom": "6.26.1", "react-router-dom": "6.30.6",
"react-split-pane": "^0.1.92", "react-split-pane": "^0.1.92",
"sockjs-client": "^1.6.0", "sockjs-client": "^1.6.0",
"ts-node": "^10.9.2", "ts-node": "^10.9.2",
+26
View File
@@ -0,0 +1,26 @@
diff --git a/index.js b/index.js
index 4dfca40730089d0b7a8ad9818bc918240ca8cb89..454d50f086915fea0a38116c8719229d433910a9 100644
--- a/index.js
+++ b/index.js
@@ -136,7 +136,7 @@ function customDecodeURIComponent(input) {
return input.replace(multiMatcher, run => decode(run));
}
-export default function decodeUriComponent(encodedURI) {
+module.exports = function decodeUriComponent(encodedURI) {
if (typeof encodedURI !== 'string') {
throw new TypeError(`Expected \`encodedURI\` to be of type \`string\`, got \`${typeof encodedURI}\``);
}
diff --git a/package.json b/package.json
index 5991062db5af96559ed102a22431f2edf29595a0..c8f13808709e64abbb3e19009bca16d9e988be31 100644
--- a/package.json
+++ b/package.json
@@ -10,7 +10,7 @@
"email": "sam.verschueren@gmail.com",
"url": "github.com/SamVerschueren"
},
- "type": "module",
+ "type": "commonjs",
"exports": {
"types": "./index.d.ts",
"default": "./index.js"
+2494 -2671
View File
File diff suppressed because it is too large. Load diff
+2 -1
View File
@@ -21,6 +21,7 @@ const run = (program, args, options = {}) => execute(program, args, {
...options, ...options,
}); });
const requiredFiles = [ const requiredFiles = [
...Object.values(require('../package.json').pnpm?.patchedDependencies || {}),
'.env.example', 'back/protos/api.proto', 'ecosystem.config.js', 'version.yaml', '.env.example', 'back/protos/api.proto', 'ecosystem.config.js', 'version.yaml',
'shell/upgrade.cjs', 'shell/install-bundle.cjs', 'shell/install-package.cjs', 'shell/upgrade.cjs', 'shell/install-bundle.cjs', 'shell/install-package.cjs',
'shell/upgrade-lock.yaml', 'shell/node-runtime-probe.cjs', 'shell/start.sh', 'shell/start-simplify.sh', 'shell/upgrade-lock.yaml', 'shell/node-runtime-probe.cjs', 'shell/start.sh', 'shell/start-simplify.sh',
@@ -40,7 +41,7 @@ function checkPackedFiles(files) {
const names = new Set(files.map((file) => file.path)); const names = new Set(files.map((file) => file.path));
for (const name of requiredFiles) assert.ok(names.has(name), `Missing npm runtime: ${name}`); for (const name of requiredFiles) assert.ok(names.has(name), `Missing npm runtime: ${name}`);
for (const name of names) { for (const name of names) {
assert.ok(/^(?:package\.json$|LICENSE$|README[^/]*\.md$|\.env\.example$|ecosystem\.config\.js$|version\.yaml$|back\/protos\/api\.proto$|cli\/(?:README[^/]*\.md$|src\/internal\/maintenance\/[^/]+\.cjs$)|sample\/|shell\/|static\/)/.test(name), `Unexpected npm file: ${name}`); assert.ok(requiredFiles.includes(name) || /^(?:package\.json$|LICENSE$|README[^/]*\.md$|\.env\.example$|ecosystem\.config\.js$|version\.yaml$|back\/protos\/api\.proto$|cli\/(?:README[^/]*\.md$|src\/internal\/maintenance\/[^/]+\.cjs$)|sample\/|shell\/|static\/)/.test(name), `Unexpected npm file: ${name}`);
assert.ok(!/^shell\/(?:pub\.sh$|preload\/(?:env\.|notify\.|__ql_notify__\.|lang_env\.sh|.*-notify\.json))/.test(name), `Generated or release-only runtime file: ${name}`); assert.ok(!/^shell\/(?:pub\.sh$|preload\/(?:env\.|notify\.|__ql_notify__\.|lang_env\.sh|.*-notify\.json))/.test(name), `Generated or release-only runtime file: ${name}`);
assert.ok(!/(?:^|\/)__pycache__\/|\.pyc$|(?:^|\/)\.DS_Store$/.test(name), name); assert.ok(!/(?:^|\/)__pycache__\/|\.pyc$|(?:^|\/)\.DS_Store$/.test(name), name);
assert.notEqual(name, 'sample/tool.ts'); assert.notEqual(name, 'sample/tool.ts');
+2 -3
View File
@@ -77,11 +77,10 @@ async function installBundle(argv = process.argv.slice(2), env = process.env) {
'--noprofile', '--noprofile',
'--norc', '--norc',
'-c', '-c',
'. "$1/shell/share.sh"\n. "$1/shell/env.sh"\nimport_config\nexport QlPort="${ql_port:-${QlPort:-5700}}" QlBaseUrl="${ql_base_url:-${QlBaseUrl:-/}}"\nenv -0', '. ./shell/share.sh\n. ./shell/env.sh\nimport_config\nexport QlPort="${ql_port:-${QlPort:-5700}}" QlBaseUrl="${ql_base_url:-${QlBaseUrl:-/}}"\nenv -0',
'ql-offline', 'ql-offline',
root,
], ],
{ env: environment, maxBuffer: 1024 * 1024 }, { cwd: root, env: environment, maxBuffer: 1024 * 1024 },
); );
const loaded = Object.fromEntries( const loaded = Object.fromEntries(
captured.stdout.split('\0').flatMap((line) => { captured.stdout.split('\0').flatMap((line) => {
+7
View File
@@ -29,6 +29,7 @@ async function packageFixture(t) {
}); });
} }
const metadata = JSON.parse(await fs.readFile('package.json', 'utf8')); const metadata = JSON.parse(await fs.readFile('package.json', 'utf8'));
for (const name of Object.values(metadata.pnpm?.patchedDependencies || {})) await copy(name);
// The structural test stays offline; full production installation and service // The structural test stays offline; full production installation and service
// upgrades run against the unmodified package in verify-panel-package.cjs. // upgrades run against the unmodified package in verify-panel-package.cjs.
metadata.dependencies = {}; metadata.dependencies = {};
@@ -67,6 +68,11 @@ test('real npm pack excludes local state and its installed lifecycle restores ve
const packed = await pack(); const packed = await pack();
const [archive] = JSON.parse(packed.stdout); const [archive] = JSON.parse(packed.stdout);
checkPackedFiles(archive.files); checkPackedFiles(archive.files);
const patches = Object.values(JSON.parse(await fs.readFile(path.join(root, 'package.json'), 'utf8')).pnpm?.patchedDependencies || {});
for (const patch of patches) {
assert.throws(() => checkPackedFiles(archive.files.filter((file) => file.path !== patch)), /Missing npm runtime/);
}
assert.throws(() => checkPackedFiles([...archive.files, { path: 'patches/undeclared.patch' }]), /Unexpected npm file/);
const names = new Set(archive.files.map((file) => file.path)); const names = new Set(archive.files.map((file) => file.path));
assert.ok(names.has('shell/upgrade-lock.yaml')); assert.ok(names.has('shell/upgrade-lock.yaml'));
assert.ok(names.has('shell/subscription-files.py')); assert.ok(names.has('shell/subscription-files.py'));
@@ -75,6 +81,7 @@ test('real npm pack excludes local state and its installed lifecycle restores ve
const prefix = path.join(temp, 'installed'); const prefix = path.join(temp, 'installed');
await execute('npm', ['install', '--offline', '--omit=dev', '--no-audit', '--no-fund', '--cache', path.join(temp, 'cache'), '--prefix', prefix, path.join(output, archive.filename)], { cwd: temp, env, timeout: 60000 }); await execute('npm', ['install', '--offline', '--omit=dev', '--no-audit', '--no-fund', '--cache', path.join(temp, 'cache'), '--prefix', prefix, path.join(output, archive.filename)], { cwd: temp, env, timeout: 60000 });
const installed = path.join(prefix, 'node_modules/@whyour/qinglong'); const installed = path.join(prefix, 'node_modules/@whyour/qinglong');
for (const patch of patches) assert.deepEqual(await fs.readFile(path.join(installed, patch)), await fs.readFile(path.join(root, patch)));
for (const { path: name } of archive.files) for (const { path: name } of archive.files)
assert.equal((await fs.readFile(path.join(installed, name))).includes(Buffer.from('DO_NOT_PUBLISH')), false, `Private fixture content in npm package: ${name}`); assert.equal((await fs.readFile(path.join(installed, name))).includes(Buffer.from('DO_NOT_PUBLISH')), false, `Private fixture content in npm package: ${name}`);
await assert.rejects(fs.access(path.join(installed, '.env')), { code: 'ENOENT' }); await assert.rejects(fs.access(path.join(installed, '.env')), { code: 'ENOENT' });
@@ -8,6 +8,30 @@ const {
const artifacts = require('../../cli/src/internal/maintenance/upgradeArtifacts.cjs'); const artifacts = require('../../cli/src/internal/maintenance/upgradeArtifacts.cjs');
const { installBundle } = require('../../shell/install-bundle.cjs'); const { installBundle } = require('../../shell/install-bundle.cjs');
test('offline environment loading treats installation paths as data and preserves the caller directory', async (t) => {
const directory = await fs.mkdtemp(path.join(require('node:os').tmpdir(), 'ql-offline-path-'));
t.after(() => fs.rm(directory, { recursive: true, force: true }));
const root = path.join(directory, 'panel space \' " $(echo injected) `echo injected`;');
await fs.mkdir(path.join(root, 'shell'), { recursive: true });
await fs.writeFile(path.join(root, 'shell/share.sh'), 'import_config() { ql_port=5789; ql_base_url=/panel/; }\n');
await fs.writeFile(path.join(root, 'shell/env.sh'), 'export QL_BRANCH=develop\n');
const cwd = process.cwd();
let captured;
t.mock.method(artifacts, 'stageUpgrade', async ({ env }) => {
captured = env;
throw new Error('reached staging');
});
await assert.rejects(installBundle(
['--file', path.join(root, 'unused.tar.gz'), '--download-only'],
{ ...process.env, QL_DIR: root },
), /reached staging/);
assert.equal(captured.QL_DIR, root);
assert.equal(captured.QlPort, '5789');
assert.equal(captured.QlBaseUrl, '/panel/');
assert.equal(captured.QL_BRANCH, 'develop');
assert.equal(process.cwd(), cwd);
});
for (const scenario of ['cancel-new-start', 'both-starts-fail']) for (const scenario of ['cancel-new-start', 'both-starts-fail'])
test(`offline application restores files and records failure: ${scenario}`, async (t) => { test(`offline application restores files and records failure: ${scenario}`, async (t) => {
const f = await manualUpgradeFixture(t); const f = await manualUpgradeFixture(t);
@@ -0,0 +1,376 @@
const assert = require('node:assert/strict');
const test = require('node:test');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { createRequire } = require('node:module');
const { once } = require('node:events');
const { Readable } = require('node:stream');
const { gzipSync } = require('node:zlib');
const express = require('express');
const bodyParser = require('body-parser');
const multer = require('multer');
const undici = require('undici');
const nodemailer = require('nodemailer');
const load = require('../helpers/load-security-module.cjs');
async function listen(t, app) {
const server = app.listen(0, '127.0.0.1');
await once(server, 'listening');
t.after(() => new Promise((resolve) => server.close(resolve)));
return `http://127.0.0.1:${server.address().port}`;
}
test('security upgrades preserve JSON, gzip, multipart and HTTP redirect handling', async (t) => {
const app = express();
app.post('/json', bodyParser.json(), (req, res) => res.json(req.body));
app.post('/upload', multer().single('file'), (req, res) => {
res.json({ name: req.body.name, content: req.file.buffer.toString() });
});
app.get('/redirect', (_req, res) => res.redirect('/result'));
app.get('/result', (_req, res) => res.json({ ok: true }));
app.use((error, _req, res, _next) =>
res.status(error.status || 400).send(error.message),
);
const base = await listen(t, app);
const value = { name: '中文', nested: { enabled: true } };
for (const compressed of [false, true]) {
const response = await undici.fetch(`${base}/json`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...(compressed ? { 'Content-Encoding': 'gzip' } : {}),
},
body: compressed
? gzipSync(JSON.stringify(value))
: JSON.stringify(value),
});
assert.equal(response.status, 200);
assert.deepEqual(await response.json(), value);
}
const malformed = await undici.fetch(`${base}/json`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Content-Encoding': 'gzip' },
body: Buffer.concat([gzipSync('{}'), Buffer.from('trailing garbage')]),
});
assert.equal(malformed.status, 400);
await malformed.text();
const form = new undici.FormData();
form.set('name', 'script');
form.set('file', new Blob(['console.log("safe")']), 'test.js');
const upload = await undici.fetch(`${base}/upload`, {
method: 'POST',
body: form,
});
assert.equal(upload.status, 200, await upload.clone().text());
assert.deepEqual(await upload.json(), {
name: 'script',
content: 'console.log("safe")',
});
const redirected = await undici.fetch(`${base}/redirect`);
assert.deepEqual(await redirected.json(), { ok: true });
const axios = require('axios');
assert.deepEqual(
(await axios.get(`${base}/redirect`, { proxy: false })).data,
{ ok: true },
);
});
test('Nodemailer still composes named recipients, Unicode subjects and HTML', async () => {
const transport = nodemailer.createTransport({
streamTransport: true,
buffer: true,
newline: 'unix',
});
try {
const info = await transport.sendMail({
from: '"青龙快讯" <sender@example.test>',
to: ['"Last, First" <first@example.test>', 'second@example.test'],
subject: '安全升级测试',
html: 'line one<br/>line two',
});
assert.deepEqual(info.envelope.to, [
'first@example.test',
'second@example.test',
]);
assert.ok(info.messageId);
assert.match(info.message.toString(), /Content-Type: text\/html/);
assert.match(info.message.toString(), /line one<br\/>line two/);
} finally {
transport.close();
}
});
test('CommonJS query-string consumers retain safe decoding with the ESM compatibility patch', () => {
const query = require('query-string');
assert.deepEqual(
{ ...query.parse('text=%E4%B8%AD%E6%96%87&bad=%E0%A4%A&plus=a%2Bb') },
{
bad: '%E0%A4%A',
plus: 'a+b',
text: '中文',
},
);
const localRequire = createRequire(require.resolve('query-string'));
const decode = localRequire('decode-uri-component');
assert.equal(typeof decode, 'function');
// A long malformed run previously caused quadratic replacement work.
const input = '%FF%41'.repeat(20000);
assert.equal(decode(input), '%FFA'.repeat(20000));
});
test('tar keeps the streaming API used by sqlite native package installation', async (t) => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ql-tar-compat-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const source = path.join(root, 'source');
const target = path.join(root, 'target');
fs.mkdirSync(source);
fs.mkdirSync(target);
fs.writeFileSync(path.join(source, 'binding.node'), 'fixture');
const sqliteRequire = createRequire(require.resolve('sqlite3'));
const tar = sqliteRequire('tar');
const chunks = [];
for await (const chunk of tar.create({ cwd: source, gzip: true }, [
'binding.node',
]))
chunks.push(chunk);
const extractor = tar.extract({ cwd: target });
const completed = once(extractor, 'close');
Readable.from(Buffer.concat(chunks)).pipe(extractor);
await completed;
assert.equal(
fs.readFileSync(path.join(target, 'binding.node'), 'utf8'),
'fixture',
);
});
for (const entry of [
{
file: 'config',
prefix: 'configs',
route: '/files',
method: 'get',
limit: 600,
},
{
file: 'log',
prefix: 'logs',
route: '/download',
method: 'post',
limit: 600,
body: { filename: 'a.log', path: '' },
},
{
file: 'script',
prefix: 'scripts',
route: '/download',
method: 'post',
limit: 600,
body: { filename: 'a.js' },
},
{
file: 'script',
prefix: 'scripts',
route: '/rename',
method: 'put',
limit: 600,
body: { filename: 'a.js', newFilename: 'b.js', path: '' },
},
{
file: 'system',
prefix: 'system',
route: '/auth/reset',
method: 'put',
limit: 60,
body: {},
},
]) {
test(`${entry.prefix}${entry.route} limits work across API aliases before the handler`, async (t) => {
const app = express();
app.use(express.json());
const router = express.Router();
const mocks = {
'../config': { tmpPath: os.tmpdir() },
'../config/util': {},
'../services/config': {},
'../services/log': {},
'../services/script': {},
'../services/scriptHistory': {},
'../services/system': {},
'../services/user': {},
'../shared/logStreamManager': {},
'../shared/i18n': { t: (x) => x },
'../data/runningInstance': {},
};
load(path.resolve(`back/api/${entry.file}.ts`), mocks).default(router);
const mounted = router.stack.find(
(layer) => layer.name === 'router',
).handle;
const selected = mounted.stack.find(
(layer) =>
layer.route?.path === entry.route && layer.route.methods[entry.method],
).route;
let calls = 0;
selected.stack.at(-1).handle = (_req, res) => {
calls++;
res.json({ code: 200 });
};
app.use('/api', router);
app.use('/open', router);
const base = await listen(t, app);
for (let i = 0; i <= entry.limit; i++) {
const response = await fetch(
`${base}/${i % 2 ? 'api' : 'open'}/${entry.prefix}${entry.route}`,
{
method: entry.method.toUpperCase(),
headers: { 'Content-Type': 'application/json' },
...(entry.body ? { body: JSON.stringify(entry.body) } : {}),
},
);
await response.text();
assert.equal(response.status, i < entry.limit ? 200 : 429);
}
assert.equal(calls, entry.limit);
});
}
test('Dva Immer integration preserves draft updates and Redux-style replacement', () => {
const maxRequire = createRequire(require.resolve('@umijs/max/package.json'));
const pluginRequire = createRequire(
maxRequire.resolve('@umijs/plugins/package.json'),
);
const plugin = pluginRequire('dva-immer').default();
const initial = { nested: { count: 1 } };
const reducer = plugin._handleActions(
{
increment: (draft) => {
draft.nested.count++;
},
replace: () => ({ nested: { count: 5 } }),
},
initial,
);
assert.deepEqual(reducer(undefined, { type: 'increment' }), {
nested: { count: 2 },
});
assert.equal(initial.nested.count, 1);
assert.deepEqual(reducer(initial, { type: 'replace' }), {
nested: { count: 5 },
});
});
test('ProLayout keeps route matching with the patched path-to-regexp API', () => {
const layoutRequire = createRequire(
require.resolve('@ant-design/pro-layout'),
);
const pathToRegexp = layoutRequire('path-to-regexp');
const keys = [];
const matcher = pathToRegexp('/scripts/:name?', keys, { end: true });
assert.equal(keys[0].name, 'name');
assert.ok(matcher.test('/scripts'));
assert.ok(matcher.test('/scripts/demo'));
assert.equal(matcher.test('/scripts/demo/extra'), false);
});
test('script uploads and finish cleanup reject paths outside the temporary directory', async (t) => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ql-upload-boundary-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const config = {
tmpPath: path.join(root, 'tmp'),
scriptPath: path.join(root, 'scripts'),
configPath: path.join(root, 'config'),
blackFileList: ['auth.json'],
};
config.writePathList = [config.scriptPath, config.configPath];
for (const dir of [
config.tmpPath,
config.scriptPath,
config.configPath,
path.join(root, 'tmp-sibling'),
])
fs.mkdirSync(dir);
const sentinel = path.join(root, 'tmp-sibling', 'sentinel');
fs.writeFileSync(sentinel, 'outside');
const alias = path.join(config.tmpPath, 'outside-link');
fs.symlinkSync(sentinel, alias);
const app = express.Router();
load(path.resolve('back/api/script.ts'), {
'../config': config,
'../services/script': {},
'../services/scriptHistory': {},
'../shared/i18n': { t: (x) => x },
'../config/util': {},
}).default(app);
const mounted = app.stack.find((layer) => layer.name === 'router').handle;
const route = mounted.stack.find(
(layer) => layer.route?.path === '/' && layer.route.methods.post,
).route;
for (const uploaded of [
sentinel,
alias,
path.join(config.tmpPath, '..', 'tmp-sibling', 'sentinel'),
]) {
let result;
let finish;
const req = { body: { filename: 'received.js' }, file: { path: uploaded } };
const res = {
on: (_event, callback) => {
finish = callback;
},
send: (value) => {
result = value;
},
};
route.stack[0].handle(req, res, () => {});
await route.stack.at(-1).handle(req, res, (error) => {
throw error;
});
finish();
await new Promise(setImmediate);
assert.equal(result.code, 403);
assert.equal(
fs.existsSync(path.join(config.scriptPath, 'received.js')),
false,
);
assert.equal(fs.readFileSync(sentinel, 'utf8'), 'outside');
assert.equal(fs.lstatSync(alias).isSymbolicLink(), true);
}
});
test('React Router keeps nested navigation and redirects with its declared router dependency', async () => {
const { createMemoryRouter, redirect } = require('react-router-dom');
const router = createMemoryRouter(
[
{ path: '/', id: 'home' },
{
path: '/scripts/:name',
id: 'script',
loader: ({ params }) => params.name,
},
{ path: '/legacy', loader: () => redirect('/scripts/demo?from=legacy') },
],
{ initialEntries: ['/'] },
);
try {
await router.navigate('/scripts/example?mode=edit');
assert.equal(router.state.location.pathname, '/scripts/example');
assert.equal(router.state.location.search, '?mode=edit');
assert.equal(router.state.loaderData.script, 'example');
await router.navigate('/legacy');
assert.equal(router.state.location.pathname, '/scripts/demo');
assert.equal(router.state.loaderData.script, 'demo');
// History navigation returns before its loader completes.
await new Promise((resolve) => {
const unsubscribe = router.subscribe((state) => {
if (state.navigation.state === 'idle') {
unsubscribe();
resolve();
}
});
router.navigate(-1);
});
assert.equal(router.state.location.pathname, '/scripts/example');
} finally {
router.dispose();
}
});
+9 -17
View File
@@ -44,11 +44,9 @@ for (const [version, exitCode] of [
path.join(statics, 'build/bootstrap/upgradeProbe.js'), path.join(statics, 'build/bootstrap/upgradeProbe.js'),
` `
const fs=require('node:fs'),crypto=require('node:crypto'); const fs=require('node:fs'),crypto=require('node:crypto');
require('node:child_process').spawn(process.execPath,['-e',${JSON.stringify( require('node:child_process').spawn(process.execPath,['-e',
`setTimeout(()=>require('node:fs').writeFileSync(${JSON.stringify( "setTimeout(()=>require('node:fs').writeFileSync(process.argv[1],'escaped'),600);",
survivor, ${JSON.stringify(survivor)}],{stdio:'inherit'});
)},'escaped'),600);`,
)}],{stdio:'inherit'});
process.send({type:'upgrade-probe',ok:${ process.send({type:'upgrade-probe',ok:${
exitCode === 0 exitCode === 0
},message:'simulated prestart failure',build:{sourceCommit:'a'.repeat(40),version:${JSON.stringify(version)},backendSha256:crypto.createHash('sha256').update('backend').digest('hex')}},()=>process.exit(${exitCode})); },message:'simulated prestart failure',build:{sourceCommit:'a'.repeat(40),version:${JSON.stringify(version)},backendSha256:crypto.createHash('sha256').update('backend').digest('hex')}},()=>process.exit(${exitCode}));
@@ -148,13 +146,9 @@ test('cancelled dependency repair kills descendants and retains the original tre
path.join(bin, 'pnpm'), path.join(bin, 'pnpm'),
`#!${process.execPath} `#!${process.execPath}
if(process.argv[2]==='--version'){console.log('8.3.1');process.exit(0);} if(process.argv[2]==='--version'){console.log('8.3.1');process.exit(0);}
require('node:child_process').spawn(process.execPath,['-e',${JSON.stringify( require('node:child_process').spawn(process.execPath,['-e',
`process.on('SIGTERM',()=>{});require('node:fs').writeFileSync(${JSON.stringify( "process.on('SIGTERM',()=>{});require('node:fs').writeFileSync(process.argv[1],'started');setTimeout(()=>require('node:fs').writeFileSync(process.argv[2],'escaped'),1400);",
started, ${JSON.stringify(started)},${JSON.stringify(survivor)}],{stdio:'inherit'});
)},'started');setTimeout(()=>require('node:fs').writeFileSync(${JSON.stringify(
survivor,
)},'escaped'),1400);`,
)}],{stdio:'inherit'});
setInterval(()=>{},1000); setInterval(()=>{},1000);
`, `,
{ mode: 0o755 }, { mode: 0o755 },
@@ -329,11 +323,9 @@ test('prestart deadline kills its process group and removes temporary data', asy
await fs.writeFile( await fs.writeFile(
path.join(statics, 'build/bootstrap/upgradeProbe.js'), path.join(statics, 'build/bootstrap/upgradeProbe.js'),
` `
require('node:child_process').spawn(process.execPath,['-e',${JSON.stringify( require('node:child_process').spawn(process.execPath,['-e',
`setTimeout(()=>require('node:fs').writeFileSync(${JSON.stringify( "setTimeout(()=>require('node:fs').writeFileSync(process.argv[1],'escaped'),2200)",
survivor, ${JSON.stringify(survivor)}],{stdio:'ignore'});
)},'escaped'),2200)`,
)}],{stdio:'ignore'});
setInterval(()=>{},1000); setInterval(()=>{},1000);
`, `,
); );