Form files: the visitor is told when the problem is the file — why and what to do; UTF-8 file names
Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
b6f9f34705
commit
97202ee03e
@@ -145,26 +145,29 @@ export type FileRefusal =
|
||||
|
||||
/**
|
||||
* Name check, before any byte of the file: the last extension must belong to
|
||||
* one of the allowed types, and NO extension of the name may be a risky one
|
||||
* ("cv.pdf.exe", "cv.exe.pdf") unless the project allowed it.
|
||||
* one of the allowed types (else `type`: simply another format), and NO
|
||||
* extension of the name may be a risky one ("cv.pdf.exe", "cv.exe.pdf") unless
|
||||
* the project allowed it, nor a second known one ("cv.pdf.docx") — else `refused`.
|
||||
*/
|
||||
export function matchFileType(
|
||||
name: string,
|
||||
allowed: readonly string[],
|
||||
types: Record<string, FormFileType>,
|
||||
risky: ReadonlySet<string>,
|
||||
): { key: string; type: FormFileType } | { refused: 'name' } {
|
||||
): { key: string; type: FormFileType } | { refused: 'refused' | 'type' } {
|
||||
const extensions = fileExtensions(name.split(/[/\\]/).pop() ?? '')
|
||||
const last = extensions.at(-1)
|
||||
if (!last || extensions.some((e) => risky.has(e))) {return { refused: 'name' }}
|
||||
// A program, an archive, a macro-enabled file — refused as such, not as "another format".
|
||||
if (extensions.some((e) => risky.has(e))) {return { refused: 'refused' }}
|
||||
if (!last) {return { refused: 'type' }}
|
||||
// "cv.pdf.docx": an extra extension that names another known type hides what the file is.
|
||||
const known = new Set(Object.values(types).flatMap((t) => t.extensions))
|
||||
if (extensions.slice(0, -1).some((e) => known.has(e))) {return { refused: 'name' }}
|
||||
if (extensions.slice(0, -1).some((e) => known.has(e))) {return { refused: 'refused' }}
|
||||
for (const key of allowed) {
|
||||
const type = types[key]
|
||||
if (type?.extensions.includes(last)) {return { type, key }}
|
||||
}
|
||||
return { refused: 'name' }
|
||||
return { refused: 'type' }
|
||||
}
|
||||
|
||||
/** Whole-file check, once the file is in memory. Returns the refusal, or null when it passes. */
|
||||
|
||||
@@ -22,10 +22,19 @@ export type FormFileFailure = {
|
||||
field: string
|
||||
/** The file's name as the visitor knows it (cleaned of control characters). */
|
||||
file?: string
|
||||
kind: 'file_count' | 'file_too_large' | 'file_type' | 'required' | 'unknown_fields'
|
||||
/**
|
||||
* - `file_too_large` — over the limit (`max`, MB)
|
||||
* - `file_type` — a format the field does not accept (`types`)
|
||||
* - `file_refused` — the right extension but not acceptable: the content does not match it, macros, a
|
||||
* program, an archive, a doubled extension, or the project's scanner said no
|
||||
* - `file_count` — more files than the field takes (`max`)
|
||||
*/
|
||||
kind: 'file_count' | 'file_refused' | 'file_too_large' | 'file_type' | 'required' | 'unknown_fields'
|
||||
/** The limit: MB for file_too_large, a count for file_count. */
|
||||
max?: number
|
||||
/** "PDF, DOC, DOCX" — for file_type. */
|
||||
/** True when the field is not required — the visitor may send the form without the file. */
|
||||
optional?: boolean
|
||||
/** "PDF, DOC, DOCX" — the formats the field accepts. */
|
||||
types?: string
|
||||
}
|
||||
|
||||
@@ -79,34 +88,35 @@ export function createFileGate({
|
||||
const file = displayName(rawName)
|
||||
const count = (counts.get(fieldName) ?? 0) + 1
|
||||
counts.set(fieldName, count)
|
||||
if (count > limits.maxFiles) {return { failure: { field: fieldName, kind: 'file_count', max: limits.maxFiles } }}
|
||||
const optional = !field.required
|
||||
if (count > limits.maxFiles) {return { failure: { field: fieldName, kind: 'file_count', max: limits.maxFiles, optional } }}
|
||||
|
||||
const types = describeFileTypes(limits.allowedTypes, options.types).labels
|
||||
const typeFailure: FormFileFailure = { field: fieldName, file, kind: 'file_type', types }
|
||||
const refusedFailure: FormFileFailure = { field: fieldName, file, kind: 'file_refused', optional, types }
|
||||
const match = matchFileType(rawName, limits.allowedTypes, options.types, options.risky)
|
||||
if ('refused' in match) {return { failure: typeFailure }}
|
||||
if ('refused' in match) {return { failure: match.refused === 'type' ? { ...refusedFailure, kind: 'file_type' } : refusedFailure }}
|
||||
|
||||
const maxBytes = Math.max(0, Math.min(limits.maxBytes, limits.maxTotalBytes - total))
|
||||
const tooLarge = (): FormFileFailure => ({ field: fieldName, file, kind: 'file_too_large', max: limitInMB(limits.maxBytes) })
|
||||
const tooLarge = (): FormFileFailure => ({ field: fieldName, file, kind: 'file_too_large', max: limitInMB(limits.maxBytes), optional })
|
||||
let checked = false
|
||||
return {
|
||||
slot: {
|
||||
checkStart: (head) => {
|
||||
if (checked || head.length < Math.min(SIGNATURE_BYTES, 4)) {return null}
|
||||
checked = true
|
||||
return looksExecutable(head) || signatureMatches(match.key, head.subarray(0, SIGNATURE_BYTES)) === false ? typeFailure : null
|
||||
return looksExecutable(head) || signatureMatches(match.key, head.subarray(0, SIGNATURE_BYTES)) === false ? refusedFailure : null
|
||||
},
|
||||
maxBytes,
|
||||
tooLarge,
|
||||
},
|
||||
token: { field: fieldName, file, key: match.key, maxBytes, rawName, tooLarge, typeFailure },
|
||||
token: { field: fieldName, file, key: match.key, maxBytes, rawName, refusedFailure, tooLarge },
|
||||
}
|
||||
}
|
||||
|
||||
const finish = async (token: BeginToken, data: Uint8Array): Promise<FormFileFailure | null> => {
|
||||
if (data.length > token.maxBytes) {return token.tooLarge()}
|
||||
const type = options.types[token.key]
|
||||
if ((await checkFileContent(token.key, type, data, { strictPdf: options.strictPdf })) !== null) {return token.typeFailure}
|
||||
if ((await checkFileContent(token.key, type, data, { strictPdf: options.strictPdf })) !== null) {return token.refusedFailure}
|
||||
const file: AcceptedFormFile = {
|
||||
name: safeFileName(token.rawName, type.extensions[0]),
|
||||
type: token.key,
|
||||
@@ -118,9 +128,9 @@ export function createFileGate({
|
||||
if (options.scan) {
|
||||
try {
|
||||
const verdict = await options.scan({ name: file.name, type: file.type, data, field: file.field, size: file.size })
|
||||
if (!verdict?.ok) {return token.typeFailure}
|
||||
if (!verdict?.ok) {return token.refusedFailure}
|
||||
} catch {
|
||||
return token.typeFailure
|
||||
return token.refusedFailure
|
||||
}
|
||||
}
|
||||
total += data.length
|
||||
@@ -145,8 +155,8 @@ type BeginToken = {
|
||||
key: string
|
||||
maxBytes: number
|
||||
rawName: string
|
||||
refusedFailure: FormFileFailure
|
||||
tooLarge: () => FormFileFailure
|
||||
typeFailure: FormFileFailure
|
||||
}
|
||||
|
||||
export type FileGate = ReturnType<typeof createFileGate>
|
||||
|
||||
@@ -132,6 +132,8 @@ export async function handleFormSubmit(req: PayloadRequest): Promise<Response> {
|
||||
|
||||
const source = Readable.fromWeb(req.body as never)
|
||||
const parser = busboy({
|
||||
// browsers send file names as UTF-8 ("Życiorys.pdf"); the parser's default would read them as Latin-1
|
||||
defParamCharset: 'utf8',
|
||||
headers: { 'content-type': contentType },
|
||||
limits: { fields: 8, fieldSize: VALUES_BYTES, files: options.maxFiles * 4 + 1, fileSize: Math.floor(options.maxSizeMB * MB) + 1 },
|
||||
})
|
||||
|
||||
@@ -131,22 +131,25 @@ export function fileFieldRules(field: BuilderField): Required<BuilderFileLimits>
|
||||
export function fileFieldError(
|
||||
field: BuilderField,
|
||||
files: readonly BuilderFile[],
|
||||
texts: Pick<BuilderFormTexts, 'fileCount' | 'fileTooLarge' | 'fileType' | 'validation'>,
|
||||
texts: Pick<BuilderFormTexts, 'fileCount' | 'fileOptional' | 'fileTooLarge' | 'fileType' | 'validation'>,
|
||||
): string | undefined {
|
||||
const rules = fileFieldRules(field)
|
||||
const label = field.label || field.name || ''
|
||||
const generic = texts.validation.replace('{field}', label)
|
||||
if (files.length > rules.maxFiles) {return (texts.fileCount ?? generic).replace('{field}', label).replace('{max}', String(rules.maxFiles))}
|
||||
// On a field that is not required the visitor may also send the form without the file — say so.
|
||||
const say = (text: string | undefined, fill: (text: string) => string) =>
|
||||
text ? `${fill(text)}${!field.required && texts.fileOptional ? ` ${texts.fileOptional}` : ''}` : generic
|
||||
if (files.length > rules.maxFiles) {return say(texts.fileCount, (t) => t.replace('{field}', label).replace('{max}', String(rules.maxFiles)))}
|
||||
for (const file of files) {
|
||||
if (rules.extensions.length > 0 && !rules.extensions.includes(fileExtensions(file.name).at(-1) ?? '')) {
|
||||
return (texts.fileType ?? generic).replace('{file}', file.name).replace('{types}', rules.typeLabels)
|
||||
return say(texts.fileType, (t) => t.replace('{file}', file.name).replace('{types}', rules.typeLabels))
|
||||
}
|
||||
if (file.size > rules.maxSizeMB * MB || file.size === 0) {
|
||||
return (texts.fileTooLarge ?? generic).replace('{file}', file.name).replace('{max}', String(rules.maxSizeMB))
|
||||
return say(texts.fileTooLarge, (t) => t.replace('{file}', file.name).replace('{max}', String(rules.maxSizeMB)))
|
||||
}
|
||||
}
|
||||
if (files.reduce((sum, f) => sum + f.size, 0) > rules.maxTotalMB * MB) {
|
||||
return (texts.fileTooLarge ?? generic).replace('{file}', files.at(-1)?.name ?? '').replace('{max}', String(rules.maxTotalMB))
|
||||
return say(texts.fileTooLarge, (t) => t.replace('{file}', files.at(-1)?.name ?? '').replace('{max}', String(rules.maxTotalMB)))
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
@@ -170,7 +173,7 @@ const isBlank = isBlankValue
|
||||
export function validateBuilderFields(
|
||||
fields: BuilderField[],
|
||||
values: Record<string, unknown>,
|
||||
texts: Pick<BuilderFormTexts, 'fileCount' | 'fileTooLarge' | 'fileType' | 'validation'>,
|
||||
texts: Pick<BuilderFormTexts, 'fileCount' | 'fileOptional' | 'fileTooLarge' | 'fileType' | 'validation'>,
|
||||
): Record<string, string> {
|
||||
const errors: Record<string, string> = {}
|
||||
for (const f of inputFields(fields)) {
|
||||
|
||||
@@ -84,6 +84,7 @@ export type BuilderFormTexts = {
|
||||
error?: string
|
||||
/** File field — see FormNotificationTexts. */
|
||||
fileCount?: string
|
||||
fileOptional?: string
|
||||
fileRemove?: string
|
||||
fileTooLarge?: string
|
||||
fileType?: string
|
||||
|
||||
@@ -86,8 +86,13 @@ export type SubmitFailure =
|
||||
/**
|
||||
* The file could not be handed to the mail server (or the form has no
|
||||
* e-mail that may carry it). The file is gone — the visitor must send it
|
||||
* again. `submissionId`: the stored attempt, marked "Not sent".
|
||||
* again. `submissionId`: the stored attempt, marked "Not sent". `field`
|
||||
* and `file`: the File field and the file name(s), so the message shows
|
||||
* at the field and names the file; `optional`: the field is not required.
|
||||
*/
|
||||
field?: string
|
||||
file?: string
|
||||
optional?: boolean
|
||||
reason: 'delivery'
|
||||
submissionId?: number | string
|
||||
success: false
|
||||
@@ -95,14 +100,16 @@ export type SubmitFailure =
|
||||
| {
|
||||
/** The offending field's name, when one field is at fault. */
|
||||
field?: string
|
||||
/** The refused file's name (file_too_large, file_type). */
|
||||
/** The refused file's name (file_too_large, file_type, file_refused). */
|
||||
file?: string
|
||||
/** What was wrong with it. */
|
||||
kind?: 'file_count' | 'file_too_large' | 'file_type' | 'invalid_format' | 'required' | 'too_long' | 'unknown_fields'
|
||||
kind?: 'file_count' | 'file_refused' | 'file_too_large' | 'file_type' | 'invalid_format' | 'required' | 'too_long' | 'unknown_fields'
|
||||
/** The offending field's label in the page's language — what the visitor sees. Absent when the field has none. */
|
||||
label?: string
|
||||
/** The limit behind file_too_large (MB) or file_count (files). */
|
||||
max?: number
|
||||
/** A file problem on a field that is not required — the form can be sent without the file. */
|
||||
optional?: boolean
|
||||
reason: 'validation'
|
||||
success: false
|
||||
/** Accepted types, "PDF, DOCX" (file_type). */
|
||||
@@ -206,6 +213,7 @@ export async function fileFailure(payload: BasePayload, formId: string, failure:
|
||||
...(failure.file ? { file: failure.file } : {}),
|
||||
...(label ? { label } : {}),
|
||||
...(failure.max !== undefined ? { max: failure.max } : {}),
|
||||
...(failure.optional ? { optional: true } : {}),
|
||||
...(failure.types ? { types: failure.types } : {}),
|
||||
}
|
||||
}
|
||||
@@ -229,9 +237,17 @@ export async function findSubmitAttempt(payload: BasePayload, attemptKey: string
|
||||
limit: 1,
|
||||
where: { attemptKey: { equals: attemptKey } },
|
||||
} as never)
|
||||
const doc = found.docs[0] as { filesDelivery?: string; id: number | string } | undefined
|
||||
const doc = found.docs[0] as { filesDelivery?: string; id: number | string; submissionFiles?: { field?: string; name?: string }[] } | undefined
|
||||
if (!doc) {return null}
|
||||
return doc.filesDelivery === 'failed' ? { reason: 'delivery', submissionId: doc.id, success: false } : { submissionId: doc.id, success: true }
|
||||
if (doc.filesDelivery !== 'failed') {return { submissionId: doc.id, success: true }}
|
||||
const kept = doc.submissionFiles ?? []
|
||||
return {
|
||||
reason: 'delivery',
|
||||
submissionId: doc.id,
|
||||
success: false,
|
||||
...(kept[0]?.field ? { field: kept[0].field } : {}),
|
||||
...(kept.length ? { file: kept.map((f) => f.name).join(', ') } : {}),
|
||||
}
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
@@ -260,6 +276,7 @@ export async function storeSubmission({
|
||||
} & Pick<SubmitFormArgs, 'formId' | 'locale' | 'payload'>): Promise<SubmitFormResult> {
|
||||
const attachments = getFormAttachments(payload)
|
||||
const delivery: FormFileDelivery | undefined = files.length ? { files } : undefined
|
||||
const fileNames = files.map((f) => ({ name: f.name, field: f.field }))
|
||||
const text = (value: unknown) =>
|
||||
// checkboxGroup → "a, b" (readable in the panel and in {{field}} e-mails)
|
||||
value == null ? '' : Array.isArray(value) ? value.join(', ') : typeof value === 'object' ? JSON.stringify(value) : String(value as boolean | number | string)
|
||||
@@ -297,7 +314,17 @@ export async function storeSubmission({
|
||||
} catch (err) {
|
||||
payload.logger.error(`[ipal] Could not record the file delivery on submission ${String(submission.id)}: ${(err as Error).message}`)
|
||||
}
|
||||
return result.state === 'sent' ? { submissionId: submission.id, success: true } : { reason: 'delivery', submissionId: submission.id, success: false }
|
||||
if (result.state === 'sent') {return { submissionId: submission.id, success: true }}
|
||||
// The message belongs at the File field and names the file — never the mail server's own words.
|
||||
const fileField = validation.fileFields.find((f) => f.name === fileNames[0]?.field)
|
||||
return {
|
||||
field: fileNames[0]?.field,
|
||||
file: fileNames.map((f) => f.name).join(', '),
|
||||
reason: 'delivery',
|
||||
submissionId: submission.id,
|
||||
success: false,
|
||||
...(fileField && !fileField.required ? { optional: true } : {}),
|
||||
}
|
||||
} catch (err) {
|
||||
payload.logger.error(`[ipal] Form submission failed: ${(err as Error).message}`)
|
||||
return { reason: 'error', success: false }
|
||||
@@ -345,7 +372,7 @@ export async function submitForm(args: SubmitFormArgs): Promise<SubmitFormResult
|
||||
return storeSubmission({ attemptKey, formId, locale, payload, validation })
|
||||
}
|
||||
|
||||
if (hasFiles && !canCarryFiles(validation.form)) {return { reason: 'delivery', success: false }}
|
||||
if (hasFiles && !canCarryFiles(validation.form)) {return { field: Object.keys(files ?? {})[0], reason: 'delivery', success: false }}
|
||||
const gate = createFileGate({ fields: validation.fileFields, options: attachments, transportMaxBytes: await mailAttachmentLimit(payload) })
|
||||
const refused = await checkBufferedFiles(gate, files ?? {})
|
||||
if (refused) {return fileFailure(payload, formId, refused, locale)}
|
||||
|
||||
Reference in New Issue
Block a user