修复报销附件上传与中文文件名(07-28-travel-reimbursement-guide)
这个提交包含在:
@@ -4,6 +4,7 @@ const { AppError } = require("../../utils/AppError");
|
||||
const { sendData } = require("../../utils/reply");
|
||||
const { buildAuditLogData } = require("../../utils/audit");
|
||||
const { signPayload, verifyToken } = require("../../utils/signedUrl");
|
||||
const { buildAttachmentContentDisposition } = require("../../utils/contentDisposition");
|
||||
const { openReadStream, StorageNotFoundError } = require("../../services/storage");
|
||||
const { toMoneyString } = require("../../utils/workflow");
|
||||
const { resolveInvoiceAvailability } = require("../../services/invoiceGovernance");
|
||||
@@ -31,11 +32,6 @@ const invoiceStatusQuerySchema = z.object({
|
||||
ids: z.string().trim().min(1).max(2000),
|
||||
});
|
||||
|
||||
function sanitizeFilename(fileName) {
|
||||
if (!fileName) return "file";
|
||||
return fileName.replace(/[\r\n"]/g, "_");
|
||||
}
|
||||
|
||||
function parseInvoiceListQuery(query) {
|
||||
const parsed = invoiceListQuerySchema.safeParse(query ?? {});
|
||||
if (!parsed.success) {
|
||||
@@ -634,7 +630,7 @@ function registerInvoicePoolReadRoutes(fastify) {
|
||||
reply.type(invoice.mime_type || "application/octet-stream");
|
||||
reply.header(
|
||||
"content-disposition",
|
||||
`inline; filename=\"${sanitizeFilename(invoice.original_name)}\"`,
|
||||
buildAttachmentContentDisposition(invoice.original_name, { disposition: "inline" }),
|
||||
);
|
||||
return reply.send(stream);
|
||||
});
|
||||
|
||||
@@ -6,6 +6,7 @@ const { AppError } = require("../utils/AppError");
|
||||
const { sendData } = require("../utils/reply");
|
||||
const { buildAuditLogData } = require("../utils/audit");
|
||||
const { sha256Hex } = require("../utils/crypto");
|
||||
const { buildAttachmentContentDisposition } = require("../utils/contentDisposition");
|
||||
const { compactDateString, currentDateString, parseDateOnlyString } = require("../utils/date");
|
||||
const { findActiveDelegationForDelegate, listActiveDelegationPrincipals } = require("../utils/delegation");
|
||||
const { hasPermission, resolveEntityPermission } = require("../constants/permissions");
|
||||
@@ -293,11 +294,6 @@ function ensureApplicantOrAdmin(request, reimbursement) {
|
||||
}
|
||||
}
|
||||
|
||||
function sanitizeAttachmentFilename(fileName) {
|
||||
if (!fileName) return "file";
|
||||
return fileName.replace(/[\r\n"]/g, "_");
|
||||
}
|
||||
|
||||
function mapReimbursementAttachment(item) {
|
||||
return {
|
||||
id: item.id,
|
||||
@@ -2481,7 +2477,12 @@ async function reimbursementRoutes(fastify) {
|
||||
const files = [];
|
||||
let governanceFields = {};
|
||||
try {
|
||||
for await (const part of request.parts()) {
|
||||
for await (const part of request.parts({
|
||||
limits: {
|
||||
files: 5,
|
||||
fileSize: fastify.config.maxUploadSizeBytes,
|
||||
},
|
||||
})) {
|
||||
if (part.type === "field") {
|
||||
governanceFields = parseMultipartGovernanceField(part, governanceFields);
|
||||
continue;
|
||||
@@ -2533,6 +2534,14 @@ async function reimbursementRoutes(fastify) {
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
if (error?.code === "FST_FILES_LIMIT") {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: { file: "too_many_files", maxFiles: 5 },
|
||||
});
|
||||
}
|
||||
if (error?.code === "FST_REQ_FILE_TOO_LARGE") {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
@@ -2809,7 +2818,7 @@ async function reimbursementRoutes(fastify) {
|
||||
reply.type(attachment.mime_type || "application/octet-stream");
|
||||
reply.header(
|
||||
"content-disposition",
|
||||
`inline; filename=\"${sanitizeAttachmentFilename(attachment.original_name)}\"`,
|
||||
buildAttachmentContentDisposition(attachment.original_name, { disposition: "inline" }),
|
||||
);
|
||||
return reply.send(stream);
|
||||
},
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
const crypto = require("node:crypto");
|
||||
|
||||
const sharp = require("sharp");
|
||||
const { buildAttachmentContentDisposition: buildContentDisposition } = require("../utils/contentDisposition");
|
||||
|
||||
const PURCHASE_ATTACHMENT_MAX_IMAGE_PIXELS = 40_000_000;
|
||||
const PURCHASE_ATTACHMENT_MAX_FILE_NAME_CODE_POINTS = 180;
|
||||
@@ -393,50 +394,11 @@ function buildAttachmentStorageKey(purchaseRequestId, extension) {
|
||||
return `purchase-requests/${purchaseRequestId.toLowerCase()}/${crypto.randomUUID()}${extension}`;
|
||||
}
|
||||
|
||||
function sanitizeHeaderFileName(fileName) {
|
||||
const source = typeof fileName === "string" && fileName.trim()
|
||||
? fileName.normalize("NFC").trim()
|
||||
: "attachment.bin";
|
||||
const sanitized = truncateCodePoints(
|
||||
source
|
||||
.replace(/[\\/]/gu, "_")
|
||||
.replace(/[\u0000-\u001f\u007f-\u009f]/gu, "_")
|
||||
.replace(/[\u200b-\u200f\u202a-\u202e\u2060-\u2069\ufeff]/gu, "_")
|
||||
.replace(/"+/gu, "_")
|
||||
.replace(/\s+/gu, " ")
|
||||
.trim(),
|
||||
PURCHASE_ATTACHMENT_MAX_FILE_NAME_CODE_POINTS,
|
||||
);
|
||||
return sanitized && sanitized !== "." && sanitized !== ".."
|
||||
? sanitized
|
||||
: "attachment.bin";
|
||||
}
|
||||
|
||||
function buildAsciiFallback(fileName) {
|
||||
const lastDotIndex = fileName.lastIndexOf(".");
|
||||
const rawExtension = lastDotIndex > 0 ? fileName.slice(lastDotIndex).toLowerCase() : ".bin";
|
||||
const extension = /^\.[a-z0-9]{1,10}$/u.test(rawExtension) ? rawExtension : ".bin";
|
||||
const rawStem = lastDotIndex > 0 ? fileName.slice(0, lastDotIndex) : fileName;
|
||||
const asciiStem = rawStem
|
||||
.normalize("NFKD")
|
||||
.replace(/[\u0300-\u036f]/gu, "")
|
||||
.replace(/[^a-zA-Z0-9._-]+/gu, "_")
|
||||
.replace(/_+/gu, "_")
|
||||
.replace(/^[._-]+|[._-]+$/gu, "")
|
||||
.slice(0, 100);
|
||||
return `${asciiStem || "attachment"}${extension}`;
|
||||
}
|
||||
|
||||
function encodeRfc5987Value(value) {
|
||||
return encodeURIComponent(value).replace(/[\u0027\u0028\u0029\u002a]/gu, (character) =>
|
||||
`%${character.charCodeAt(0).toString(16).toUpperCase()}`,
|
||||
);
|
||||
}
|
||||
|
||||
function buildAttachmentContentDisposition(fileName) {
|
||||
const safeFileName = sanitizeHeaderFileName(fileName);
|
||||
const asciiFallback = buildAsciiFallback(safeFileName);
|
||||
return `attachment; filename="${asciiFallback}"; filename*=UTF-8''${encodeRfc5987Value(safeFileName)}`;
|
||||
function buildAttachmentContentDisposition(fileName, options = {}) {
|
||||
return buildContentDisposition(fileName, {
|
||||
...options,
|
||||
maxCodePoints: PURCHASE_ATTACHMENT_MAX_FILE_NAME_CODE_POINTS,
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
const DEFAULT_FILE_NAME = "attachment.bin";
|
||||
const DEFAULT_MAX_FILE_NAME_CODE_POINTS = 180;
|
||||
const ALLOWED_DISPOSITIONS = new Set(["attachment", "inline"]);
|
||||
|
||||
function truncateCodePoints(value, maxCodePoints) {
|
||||
const codePoints = Array.from(value);
|
||||
return codePoints.length <= maxCodePoints
|
||||
? value
|
||||
: codePoints.slice(0, maxCodePoints).join("");
|
||||
}
|
||||
|
||||
function sanitizeHeaderFileName(fileName, { maxCodePoints = DEFAULT_MAX_FILE_NAME_CODE_POINTS } = {}) {
|
||||
const source = typeof fileName === "string" && fileName.trim()
|
||||
? fileName.normalize("NFC").trim()
|
||||
: DEFAULT_FILE_NAME;
|
||||
const sanitized = truncateCodePoints(
|
||||
source
|
||||
.replace(/[\\/]/gu, "_")
|
||||
.replace(/[\u0000-\u001f\u007f-\u009f]/gu, "_")
|
||||
.replace(/[\u200b-\u200f\u202a-\u202e\u2060-\u2069\ufeff]/gu, "_")
|
||||
.replace(/"+/gu, "_")
|
||||
.replace(/\s+/gu, " ")
|
||||
.trim(),
|
||||
maxCodePoints,
|
||||
);
|
||||
return sanitized && sanitized !== "." && sanitized !== ".."
|
||||
? sanitized
|
||||
: DEFAULT_FILE_NAME;
|
||||
}
|
||||
|
||||
function buildAsciiFallback(fileName) {
|
||||
const lastDotIndex = fileName.lastIndexOf(".");
|
||||
const rawExtension = lastDotIndex > 0 ? fileName.slice(lastDotIndex).toLowerCase() : ".bin";
|
||||
const extension = /^\.[a-z0-9]{1,10}$/u.test(rawExtension) ? rawExtension : ".bin";
|
||||
const rawStem = lastDotIndex > 0 ? fileName.slice(0, lastDotIndex) : fileName;
|
||||
const asciiStem = rawStem
|
||||
.normalize("NFKD")
|
||||
.replace(/[\u0300-\u036f]/gu, "")
|
||||
.replace(/[^a-zA-Z0-9._-]+/gu, "_")
|
||||
.replace(/_+/gu, "_")
|
||||
.replace(/^[._-]+|[._-]+$/gu, "")
|
||||
.slice(0, 100);
|
||||
return `${asciiStem || "attachment"}${extension}`;
|
||||
}
|
||||
|
||||
function encodeRfc5987Value(value) {
|
||||
return encodeURIComponent(value).replace(/[\u0027\u0028\u0029\u002a]/gu, (character) =>
|
||||
`%${character.charCodeAt(0).toString(16).toUpperCase()}`,
|
||||
);
|
||||
}
|
||||
|
||||
function buildAttachmentContentDisposition(
|
||||
fileName,
|
||||
{ disposition = "attachment", maxCodePoints = DEFAULT_MAX_FILE_NAME_CODE_POINTS } = {},
|
||||
) {
|
||||
if (!ALLOWED_DISPOSITIONS.has(disposition)) {
|
||||
throw new TypeError("disposition must be attachment or inline");
|
||||
}
|
||||
const safeFileName = sanitizeHeaderFileName(fileName, { maxCodePoints });
|
||||
const asciiFallback = buildAsciiFallback(safeFileName);
|
||||
return `${disposition}; filename="${asciiFallback}"; filename*=UTF-8''${encodeRfc5987Value(safeFileName)}`;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
DEFAULT_MAX_FILE_NAME_CODE_POINTS,
|
||||
buildAttachmentContentDisposition,
|
||||
};
|
||||
@@ -0,0 +1,80 @@
|
||||
const fs = require("node:fs/promises");
|
||||
const os = require("node:os");
|
||||
const path = require("node:path");
|
||||
|
||||
const Fastify = require("fastify");
|
||||
|
||||
const { AppError } = require("../../../src/utils/AppError");
|
||||
const { registerInvoicePoolReadRoutes } = require("../../../src/routes/invoicePool/read");
|
||||
const { signPayload } = require("../../../src/utils/signedUrl");
|
||||
|
||||
const INVOICE_ID = "11111111-1111-4111-8111-111111111111";
|
||||
const ACTOR_ID = "22222222-2222-4222-8222-222222222222";
|
||||
const JWT_SECRET = "synthetic-test-secret";
|
||||
|
||||
async function buildApp() {
|
||||
const storageDir = await fs.mkdtemp(path.join(os.tmpdir(), "hyb-oa-invoice-file-"));
|
||||
await fs.writeFile(path.join(storageDir, "invoice.pdf"), "%PDF synthetic\n%%EOF\n");
|
||||
|
||||
const prisma = {
|
||||
invoicePool: {
|
||||
findUnique: vi.fn().mockResolvedValue({
|
||||
storage_path: "invoice.pdf",
|
||||
mime_type: "application/pdf",
|
||||
original_name: "住宿电子普通发票.pdf",
|
||||
}),
|
||||
},
|
||||
auditLog: {
|
||||
create: vi.fn().mockResolvedValue({ id: "audit-1" }),
|
||||
},
|
||||
};
|
||||
|
||||
const app = Fastify();
|
||||
app.decorate("prisma", prisma);
|
||||
app.decorate("config", { jwtSecret: JWT_SECRET, storageDir });
|
||||
app.decorate("authenticate", async () => {});
|
||||
app.decorate("hasPermission", () => false);
|
||||
app.decorate("requirePermission", () => async () => {});
|
||||
app.setErrorHandler((error, request, reply) => {
|
||||
if (error instanceof AppError) {
|
||||
return reply.status(error.statusCode).send({
|
||||
requestId: request.id,
|
||||
error: { code: error.code, message: error.message, details: error.details ?? {} },
|
||||
});
|
||||
}
|
||||
return reply.status(500).send({
|
||||
requestId: request.id,
|
||||
error: { code: "SYS_001", message: "服务器内部错误", details: {} },
|
||||
});
|
||||
});
|
||||
await app.register(registerInvoicePoolReadRoutes, { prefix: "/api" });
|
||||
return { app, prisma, storageDir };
|
||||
}
|
||||
|
||||
describe("GET /api/invoice-pool/:id/file", () => {
|
||||
it("returns a Chinese PDF name through a safe inline Content-Disposition", async () => {
|
||||
const { app, prisma, storageDir } = await buildApp();
|
||||
const exp = Date.now() + 60_000;
|
||||
const token = signPayload({ invoiceId: INVOICE_ID, actorId: ACTOR_ID, exp }, JWT_SECRET);
|
||||
|
||||
try {
|
||||
const response = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/invoice-pool/${INVOICE_ID}/file?token=${encodeURIComponent(token)}`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.headers["content-type"]).toContain("application/pdf");
|
||||
expect(response.headers["content-disposition"]).toBe(
|
||||
"inline; filename=\"attachment.pdf\"; filename*=UTF-8''%E4%BD%8F%E5%AE%BF%E7%94%B5%E5%AD%90%E6%99%AE%E9%80%9A%E5%8F%91%E7%A5%A8.pdf",
|
||||
);
|
||||
expect(response.headers["content-disposition"]).not.toContain("住宿电子普通发票");
|
||||
expect(prisma.auditLog.create).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ data: expect.objectContaining({ action: "INVOICE_FILE_DOWNLOADED" }) }),
|
||||
);
|
||||
} finally {
|
||||
await app.close();
|
||||
await fs.rm(storageDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -180,7 +180,7 @@ async function buildApp({ reimbursementStatus = "draft" } = {}) {
|
||||
|
||||
await app.register(multipart, {
|
||||
attachFieldsToBody: false,
|
||||
limits: { files: 5, fileSize: 5 * 1024 * 1024 },
|
||||
limits: { files: 1, fileSize: 5 * 1024 * 1024 },
|
||||
});
|
||||
await app.register(reimbursementRoutes, { prefix: "/api" });
|
||||
|
||||
@@ -188,7 +188,7 @@ async function buildApp({ reimbursementStatus = "draft" } = {}) {
|
||||
}
|
||||
|
||||
describe("reimbursement attachment routes", () => {
|
||||
it("uploads multiple attachment materials without invoice OCR handling", async () => {
|
||||
it("uploads five attachment materials with the production global one-file baseline", async () => {
|
||||
const { app, prisma, tempDir, reimbursementId, createdAttachments } = await buildApp();
|
||||
|
||||
try {
|
||||
@@ -204,6 +204,21 @@ describe("reimbursement attachment routes", () => {
|
||||
contentType: "image/png",
|
||||
content: "png-content",
|
||||
},
|
||||
{
|
||||
filename: "order.jpg",
|
||||
contentType: "image/jpeg",
|
||||
content: "jpg-content",
|
||||
},
|
||||
{
|
||||
filename: "note.webp",
|
||||
contentType: "image/webp",
|
||||
content: "webp-content",
|
||||
},
|
||||
{
|
||||
filename: "extra.pdf",
|
||||
contentType: "application/pdf",
|
||||
content: "%PDF extra",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
@@ -218,7 +233,7 @@ describe("reimbursement attachment routes", () => {
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.json().data.items).toHaveLength(2);
|
||||
expect(response.json().data.items).toHaveLength(5);
|
||||
expect(response.json().data.items[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
originalName: "contract.pdf",
|
||||
@@ -230,7 +245,7 @@ describe("reimbursement attachment routes", () => {
|
||||
uploadedBy: expect.objectContaining({ name: "测试用户" }),
|
||||
}),
|
||||
);
|
||||
expect(prisma.reimbursementAttachment.create).toHaveBeenCalledTimes(2);
|
||||
expect(prisma.reimbursementAttachment.create).toHaveBeenCalledTimes(5);
|
||||
expect(prisma.auditLog.create).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: expect.objectContaining({
|
||||
@@ -254,6 +269,41 @@ describe("reimbursement attachment routes", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("returns a stable validation error when a request contains six files", async () => {
|
||||
const { app, prisma, tempDir, reimbursementId } = await buildApp();
|
||||
|
||||
try {
|
||||
const requestPayload = buildMultipartRequest({
|
||||
files: Array.from({ length: 6 }, (_, index) => ({
|
||||
filename: `attachment-${index + 1}.pdf`,
|
||||
contentType: "application/pdf",
|
||||
content: `%PDF attachment ${index + 1}`,
|
||||
})),
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: `/api/reimbursements/${reimbursementId}/attachments`,
|
||||
headers: {
|
||||
authorization: "Bearer test",
|
||||
...requestPayload.headers,
|
||||
},
|
||||
payload: requestPayload.payload,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
expect(response.json().error).toMatchObject({
|
||||
code: "VALID_001",
|
||||
details: { file: "too_many_files", maxFiles: 5 },
|
||||
});
|
||||
expect(prisma.reimbursementAttachment.create).not.toHaveBeenCalled();
|
||||
expect(prisma.auditLog.create).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
await app.close();
|
||||
await fs.rm(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects attachment upload after reimbursement leaves editable status", async () => {
|
||||
const { app, prisma, tempDir, reimbursementId } = await buildApp({ reimbursementStatus: "reviewing" });
|
||||
|
||||
@@ -322,6 +372,9 @@ describe("reimbursement attachment routes", () => {
|
||||
|
||||
expect(downloadResponse.statusCode).toBe(200);
|
||||
expect(downloadResponse.headers["content-type"]).toContain("image/png");
|
||||
expect(downloadResponse.headers["content-disposition"]).toBe(
|
||||
"inline; filename=\"payment.png\"; filename*=UTF-8''payment.png",
|
||||
);
|
||||
expect(downloadResponse.body).toBe("png-content");
|
||||
|
||||
const deleteResponse = await app.inject({
|
||||
@@ -358,6 +411,39 @@ describe("reimbursement attachment routes", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("returns Chinese attachment names through a safe inline Content-Disposition", async () => {
|
||||
const { app, tempDir, reimbursementId, createdAttachments } = await buildApp();
|
||||
|
||||
try {
|
||||
const requestPayload = buildMultipartRequest({
|
||||
files: [{ filename: "payment.pdf", contentType: "application/pdf", content: "%PDF payment" }],
|
||||
});
|
||||
const uploadResponse = await app.inject({
|
||||
method: "POST",
|
||||
url: `/api/reimbursements/${reimbursementId}/attachments`,
|
||||
headers: { authorization: "Bearer test", ...requestPayload.headers },
|
||||
payload: requestPayload.payload,
|
||||
});
|
||||
const attachmentId = uploadResponse.json().data.items[0].id;
|
||||
createdAttachments[0].original_name = "支付截图.pdf";
|
||||
|
||||
const response = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/reimbursements/${reimbursementId}/attachments/${attachmentId}/file`,
|
||||
headers: { authorization: "Bearer test" },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.headers["content-disposition"]).toBe(
|
||||
"inline; filename=\"attachment.pdf\"; filename*=UTF-8''%E6%94%AF%E4%BB%98%E6%88%AA%E5%9B%BE.pdf",
|
||||
);
|
||||
expect(response.headers["content-disposition"]).not.toContain("支付截图");
|
||||
} finally {
|
||||
await app.close();
|
||||
await fs.rm(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects attachment deletion without a meaningful reason before mutation", async () => {
|
||||
const { app, prisma, tempDir, reimbursementId } = await buildApp();
|
||||
|
||||
|
||||
@@ -542,4 +542,13 @@ describe("purchase attachment storage and response helpers", () => {
|
||||
expect(header).not.toContain("\\quote");
|
||||
expect(header).toContain("filename*=UTF-8''");
|
||||
});
|
||||
|
||||
it("supports safe inline Content-Disposition without changing the default", () => {
|
||||
const header = buildAttachmentContentDisposition("铁路电子客票.pdf", { disposition: "inline" });
|
||||
|
||||
expect(header).toBe(
|
||||
"inline; filename=\"attachment.pdf\"; filename*=UTF-8''%E9%93%81%E8%B7%AF%E7%94%B5%E5%AD%90%E5%AE%A2%E7%A5%A8.pdf",
|
||||
);
|
||||
expect(() => buildAttachmentContentDisposition("file.pdf", { disposition: "preview" })).toThrow(TypeError);
|
||||
});
|
||||
});
|
||||
|
||||
在新工单中引用
屏蔽一个用户