63 lines
2.2 KiB
TypeScript
63 lines
2.2 KiB
TypeScript
// 展示名写入 TEXT 字段。768 个 UTF-8 字节进行百分号编码后至多占 2304 字节。
|
|
export const MAX_UPLOAD_FILE_NAME_BYTES = 768
|
|
|
|
const controlCharacters = /[\x00-\x1f\x7f]/
|
|
const invalidFileNameCharacters = /[/\\<>:"|?*]|[\x00-\x1f\x7f]/
|
|
const unpairedSurrogate = new RegExp('[\\uD800-\\uDFFF]', 'u')
|
|
|
|
function containsUnsupportedPathOrCharacters(fileName: string): boolean {
|
|
let candidate = fileName
|
|
for (let pass = 0; pass <= 5; pass += 1) {
|
|
const segment = candidate.trim()
|
|
if (invalidFileNameCharacters.test(candidate) || segment === '.' || segment === '..') {
|
|
return true
|
|
}
|
|
if (!candidate.includes('%')) break
|
|
// ASCII 转义独立解码,避免合法的字面百分号掩盖编码分隔符。
|
|
const decoded = candidate.replace(/%(?:25)*([0-7][0-9a-f])/gi, (_, hex: string) =>
|
|
String.fromCharCode(Number.parseInt(hex, 16)),
|
|
)
|
|
if (decoded === candidate) break
|
|
candidate = decoded
|
|
}
|
|
return false
|
|
}
|
|
|
|
export function validateUploadFileName(
|
|
value: unknown,
|
|
maxBytes = MAX_UPLOAD_FILE_NAME_BYTES,
|
|
) {
|
|
const raw = typeof value === 'string' ? value : ''
|
|
const fileName = raw.trim().normalize('NFC')
|
|
const label = raw.length > 96
|
|
? `${raw.slice(0, 64)}…${raw.slice(-24)}`
|
|
: raw
|
|
|
|
if (
|
|
controlCharacters.test(raw)
|
|
|| unpairedSurrogate.test(fileName)
|
|
|| containsUnsupportedPathOrCharacters(fileName)
|
|
) {
|
|
return {
|
|
fileName: null,
|
|
code: 'FILE_NAME_INVALID',
|
|
error: `文件名包含不支持的路径或字符。请修改「${JSON.stringify(label).slice(1, -1)}」后重新选择`,
|
|
} as const
|
|
}
|
|
if (!fileName) {
|
|
return { fileName: null, code: 'FILE_NAME_EMPTY', error: '文件名不能为空' } as const
|
|
}
|
|
if (fileName.length > maxBytes || new TextEncoder().encode(fileName).length > maxBytes) {
|
|
return {
|
|
fileName: null,
|
|
code: 'FILE_NAME_TOO_LONG',
|
|
error: `文件名过长(最多支持 ${maxBytes} 个 UTF-8 字节)。请缩短「${label}」后重新选择`,
|
|
} as const
|
|
}
|
|
return { fileName } as const
|
|
}
|
|
|
|
export function normalizeUploadFileName(value: unknown): string | null {
|
|
return validateUploadFileName(value).fileName
|
|
}
|