Files
picpeak/backend/src/middleware/uploadValidation.js
T
Paul Nothaft 9143997f8e style(backend): clear the eslint backlog to zero
929 problems (928 errors, 1 warning) -> 0, exit 0.

Rule breakdown, which corrects the report's premise -- `indent` dominated, not
`quotes`: indent 719, quotes 68, no-unused-vars 54, no-empty 36,
no-useless-escape 22, no-case-declarations 17, no-inner-declarations 6,
no-control-regex 5, no-useless-catch 1, no-console 1 (warn).

--fix handled only indent + quotes (719+68 = exactly the "fixable" count).
no-useless-escape was NOT auto-fixable in this eslint version, so the one
genuinely risky class never went through the autofixer -- all 22 were done by
hand. Two mechanical proofs on the autofix diff: a token-level AST diff
(espree, before vs after) shows exactly 68 differing tokens, all quotes, with
the 719 indent fixes producing zero token changes; and a cooked-value diff of
every string/template/regex literal shows 0 differences.

Regex escapes: eslint was correctly conservative and did not flag the
load-bearing ones -- \- in [^a-zA-Z0-9_\-\.] (unescaping makes an invalid
reversed _ -> . range) or in [!@#$%^&*()_+\-=...] (would become a + -> = range
silently matching ",-."). Every removal was a \/ \[ or \. inside a character
class; all 11 old/new pairs were brute-forced over 794 inputs with 0
mismatches.

Manual fixes: no-empty were all deliberate best-effort catches around activity
logging, annotated rather than restructured; no-case-declarations braced in
two adminBackup switches; no-inner-declarations converted to const arrows
after checking no call precedes the declaration and no this/arguments use;
no-control-regex and no-console got targeted disables with stated reasons;
one `catch (e) { throw e; }` wrapper removed.

Two unused bindings were near-misses worth noting: secureStatic.js's
`fullPath` is a path-traversal guard (safePathJoin throws on escape) and
restoreService.js's `backupManifest` is the throw-on-corrupt-manifest gate
before a rollback -- deleting either would have silently removed a check. Only
the bindings were dropped; the calls stay.

Two real bugs found and deliberately preserved with a comment plus a narrow
disable rather than deleted, since deleting would erase the evidence:
_workflowSeedBoot.js's `booted` is written but never read, so the intended
once-per-process guard is missing its early return and workflows re-seed on
every call; and quoteService.js's VALID_QUOTE_TRANSITIONS is a full state
machine nothing consults, so quote status changes are unvalidated.

Backend test suite: 253 suites / 2552 tests passing, 0 failures, before and
after.

Refs testplan REPORT.md #22 (Part 1.2.02).
2026-09-01 16:46:34 +02:00

111 lines
3.1 KiB
JavaScript

const fs = require('fs').promises;
const path = require('path');
const sharp = require('sharp');
const logger = require('../utils/logger');
/**
* Validate uploaded file is complete and not corrupted
*/
async function validateUploadedFile(filePath) {
try {
// Check file exists and has size
const stats = await fs.stat(filePath);
if (stats.size === 0) {
throw new Error('File is empty');
}
// For image files, verify they can be read by Sharp
const ext = path.extname(filePath).toLowerCase();
const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
if (imageExtensions.includes(ext)) {
// Try to read metadata - this will fail if image is corrupted
let metadata;
try {
metadata = await sharp(filePath, {
failOn: 'none', // Don't fail on recoverable errors
limitInputPixels: 268402689 // ~16k x 16k max
}).metadata();
} catch (metadataError) {
// If metadata reading fails, the file is likely incomplete
throw new Error(`Invalid image file: ${metadataError.message}`);
}
if (!metadata || !metadata.width || !metadata.height) {
throw new Error('Invalid image dimensions - file may be incomplete');
}
// Check for reasonable dimensions
if (metadata.width < 10 || metadata.height < 10) {
throw new Error('Image dimensions too small');
}
// Additional check: verify we can actually decode a small portion of the image
try {
await sharp(filePath, {
failOn: 'none',
limitInputPixels: 268402689
})
.resize(10, 10) // Try to resize to very small size
.toBuffer();
} catch (decodeError) {
throw new Error(`Image decode failed - file may be corrupted: ${decodeError.message}`);
}
return true;
}
return true;
} catch (error) {
logger.error(`File validation failed for ${filePath}:`, error.message);
throw error;
}
}
/**
* Middleware to validate uploaded files after multer processing
*/
async function validateUploadedFiles(req, res, next) {
if (!req.files || req.files.length === 0) {
return next();
}
const validFiles = [];
const invalidFiles = [];
// Validate each file
for (const file of req.files) {
try {
await validateUploadedFile(file.path);
validFiles.push(file);
} catch (error) {
logger.warn(`Removing invalid upload ${file.originalname}: ${error.message}`);
invalidFiles.push({
filename: file.originalname,
error: error.message
});
// Delete the invalid file
try {
await fs.unlink(file.path);
} catch (unlinkErr) {
logger.error(`Failed to delete invalid file ${file.path}:`, unlinkErr.message);
}
}
}
// Update req.files to only include valid files
req.files = validFiles;
// Store invalid files info for response
if (invalidFiles.length > 0) {
req.invalidFiles = invalidFiles;
}
next();
}
module.exports = {
validateUploadedFile,
validateUploadedFiles
};