'use strict'; const fs = require('fs'); const path = require('path'); const { AppError } = require('../../core/errors'); const { log: auditLog } = require('../../core/audit'); // 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) { const org = await models.Organization.findByPk(orgId); if (!org) throw new AppError('NOT_FOUND', 'Organization not found.', 404); return org; } async function updateOrg(models, req, orgId, data) { if (data.timezone) { const valid = Intl.supportedValuesOf('timeZone'); if (!valid.includes(data.timezone)) { throw new AppError('VALIDATION_FAILED', 'Invalid timezone.', 400, 'timezone'); } } const org = await getOrg(models, orgId); await org.update(data); await auditLog(req, 'org.update', 'organization', orgId, data); return org; } async function getBranding(models, orgId) { let branding = await models.Branding.findOne({ where: { organizationId: orgId } }); if (!branding) { branding = await models.Branding.create({ organizationId: orgId }); } return branding; } async function updateBranding(models, req, orgId, data) { const branding = await getBranding(models, orgId); await branding.update(data); await auditLog(req, 'branding.update', 'branding', branding.id, 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']; const EXT_MAP = { 'image/png': '.png', 'image/jpeg': '.jpg', 'image/gif': '.gif', 'image/webp': '.webp' }; 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(SNIFF_BYTES); const read = fs.readSync(fd, buf, 0, SNIFF_BYTES, 0); fs.closeSync(fd); const result = await fileTypeFromBuffer(buf.subarray(0, read)); detectedMime = result?.mime; } catch { await fs.promises.unlink(file.path).catch(() => {}); throw new AppError('UPLOAD_TYPE_INVALID', 'Could not read uploaded file.', 400); } if (!detectedMime || !ALLOWED.includes(detectedMime)) { await fs.promises.unlink(file.path).catch(() => {}); 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}_${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); 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); } // 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; } 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 };