修复报销附件上传与中文文件名(07-28-travel-reimbursement-guide)

这个提交包含在:
2026-07-30 14:41:08 +08:00
父节点 531d2846a6
当前提交 734153847b
共修改 15 个文件,包含 434 行新增和 65 行删除
@@ -473,6 +473,98 @@ const TRAVEL_TRANSPORT_EXPENSE_TYPE_CODES = { bus: "travel_bus" };
// model and fee-control service both support eligible-day multiplication.
```
## Scenario: Reimbursement Attachment Batch And UTF-8 Filename Boundary
### 1. Scope / Trigger
- Trigger: changing reimbursement supporting-material upload limits, multipart
parsing, attachment/invoice file responses or tests that register multipart.
- Purpose: preserve the global one-file safety default while supporting the
reimbursement UI's bounded multi-file request and legal Chinese file names.
### 2. Signatures
- Upload: `POST /api/reimbursements/:id/attachments`, multipart field `files`,
one to five PDF/JPG/PNG/WebP files per request.
- Route parser: `request.parts({ limits: { files: 5, fileSize } })`; the global
`@fastify/multipart` registration remains `limits.files=1`.
- Download headers: `buildAttachmentContentDisposition(name, {
disposition: "inline" })` for reimbursement attachments and invoice PDFs.
- Client constant: `MAX_REIMBURSEMENT_ATTACHMENT_FILES=5` is shared by PC and
mobile reimbursement detail pages.
### 3. Contracts
- Do not relax the application-wide multipart file count. Only the
reimbursement supporting-material route overrides it to five.
- Parse the complete multipart request before storage/database writes so a
sixth file cannot leave a partial five-file upload.
- `FST_FILES_LIMIT` maps to `400 VALID_001` with
`{ file: "too_many_files", maxFiles: 5 }`; PC and mobile show the same
bounded message. Generic error mapping must not assume every module has the
reimbursement limit when `maxFiles` is absent.
- Preserve the original name in the database. HTTP `Content-Disposition` uses
an ASCII `filename` fallback plus RFC 5987 UTF-8 `filename*`; never place raw
Chinese, CR/LF, quotes, path separators or control characters in the legacy
quoted parameter.
- Reimbursement attachments and invoice PDFs retain `inline`; purchase,
employee and payment receipt downloads keep their existing default
`attachment` behavior through the same shared builder.
### 4. Validation & Error Matrix
- One to five allowed files -> parse and persist all files.
- Six or more files -> `400 VALID_001 / file=too_many_files`, with zero storage,
database and audit writes.
- Unsupported MIME, empty file or oversized file -> existing stable file
validation error; no partial persistence.
- Chinese name -> `inline; filename="attachment.<ext>"; filename*=UTF-8''...`.
- Invalid disposition value -> `TypeError`; callers may use only `inline` or
`attachment`.
### 5. Good/Base/Bad Cases
- Good: PC selects five payment screenshots; the route succeeds even though
the test app and production app both register global `files=1`.
- Base: one ASCII PDF keeps an ASCII fallback and an equivalent `filename*`.
- Bad: set the test-only global limit to five, which hides a missing route
override; or interpolate a Chinese database name directly into a Node header.
### 6. Tests Required
- Register multipart with the production global `files=1` in reimbursement
route tests, then assert five files succeed.
- Send six files and assert `400`, `VALID_001`, `too_many_files`, and no
attachment/audit writes.
- Download an existing Chinese-name reimbursement attachment and invoice PDF;
assert `inline`, ASCII `filename`, percent-encoded `filename*`, and no raw
Chinese in the header.
- Cover CR/LF, quote and path cleanup in the shared Content-Disposition helper,
while retaining existing purchase `attachment` regression tests.
- Run backend full tests and frontend typecheck/build because the limit and
error message cross API and both UI variants.
### 7. Wrong vs Correct
#### Wrong
```js
await fastify.register(multipart, { limits: { files: 5 } }); // test-only drift
reply.header("content-disposition", `inline; filename="${originalName}"`);
```
#### Correct
```js
for await (const part of request.parts({ limits: { files: 5, fileSize } })) {
// Buffer and validate the bounded request before persistence.
}
reply.header(
"content-disposition",
buildAttachmentContentDisposition(originalName, { disposition: "inline" }),
);
```
## Scenario: Payment Batch Receipt Attention Count
### 1. Scope / Trigger
@@ -68,6 +68,15 @@
- 当前 `ReimbursementItem` 没有天数或数量字段,`ExpenseStandard.per_unit=day` 也不会在费用控制中乘以天数。因此本轮不创建 100/80 元 block 或 warn 标准,员工分别新增补助明细,以“天数 × 单价”人工算出总额并在说明写明计算式,由主管和财务复核。
- 自动带出差旅起止日、计算符合条件的补助天数以及按天校验属于后续产品能力,不阻塞本次真实报销。
## 报销附件上传与中文文件名
- 生产复现显示 PC 一次发送多个补充附件时触发 `FST_FILES_LIMIT`:全局 multipart 合同为 `files=1`,而报销附件路由、PC/手机页面和既有测试均按多文件设计。测试曾把全局上限改成 5,掩盖了生产差异。
- 保持全局 `files=1`,仅在报销附件 `request.parts()` 调用传入 `limits.files=5` 和既有文件大小限制;捕获 `FST_FILES_LIMIT` 并映射为 `VALID_001 / file=too_many_files`。
- 客户端共享 `MAX_REIMBURSEMENT_ATTACHMENT_FILES=5`,PC 与手机选择后先拦截超限并显示相同提示;API 仍接受数组,单次请求最多 5 个。
- 生产还复现了中文附件打开失败:原实现仅替换 CR/LF/引号,仍把中文直接放进 `filename="..."`,Node 以 `ERR_INVALID_CHAR` 拒绝响应头。
- 把现有采购附件的安全 Content-Disposition 构造能力提炼/扩展为可选 `attachment` 或 `inline` 处置类型,生成安全 ASCII `filename` 与 RFC 5987 UTF-8 `filename*`。报销附件与发票 PDF 使用 `inline`;采购、回单等既有 `attachment` 调用保持不变。
- 不改变文件原名在数据库中的业务展示值,不重写已上传文件;修复部署后既有中文名附件即可正常打开。
## 失败与回退
- adapter 聚焦测试、配置 smoke、腾讯调用或任一真实样票验证失败:停止开放真实票据,不继续制造 pending/retry 数据。
@@ -70,6 +70,22 @@
- [x] 明确当前由员工按“天数 × 单价”人工填写总额;不配置会误判多日补助的单条费用标准。
- [x] 重新生成并检查一页版差旅报销 PDF。
## 5.2 真实首笔报销附件阻断修复
- [x] 报销附件路由显式支持单次最多 5 个文件,并稳定映射 `FST_FILES_LIMIT`。
- [x] PC/手机共享最多 5 个文件的选择限制、提示和客户端拦截。
- [x] 报销附件与发票 PDF 使用安全 ASCII fallback + RFC 5987 UTF-8 文件名响应头。
- [x] 测试恢复生产全局 `files=1`,覆盖路由级 5 个成功、6 个失败、中文名及头注入清理。
- [x] 完成后端、前端、流程、文档、敏感内容和 Trellis 门禁;提交后另行取得生产部署批准。
## 2026-07-30 报销附件阻断修复验证
- 生产日志根因已由聚焦回归锁定:PC 多文件请求触发全局 `FST_FILES_LIMIT`,中文原名直接进入响应头触发 `ERR_INVALID_CHAR`;手机并非独立后端链路。
- 报销附件路由保持生产全局 `files=1` 基线并局部覆盖为 5;第 6 个文件返回 `400 VALID_001 / too_many_files`,且附件和审计写入均为 0。
- 报销附件与发票 PDF 已统一使用安全 `inline` Content-Disposition;采购、员工附件和付款回单仍保持默认 `attachment`。
- 聚焦测试 3 个文件/47 项、后端全量 169 个文件/1082 项、Prisma validate、前端 typecheck/build、流程合同、文档审计、Trellis governance、敏感内容、task validate 与 `git diff --check` 均通过;文档审计仅保留 22 个既有未注册文档 warning。
- 本地修复尚未提交、推送或部署;只有部署并完成公网与 PC/手机实测后,才能通知用户重新验收。
## 6. 验证与审查
- [x] 静态核对页面/API 上传格式、明细绑定和员工/财务字段边界。
@@ -27,6 +27,7 @@
- 配置并正式启用生产腾讯 OCR,完成配置门禁、受控发布、公网检查和授权 PDF 样票验证。
- 在现有腾讯 provider 内改用通用票据识别高级版,补齐住宿电子普通发票和铁路电子客票的安全归一化、质量门禁、大小限制和测试。
- 固化公司差旅补助规定,补齐不与城际大巴费用混淆的费用类型,并同步员工指南和报销事实源。
- 修复真实首笔报销暴露的 PC 多附件上传与中文文件名打开失败,保持 PC/手机和生产 multipart 合同一致。
## Requirements
@@ -54,6 +55,10 @@
- 公司或其他单位已直接承担餐食或车辆费用的,不重复领取相应补助;城际交通、住宿及其他经批准的必要差旅费用凭有效材料实报实销。
- 当前报销明细没有天数字段,两项补助分别作为独立明细人工填写总额和计算式,例如“伙食补助费:3 天 × 100 元”;不得把现有 `per_unit=day` 费用标准直接配置为 100/80 元,因为当前校验不会按天数乘算,会误判多日补助。
- `travel_bus` 保留为城际大巴车票费用;市内交通补助使用独立费用类型,不得共用代码或混同展示。
- 报销补充附件在 PC 与手机端均允许单次选择 1–5 个文件;服务端必须在该路由显式覆盖全局单文件 multipart 上限,第 6 个文件进入稳定的 `VALID_001` 错误,不得退化成 `SYS_001`。
- PC 与手机选择器均显示“单次最多 5 个”,并在请求前拦截超过 5 个文件的选择;客户端限制只改善体验,服务端仍是最终边界。
- 报销附件和发票 PDF 的中文原文件名不得直接进入 HTTP 响应头;`Content-Disposition` 使用安全 ASCII fallback 与 RFC 5987 `filename*`,同时清理控制字符、路径和响应头注入字符。
- 报销附件继续使用 `inline` 语义,发票 PDF 继续支持当前预览/下载流程;修复不得改变附件权限、用途留痕、审计或存储内容。
- 文档不放真实票据、支付截图、账号、订单号、银行信息或完整业务数据。
## Acceptance Criteria
@@ -71,12 +76,16 @@
- [x] 未配置会把多日补助误判为超标的 100/80 元单条费用标准;指南要求员工按天数人工计算并在说明中写出算式。
- [x] 在真实 OCR 验收完成前不得仅因指南已完成就通知杨俊可以提交。
- [x] 全程不把真实票据、支付截图、完整账号、银行资料、Secret 或原始 payload 写入仓库、任务或聊天。
- [x] PC 与手机均可一次上传 1–5 个报销补充附件;选择第 6 个时客户端提前提示,绕过客户端直调服务端仍返回稳定 `VALID_001` 而非 500。
- [x] 中文文件名的报销附件和发票 PDF 均返回合法 `Content-Disposition`,保留 `inline` 与 UTF-8 文件名语义且无响应头注入。
- [x] 聚焦测试使用与生产一致的全局 `files=1` 基线,证明路由级覆盖有效,并覆盖 5 个成功、6 个失败、中文名和恶意文件名。
## Out of Scope
- 新增第二个 OCR provider、开放图片发票、自动验真或增加人工发票字段。
- 本轮不做通用发票平台或覆盖全部票种;仅支持现有住宿 VAT/电子普通发票和电子发票(铁路电子客票)主路径。
- 修改报销页面、上传格式、审批规则或自动按天计算;本轮只调整差旅相关费用类型名称并新增独立的市内交通补助类型,不配置 100/80 元费用标准。
- 改变全局 multipart 单文件默认值,或放宽发票上传“一份请求一张正式票据”的边界。
- 代替杨俊上传票据、创建报销、提交审批,或代替主管/财务处理。
- 制定覆盖所有费用类别的完整财务制度;本轮只收口首笔差旅的实报实销材料和两项包干补助。
+6
查看文件
@@ -359,6 +359,12 @@ export function mapApiErrorMessage(
return "附件超过大小限制,请压缩后重新上传。";
}
if (details?.file === "too_many_files") {
return details?.maxFiles === 5
? "单次最多上传 5 个附件,请分批上传。"
: "一次选择的附件过多,请减少数量后分批上传。";
}
if (details?.file === "dangerous_filename") {
return "附件名称不安全,请重命名后重新上传。";
}
+2
查看文件
@@ -490,6 +490,8 @@ export async function deleteReimbursementItem(reimbursementId: string, itemId: s
);
}
export const MAX_REIMBURSEMENT_ATTACHMENT_FILES = 5;
export async function uploadReimbursementAttachments(reimbursementId: string, files: File[]) {
const formData = new FormData();
for (const file of files) {
@@ -20,6 +20,7 @@ import {
deleteReimbursementItem,
downloadReimbursementAttachment,
fetchReimbursementDetail,
MAX_REIMBURSEMENT_ATTACHMENT_FILES,
precheckReimbursement,
submitReimbursement,
updateReimbursementItem,
@@ -678,6 +679,9 @@ export function MobileReimbursementDetailPage() {
if (!files.length) {
throw new Error("请选择附件材料");
}
if (files.length > MAX_REIMBURSEMENT_ATTACHMENT_FILES) {
throw new Error(`单次最多上传 ${MAX_REIMBURSEMENT_ATTACHMENT_FILES} 个附件,请分批上传。`);
}
return uploadReimbursementAttachments(reimbursementId, files);
},
onSuccess: async () => {
@@ -1088,7 +1092,7 @@ export function MobileReimbursementDetailPage() {
<div className="flex items-center justify-between gap-3">
<div>
<h2 className="text-base font-semibold text-zinc-900">附件材料</h2>
<p className="mt-1 text-xs text-zinc-500">合同、订单、付款截图或情况说明</p>
<p className="mt-1 text-xs text-zinc-500">PDF/JPG/PNG/WebP,单次最多 5 个</p>
</div>
{canManageAttachments ? (
<Button
@@ -1110,7 +1114,16 @@ export function MobileReimbursementDetailPage() {
type="file"
accept="application/pdf,image/jpeg,image/png,image/webp"
multiple
onChange={(event) => setSelectedAttachmentFiles(Array.from(event.target.files ?? []))}
onChange={(event) => {
const files = Array.from(event.target.files ?? []);
if (files.length > MAX_REIMBURSEMENT_ATTACHMENT_FILES) {
setSelectedAttachmentFiles([]);
event.target.value = "";
toast.error(`单次最多上传 ${MAX_REIMBURSEMENT_ATTACHMENT_FILES} 个附件,请分批上传。`);
return;
}
setSelectedAttachmentFiles(files);
}}
/>
{selectedAttachmentFiles.length ? (
<div className="rounded-lg border border-zinc-200 bg-zinc-50 px-3 py-2 text-xs text-zinc-600">
+15 -2
查看文件
@@ -13,6 +13,7 @@ import {
deleteReimbursementItem,
downloadReimbursementAttachment,
fetchReimbursementDetail,
MAX_REIMBURSEMENT_ATTACHMENT_FILES,
precheckReimbursement,
submitReimbursement,
updateReimbursementItem,
@@ -662,6 +663,9 @@ export function ReimbursementDetailPage() {
if (!files.length) {
throw new Error("请选择附件材料");
}
if (files.length > MAX_REIMBURSEMENT_ATTACHMENT_FILES) {
throw new Error(`单次最多上传 ${MAX_REIMBURSEMENT_ATTACHMENT_FILES} 个附件,请分批上传。`);
}
return uploadReimbursementAttachments(reimbursementId, files);
},
onSuccess: async () => {
@@ -1496,7 +1500,7 @@ export function ReimbursementDetailPage() {
<div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
<div className="space-y-1">
<h3 className="text-base font-semibold text-zinc-900">补充附件</h3>
<p className="text-xs text-zinc-500">合同、订单、支付截图或情况说明;敏感附件下载会要求填写用途。</p>
<p className="text-xs text-zinc-500">合同、订单、支付截图或情况说明;PDF/JPG/PNG/WebP,单次最多 5 个。</p>
</div>
{canEditItems ? (
<div className="flex flex-col gap-2 md:flex-row md:items-center">
@@ -1516,7 +1520,16 @@ export function ReimbursementDetailPage() {
type="file"
accept="application/pdf,image/jpeg,image/png,image/webp"
multiple
onChange={(event) => setSelectedAttachmentFiles(Array.from(event.target.files ?? []))}
onChange={(event) => {
const files = Array.from(event.target.files ?? []);
if (files.length > MAX_REIMBURSEMENT_ATTACHMENT_FILES) {
setSelectedAttachmentFiles([]);
event.target.value = "";
toast.error(`单次最多上传 ${MAX_REIMBURSEMENT_ATTACHMENT_FILES} 个附件,请分批上传。`);
return;
}
setSelectedAttachmentFiles(files);
}}
/>
<Button
type="button"
+2 -6
查看文件
@@ -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);
});
+16 -7
查看文件
@@ -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 = {
+67
查看文件
@@ -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);
});
});