实现企微原生材料预览(07-27-yang-jun-reimbursement-readiness)
ci-e2e / e2e (push) Canceled after 0s
ci-minimal / check-minimal (push) Canceled after 0s

这个提交包含在:
2026-07-31 18:57:34 +08:00
父节点 e123d50f86
当前提交 410d8cd71b
共修改 23 个文件,包含 1352 行新增和 69 行删除
+38 -20
查看文件
@@ -105,6 +105,19 @@ function resolveInvoiceStatusReason(invoice) {
return resolveInvoiceAvailability(invoice);
}
function resolveSignedFileOrigin(config, request) {
const configured = String(config.appOrigin ?? "")
.split(",")
.map((item) => item.trim())
.find(Boolean);
return configured || `${request.protocol}://${request.headers.host ?? "localhost:3000"}`;
}
function resolvePreviewUrlTtlMs(config) {
const configuredSeconds = Math.max(30, Number(config.signedUrlTtlSeconds ?? 120));
return Math.min(configuredSeconds, 120) * 1000;
}
function ensureInvoiceReadableByUser(request, invoice) {
const roleCodes = request.employee.roleCodes;
const permissionCodes = request.employee.permissionCodes ?? [];
@@ -179,6 +192,9 @@ function registerInvoicePoolReadRoutes(fastify) {
owner_employee_id: true,
uploaded_by_employee_id: true,
linked_reimbursement_id: true,
original_name: true,
mime_type: true,
file_size: true,
linked_item_id: true,
travel_order_id: true,
invoice_code: true,
@@ -467,6 +483,9 @@ function registerInvoicePoolReadRoutes(fastify) {
owner_employee_id: true,
uploaded_by_employee_id: true,
linked_reimbursement_id: true,
original_name: true,
mime_type: true,
file_size: true,
linked_reimbursement: {
select: {
owner_id: true,
@@ -497,7 +516,7 @@ function registerInvoicePoolReadRoutes(fastify) {
});
}
const expiresAt = Date.now() + fastify.config.signedUrlTtlSeconds * 1000;
const expiresAt = Date.now() + resolvePreviewUrlTtlMs(fastify.config);
const token = signPayload(
{
invoiceId: invoice.id,
@@ -507,9 +526,7 @@ function registerInvoicePoolReadRoutes(fastify) {
fastify.config.jwtSecret,
);
const origin =
fastify.config.appOrigin ||
`${request.protocol}://${request.headers.host ?? "localhost:3000"}`;
const origin = resolveSignedFileOrigin(fastify.config, request);
const signedUrl = `${origin}/api/invoice-pool/${invoice.id}/file?token=${encodeURIComponent(token)}`;
await fastify.prisma.auditLog.create({
@@ -528,6 +545,9 @@ function registerInvoicePoolReadRoutes(fastify) {
return sendData(reply, request, {
signedUrl,
expiresAt: new Date(expiresAt).toISOString(),
originalName: invoice.original_name,
mimeType: invoice.mime_type,
fileSize: invoice.file_size,
});
},
);
@@ -610,24 +630,22 @@ function registerInvoicePoolReadRoutes(fastify) {
});
}
try {
await fastify.prisma.auditLog.create({
data: buildAuditLogData(request, {
actorId,
action: "INVOICE_FILE_DOWNLOADED",
targetType: "invoice_pool",
targetId: parsedInvoiceId.data,
extra: {
invoiceId: parsedInvoiceId.data,
exp: payload.exp,
},
}),
});
} catch (error) {
fastify.log.error({ err: error, invoiceId: parsedInvoiceId.data }, "Audit log write failed");
}
await fastify.prisma.auditLog.create({
data: buildAuditLogData(request, {
actorId,
action: "INVOICE_FILE_DOWNLOADED",
targetType: "invoice_pool",
targetId: parsedInvoiceId.data,
extra: {
invoiceId: parsedInvoiceId.data,
exp: payload.exp,
},
}),
});
reply.type(invoice.mime_type || "application/octet-stream");
reply.header("cache-control", "private, no-store");
reply.header("referrer-policy", "no-referrer");
reply.header(
"content-disposition",
buildAttachmentContentDisposition(invoice.original_name, { disposition: "inline" }),
+140 -13
查看文件
@@ -7,6 +7,7 @@ const { sendData } = require("../utils/reply");
const { buildAuditLogData } = require("../utils/audit");
const { sha256Hex } = require("../utils/crypto");
const { buildAttachmentContentDisposition } = require("../utils/contentDisposition");
const { signPayload, verifyToken } = require("../utils/signedUrl");
const { compactDateString, currentDateString, parseDateOnlyString } = require("../utils/date");
const { findActiveDelegationForDelegate, listActiveDelegationPrincipals } = require("../utils/delegation");
const { hasPermission, resolveEntityPermission } = require("../constants/permissions");
@@ -76,6 +77,22 @@ const REIMBURSEMENT_ATTACHMENT_DELETE_BODY_SCHEMA = z
reason: z.string().trim().min(2).max(200),
})
.strict();
const REIMBURSEMENT_ATTACHMENT_PREVIEW_BODY_SCHEMA = z
.object({ reason: z.string().trim().max(200).optional() })
.strict();
function resolveSignedFileOrigin(config, request) {
const configured = String(config.appOrigin ?? "")
.split(",")
.map((item) => item.trim())
.find(Boolean);
return configured || `${request.protocol}://${request.headers.host ?? "localhost:3000"}`;
}
function resolvePreviewUrlTtlMs(config) {
const configuredSeconds = Math.max(30, Number(config.signedUrlTtlSeconds ?? 120));
return Math.min(configuredSeconds, 120) * 1000;
}
const REIMBURSEMENT_CREATE_BODY_SCHEMA = z
.object({
@@ -2106,6 +2123,8 @@ async function reimbursementRoutes(fastify) {
seller_name: true,
total_amount: true,
original_name: true,
mime_type: true,
file_size: true,
linked_item_id: true,
},
},
@@ -2280,6 +2299,8 @@ async function reimbursementRoutes(fastify) {
sellerName: item.seller_name ?? null,
totalAmount: toMoneyString(item.total_amount),
originalName: item.original_name ?? null,
mimeType: item.mime_type ?? null,
fileSize: item.file_size ?? null,
linkedItemId: item.linked_item_id ?? null,
})),
pendingWorkflow: pendingInstance
@@ -2725,9 +2746,7 @@ async function reimbursementRoutes(fastify) {
fastify.get(
"/reimbursements/:id/attachments/:attachmentId/file",
{
preHandler: fastify.authenticate,
},
{},
async (request, reply) => {
const reimbursementId = parseReimbursementId(request.params?.id);
const parsedAttachmentId = UUID_SCHEMA.safeParse(request.params?.attachmentId);
@@ -2740,6 +2759,28 @@ async function reimbursementRoutes(fastify) {
});
}
const previewToken = typeof request.query?.previewToken === "string" ? request.query.previewToken : "";
let previewGrant = null;
if (previewToken) {
const verified = verifyToken(previewToken, fastify.config.jwtSecret);
const payload = verified.ok ? verified.payload : null;
const parsedActorId = UUID_SCHEMA.safeParse(payload?.actorId);
if (
!verified.ok ||
payload?.purpose !== "wecom_preview" ||
payload?.reimbursementId !== reimbursementId ||
payload?.attachmentId !== parsedAttachmentId.data ||
typeof payload?.exp !== "number" ||
payload.exp <= Date.now() ||
!parsedActorId.success
) {
throw new AppError({ code: "PERM_001", message: "无权限", statusCode: 403 });
}
previewGrant = { actorId: parsedActorId.data };
} else {
await fastify.authenticate(request);
}
const attachment = await fastify.prisma.reimbursementAttachment.findFirst({
where: {
id: parsedAttachmentId.data,
@@ -2750,6 +2791,7 @@ async function reimbursementRoutes(fastify) {
storage_path: true,
original_name: true,
mime_type: true,
file_size: true,
governance_status: true,
sensitivity_level: true,
attachment_type: true,
@@ -2770,15 +2812,23 @@ async function reimbursementRoutes(fastify) {
});
}
ensureOwnOrCanViewAll(fastify, request, attachment.reimbursement_form);
const downloadReason = sanitizeDownloadReason(request.query?.reason);
if (requiresDownloadReason(attachment) && !downloadReason) {
throw new AppError({
code: "VALID_001",
message: "参数校验失败",
statusCode: 400,
details: { reason: "required" },
});
let actorId;
let downloadReason;
if (previewGrant) {
actorId = previewGrant.actorId;
downloadReason = "企业微信在线预览";
} else {
ensureOwnOrCanViewAll(fastify, request, attachment.reimbursement_form);
actorId = request.employee.id;
downloadReason = sanitizeDownloadReason(request.query?.reason);
if (requiresDownloadReason(attachment) && !downloadReason) {
throw new AppError({
code: "VALID_001",
message: "参数校验失败",
statusCode: 400,
details: { reason: "required" },
});
}
}
let stream = null;
@@ -2801,7 +2851,7 @@ async function reimbursementRoutes(fastify) {
await fastify.prisma.auditLog.create({
data: buildAuditLogData(request, {
actorId: request.employee.id,
actorId,
action: "REIMBURSEMENT_ATTACHMENT_DOWNLOADED",
targetType: "reimbursement",
targetId: reimbursementId,
@@ -2816,6 +2866,8 @@ async function reimbursementRoutes(fastify) {
});
reply.type(attachment.mime_type || "application/octet-stream");
reply.header("cache-control", "private, no-store");
reply.header("referrer-policy", "no-referrer");
reply.header(
"content-disposition",
buildAttachmentContentDisposition(attachment.original_name, { disposition: "inline" }),
@@ -2824,6 +2876,81 @@ async function reimbursementRoutes(fastify) {
},
);
fastify.post(
"/reimbursements/:id/attachments/:attachmentId/preview-url",
{ preHandler: fastify.authenticate },
async (request, reply) => {
const reimbursementId = parseReimbursementId(request.params?.id);
const parsedAttachmentId = UUID_SCHEMA.safeParse(request.params?.attachmentId);
const parsedBody = REIMBURSEMENT_ATTACHMENT_PREVIEW_BODY_SCHEMA.safeParse(request.body ?? {});
if (!parsedAttachmentId.success || !parsedBody.success) {
throw new AppError({ code: "VALID_001", message: "参数校验失败", statusCode: 400 });
}
const attachment = await fastify.prisma.reimbursementAttachment.findFirst({
where: { id: parsedAttachmentId.data, reimbursement_id: reimbursementId },
select: {
id: true,
original_name: true,
mime_type: true,
file_size: true,
governance_status: true,
sensitivity_level: true,
attachment_type: true,
download_policy: true,
reimbursement_form: { select: { owner_id: true, submitter_id: true } },
},
});
if (!attachment) {
throw new AppError({ code: "SYS_404", message: "Not Found", statusCode: 404 });
}
ensureOwnOrCanViewAll(fastify, request, attachment.reimbursement_form);
const reason = sanitizeDownloadReason(parsedBody.data.reason);
if (requiresDownloadReason(attachment) && !reason) {
throw new AppError({
code: "VALID_001",
message: "参数校验失败",
statusCode: 400,
details: { reason: "required" },
});
}
const expiresAt = Date.now() + resolvePreviewUrlTtlMs(fastify.config);
const previewToken = signPayload({
purpose: "wecom_preview",
reimbursementId,
attachmentId: attachment.id,
actorId: request.employee.id,
exp: expiresAt,
}, fastify.config.jwtSecret);
const origin = resolveSignedFileOrigin(fastify.config, request);
const signedUrl = `${origin}/api/reimbursements/${reimbursementId}/attachments/${attachment.id}/file?previewToken=${encodeURIComponent(previewToken)}`;
await fastify.prisma.auditLog.create({
data: buildAuditLogData(request, {
actorId: request.employee.id,
action: "REIMBURSEMENT_ATTACHMENT_PREVIEW_URL_ISSUED",
targetType: "reimbursement",
targetId: reimbursementId,
extra: {
attachmentId: attachment.id,
attachmentType: attachment.attachment_type ?? ATTACHMENT_TYPE.supportingMaterial,
sensitivityLevel: attachment.sensitivity_level ?? SENSITIVITY_LEVEL.internal,
reason,
expiresAt,
},
}),
});
return sendData(reply, request, {
signedUrl,
expiresAt: new Date(expiresAt).toISOString(),
originalName: attachment.original_name,
mimeType: attachment.mime_type,
fileSize: attachment.file_size,
});
},
);
fastify.post(
"/reimbursements/:id/items",
{
+47
查看文件
@@ -16,6 +16,10 @@ const {
autoBindExistingWecomEmployee,
fetchWecomLoginIdentity,
} = require("../services/integrations/wecomLoginAutoBinding");
const {
getWecomJsApiTicket,
signWecomJsSdkUrl,
} = require("../services/integrations/wecomJsSdk");
const BIND_COOKIE_NAME = "wecom_bind";
const PENDING_LOGIN_BIND_COOKIE_NAME = "wecom_login_bind";
@@ -34,6 +38,7 @@ const QUERY_SCHEMA = z.object({
deviceFingerprint: z.string().trim().min(1).max(128).optional(),
});
const BIND_BODY_SCHEMA = z.object({ returnTo: z.string().optional() }).strict().optional();
const JS_SDK_SIGNATURE_BODY_SCHEMA = z.object({ url: z.string().trim().url().max(2048) }).strict();
function refreshCookieOptions(config) {
return {
@@ -108,6 +113,23 @@ function resolvePrimaryAppOrigin(config, request) {
return `${protocol}://${host}`;
}
function normalizeJsSdkPageUrl(rawUrl, config, request) {
let parsed;
try {
parsed = new URL(rawUrl);
} catch {
throw new AppError({ code: "VALID_001", message: "参数校验失败", statusCode: 400, details: { url: "invalid" } });
}
if (!["http:", "https:"].includes(parsed.protocol) || parsed.username || parsed.password || parsed.hash) {
throw new AppError({ code: "VALID_001", message: "参数校验失败", statusCode: 400, details: { url: "invalid" } });
}
const allowedOrigin = new URL(resolvePrimaryAppOrigin(config, request)).origin;
if (parsed.origin !== allowedOrigin) {
throw new AppError({ code: "PERM_001", message: "无权限", statusCode: 403 });
}
return parsed.href;
}
function parseAllowedReturnHosts(config, request) {
const hosts = new Set();
const appOrigins = String(config.appOrigin || "")
@@ -465,6 +487,31 @@ async function wecomAuthRoutes(fastify) {
return sendData(reply, request, resolveWecomEntryConfig(fastify.config));
});
fastify.post("/wecom/js-sdk-signature", { preHandler: fastify.authenticate }, async (request, reply) => {
const parsed = JS_SDK_SIGNATURE_BODY_SCHEMA.safeParse(request.body ?? {});
if (!parsed.success) {
throw new AppError({ code: "VALID_001", message: "参数校验失败", statusCode: 400, details: { url: "invalid" } });
}
const pageUrl = normalizeJsSdkPageUrl(parsed.data.url, fastify.config, request);
const ticketResult = await getWecomJsApiTicket({
config: fastify.config,
timeoutMs: fastify.config.wecomRequestTimeoutMs,
});
if (!ticketResult.ok) {
request.log.warn({ errorCode: ticketResult.code }, "wecom jsapi ticket unavailable");
throw new AppError({
code: "SYS_001",
message: "企业微信文件预览暂时不可用",
statusCode: 503,
details: { wecom: "jsapi_ticket_unavailable" },
});
}
return sendData(reply, request, {
corpId: String(fastify.config.wecomCorpId ?? ""),
...signWecomJsSdkUrl({ ticket: ticketResult.ticket, url: pageUrl }),
});
});
fastify.get("/wecom/login", async (request, reply) => {
const parsed = QUERY_SCHEMA.safeParse(request.query ?? {});
if (!parsed.success) {
@@ -0,0 +1,110 @@
const crypto = require("node:crypto");
const { getWecomAppAccessToken } = require("./wecomAccessToken");
const ticketCache = new Map();
function toSafeString(value, maxLength = 2000) {
if (value == null) return "";
return String(value).trim().slice(0, maxLength);
}
function credentialKey(config) {
return crypto
.createHash("sha256")
.update([
toSafeString(config?.wecomCorpId, 128),
toSafeString(config?.wecomAgentId, 64),
toSafeString(config?.wecomAgentSecret, 500),
].join(":"))
.digest("hex");
}
function sanitizeTicketResponse(payload) {
if (!payload || typeof payload !== "object") return null;
const result = {};
for (const key of ["errcode", "errmsg"]) {
if (payload[key] != null) result[key] = payload[key];
}
return Object.keys(result).length ? result : null;
}
async function getWecomJsApiTicket({ config, timeoutMs, fetchImpl = fetch }) {
const cacheKey = credentialKey(config);
const cached = ticketCache.get(cacheKey);
if (cached?.ticket && cached.expiresAt > Date.now() + 60 * 1000) {
return { ok: true, code: "wecom_jsapi_ticket_cached", ticket: cached.ticket };
}
const tokenResult = await getWecomAppAccessToken({ config, timeoutMs, fetchImpl });
if (!tokenResult.ok) {
return { ok: false, code: tokenResult.code, ticket: null };
}
const timeout = Math.max(100, Number(timeoutMs ?? config?.wecomRequestTimeoutMs ?? 5000));
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeout);
const url = new URL("https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket");
url.searchParams.set("access_token", tokenResult.accessToken);
try {
const response = await fetchImpl(url, { method: "GET", signal: controller.signal });
const payload = await response.json().catch(() => null);
if (!response.ok) {
return {
ok: false,
code: response.status >= 500 ? "wecom_jsapi_ticket_http_5xx" : "wecom_jsapi_ticket_http_error",
response: { status: response.status, body: sanitizeTicketResponse(payload) },
ticket: null,
};
}
if (!payload || Number(payload.errcode ?? 0) !== 0 || !payload.ticket) {
return {
ok: false,
code: "wecom_jsapi_ticket_api_error",
response: sanitizeTicketResponse(payload),
ticket: null,
};
}
const expiresIn = Math.max(300, Number(payload.expires_in ?? 7200));
const ticket = String(payload.ticket);
ticketCache.set(cacheKey, {
ticket,
expiresAt: Date.now() + Math.max(60, expiresIn - 120) * 1000,
});
return { ok: true, code: "wecom_jsapi_ticket_fetched", ticket };
} catch (error) {
return {
ok: false,
code: error?.name === "AbortError" ? "wecom_jsapi_ticket_timeout" : "wecom_jsapi_ticket_network_error",
ticket: null,
};
} finally {
clearTimeout(timer);
}
}
function signWecomJsSdkUrl({ ticket, url, timestamp = Math.floor(Date.now() / 1000), nonceStr = crypto.randomUUID() }) {
const canonical = [
`jsapi_ticket=${ticket}`,
`noncestr=${nonceStr}`,
`timestamp=${timestamp}`,
`url=${url}`,
].join("&");
return {
timestamp,
nonceStr,
signature: crypto.createHash("sha1").update(canonical).digest("hex"),
};
}
function clearWecomJsApiTicketCache() {
ticketCache.clear();
}
module.exports = {
clearWecomJsApiTicketCache,
getWecomJsApiTicket,
signWecomJsSdkUrl,
};
@@ -6,33 +6,60 @@ const Fastify = require("fastify");
const { AppError } = require("../../../src/utils/AppError");
const { registerInvoicePoolReadRoutes } = require("../../../src/routes/invoicePool/read");
const { signPayload } = require("../../../src/utils/signedUrl");
const { signPayload, verifyToken } = 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() {
async function buildApp({ auditFailure = null, invoiceOverrides = {}, employee = null, pendingTask = null } = {}) {
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 fileContents = "%PDF synthetic\n%%EOF\n";
await fs.writeFile(path.join(storageDir, "invoice.pdf"), fileContents);
const prisma = {
invoicePool: {
findUnique: vi.fn().mockResolvedValue({
id: INVOICE_ID,
owner_employee_id: ACTOR_ID,
uploaded_by_employee_id: ACTOR_ID,
linked_reimbursement_id: null,
linked_reimbursement: null,
storage_path: "invoice.pdf",
mime_type: "application/pdf",
original_name: "住宿电子普通发票.pdf",
file_size: Buffer.byteLength(fileContents),
...invoiceOverrides,
}),
},
workflowTask: {
findFirst: vi.fn().mockResolvedValue(pendingTask),
},
auditLog: {
create: vi.fn().mockResolvedValue({ id: "audit-1" }),
create: auditFailure
? vi.fn().mockRejectedValue(auditFailure)
: 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("config", {
jwtSecret: JWT_SECRET,
storageDir,
appOrigin: "https://oa.hyinda.com",
signedUrlTtlSeconds: 600,
});
app.decorate("authenticate", async (request) => {
if (!request.headers.authorization) {
throw new AppError({ code: "AUTH_001", message: "未登录", statusCode: 401 });
}
request.employee = employee ?? {
id: ACTOR_ID,
roleCodes: ["finance"],
permissionCodes: [],
};
});
app.decorate("hasPermission", () => false);
app.decorate("requirePermission", () => async () => {});
app.setErrorHandler((error, request, reply) => {
@@ -48,7 +75,7 @@ async function buildApp() {
});
});
await app.register(registerInvoicePoolReadRoutes, { prefix: "/api" });
return { app, prisma, storageDir };
return { app, prisma, storageDir, fileContents };
}
describe("GET /api/invoice-pool/:id/file", () => {
@@ -77,4 +104,119 @@ describe("GET /api/invoice-pool/:id/file", () => {
await fs.rm(storageDir, { recursive: true, force: true });
}
});
it("fails closed when the file access audit cannot be written", async () => {
const { app, storageDir } = await buildApp({ auditFailure: new Error("synthetic audit outage") });
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(500);
expect(response.json().error.code).toBe("SYS_001");
expect(response.body).not.toContain("%PDF synthetic");
} finally {
await app.close();
await fs.rm(storageDir, { recursive: true, force: true });
}
});
});
describe("POST /api/invoice-pool/:id/signed-url", () => {
it("issues an object-bound URL for at most 120 seconds with preview metadata", async () => {
const { app, prisma, storageDir, fileContents } = await buildApp();
const issuedBefore = Date.now();
try {
const response = await app.inject({
method: "POST",
url: `/api/invoice-pool/${INVOICE_ID}/signed-url`,
headers: { authorization: "Bearer test", "content-type": "application/json" },
payload: {},
});
expect(response.statusCode).toBe(200);
expect(response.json().data).toEqual(expect.objectContaining({
signedUrl: expect.stringMatching(/^https:\/\/oa\.hyinda\.com\/api\/invoice-pool\//),
originalName: "住宿电子普通发票.pdf",
mimeType: "application/pdf",
fileSize: Buffer.byteLength(fileContents),
}));
const url = new URL(response.json().data.signedUrl);
const verified = verifyToken(url.searchParams.get("token"), JWT_SECRET);
expect(verified).toEqual(expect.objectContaining({
ok: true,
payload: expect.objectContaining({ invoiceId: INVOICE_ID, actorId: ACTOR_ID }),
}));
expect(verified.payload.exp).toBeGreaterThanOrEqual(issuedBefore + 119_000);
expect(verified.payload.exp).toBeLessThanOrEqual(Date.now() + 120_000);
expect(prisma.auditLog.create).toHaveBeenCalledWith(expect.objectContaining({
data: expect.objectContaining({
action: "INVOICE_SIGNED_URL_ISSUED",
actor_id: ACTOR_ID,
target_id: INVOICE_ID,
}),
}));
} finally {
await app.close();
await fs.rm(storageDir, { recursive: true, force: true });
}
});
it("requires authentication before issuing a signed URL", async () => {
const { app, prisma, storageDir } = await buildApp();
try {
const response = await app.inject({
method: "POST",
url: `/api/invoice-pool/${INVOICE_ID}/signed-url`,
payload: {},
});
expect(response.statusCode).toBe(401);
expect(prisma.invoicePool.findUnique).not.toHaveBeenCalled();
} finally {
await app.close();
await fs.rm(storageDir, { recursive: true, force: true });
}
});
it("allows the current pending approver without granting invoice management permission", async () => {
const approverId = "33333333-3333-4333-8333-333333333333";
const linkedReimbursementId = "44444444-4444-4444-8444-444444444444";
const { app, prisma, storageDir } = await buildApp({
employee: { id: approverId, roleCodes: ["manager"], permissionCodes: [] },
invoiceOverrides: {
owner_employee_id: ACTOR_ID,
uploaded_by_employee_id: ACTOR_ID,
linked_reimbursement_id: linkedReimbursementId,
linked_reimbursement: { owner_id: ACTOR_ID, submitter_id: ACTOR_ID },
},
pendingTask: { id: "synthetic-pending-task" },
});
try {
const response = await app.inject({
method: "POST",
url: `/api/invoice-pool/${INVOICE_ID}/signed-url`,
headers: { authorization: "Bearer test", "content-type": "application/json" },
payload: {},
});
expect(response.statusCode).toBe(200);
expect(prisma.workflowTask.findFirst).toHaveBeenCalledWith(expect.objectContaining({
where: expect.objectContaining({ status: "pending" }),
}));
expect(prisma.auditLog.create).toHaveBeenCalledWith(expect.objectContaining({
data: expect.objectContaining({ actor_id: approverId, action: "INVOICE_SIGNED_URL_ISSUED" }),
}));
} finally {
await app.close();
await fs.rm(storageDir, { recursive: true, force: true });
}
});
});
@@ -7,6 +7,10 @@ const multipart = require("@fastify/multipart");
const { AppError } = require("../../../src/utils/AppError");
const reimbursementRoutes = require("../../../src/routes/reimbursements");
const { signPayload, verifyToken } = require("../../../src/utils/signedUrl");
const ACTOR_ID = "cccccccc-cccc-4ccc-8ccc-cccccccccccc";
const JWT_SECRET = "synthetic-reimbursement-preview-secret";
function buildMultipartRequest({ files, fields = {} }) {
const boundary = "----codex-reimbursement-attachment-boundary";
@@ -49,8 +53,8 @@ async function buildApp({ reimbursementStatus = "draft" } = {}) {
reimbursementForm: {
findUnique: vi.fn().mockResolvedValue({
id: reimbursementId,
owner_id: "actor-1",
submitter_id: "actor-1",
owner_id: ACTOR_ID,
submitter_id: ACTOR_ID,
status: reimbursementStatus,
}),
},
@@ -76,7 +80,7 @@ async function buildApp({ reimbursementStatus = "draft" } = {}) {
storage_path: data.storage_path,
created_at: new Date("2026-05-08T08:00:00.000Z"),
uploader: {
id: "actor-1",
id: ACTOR_ID,
employee_no: "E001",
name: "测试用户",
},
@@ -109,13 +113,14 @@ async function buildApp({ reimbursementStatus = "draft" } = {}) {
storage_path: item.storage_path,
original_name: item.original_name,
mime_type: item.mime_type,
file_size: item.file_size,
governance_status: item.governance_status,
sensitivity_level: item.sensitivity_level,
attachment_type: item.attachment_type,
download_policy: item.download_policy,
reimbursement_form: {
owner_id: "actor-1",
submitter_id: "actor-1",
owner_id: ACTOR_ID,
submitter_id: ACTOR_ID,
},
};
}),
@@ -126,8 +131,8 @@ async function buildApp({ reimbursementStatus = "draft" } = {}) {
$queryRaw: vi.fn().mockResolvedValue([
{
id: reimbursementId,
owner_id: "actor-1",
submitter_id: "actor-1",
owner_id: ACTOR_ID,
submitter_id: ACTOR_ID,
status: reimbursementStatus,
},
]),
@@ -140,13 +145,16 @@ async function buildApp({ reimbursementStatus = "draft" } = {}) {
appTimezone: "Asia/Shanghai",
storageDir: tempDir,
maxUploadSizeBytes: 5 * 1024 * 1024,
jwtSecret: JWT_SECRET,
appOrigin: "https://oa.hyinda.com",
signedUrlTtlSeconds: 600,
});
app.decorate("authenticate", async (request) => {
if (!request.headers.authorization) {
throw new AppError({ code: "AUTH_001", message: "未登录", statusCode: 401 });
}
request.employee = {
id: "actor-1",
id: ACTOR_ID,
roleCodes: ["employee"],
permissionCodes: ["expense.edit_own", "expense.view_own"],
};
@@ -464,4 +472,214 @@ describe("reimbursement attachment routes", () => {
await fs.rm(tempDir, { recursive: true, force: true });
}
});
it("issues and consumes a short-lived object-bound WeCom preview URL", async () => {
const { app, prisma, tempDir, reimbursementId } = await buildApp();
try {
const requestPayload = buildMultipartRequest({
files: [{ filename: "evidence.pdf", contentType: "application/pdf", content: "%PDF preview" }],
});
const uploadResponse = await app.inject({
method: "POST",
url: `/api/reimbursements/${reimbursementId}/attachments`,
headers: { authorization: "Bearer test", ...requestPayload.headers },
payload: requestPayload.payload,
});
const attachment = uploadResponse.json().data.items[0];
const issuedBefore = Date.now();
const previewResponse = await app.inject({
method: "POST",
url: `/api/reimbursements/${reimbursementId}/attachments/${attachment.id}/preview-url`,
headers: { authorization: "Bearer test", "content-type": "application/json" },
payload: {},
});
expect(previewResponse.statusCode).toBe(200);
expect(previewResponse.json().data).toEqual(expect.objectContaining({
signedUrl: expect.stringMatching(/^https:\/\/oa\.hyinda\.com\/api\/reimbursements\//),
originalName: "evidence.pdf",
mimeType: "application/pdf",
fileSize: Buffer.byteLength("%PDF preview"),
}));
const signedUrl = new URL(previewResponse.json().data.signedUrl);
const verified = verifyToken(signedUrl.searchParams.get("previewToken"), JWT_SECRET);
expect(verified).toEqual(expect.objectContaining({
ok: true,
payload: expect.objectContaining({
purpose: "wecom_preview",
reimbursementId,
attachmentId: attachment.id,
actorId: ACTOR_ID,
}),
}));
expect(verified.payload.exp).toBeGreaterThanOrEqual(issuedBefore + 119_000);
expect(verified.payload.exp).toBeLessThanOrEqual(Date.now() + 120_000);
expect(prisma.auditLog.create).toHaveBeenCalledWith(expect.objectContaining({
data: expect.objectContaining({ action: "REIMBURSEMENT_ATTACHMENT_PREVIEW_URL_ISSUED" }),
}));
const fileResponse = await app.inject({
method: "GET",
url: `${signedUrl.pathname}${signedUrl.search}`,
});
expect(fileResponse.statusCode).toBe(200);
expect(fileResponse.body).toBe("%PDF preview");
expect(fileResponse.headers["cache-control"]).toBe("private, no-store");
expect(fileResponse.headers["referrer-policy"]).toBe("no-referrer");
expect(prisma.auditLog.create).toHaveBeenCalledWith(expect.objectContaining({
data: expect.objectContaining({
action: "REIMBURSEMENT_ATTACHMENT_DOWNLOADED",
actor_id: ACTOR_ID,
extra: expect.objectContaining({ reason: "企业微信在线预览" }),
}),
}));
} finally {
await app.close();
await fs.rm(tempDir, { recursive: true, force: true });
}
});
it("rejects tampered, expired, and object-mismatched preview grants", async () => {
const { app, tempDir, reimbursementId } = await buildApp();
try {
const requestPayload = buildMultipartRequest({
files: [{ filename: "evidence.pdf", contentType: "application/pdf", content: "%PDF preview" }],
});
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;
const basePayload = {
purpose: "wecom_preview",
reimbursementId,
attachmentId,
actorId: ACTOR_ID,
};
const validToken = signPayload({ ...basePayload, exp: Date.now() + 60_000 }, JWT_SECRET);
const tamperedToken = `${validToken.slice(0, -1)}${validToken.endsWith("a") ? "b" : "a"}`;
const expiredToken = signPayload({ ...basePayload, exp: Date.now() - 1 }, JWT_SECRET);
const mismatchedToken = signPayload({
...basePayload,
reimbursementId: "dddddddd-dddd-4ddd-8ddd-dddddddddddd",
exp: Date.now() + 60_000,
}, JWT_SECRET);
for (const token of [tamperedToken, expiredToken, mismatchedToken]) {
const response = await app.inject({
method: "GET",
url: `/api/reimbursements/${reimbursementId}/attachments/${attachmentId}/file?previewToken=${encodeURIComponent(token)}`,
});
expect(response.statusCode).toBe(403);
expect(response.json().error.code).toBe("PERM_001");
}
} finally {
await app.close();
await fs.rm(tempDir, { recursive: true, force: true });
}
});
it("requires login and any configured download reason before issuing a preview URL", async () => {
const { app, prisma, tempDir, reimbursementId, createdAttachments } = await buildApp();
try {
const requestPayload = buildMultipartRequest({
files: [{ filename: "evidence.pdf", contentType: "application/pdf", content: "%PDF preview" }],
});
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].download_policy = "reason_required";
prisma.auditLog.create.mockClear();
const unauthenticated = await app.inject({
method: "POST",
url: `/api/reimbursements/${reimbursementId}/attachments/${attachmentId}/preview-url`,
payload: {},
});
const missingReason = await app.inject({
method: "POST",
url: `/api/reimbursements/${reimbursementId}/attachments/${attachmentId}/preview-url`,
headers: { authorization: "Bearer test", "content-type": "application/json" },
payload: {},
});
expect(unauthenticated.statusCode).toBe(401);
expect(missingReason.statusCode).toBe(400);
expect(missingReason.json().error.details).toEqual({ reason: "required" });
expect(prisma.auditLog.create).not.toHaveBeenCalled();
} finally {
await app.close();
await fs.rm(tempDir, { recursive: true, force: true });
}
});
it("fails closed before preview bytes when the access audit cannot be written", async () => {
const { app, prisma, tempDir, reimbursementId } = await buildApp();
try {
const requestPayload = buildMultipartRequest({
files: [{ filename: "evidence.pdf", contentType: "application/pdf", content: "%PDF preview" }],
});
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;
const previewToken = signPayload({
purpose: "wecom_preview",
reimbursementId,
attachmentId,
actorId: ACTOR_ID,
exp: Date.now() + 60_000,
}, JWT_SECRET);
prisma.auditLog.create.mockRejectedValueOnce(new Error("synthetic audit outage"));
const response = await app.inject({
method: "GET",
url: `/api/reimbursements/${reimbursementId}/attachments/${attachmentId}/file?previewToken=${encodeURIComponent(previewToken)}`,
});
expect(response.statusCode).toBe(500);
expect(response.json().error.code).toBe("SYS_001");
expect(response.body).not.toContain("%PDF preview");
} finally {
await app.close();
await fs.rm(tempDir, { recursive: true, force: true });
}
});
it("rejects missing or invalid authorization before looking up the attachment", async () => {
const { app, prisma, tempDir, reimbursementId } = await buildApp();
const attachmentId = "bbbbbbbb-bbbb-4bbb-8bbb-000000000001";
try {
const unauthenticated = await app.inject({
method: "GET",
url: `/api/reimbursements/${reimbursementId}/attachments/${attachmentId}/file`,
});
const invalidGrant = await app.inject({
method: "GET",
url: `/api/reimbursements/${reimbursementId}/attachments/${attachmentId}/file?previewToken=invalid`,
});
expect(unauthenticated.statusCode).toBe(401);
expect(invalidGrant.statusCode).toBe(403);
expect(prisma.reimbursementAttachment.findFirst).not.toHaveBeenCalled();
} finally {
await app.close();
await fs.rm(tempDir, { recursive: true, force: true });
}
});
});
+115
查看文件
@@ -4,6 +4,8 @@ const fastifyCookie = require("@fastify/cookie");
const { AppError } = require("../../../src/utils/AppError");
const wecomAuthRoutes = require("../../../src/routes/wecomAuth");
const { signPayload, verifyToken } = require("../../../src/utils/signedUrl");
const { clearWecomAppAccessTokenCache } = require("../../../src/services/integrations/wecomAccessToken");
const { clearWecomJsApiTicketCache } = require("../../../src/services/integrations/wecomJsSdk");
const NOW = new Date("2026-03-22T11:00:00.000Z");
const EMPLOYEE_ID = "11111111-1111-4111-8111-111111111111";
@@ -103,6 +105,8 @@ function mockWecomFetchWithPayload(payload) {
afterEach(() => {
global.fetch = originalFetch;
clearWecomAppAccessTokenCache();
clearWecomJsApiTicketCache();
vi.restoreAllMocks();
});
@@ -1069,4 +1073,115 @@ describe("wecom auth routes R27", () => {
await app.close();
});
it("signs a same-origin page URL without exposing WeCom credentials", async () => {
global.fetch = vi.fn()
.mockResolvedValueOnce({
ok: true,
json: async () => ({ errcode: 0, access_token: "synthetic-access-token", expires_in: 7200 }),
})
.mockResolvedValueOnce({
ok: true,
json: async () => ({ errcode: 0, ticket: "synthetic-jsapi-ticket", expires_in: 7200 }),
});
const app = await buildApp();
const response = await app.inject({
method: "POST",
url: "/api/auth/wecom/js-sdk-signature",
headers: { authorization: "Bearer test-token", "content-type": "application/json" },
payload: { url: "https://oa.hyinda.com/mobile/reimbursements/test?source=wecom" },
});
expect(response.statusCode).toBe(200);
expect(response.json().data).toEqual({
corpId: "wx-test-corp",
timestamp: expect.any(Number),
nonceStr: expect.any(String),
signature: expect.stringMatching(/^[a-f0-9]{40}$/),
});
const serialized = JSON.stringify(response.json()).toLowerCase();
expect(serialized).not.toContain("synthetic-access-token");
expect(serialized).not.toContain("synthetic-jsapi-ticket");
expect(serialized).not.toContain("wecom-secret");
expect(global.fetch).toHaveBeenCalledTimes(2);
await app.close();
});
it("rejects cross-origin and credential-bearing JS-SDK signing URLs before provider access", async () => {
global.fetch = vi.fn();
const app = await buildApp();
const crossOrigin = await app.inject({
method: "POST",
url: "/api/auth/wecom/js-sdk-signature",
headers: { authorization: "Bearer test-token", "content-type": "application/json" },
payload: { url: "https://evil.example/mobile" },
});
const credentialUrl = await app.inject({
method: "POST",
url: "/api/auth/wecom/js-sdk-signature",
headers: { authorization: "Bearer test-token", "content-type": "application/json" },
payload: { url: "https://user:[email protected]/mobile" },
});
const fragmentUrl = await app.inject({
method: "POST",
url: "/api/auth/wecom/js-sdk-signature",
headers: { authorization: "Bearer test-token", "content-type": "application/json" },
payload: { url: "https://oa.hyinda.com/mobile#detail" },
});
expect(crossOrigin.statusCode).toBe(403);
expect(credentialUrl.statusCode).toBe(400);
expect(fragmentUrl.statusCode).toBe(400);
expect(global.fetch).not.toHaveBeenCalled();
await app.close();
});
it("returns a stable redacted error when the JSAPI ticket provider fails", async () => {
global.fetch = vi.fn()
.mockResolvedValueOnce({
ok: true,
json: async () => ({ errcode: 0, access_token: "synthetic-access-token", expires_in: 7200 }),
})
.mockResolvedValueOnce({
ok: true,
json: async () => ({ errcode: 40001, errmsg: "provider-secret-detail" }),
});
const app = await buildApp();
const response = await app.inject({
method: "POST",
url: "/api/auth/wecom/js-sdk-signature",
headers: { authorization: "Bearer test-token", "content-type": "application/json" },
payload: { url: "https://oa.hyinda.com/mobile" },
});
expect(response.statusCode).toBe(503);
expect(response.json().error.details).toEqual({ wecom: "jsapi_ticket_unavailable" });
expect(JSON.stringify(response.json())).not.toContain("provider-secret-detail");
expect(JSON.stringify(response.json())).not.toContain("synthetic-access-token");
await app.close();
});
it("fails closed without provider access when JS-SDK credentials are incomplete", async () => {
global.fetch = vi.fn();
const app = await buildApp({ config: { wecomAgentSecret: "" } });
const response = await app.inject({
method: "POST",
url: "/api/auth/wecom/js-sdk-signature",
headers: { authorization: "Bearer test-token", "content-type": "application/json" },
payload: { url: "https://oa.hyinda.com/mobile" },
});
expect(response.statusCode).toBe(503);
expect(response.json().error.details).toEqual({ wecom: "jsapi_ticket_unavailable" });
expect(global.fetch).not.toHaveBeenCalled();
await app.close();
});
});