diff --git a/packages/napcat-webui-backend/src/api/UpdateNapCat.ts b/packages/napcat-webui-backend/src/api/UpdateNapCat.ts index ef3c19a3e..ef9cfc38a 100644 --- a/packages/napcat-webui-backend/src/api/UpdateNapCat.ts +++ b/packages/napcat-webui-backend/src/api/UpdateNapCat.ts @@ -42,6 +42,13 @@ const SKIP_UPDATE_FILES = [ 'NapCatWinBootHook.dll', ]; +// 更新时若文件已存在则保留(不覆盖)的用户配置文件(使用相对路径精确匹配) +// 这些文件保存了用户的自定义设置,更新时应予以保留; +// 新增的配置项将在运行时通过 TypeBox schema 默认值自动填充,用户不会错过新配置选项。 +const PRESERVE_USER_CONFIG_RELATIVE_PATHS = new Set([ + path.normalize('config/napcat.json'), +]); + /** * 递归扫描目录中的所有文件 */ @@ -59,9 +66,12 @@ function scanFilesRecursively (dirPath: string, basePath: string = dirPath): Arr for (const item of items) { const fullPath = path.join(dirPath, item); const relativePath = path.relative(basePath, fullPath); - const stat = fs.statSync(fullPath); + const stat = fs.lstatSync(fullPath); - if (stat.isDirectory()) { + if (stat.isSymbolicLink()) { + // 跳过符号链接,避免潜在的路径穿越风险 + continue; + } else if (stat.isDirectory()) { // 递归扫描子目录 files.push(...scanFilesRecursively(fullPath, basePath)); } else if (stat.isFile()) { @@ -263,8 +273,16 @@ export const UpdateNapCatHandler: RequestHandler = async (req, res) => { }> = []; // 先尝试直接替换文件 + const resolvedBinaryPath = path.resolve(webUiPathWrapper.binaryPath); for (const fileInfo of allFiles) { - const targetFilePath = path.join(webUiPathWrapper.binaryPath, fileInfo.relativePath); + // 防止路径穿越攻击:确保目标路径严格位于 binaryPath 子目录内 + const targetFilePath = path.resolve(webUiPathWrapper.binaryPath, fileInfo.relativePath); + if (!targetFilePath.startsWith(resolvedBinaryPath + path.sep)) { + webUiLogger?.logWarn(`[NapCat Update] Skipping suspicious path: ${fileInfo.relativePath}`); + continue; + } + + const normalizedRelativePath = path.normalize(fileInfo.relativePath); // 跳过指定的文件 if (SKIP_UPDATE_FILES.includes(path.basename(fileInfo.relativePath))) { @@ -272,6 +290,12 @@ export const UpdateNapCatHandler: RequestHandler = async (req, res) => { continue; } + // 保留已存在的用户配置文件,避免覆盖用户设置 + if (PRESERVE_USER_CONFIG_RELATIVE_PATHS.has(normalizedRelativePath) && fs.existsSync(targetFilePath)) { + webUiLogger?.log(`[NapCat Update] Preserving existing user config: ${fileInfo.relativePath}`); + continue; + } + try { // 确保目标目录存在 const targetDir = path.dirname(targetFilePath);