From 301efa9e72f7db144261ab3b56e7ac87ba44667e Mon Sep 17 00:00:00 2001 From: whyour Date: Mon, 12 Oct 2026 01:13:53 +0800 Subject: [PATCH] fix(scripts): validate destinations immediately before file writes --- back/api/script.ts | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/back/api/script.ts b/back/api/script.ts index e1e7da89..f97dc746 100644 --- a/back/api/script.ts +++ b/back/api/script.ts @@ -35,6 +35,23 @@ function isPathAllowed(targetPath: string): boolean { ); } +async function writeScriptFile( + targetPath: string, + content: string, +): Promise { + const target = resolve(targetPath); + for (const writableRoot of config.writePathList) { + const root = resolve(writableRoot); + const prefix = root.endsWith(sep) ? root : root + sep; + // Check the actual write target, including filename, at the write boundary. + if (!target.startsWith(prefix)) continue; + if (!isPathAllowed(target)) return false; + await writeFileWithLock(target, content); + return true; + } + return false; +} + async function existingWritableRealPath(targetPath: string): Promise { if (!isPathAllowed(targetPath)) { throw new ScriptHistoryError(403, '暂无权限'); @@ -373,7 +390,9 @@ export default (app: Router) => { await rmPath(originFilePath); } } - await writeFileWithLock(filePath, content); + if (!(await writeScriptFile(filePath, content))) { + return res.send({ code: 403, message: t('暂无权限') }); + } return res.send({ code: 200 }); } catch (e) { return historyError(e, res, next); @@ -513,7 +532,9 @@ export default (app: Router) => { if (!isPathAllowed(filePath)) { return res.send({ code: 403, message: t('暂无权限') }); } - await writeFileWithLock(filePath, content || ''); + if (!(await writeScriptFile(filePath, content || ''))) { + return res.send({ code: 403, message: t('暂无权限') }); + } const scriptService = Container.get(ScriptService); const result = await scriptService.runScript(filePath);