实现企微原生材料预览(07-27-yang-jun-reimbursement-readiness)
这个提交包含在:
@@ -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",
|
||||
{
|
||||
|
||||
@@ -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) {
|
||||
|
||||
在新工单中引用
屏蔽一个用户