"use strict"; /** * File integrity monitoring (FIM) for user-upload directories. * Detects on-disk tampering outside the normal upload flow. */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.FILE_INTEGRITY_ROOTS = void 0; exports.recordUploadedFile = recordUploadedFile; exports.scanRoot = scanRoot; exports.runFileIntegrityCheck = runFileIntegrityCheck; exports.rebuildBaseline = rebuildBaseline; const crypto_1 = __importDefault(require("crypto")); const fs_1 = __importDefault(require("fs")); const path_1 = __importDefault(require("path")); const fileIntegrityRepository = __importStar(require("../repositories/fileIntegrityRepository")); const securityAlertRepository = __importStar(require("../repositories/securityAlertRepository")); const auditLogRepository = __importStar(require("../repositories/auditLogRepository")); const securityService_1 = require("./securityService"); const faqUpload_1 = require("../middleware/faqUpload"); const supportService_1 = require("./supportService"); const apkStorageService_1 = require("./apkStorageService"); exports.FILE_INTEGRITY_ROOTS = { faq: 'faq-uploads', support: 'support-uploads', apkPublished: 'apk-releases-published', }; function resolveRootDir(rootKey) { if (rootKey === exports.FILE_INTEGRITY_ROOTS.faq) return (0, faqUpload_1.ensureFaqUploadDir)(); if (rootKey === exports.FILE_INTEGRITY_ROOTS.apkPublished) return (0, apkStorageService_1.ensureApkPublishedDir)(); return (0, supportService_1.ensureUploadDir)(); } function sha256File(filePath) { const data = fs_1.default.readFileSync(filePath); return crypto_1.default.createHash('sha256').update(data).digest('hex'); } function listFilesRecursive(rootDir) { if (!fs_1.default.existsSync(rootDir)) return []; const out = []; const walk = (dir) => { for (const entry of fs_1.default.readdirSync(dir, { withFileTypes: true })) { const absolutePath = path_1.default.join(dir, entry.name); if (entry.isDirectory()) { walk(absolutePath); continue; } if (!entry.isFile()) continue; const relativePath = path_1.default.relative(rootDir, absolutePath).split(path_1.default.sep).join('/'); out.push({ relativePath, absolutePath }); } }; walk(rootDir); return out; } /** Records or refreshes the integrity baseline for one uploaded file. */ async function recordUploadedFile(rootKey, filename) { const rootDir = resolveRootDir(rootKey); const safeName = path_1.default.basename(filename); const absolutePath = path_1.default.join(rootDir, safeName); if (!fs_1.default.existsSync(absolutePath)) return; const stat = fs_1.default.statSync(absolutePath); const hash = sha256File(absolutePath); await fileIntegrityRepository.upsertSnapshot({ rootKey, relativePath: safeName, contentSha256: hash, sizeBytes: stat.size, }); } /** Scans one upload root and returns integrity issues vs stored baselines. */ async function scanRoot(rootKey) { const rootDir = resolveRootDir(rootKey); const snapshots = await fileIntegrityRepository.listSnapshots(rootKey); const snapshotByPath = new Map(snapshots.map((s) => [s.relative_path, s])); const issues = []; const seen = new Set(); for (const { relativePath, absolutePath } of listFilesRecursive(rootDir)) { seen.add(relativePath); const stat = fs_1.default.statSync(absolutePath); const hash = sha256File(absolutePath); const snap = snapshotByPath.get(relativePath); if (!snap) { issues.push({ rootKey, relativePath, issue: 'added', actualHash: hash }); await fileIntegrityRepository.upsertSnapshot({ rootKey, relativePath, contentSha256: hash, sizeBytes: stat.size, }); continue; } if (snap.content_sha256 !== hash || Number(snap.size_bytes) !== stat.size) { issues.push({ rootKey, relativePath, issue: 'modified', expectedHash: snap.content_sha256, actualHash: hash, }); } } for (const snap of snapshots) { if (!seen.has(snap.relative_path)) { issues.push({ rootKey, relativePath: snap.relative_path, issue: 'deleted' }); } } return issues; } /** Scans all upload roots, raises alerts and audits on unexpected changes. */ async function runFileIntegrityCheck() { const roots = Object.values(exports.FILE_INTEGRITY_ROOTS); const allIssues = []; for (const rootKey of roots) { const issues = await scanRoot(rootKey); const suspicious = issues.filter((i) => i.issue === 'modified' || i.issue === 'deleted'); allIssues.push(...suspicious); for (const issue of suspicious) { const alreadyOpen = await securityAlertRepository.hasOpenFileIntegrityAlert({ rootKey: issue.rootKey, relativePath: issue.relativePath, issue: issue.issue, }); if (!alreadyOpen) { await auditLogRepository.create({ action: 'file_integrity_violation', resourceType: 'file', metadata: issue, }); await (0, securityService_1.raiseAlert)({ severity: 'high', alertType: 'file_integrity_violation', title: `Upload file integrity violation (${issue.issue})`, details: `${issue.rootKey}/${issue.relativePath} — expected baseline mismatch or deletion.`, metadata: issue, }); } // File is gone: drop baseline so the 5‑min monitor does not re-alert forever. // (Common when upload dir is ephemeral Docker storage without a volume.) if (issue.issue === 'deleted') { await fileIntegrityRepository.deleteSnapshot(issue.rootKey, issue.relativePath); } } } return allIssues; } /** Rebuilds baselines for all files in a root (admin maintenance). */ async function rebuildBaseline(rootKey) { await fileIntegrityRepository.deleteAllForRoot(rootKey); const rootDir = resolveRootDir(rootKey); let count = 0; for (const { relativePath, absolutePath } of listFilesRecursive(rootDir)) { const stat = fs_1.default.statSync(absolutePath); await fileIntegrityRepository.upsertSnapshot({ rootKey, relativePath, contentSha256: sha256File(absolutePath), sizeBytes: stat.size, }); count++; } return count; } //# sourceMappingURL=fileIntegrityService.js.map