This commit is contained in:
Ccjcarkbla
2026-09-13 10:00:13 -04:00
parent 9b04f26c82
commit 349f469602
31 changed files with 1455 additions and 37 deletions
+73 -13
View File
@@ -5,7 +5,12 @@ const path = require('path');
const { AppError } = require('../../core/errors');
const { log: auditLog } = require('../../core/audit');
const UPLOADS_DIR = () => process.env.UPLOADS_DIR || path.join(__dirname, '..', '..', 'uploads');
// Resolved to an absolute path: res.sendFile() rejects relative paths, and
// UPLOADS_DIR is commonly configured as './uploads'.
// file-type's documented minimum sniff size
const SNIFF_BYTES = 4100;
const UPLOADS_DIR = () => path.resolve(process.env.UPLOADS_DIR || path.join(__dirname, '..', '..', 'uploads'));
async function getOrg(models, orgId) {
@@ -42,6 +47,17 @@ async function updateBranding(models, req, orgId, data) {
return branding;
}
async function moveFile(src, dest) {
try {
await fs.promises.rename(src, dest);
} catch (err) {
// Cross-device rename (systemd PrivateTmp, docker tmpfs, separate volumes)
if (err.code !== 'EXDEV') throw err;
await fs.promises.copyFile(src, dest);
await fs.promises.unlink(src).catch(() => {});
}
}
async function uploadLogo(models, req, orgId, file) {
const { fileTypeFromBuffer } = await import('file-type');
const ALLOWED = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'];
@@ -49,11 +65,13 @@ async function uploadLogo(models, req, orgId, file) {
let detectedMime;
try {
// file-type needs 4100 bytes: detectors read past the magic number (a PNG
// header alone makes it run off the end and throw EndOfStreamError).
const fd = fs.openSync(file.path, 'r');
const buf = Buffer.alloc(12);
fs.readSync(fd, buf, 0, 12, 0);
const buf = Buffer.alloc(SNIFF_BYTES);
const read = fs.readSync(fd, buf, 0, SNIFF_BYTES, 0);
fs.closeSync(fd);
const result = await fileTypeFromBuffer(buf);
const result = await fileTypeFromBuffer(buf.subarray(0, read));
detectedMime = result?.mime;
} catch {
await fs.promises.unlink(file.path).catch(() => {});
@@ -65,23 +83,65 @@ async function uploadLogo(models, req, orgId, file) {
throw new AppError('UPLOAD_TYPE_INVALID', 'Only PNG, JPG, GIF, and WebP images are supported.', 400);
}
const uploadsDir = UPLOADS_DIR();
const version = Date.now();
const ext = EXT_MAP[detectedMime];
const safeName = `logo_${orgId}_${Date.now()}${ext}`;
const destPath = path.join(UPLOADS_DIR(), safeName);
const safeName = `logo_${orgId}_${version}${ext}`;
try {
await fs.promises.mkdir(uploadsDir, { recursive: true });
} catch (err) {
await fs.promises.unlink(file.path).catch(() => {});
throw new AppError('UPLOAD_FAILED', `Uploads directory is not writable (${uploadsDir}): ${err.code}.`, 500);
}
const branding = await getBranding(models, orgId);
// Delete old logo
if (branding.logoPath) {
const oldFile = path.join(UPLOADS_DIR(), path.basename(branding.logoPath));
await fs.promises.unlink(oldFile).catch(() => {});
try {
await moveFile(file.path, path.join(uploadsDir, safeName));
} catch (err) {
await fs.promises.unlink(file.path).catch(() => {});
throw new AppError('UPLOAD_FAILED', `Could not store the logo (${err.code}).`, 500);
}
await fs.promises.rename(file.path, destPath);
await branding.update({ logoPath: `/api/v1/org/logo` });
// Remove previous logos for this org (filenames, not the API path, are the source of truth)
await removeOldLogos(uploadsDir, orgId, safeName);
await branding.update({ logoPath: `/api/v1/org/logo/${orgId}?v=${version}` });
await auditLog(req, 'logo.upload', 'branding', branding.id, { filename: safeName });
return branding;
}
module.exports = { getOrg, updateOrg, getBranding, updateBranding, uploadLogo };
async function removeOldLogos(uploadsDir, orgId, keepName) {
try {
const files = await fs.promises.readdir(uploadsDir);
await Promise.all(
files
.filter(f => f.startsWith(`logo_${orgId}_`) && f !== keepName)
.map(f => fs.promises.unlink(path.join(uploadsDir, f)).catch(() => {}))
);
} catch { /* non-fatal */ }
}
function findLogoFile(orgId) {
const uploadsDir = UPLOADS_DIR();
let files;
try {
files = fs.readdirSync(uploadsDir);
} catch {
return null;
}
const matches = files
.filter(f => f.startsWith(`logo_${orgId}_`))
.sort((a, b) => logoTimestamp(a) - logoTimestamp(b));
if (!matches.length) return null;
return path.join(uploadsDir, matches[matches.length - 1]);
}
function logoTimestamp(filename) {
const m = filename.match(/^logo_\d+_(\d+)\./);
return m ? parseInt(m[1], 10) : 0;
}
module.exports = { getOrg, updateOrg, getBranding, updateBranding, uploadLogo, findLogoFile };