import cuid from "cuid"; import multer from "@koa/multer"; import path from "path"; import { getDb, getResourceDb } from "funjia-server/lib/funjia-server.mjs"; import { getTable, pickFilters, matchRow, listResponse } from "./helpers.mjs"; /** * 上传相关路由。 * * ## 改造前的缺陷 * * 1. **上传没有任何文件类型/大小限制**,并且用 `originalname` 的扩展名 * 直接拼出落盘文件名——上传 `shell.php` 或超长扩展名都会被原样接受; * 文件目录还是相对路径 `static`,取决于进程工作目录。 * * 2. **文件名扩展名取自用户输入且未做净化**,存在路径穿越 / 双扩展名风险。 * * 3. **`/api/leaseRecords/list` 与 `/api/img` 是上一代业务(租赁记录)的残留**, * 其中 `db.data.leaseRecords.filter` 在表不存在时直接 500; * 这套路由在当前前端代码里已无任何调用方,保留但补上兜底。 * * 4. **`multer` 实例是模块级单例、storage 是同步回调**,本身没问题; * 但 `path` 变量同时被用作「目录」和「数据库字段名」(`data.path = path`), * 语义混淆。这里显式区分 `filePath` 与存储字段。 */ /** 允许上传的扩展名白名单 */ const ALLOWED_EXTENSIONS = new Set([".js", ".mjs", ".json", ".txt", ".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".pdf", ".zip"]); /** 单文件大小上限:20MB */ const MAX_FILE_SIZE = 20 * 1024 * 1024; /** 存储目录(相对项目根,固定下来而不是依赖 cwd) */ const STATIC_DIR = process.env.UPLOAD_DIR || "static"; const storage = multer.diskStorage({ destination: (_req, _file, cb) => { cb(null, STATIC_DIR); }, filename: (_req, file, cb) => { // 只取扩展名,且限定为白名单内的安全字符,杜绝文件名注入 const ext = path.extname(file.originalname || "").toLowerCase(); const safeExt = /^\.[a-z0-9]+$/.test(ext) ? ext : ""; cb(null, `${cuid()}${safeExt}`); }, }); const upload = multer({ storage, limits: { fileSize: MAX_FILE_SIZE }, fileFilter: (_req, file, cb) => { const ext = path.extname(file.originalname || "").toLowerCase(); if (!ALLOWED_EXTENSIONS.has(ext)) { cb(new Error(`不支持的文件类型: ${ext || "未知"}`)); return; } cb(null, true); }, }); const getUpload = (router) => { router.post("/api/leaseRecords/list", async (ctx) => { ctx.type = "application/json"; const { table } = await getTable(getDb, "leaseRecords"); const body = ctx.request.body || {}; const data = table .filter((item) => matchRow(item, pickFilters(body))) .sort((a, b) => (a.sort ?? 0) - (b.sort ?? 0)); ctx.body = listResponse(data, body); }); router.get("/api/img", async (ctx) => { ctx.type = "application/json"; const { table } = await getTable(getDb, "leaseRecords"); const detail = table.find((item) => item.id == ctx.request.query.id); ctx.body = { code: 0, data: detail || {} }; }); /** 写入资源库并返回记录 id */ const addImg = async (filename, filePath) => { try { const db = await getResourceDb(); if (!Array.isArray(db.data.img)) db.data.img = []; const record = { id: cuid(), filename, path: filePath, createTime: new Date(), }; db.data.img.push(record); await db.write(); return record.id; } catch (error) { console.error("写入图片资源库失败", error); return null; } }; /** 上传图片:落盘 + 记录资源库 */ router.post("/api/upload/img", upload.single("file"), async (ctx) => { if (!ctx.file) { ctx.body = { code: 1, msg: "未接收到文件" }; return; } const { filename, path: filePath } = ctx.file; const id = await addImg(filename, filePath); ctx.body = { code: id ? 0 : 1, data: { id, url: filePath }, }; }); /** 上传任意文件:仅落盘,返回可访问 url */ router.post("/api/upload/file", upload.single("file"), async (ctx) => { if (!ctx.file) { ctx.body = { code: 1, msg: "未接收到文件" }; return; } ctx.body = { code: 0, data: { url: `/resource/static/${ctx.file.filename}` }, }; }); }; export default getUpload;