Add material pack attachment file policy
This commit is contained in:
1 parent
e512ee68dc
commit
79c9420e4e
19 files changed
+487
-182
No files matched your search
@@ -13,6 +13,7 @@ import {
|
||||
} from "../../domains/seal/material-pack/index.js";
|
||||
import {
|
||||
booleanOption,
|
||||
materialPackFilePolicyOptions,
|
||||
parseWebhookMode,
|
||||
stringOption,
|
||||
webhookRateOption,
|
||||
@@ -20,11 +21,15 @@ import {
|
||||
} from "../parser.js";
|
||||
import { outputOptions } from "../printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
import type { MaterialPackFilePolicyPatch } from "../../domains/seal/material-pack/policy.js";
|
||||
|
||||
export async function handleWebhookMaterialPackPreview(filePath: string) {
|
||||
export async function handleWebhookMaterialPackPreview(
|
||||
filePath: string,
|
||||
filePolicy?: MaterialPackFilePolicyPatch
|
||||
) {
|
||||
if (!existsSync(filePath)) throw new Error(`File not found: ${filePath}`);
|
||||
const input = readMaterialPackFile(filePath);
|
||||
console.log(JSON.stringify(await previewMaterialPack(input.fileBuffer, input.fileName), null, 2));
|
||||
console.log(JSON.stringify(await previewMaterialPack(input.fileBuffer, input.fileName, filePolicy), null, 2));
|
||||
}
|
||||
|
||||
export async function handleWebhookCommand(
|
||||
@@ -36,7 +41,10 @@ export async function handleWebhookCommand(
|
||||
) {
|
||||
if (action === "ready" || action === "status") {
|
||||
const filePath = maybeName ?? stringOption(args.options.file) ?? stringOption(args.options.input);
|
||||
const result = await checkWebhookReadiness(client, corp, { filePath });
|
||||
const result = await checkWebhookReadiness(client, corp, {
|
||||
filePath,
|
||||
webhook: stringOption(args.options.webhook) ?? stringOption(args.options.selector)
|
||||
});
|
||||
console.error(`[webhook-ready] 企业环境: ${result.corp.name} (${result.corp.id}) [${result.stateMode}]`);
|
||||
if (result.corp.tenant?.name) {
|
||||
console.error(`[webhook-ready] 租户信息: ${result.corp.tenant.name} (${result.corp.tenant.id})`);
|
||||
@@ -96,7 +104,8 @@ export async function handleWebhookCommand(
|
||||
}
|
||||
const result = await pushMaterialPack(input.fileBuffer, input.fileName, {
|
||||
webhookUrl: integration.incomingDocumentWebhook.url,
|
||||
secret: integration.secret
|
||||
secret: integration.secret,
|
||||
materialPackFilePolicy: integration.materialPackFilePolicy
|
||||
});
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
return;
|
||||
@@ -142,6 +151,7 @@ export async function handleWebhookCommand(
|
||||
throw new Error("Usage: seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic]");
|
||||
}
|
||||
const autoApprovalRate = webhookRateOption(args.options);
|
||||
const materialPackFilePolicy = materialPackFilePolicyOptions(args.options);
|
||||
await runTool(
|
||||
"seal_webhook_add",
|
||||
client,
|
||||
@@ -151,7 +161,8 @@ export async function handleWebhookCommand(
|
||||
mode: parseWebhookMode(stringOption(args.options.mode)),
|
||||
outgoingResultWebhook,
|
||||
autoApprovalRate,
|
||||
secret: stringOption(args.options.secret)
|
||||
secret: stringOption(args.options.secret),
|
||||
materialPackFilePolicy
|
||||
},
|
||||
outputOptions(args.options)
|
||||
);
|
||||
@@ -174,13 +185,15 @@ export async function handleWebhookCommand(
|
||||
stringOption(args.options.outgoingResultWebhook) ??
|
||||
stringOption(args.options["outgoing-result-webhook"]);
|
||||
const autoApprovalRate = webhookRateOption(args.options);
|
||||
const materialPackFilePolicy = materialPackFilePolicyOptions(args.options);
|
||||
if (
|
||||
name === undefined &&
|
||||
mode === undefined &&
|
||||
outgoingResultWebhook === undefined &&
|
||||
autoApprovalRate === undefined &&
|
||||
secret === undefined &&
|
||||
!rotateSecret
|
||||
!rotateSecret &&
|
||||
materialPackFilePolicy === undefined
|
||||
) {
|
||||
throw new Error("Webhook update requires at least one field option");
|
||||
}
|
||||
@@ -195,7 +208,8 @@ export async function handleWebhookCommand(
|
||||
outgoingResultWebhook,
|
||||
autoApprovalRate,
|
||||
secret,
|
||||
rotateSecret
|
||||
rotateSecret,
|
||||
materialPackFilePolicy
|
||||
},
|
||||
outputOptions(args.options)
|
||||
);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { WebhookMode } from "../domains/seal/types.js";
|
||||
import type { MaterialPackFilePolicyPatch } from "../domains/seal/material-pack/policy.js";
|
||||
import type { ParsedArgs } from "./types.js";
|
||||
|
||||
export function parseArgs(argv: string[]): ParsedArgs {
|
||||
@@ -201,3 +202,23 @@ export function webhookRateOption(options: Record<string, string | boolean>): nu
|
||||
export function webhookShowSecretOption(options: Record<string, string | boolean>): boolean | undefined {
|
||||
return booleanOption(options.showSecret) ?? booleanOption(options["show-secret"]);
|
||||
}
|
||||
|
||||
export function materialPackFilePolicyOptions(
|
||||
options: Record<string, string | boolean>
|
||||
): MaterialPackFilePolicyPatch | undefined {
|
||||
const minFileSizeBytes = numberOption(
|
||||
options.minFileSizeBytes ?? options["min-file-size-bytes"] ?? options.minFileSize ?? options["min-file-size"]
|
||||
);
|
||||
const maxFileSizeBytes = numberOption(
|
||||
options.maxFileSizeBytes ?? options["max-file-size-bytes"] ?? options.maxFileSize ?? options["max-file-size"]
|
||||
);
|
||||
const allowedExtensions = splitOption(
|
||||
options.allowedExtensions ?? options["allowed-extensions"] ?? options.extensions
|
||||
);
|
||||
|
||||
if (minFileSizeBytes === undefined && maxFileSizeBytes === undefined && allowedExtensions === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return { minFileSizeBytes, maxFileSizeBytes, allowedExtensions };
|
||||
}
|
||||
+4
-4
@@ -118,14 +118,14 @@ Usage:
|
||||
seal-use billing status [--corp <corpId>]
|
||||
seal-use billing plans [--corp <corpId>]
|
||||
seal-use billing features [--corp <corpId>]
|
||||
seal-use webhook ready [<材料包.zip>] [--corp <corpId>]
|
||||
seal-use webhook ready [<材料包.zip>] [--webhook <idOrName>] [--corp <corpId>]
|
||||
seal-use webhook status [<材料包.zip>] [--corp <corpId>]
|
||||
seal-use webhook list [--query <text>] [--show-secret] [--corp <corpId>]
|
||||
seal-use webhook get|find <idOrName> [--show-secret] [--corp <corpId>]
|
||||
seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--corp <corpId>]
|
||||
seal-use webhook update <idOrName> [--name <name>] [--result-url <url>] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>|--rotate-secret] [--corp <corpId>]
|
||||
seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--min-file-size 500] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--corp <corpId>]
|
||||
seal-use webhook update <idOrName> [--name <name>] [--result-url <url>] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>|--rotate-secret] [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--corp <corpId>]
|
||||
seal-use webhook delete <idOrName> --yes [--corp <corpId>]
|
||||
seal-use webhook material-pack preview <材料包.zip|信息表.xlsx> [--corp <corpId>]
|
||||
seal-use webhook material-pack preview <材料包.zip|信息表.xlsx> [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--corp <corpId>]
|
||||
seal-use webhook material-pack push <材料包.zip|信息表.xlsx> [--webhook <idOrName>] [--corp <corpId>]
|
||||
seal-use deploy hosecloud requirements [--corp <corpId>]
|
||||
seal-use deploy hosecloud list [--corp <corpId>]
|
||||
|
||||
+8
-2
@@ -31,7 +31,13 @@ import { handleUpdateCommand } from "./commands/update.js";
|
||||
import { handleUsersCommand } from "./commands/users.js";
|
||||
import { handleWebhookCommand, handleWebhookMaterialPackPreview } from "./commands/webhook.js";
|
||||
import { selectCorp } from "./helpers.js";
|
||||
import { booleanOption, numberOption, parseArgs, stringOption } from "./parser.js";
|
||||
import {
|
||||
booleanOption,
|
||||
materialPackFilePolicyOptions,
|
||||
numberOption,
|
||||
parseArgs,
|
||||
stringOption
|
||||
} from "./parser.js";
|
||||
import {
|
||||
formatConsoleOutput,
|
||||
joinOutput,
|
||||
@@ -174,7 +180,7 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
|
||||
if (area === "webhook" && action === "material-pack" && maybeName === "preview") {
|
||||
const filePath = args.command[3] ?? stringOption(args.options.file) ?? stringOption(args.options.input);
|
||||
if (!filePath) throw new Error("Usage: seal-use webhook material-pack preview <材料包.zip>");
|
||||
await handleWebhookMaterialPackPreview(filePath);
|
||||
await handleWebhookMaterialPackPreview(filePath, materialPackFilePolicyOptions(args.options));
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -112,10 +112,20 @@ describe("Seal Webhook API", () => {
|
||||
|
||||
const updated = await updateWebhookIntegration(client, "integration-1", {
|
||||
name: "Renamed webhook",
|
||||
rotateSecret: true
|
||||
rotateSecret: true,
|
||||
materialPackFilePolicy: {
|
||||
minFileSizeBytes: 1000,
|
||||
maxFileSizeBytes: 2000,
|
||||
allowedExtensions: ["PDF", "xlsx"]
|
||||
}
|
||||
});
|
||||
expect(updated.name).toBe("Renamed webhook");
|
||||
expect(updated.secret).not.toBe("webhook-secret");
|
||||
expect(updated.materialPackFilePolicy).toEqual({
|
||||
minFileSizeBytes: 1000,
|
||||
maxFileSizeBytes: 2000,
|
||||
allowedExtensions: [".pdf", ".xlsx"]
|
||||
});
|
||||
expect((posted?.integrations as Array<Record<string, unknown>>)[1]).toMatchObject({ type: "hosecloud" });
|
||||
|
||||
const found = findWebhookIntegration([updated], "Renamed webhook");
|
||||
|
||||
+19
-2
@@ -1,6 +1,11 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import ky, { HTTPError, KyInstance } from "ky";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
mergeMaterialPackFilePolicy,
|
||||
normalizeMaterialPackFilePolicy,
|
||||
type MaterialPackFilePolicyPatch
|
||||
} from "./material-pack/policy.js";
|
||||
import { CorpConfig } from "../../core/config/types.js";
|
||||
import { ensureHoseOpenapiToken, fetchHoseCloseApiToken, defaultSealUrl, normalizeBaseUrl } from "../../core/auth/hose.js";
|
||||
import {
|
||||
@@ -289,6 +294,7 @@ export async function addWebhookIntegration(
|
||||
outgoingResultWebhook: string;
|
||||
autoApprovalRate?: number;
|
||||
secret?: string;
|
||||
materialPackFilePolicy?: MaterialPackFilePolicyPatch;
|
||||
},
|
||||
endpoint = "api/v1/agent/ai-approval/config"
|
||||
): Promise<WebhookIntegration> {
|
||||
@@ -317,6 +323,7 @@ export async function updateWebhookIntegration(
|
||||
autoApprovalRate?: number;
|
||||
secret?: string;
|
||||
rotateSecret?: boolean;
|
||||
materialPackFilePolicy?: MaterialPackFilePolicyPatch;
|
||||
},
|
||||
endpoint = "api/v1/agent/ai-approval/config"
|
||||
): Promise<WebhookIntegration> {
|
||||
@@ -335,7 +342,15 @@ export async function updateWebhookIntegration(
|
||||
: { autoApprovalRate: validApprovalRate(params.autoApprovalRate) }),
|
||||
...(params.rotateSecret || params.secret !== undefined
|
||||
? { secret: params.rotateSecret ? generateWebhookSecret() : requiredText(params.secret ?? "", "secret") }
|
||||
: {})
|
||||
: {}),
|
||||
...(params.materialPackFilePolicy === undefined
|
||||
? {}
|
||||
: {
|
||||
materialPackFilePolicy: mergeMaterialPackFilePolicy(
|
||||
entry.integration.materialPackFilePolicy,
|
||||
params.materialPackFilePolicy
|
||||
)
|
||||
})
|
||||
});
|
||||
|
||||
const saved = await saveApprovalStylePreferences(client, {
|
||||
@@ -445,6 +460,7 @@ function createWebhookIntegration(
|
||||
outgoingResultWebhook: string;
|
||||
autoApprovalRate?: number;
|
||||
secret?: string;
|
||||
materialPackFilePolicy?: MaterialPackFilePolicyPatch;
|
||||
}
|
||||
): WebhookIntegration {
|
||||
const name = requiredText(params.name, "name");
|
||||
@@ -470,7 +486,8 @@ function createWebhookIntegration(
|
||||
url: `${root}/api/v1/integrations/webhook/${webhookId}/manual-result`
|
||||
},
|
||||
secret: params.secret ? requiredText(params.secret, "secret") : generateWebhookSecret(),
|
||||
autoApprovalRate
|
||||
autoApprovalRate,
|
||||
materialPackFilePolicy: normalizeMaterialPackFilePolicy(params.materialPackFilePolicy)
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
export * from "./types.js";
|
||||
export * from "./policy.js";
|
||||
export * from "./signature.js";
|
||||
export * from "./validate.js";
|
||||
export * from "./parse.js";
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { z } from "zod"
|
||||
|
||||
export const DEFAULT_MATERIAL_PACK_ALLOWED_EXTENSIONS = [
|
||||
".pdf",
|
||||
".xls",
|
||||
".xlsx",
|
||||
".csv",
|
||||
".doc",
|
||||
".docx",
|
||||
".ppt",
|
||||
".pptx",
|
||||
".txt",
|
||||
".rtf",
|
||||
".odt",
|
||||
".ods",
|
||||
".odp",
|
||||
".jpg",
|
||||
".jpeg",
|
||||
".png",
|
||||
".gif",
|
||||
".bmp",
|
||||
".webp",
|
||||
".heic",
|
||||
".eml",
|
||||
".msg"
|
||||
] as const
|
||||
|
||||
export const DEFAULT_MATERIAL_PACK_FILE_POLICY = {
|
||||
minFileSizeBytes: 500,
|
||||
allowedExtensions: [...DEFAULT_MATERIAL_PACK_ALLOWED_EXTENSIONS]
|
||||
}
|
||||
|
||||
const fileExtensionSchema = z.string().trim().min(1).transform((value) => {
|
||||
const normalized = value.toLowerCase()
|
||||
return normalized.startsWith(".") ? normalized : `.${normalized}`
|
||||
}).refine((value) => /^\.[a-z0-9][a-z0-9+_-]*$/.test(value), {
|
||||
message: "文件后缀必须是简单扩展名,例如 .pdf 或 xlsx"
|
||||
})
|
||||
|
||||
export const MaterialPackFilePolicySchema = z.object({
|
||||
minFileSizeBytes: z.number().int().min(0).default(DEFAULT_MATERIAL_PACK_FILE_POLICY.minFileSizeBytes),
|
||||
maxFileSizeBytes: z.number().int().positive().nullable().optional(),
|
||||
allowedExtensions: z.array(fileExtensionSchema).min(1).default([...DEFAULT_MATERIAL_PACK_ALLOWED_EXTENSIONS])
|
||||
.transform((extensions) => [...new Set(extensions)])
|
||||
}).superRefine((policy, ctx) => {
|
||||
if (
|
||||
policy.maxFileSizeBytes !== undefined &&
|
||||
policy.maxFileSizeBytes !== null &&
|
||||
policy.maxFileSizeBytes < policy.minFileSizeBytes
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["maxFileSizeBytes"],
|
||||
message: "最大文件大小不能小于最小文件大小"
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
export const MaterialPackFilePolicyPatchSchema = z.object({
|
||||
minFileSizeBytes: z.number().int().min(0).optional(),
|
||||
maxFileSizeBytes: z.number().int().positive().nullable().optional(),
|
||||
allowedExtensions: z.array(fileExtensionSchema).min(1)
|
||||
.transform((extensions) => [...new Set(extensions)])
|
||||
}).optional()
|
||||
|
||||
export type MaterialPackFilePolicy = z.infer<typeof MaterialPackFilePolicySchema>
|
||||
export type MaterialPackFilePolicyPatch = Partial<MaterialPackFilePolicy>
|
||||
|
||||
export function normalizeMaterialPackFilePolicy(
|
||||
policy: MaterialPackFilePolicyPatch | undefined = undefined
|
||||
): MaterialPackFilePolicy {
|
||||
return MaterialPackFilePolicySchema.parse(policy ?? {})
|
||||
}
|
||||
|
||||
export function mergeMaterialPackFilePolicy(
|
||||
current: MaterialPackFilePolicy | undefined,
|
||||
patch: MaterialPackFilePolicyPatch
|
||||
): MaterialPackFilePolicy {
|
||||
return normalizeMaterialPackFilePolicy({
|
||||
...normalizeMaterialPackFilePolicy(current),
|
||||
...patch
|
||||
})
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import type { WebhookReadyResult } from "./types.js";
|
||||
export async function checkWebhookReadiness(
|
||||
client: KyInstance,
|
||||
corp: CorpConfig,
|
||||
options: { filePath?: string } = {}
|
||||
options: { filePath?: string; webhook?: string } = {}
|
||||
): Promise<WebhookReadyResult> {
|
||||
const globalConfig = loadGlobalConfig();
|
||||
const stateMode = globalConfig.stateful ? "stateful" : "stateless";
|
||||
@@ -66,6 +66,12 @@ export async function checkWebhookReadiness(
|
||||
? { id: rawWebhooks[0]!.id, name: rawWebhooks[0]!.name, mode: rawWebhooks[0]!.mode }
|
||||
: null;
|
||||
|
||||
const materialPackWebhook = options.webhook
|
||||
? api.findWebhookIntegration(rawWebhooks, options.webhook)
|
||||
: isSingle
|
||||
? rawWebhooks[0]
|
||||
: undefined;
|
||||
|
||||
let materialPack: WebhookReadyResult["materialPack"];
|
||||
if (options.filePath) {
|
||||
if (!existsSync(options.filePath)) {
|
||||
@@ -79,7 +85,11 @@ export async function checkWebhookReadiness(
|
||||
} else {
|
||||
try {
|
||||
const input = readMaterialPackFile(options.filePath);
|
||||
const preview = await previewMaterialPack(input.fileBuffer, input.fileName);
|
||||
const preview = await previewMaterialPack(
|
||||
input.fileBuffer,
|
||||
input.fileName,
|
||||
materialPackWebhook?.materialPackFilePolicy
|
||||
);
|
||||
materialPack = {
|
||||
valid: true,
|
||||
filePath: options.filePath,
|
||||
|
||||
@@ -4,6 +4,7 @@ import { buildAttachmentPlans, injectAttachmentPlan } from "./attachments.js"
|
||||
import { parseMaterialWorkbook } from "./parse.js"
|
||||
import { extractZipEntry, readZipEntries, validatePackEntries, type ZipEntry } from "./validate.js"
|
||||
import { MaterialPackValidationError, type MaterialPackPreview, type MaterialPackPushResult } from "./types.js"
|
||||
import type { MaterialPackFilePolicyPatch } from "./policy.js"
|
||||
|
||||
function webhookInfo(url: string): { baseUrl: string; webhookId: string } {
|
||||
const parsed = new URL(url)
|
||||
@@ -54,12 +55,16 @@ function validateDocIdDirectories(entries: ZipEntry[], documentIds: string[]): v
|
||||
if (errors.length) throw new MaterialPackValidationError(errors)
|
||||
}
|
||||
|
||||
async function prepare(fileBuffer: Uint8Array, fileName: string) {
|
||||
async function prepare(
|
||||
fileBuffer: Uint8Array,
|
||||
fileName: string,
|
||||
filePolicy?: MaterialPackFilePolicyPatch
|
||||
) {
|
||||
let entries: ZipEntry[] = []
|
||||
let workbook = fileBuffer
|
||||
if (isZip(fileBuffer, fileName)) {
|
||||
entries = await readZipEntries(fileBuffer)
|
||||
validatePackEntries(entries)
|
||||
validatePackEntries(entries, filePolicy)
|
||||
const info = entries.find((entry) => entry.fileName === "信息表.xlsx")
|
||||
if (!info) throw new Error("ZIP 根目录缺少信息表.xlsx")
|
||||
workbook = await extractZipEntry(fileBuffer, info)
|
||||
@@ -72,8 +77,12 @@ async function prepare(fileBuffer: Uint8Array, fileName: string) {
|
||||
return { entries, parsed, plans, documents, fileBuffer }
|
||||
}
|
||||
|
||||
export async function previewMaterialPack(fileBuffer: Uint8Array, fileName: string): Promise<MaterialPackPreview> {
|
||||
const prepared = await prepare(fileBuffer, fileName)
|
||||
export async function previewMaterialPack(
|
||||
fileBuffer: Uint8Array,
|
||||
fileName: string,
|
||||
filePolicy?: MaterialPackFilePolicyPatch
|
||||
): Promise<MaterialPackPreview> {
|
||||
const prepared = await prepare(fileBuffer, fileName, filePolicy)
|
||||
const documents = prepared.parsed.map((item, index) =>
|
||||
injectAttachmentPlan(item.document, prepared.plans[index]!, new Map())
|
||||
)
|
||||
@@ -83,9 +92,14 @@ export async function previewMaterialPack(fileBuffer: Uint8Array, fileName: stri
|
||||
export async function pushMaterialPack(
|
||||
fileBuffer: Uint8Array,
|
||||
fileName: string,
|
||||
config: { webhookUrl: string; secret: string; docIdSuffix?: string }
|
||||
config: {
|
||||
webhookUrl: string;
|
||||
secret: string;
|
||||
docIdSuffix?: string;
|
||||
materialPackFilePolicy?: MaterialPackFilePolicyPatch;
|
||||
}
|
||||
): Promise<MaterialPackPushResult> {
|
||||
const prepared = await prepare(fileBuffer, fileName)
|
||||
const prepared = await prepare(fileBuffer, fileName, config.materialPackFilePolicy)
|
||||
const { baseUrl, webhookId } = webhookInfo(config.webhookUrl)
|
||||
const results: MaterialPackPushResult["results"] = []
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ export type MaterialPackPushResult = {
|
||||
|
||||
export class MaterialPackValidationError extends Error {
|
||||
constructor(public readonly errors: string[], public readonly warnings: string[] = []) {
|
||||
super(`材料包校验失败:${errors.length} 个错误`)
|
||||
super([`材料包校验失败:${errors.length} 个错误`, ...errors.map((error) => `- ${error}`)].join("\n"))
|
||||
this.name = "MaterialPackValidationError"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { validatePackEntries, type ZipEntry } from "./validate.js"
|
||||
|
||||
function entries(attachment: Partial<ZipEntry> = {}): ZipEntry[] {
|
||||
return [
|
||||
{ fileName: "信息表.xlsx", uncompressedSize: 100, compressedSize: 80, raw: {} },
|
||||
{
|
||||
fileName: "DOC-001/合同/合同.pdf",
|
||||
uncompressedSize: 500,
|
||||
compressedSize: 400,
|
||||
raw: {},
|
||||
...attachment
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
describe("material pack attachment file policy", () => {
|
||||
test("accepts the default 500-byte minimum and common PDF extension", () => {
|
||||
expect(() => validatePackEntries(entries())).not.toThrow()
|
||||
})
|
||||
|
||||
test("rejects attachments smaller than the configured minimum", () => {
|
||||
expect(() => validatePackEntries(entries({ uncompressedSize: 499 }))).toThrow(
|
||||
"附件文件过小"
|
||||
)
|
||||
})
|
||||
|
||||
test("rejects attachments larger than the configured maximum", () => {
|
||||
expect(() => validatePackEntries(entries({ uncompressedSize: 1001 }), {
|
||||
maxFileSizeBytes: 1000
|
||||
})).toThrow("附件文件过大")
|
||||
})
|
||||
|
||||
test("rejects extensions outside the configured whitelist", () => {
|
||||
expect(() => validatePackEntries(entries({ fileName: "DOC-001/合同/合同.exe" }), {
|
||||
allowedExtensions: [".pdf"]
|
||||
})).toThrow("附件后缀不在白名单中")
|
||||
})
|
||||
|
||||
test("rejects an invalid size range before any upload can start", () => {
|
||||
expect(() => validatePackEntries(entries(), {
|
||||
minFileSizeBytes: 1000,
|
||||
maxFileSizeBytes: 999
|
||||
})).toThrow("最大文件大小不能小于最小文件大小")
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,11 @@
|
||||
import yauzl from "yauzl";
|
||||
import iconv from "iconv-lite";
|
||||
import { MaterialPackValidationError } from "./types.js";
|
||||
import {
|
||||
normalizeMaterialPackFilePolicy,
|
||||
type MaterialPackFilePolicy,
|
||||
type MaterialPackFilePolicyPatch
|
||||
} from "./policy.js";
|
||||
|
||||
export const MATERIAL_PACK_LIMITS = { maxEntries: 1000, maxTotalSize: 500 * 1024 * 1024, maxCompressionRatio: 150 };
|
||||
|
||||
@@ -41,14 +46,17 @@ function isJunk(name: string): boolean {
|
||||
return name.split("/").includes("__MACOSX") || base === ".DS_Store" || base.startsWith("._") || base.startsWith(".~") || base.startsWith("~$");
|
||||
}
|
||||
|
||||
export function validatePackEntries(entries: ZipEntry[]): void {
|
||||
export function validatePackEntries(entries: ZipEntry[], policy?: MaterialPackFilePolicyPatch): void {
|
||||
const errors: string[] = [];
|
||||
const filePolicy = normalizeMaterialPackFilePolicy(policy);
|
||||
if (entries.length > MATERIAL_PACK_LIMITS.maxEntries) errors.push(`文件数超过 ${MATERIAL_PACK_LIMITS.maxEntries}`);
|
||||
const total = entries.reduce((sum, entry) => sum + entry.uncompressedSize, 0);
|
||||
if (total > MATERIAL_PACK_LIMITS.maxTotalSize) errors.push("解压后总大小超过 500MB");
|
||||
for (const entry of entries) {
|
||||
if (entry.fileName.startsWith("/") || entry.fileName.split("/").includes("..")) errors.push(`存在不安全路径: ${entry.fileName}`);
|
||||
if (entry.compressedSize > 0 && entry.uncompressedSize / entry.compressedSize > MATERIAL_PACK_LIMITS.maxCompressionRatio) errors.push(`压缩比超过 150: ${entry.fileName}`);
|
||||
if (entry.fileName === "信息表.xlsx") continue;
|
||||
validateAttachmentFile(entry, filePolicy, errors);
|
||||
}
|
||||
const info = entries.find((entry) => entry.fileName === "信息表.xlsx");
|
||||
if (!info) errors.push("ZIP 根目录缺少精确名为「信息表.xlsx」的文件");
|
||||
@@ -56,6 +64,39 @@ export function validatePackEntries(entries: ZipEntry[]): void {
|
||||
if (errors.length) throw new MaterialPackValidationError(errors);
|
||||
}
|
||||
|
||||
function validateAttachmentFile(
|
||||
entry: ZipEntry,
|
||||
policy: MaterialPackFilePolicy,
|
||||
errors: string[]
|
||||
): void {
|
||||
const extension = getFileExtension(entry.fileName);
|
||||
if (!extension || !policy.allowedExtensions.includes(extension)) {
|
||||
errors.push(
|
||||
`附件后缀不在白名单中: ${entry.fileName}(允许: ${policy.allowedExtensions.join(", ")})`
|
||||
);
|
||||
}
|
||||
if (entry.uncompressedSize < policy.minFileSizeBytes) {
|
||||
errors.push(
|
||||
`附件文件过小: ${entry.fileName}(${entry.uncompressedSize} B,小于最小值 ${policy.minFileSizeBytes} B)`
|
||||
);
|
||||
}
|
||||
if (
|
||||
policy.maxFileSizeBytes !== undefined &&
|
||||
policy.maxFileSizeBytes !== null &&
|
||||
entry.uncompressedSize > policy.maxFileSizeBytes
|
||||
) {
|
||||
errors.push(
|
||||
`附件文件过大: ${entry.fileName}(${entry.uncompressedSize} B,大于最大值 ${policy.maxFileSizeBytes} B)`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function getFileExtension(fileName: string): string {
|
||||
const baseName = fileName.split("/").pop() ?? fileName;
|
||||
const dotIndex = baseName.lastIndexOf(".");
|
||||
return dotIndex > 0 ? baseName.slice(dotIndex).toLowerCase() : "";
|
||||
}
|
||||
|
||||
export function extractZipEntry(buffer: Uint8Array, target: ZipEntry): Promise<Buffer> {
|
||||
return new Promise((resolve, reject) => {
|
||||
yauzl.fromBuffer(Buffer.from(buffer), { lazyEntries: true, autoClose: true, decodeStrings: false }, (openError: Error | null, zipFile: any) => {
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
pushMaterialPack,
|
||||
readMaterialPackFile
|
||||
} from "./material-pack/index.js";
|
||||
import { MaterialPackFilePolicyPatchSchema, MaterialPackFilePolicySchema } from "./material-pack/policy.js";
|
||||
import {
|
||||
extractApprovalRunAttachments
|
||||
} from "./attachments.js";
|
||||
@@ -954,7 +955,8 @@ export const sealTools = [
|
||||
mode: z.enum(["assisted", "semi_automatic", "fully_automatic"]).optional(),
|
||||
outgoingResultWebhook: z.string().url().describe("Seal 完成 AI 审核后回调的外部地址"),
|
||||
autoApprovalRate: z.number().int().min(0).max(100).optional(),
|
||||
secret: z.string().min(1).optional().describe("可选;不传则生成 32 位十六进制 secret")
|
||||
secret: z.string().min(1).optional().describe("可选;不传则生成 32 位十六进制 secret"),
|
||||
materialPackFilePolicy: MaterialPackFilePolicyPatchSchema.describe("材料包附件文件策略:大小和后缀白名单")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
@@ -964,6 +966,7 @@ export const sealTools = [
|
||||
outgoingResultWebhook: string;
|
||||
autoApprovalRate?: number;
|
||||
secret?: string;
|
||||
materialPackFilePolicy?: Partial<z.infer<typeof MaterialPackFilePolicySchema>>;
|
||||
},
|
||||
context: ToolContext
|
||||
) => {
|
||||
@@ -990,7 +993,8 @@ export const sealTools = [
|
||||
outgoingResultWebhook: z.string().url().optional(),
|
||||
autoApprovalRate: z.number().int().min(0).max(100).optional(),
|
||||
secret: z.string().min(1).optional(),
|
||||
rotateSecret: z.boolean().optional().describe("生成新 secret;与 secret 二选一")
|
||||
rotateSecret: z.boolean().optional().describe("生成新 secret;与 secret 二选一"),
|
||||
materialPackFilePolicy: MaterialPackFilePolicyPatchSchema.describe("材料包附件文件策略:大小和后缀白名单")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
@@ -1002,6 +1006,7 @@ export const sealTools = [
|
||||
autoApprovalRate?: number;
|
||||
secret?: string;
|
||||
rotateSecret?: boolean;
|
||||
materialPackFilePolicy?: Partial<z.infer<typeof MaterialPackFilePolicySchema>>;
|
||||
},
|
||||
context: ToolContext
|
||||
) => {
|
||||
@@ -1608,7 +1613,8 @@ export const sealTools = [
|
||||
}
|
||||
return pushMaterialPack(input.fileBuffer, input.fileName, {
|
||||
webhookUrl: integration.incomingDocumentWebhook.url,
|
||||
secret: integration.secret
|
||||
secret: integration.secret,
|
||||
materialPackFilePolicy: integration.materialPackFilePolicy
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { DEFAULT_MATERIAL_PACK_FILE_POLICY, MaterialPackFilePolicySchema } from "./material-pack/policy.js";
|
||||
|
||||
export const HosecloudStaffSchema = z.object({
|
||||
staffId: z.string(),
|
||||
@@ -181,7 +182,8 @@ export const WebhookIntegrationSchema = z.object({
|
||||
outgoingResultWebhook: z.string().url(),
|
||||
incomingManualResultWebhook: WebhookEndpointSchema,
|
||||
secret: z.string().min(1),
|
||||
autoApprovalRate: z.number().int().min(0).max(100).optional()
|
||||
autoApprovalRate: z.number().int().min(0).max(100).optional(),
|
||||
materialPackFilePolicy: MaterialPackFilePolicySchema.default(DEFAULT_MATERIAL_PACK_FILE_POLICY)
|
||||
}).passthrough();
|
||||
|
||||
export const ApprovalStylePreferencesSchema = z.object({
|
||||
|
||||
Reference in new issue
Block a user