fix: resolve high-severity dependency and code scanning alerts

Upgrade SQLite to 1.1.5 so tar resolves safely without an override.
Update vulnerable dependencies while retaining scoped compatibility overrides
and the CommonJS decoder patch required by Umi's query-string consumers.

Limit sensitive endpoints, constrain script file operations to checked paths,
and serialize Python environment values safely. Add compatibility regressions
and include the decoder patch in Docker and npm installation inputs.
This commit is contained in:
whyour committed 2026-11-20 02:07:41 +08:00
1 parent 0902bc074d
commit b6bdba9a8d
13 files changed
+1064 -746

No files matched your search

+2
View File
@@ -9,6 +9,7 @@ import { t } from '../shared/i18n';
import ConfigService from '../services/config';
import { writeFileWithLock } from '../shared/utils';
import { resolveFileAccess } from '../shared/fileAccess';
import { rateLimit } from 'express-rate-limit';
const route = Router();
export default (app: Router) => {
@@ -30,6 +31,7 @@ export default (app: Router) => {
route.get(
'/files',
rateLimit({ windowMs: 60 * 1000, limit: 120 }),
async (req: Request, res: Response, next: NextFunction) => {
const logger: Logger = Container.get('logger');
try {
+2
View File
@@ -13,6 +13,7 @@ import {
import LogService from '../services/log';
import { InstanceStatus, RunningInstanceModel } from '../data/runningInstance';
import { MAX_LOG_CHUNK_BYTES, readLogChunk } from '../shared/logReader';
import { rateLimit } from 'express-rate-limit';
const route = Router();
const blacklist = ['.tmp'];
@@ -138,6 +139,7 @@ export default (app: Router) => {
route.post(
'/download',
rateLimit({ windowMs: 60 * 1000, limit: 60 }),
celebrate({
body: Joi.object({
filename: Joi.string().required(),
+69 -27
View File
@@ -1,4 +1,7 @@
import { directoryCheckHandler, directoryPageHandler } from '../shared/directoryPageRoute';
import {
directoryCheckHandler,
directoryPageHandler,
} from '../shared/directoryPageRoute';
import { randomUUID } from 'crypto';
import { resolveFileAccess } from '../shared/fileAccess';
import { fileExist, readDirs, readDir, rmPath, IFile } from '../config/util';
@@ -14,19 +17,20 @@ import ScriptHistoryService from '../services/scriptHistory';
import { t } from '../shared/i18n';
import multer from 'multer';
import { writeFileWithLock } from '../shared/utils';
import { rateLimit } from 'express-rate-limit';
import {
ScriptHistoryError,
HistoryUnavailableError,
} from '../shared/scriptHistory';
const route = Router();
const blacklist = [
'node_modules',
'.git',
'.pnpm',
'pnpm-lock.yaml',
'yarn.lock',
'package-lock.json',
];
'node_modules',
'.git',
'.pnpm',
'pnpm-lock.yaml',
'yarn.lock',
'package-lock.json',
];
function isPathAllowed(targetPath: string): boolean {
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> {
if (!isPathAllowed(targetPath)) {
throw new ScriptHistoryError(403, '暂无权限');
@@ -84,8 +108,14 @@ const upload = multer({ storage: storage });
export default (app: Router) => {
app.use('/scripts', route);
route.get('/entries', ...directoryPageHandler(() => config.scriptPath, blacklist, false));
route.post('/entries/check', ...directoryCheckHandler(() => config.scriptPath, blacklist));
route.get(
'/entries',
...directoryPageHandler(() => config.scriptPath, blacklist, false),
);
route.post(
'/entries/check',
...directoryCheckHandler(() => config.scriptPath, blacklist),
);
route.get(
'/',
@@ -244,7 +274,10 @@ export default (app: Router) => {
'/',
(req: Request, res: Response, next: NextFunction) => {
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();
},
@@ -292,18 +325,19 @@ export default (app: Router) => {
}
if (req.file) {
const uploadPath = join(path, filename);
if (!isPathAllowed(uploadPath)) {
const uploadPath = writablePath(join(path, filename));
const temporaryPath = uploadedPath(req.file.path);
if (!uploadPath || !temporaryPath) {
return res.send({ code: 403, message: t('暂无权限') });
}
await fs.copyFile(req.file.path, uploadPath);
await fs.unlink(req.file.path);
await fs.copyFile(temporaryPath, uploadPath);
await fs.unlink(temporaryPath);
return res.send({ code: 200 });
}
if (directory) {
const dirPath = join(path, directory);
if (!isPathAllowed(dirPath)) {
const dirPath = writablePath(join(path, directory));
if (!dirPath) {
return res.send({ code: 403, message: t('暂无权限') });
}
await fs.mkdir(dirPath, { recursive: true });
@@ -313,9 +347,9 @@ export default (app: Router) => {
if (!originFilename) {
originFilename = filename;
}
const originFilePath = join(path, originFilename);
const filePath = join(path, filename);
if (!isPathAllowed(filePath) || !isPathAllowed(originFilePath)) {
const originFilePath = writablePath(join(path, originFilename));
const filePath = writablePath(join(path, filename));
if (!filePath || !originFilePath) {
return res.send({ code: 403, message: t('暂无权限') });
}
// Check the canonical parent directly at the directory creation boundary.
@@ -462,6 +496,7 @@ export default (app: Router) => {
route.post(
'/download',
rateLimit({ windowMs: 60 * 1000, limit: 60 }),
celebrate({
body: Joi.object({
filename: Joi.string().required(),
@@ -513,8 +548,10 @@ export default (app: Router) => {
path = '';
}
const { name, ext } = parse(filename);
const filePath = join(config.scriptPath, path, `${name}.swap${ext}`);
if (!isPathAllowed(filePath)) {
const filePath = writablePath(
join(config.scriptPath, path, `${name}.swap${ext}`),
);
if (!filePath) {
return res.send({ code: 403, message: t('暂无权限') });
}
await writeFileWithLock(filePath, content || '');
@@ -544,8 +581,10 @@ export default (app: Router) => {
path = '';
}
const { name, ext } = parse(filename);
const filePath = join(config.scriptPath, path, `${name}.swap${ext}`);
if (!isPathAllowed(filePath)) {
const filePath = writablePath(
join(config.scriptPath, path, `${name}.swap${ext}`),
);
if (!filePath) {
return res.send({ code: 403, message: t('暂无权限') });
}
const logPath = resolveFileAccess(config.logPath, [
@@ -573,6 +612,7 @@ export default (app: Router) => {
route.put(
'/rename',
rateLimit({ windowMs: 60 * 1000, limit: 60 }),
celebrate({
body: Joi.object({
filename: Joi.string().required(),
@@ -590,9 +630,11 @@ export default (app: Router) => {
if (!path) {
path = '';
}
const filePath = join(config.scriptPath, path, filename);
const newPath = join(config.scriptPath, path, newFilename);
if (!isPathAllowed(filePath) || !isPathAllowed(newPath)) {
const filePath = writablePath(join(config.scriptPath, path, filename));
const newPath = writablePath(
join(config.scriptPath, path, newFilename),
);
if (!filePath || !newPath) {
return res.send({ code: 403, message: t('暂无权限') });
}
await fs.rename(filePath, newPath);
+1
View File
@@ -424,6 +424,7 @@ export default (app: Router) => {
route.put(
'/auth/reset',
rateLimit({ windowMs: 15 * 60 * 1000, limit: 20 }),
celebrate({
body: Joi.object({
retries: Joi.number().optional(),
+5 -9
View File
@@ -264,7 +264,7 @@ export default class EnvService {
const groups = groupBy(envs, 'name');
let 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) {
if (Object.prototype.hasOwnProperty.call(groups, key)) {
const group = groups[key];
@@ -277,17 +277,13 @@ export default class EnvService {
.replace(/'/g, "'\\''")
.trim();
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(
group.map((x) => x.value).join('&'),
)};\n`;
py_env_string += `os.environ['${key}']='''${_env_value.replace(
/\'/g,
"\\'",
)}'''\n`;
// Serialize data instead of constructing an escaped Python literal.
py_env_string += `os.environ['${key}']=json.loads(${JSON.stringify(
JSON.stringify(group.map((x) => x.value).join('&')),
)})\n`;
}
}
}
+1
View File
@@ -8,6 +8,7 @@ ENV NPM_CONFIG_PREFIX=/opt/node-global
ENV PATH=/opt/node-global/bin:${PATH}
COPY package.json .npmrc pnpm-lock.yaml /tmp/build/
COPY patches/ /tmp/build/patches/
RUN set -x \
&& apk add --no-cache git \
&& 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}
COPY package.json .npmrc pnpm-lock.yaml /tmp/build/
COPY patches/ /tmp/build/patches/
RUN set -x \
&& apk add --no-cache git \
&& 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
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/lib/node_modules/. /usr/local/lib/node_modules/
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.
FROM python:3.10.19-slim-bookworm@sha256:23f63358922e79a794f71be8f3723c84e5ccca9638af3f74456dc73d6184499e AS builder
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/lib/node_modules/. /usr/local/lib/node_modules/
RUN set -x && \
+24 -16
View File
@@ -17,6 +17,7 @@
"back/protos/api.proto",
"cli/src/internal/maintenance/*.cjs",
"ecosystem.config.js",
"patches/*.patch",
"README*.md",
"sample/*.sample.*",
"sample/notify.js",
@@ -115,13 +116,20 @@
}
},
"overrides": {
"sqlite3": "npm:@whyour/sqlite3@1.1.4",
"sqlite3": "npm:@whyour/sqlite3@1.1.5",
"@codemirror/state": "6.5.4",
"@codemirror/view": "6.39.16",
"proxy-addr": "2.0.8",
"websocket-driver": "0.7.5",
"brace-expansion@1": "1.1.21",
"brace-expansion@2": "2.1.7"
"axios@0": "0.34.0",
"immer@8": "9.0.21",
"vite@7": "7.3.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": {
@@ -131,7 +139,7 @@
"@grpc/proto-loader": "^0.8.0",
"@keyv/sqlite": "^4.0.1",
"@otplib/preset-default": "^12.0.1",
"body-parser": "^1.20.3",
"body-parser": "^1.20.9",
"celebrate": "^15.0.3",
"chokidar": "^4.0.1",
"compression": "1.8.2",
@@ -140,7 +148,7 @@
"cross-spawn": "^7.0.6",
"dayjs": "^1.11.13",
"dotenv": "^16.4.6",
"express": "^4.21.2",
"express": "^4.22.3",
"express-jwt": "^8.4.1",
"express-rate-limit": "^7.4.1",
"express-urlrewrite": "^2.0.3",
@@ -152,10 +160,10 @@
"js-yaml": "^4.1.0",
"jsonwebtoken": "^9.0.2",
"keyv": "^5.2.3",
"lodash": "^4.17.21",
"multer": "2.4.0",
"lodash": "^4.18.0",
"multer": "2.5.0",
"node-cron": "4.6.0",
"nodemailer": "^10.0.9",
"nodemailer": "^10.1.4",
"p-queue-cjs": "7.3.4",
"proper-lockfile": "^4.1.2",
"ps-tree": "^1.2.0",
@@ -163,14 +171,14 @@
"request-ip": "3.3.0",
"sequelize": "6.37.8",
"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",
"typedi": "^0.10.0",
"undici": "^7.9.0",
"undici": "^7.30.1",
"uuid": "^11.0.3",
"winston": "^3.17.0",
"winston-daily-rotate-file": "^5.0.0",
"tar": "7.5.20"
"winston-daily-rotate-file": "^5.0.0"
},
"devDependencies": {
"@ant-design/icons": "^5.0.1",
@@ -213,7 +221,7 @@
"antd": "^4.24.16",
"antd-img-crop": "^4.23.0",
"axios": "^1.4.0",
"compression-webpack-plugin": "9.2.0",
"compression-webpack-plugin": "12.0.0",
"concurrently": "^7.0.0",
"file-saver": "2.0.2",
"lint-staged": "^13.0.3",
@@ -235,7 +243,7 @@
"react-dom": "18.3.1",
"react-hotkeys-hook": "^4.6.1",
"react-intl-universal": "^2.12.0",
"react-router-dom": "6.26.1",
"react-router-dom": "6.30.4",
"react-split-pane": "^0.1.92",
"sockjs-client": "^1.6.0",
"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"
+555 -694
View File
File diff suppressed because it is too large. Load diff
@@ -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: 120,
},
{
file: 'log',
prefix: 'logs',
route: '/download',
method: 'post',
limit: 60,
body: { filename: 'a.log', path: '' },
},
{
file: 'script',
prefix: 'scripts',
route: '/download',
method: 'post',
limit: 60,
body: { filename: 'a.js' },
},
{
file: 'script',
prefix: 'scripts',
route: '/rename',
method: 'put',
limit: 60,
body: { filename: 'a.js', newFilename: 'b.js', path: '' },
},
{
file: 'system',
prefix: 'system',
route: '/auth/reset',
method: 'put',
limit: 20,
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();
}
});