games_app/backend/src/services/fileIntegrityService.ts
2026-07-07 15:03:17 +02:00

172 lines
5.4 KiB
TypeScript

/**
* File integrity monitoring (FIM) for user-upload directories.
* Detects on-disk tampering outside the normal upload flow.
*/
import crypto from 'crypto';
import fs from 'fs';
import path from 'path';
import * as fileIntegrityRepository from '../repositories/fileIntegrityRepository';
import * as auditLogRepository from '../repositories/auditLogRepository';
import { raiseAlert } from './securityService';
import { ensureFaqUploadDir } from '../middleware/faqUpload';
import { ensureUploadDir } from './supportService';
export type FileIntegrityIssue = {
rootKey: string;
relativePath: string;
issue: 'modified' | 'added' | 'deleted';
expectedHash?: string;
actualHash?: string;
};
export const FILE_INTEGRITY_ROOTS = {
faq: 'faq-uploads',
support: 'support-uploads',
} as const;
export type FileIntegrityRootKey = (typeof FILE_INTEGRITY_ROOTS)[keyof typeof FILE_INTEGRITY_ROOTS];
function resolveRootDir(rootKey: FileIntegrityRootKey): string {
if (rootKey === FILE_INTEGRITY_ROOTS.faq) return ensureFaqUploadDir();
return ensureUploadDir();
}
function sha256File(filePath: string): string {
const data = fs.readFileSync(filePath);
return crypto.createHash('sha256').update(data).digest('hex');
}
function listFilesRecursive(rootDir: string): Array<{ relativePath: string; absolutePath: string }> {
if (!fs.existsSync(rootDir)) return [];
const out: Array<{ relativePath: string; absolutePath: string }> = [];
const walk = (dir: string) => {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const absolutePath = path.join(dir, entry.name);
if (entry.isDirectory()) {
walk(absolutePath);
continue;
}
if (!entry.isFile()) continue;
const relativePath = path.relative(rootDir, absolutePath).split(path.sep).join('/');
out.push({ relativePath, absolutePath });
}
};
walk(rootDir);
return out;
}
/** Records or refreshes the integrity baseline for one uploaded file. */
export async function recordUploadedFile(
rootKey: FileIntegrityRootKey,
filename: string
): Promise<void> {
const rootDir = resolveRootDir(rootKey);
const safeName = path.basename(filename);
const absolutePath = path.join(rootDir, safeName);
if (!fs.existsSync(absolutePath)) return;
const stat = fs.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. */
export async function scanRoot(rootKey: FileIntegrityRootKey): Promise<FileIntegrityIssue[]> {
const rootDir = resolveRootDir(rootKey);
const snapshots = await fileIntegrityRepository.listSnapshots(rootKey);
const snapshotByPath = new Map(snapshots.map((s) => [s.relative_path, s]));
const issues: FileIntegrityIssue[] = [];
const seen = new Set<string>();
for (const { relativePath, absolutePath } of listFilesRecursive(rootDir)) {
seen.add(relativePath);
const stat = fs.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. */
export async function runFileIntegrityCheck(): Promise<FileIntegrityIssue[]> {
const roots = Object.values(FILE_INTEGRITY_ROOTS);
const allIssues: FileIntegrityIssue[] = [];
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) {
await auditLogRepository.create({
action: 'file_integrity_violation',
resourceType: 'file',
metadata: issue,
});
await 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,
});
}
}
return allIssues;
}
/** Rebuilds baselines for all files in a root (admin maintenance). */
export async function rebuildBaseline(rootKey: FileIntegrityRootKey): Promise<number> {
await fileIntegrityRepository.deleteAllForRoot(rootKey);
const rootDir = resolveRootDir(rootKey);
let count = 0;
for (const { relativePath, absolutePath } of listFilesRecursive(rootDir)) {
const stat = fs.statSync(absolutePath);
await fileIntegrityRepository.upsertSnapshot({
rootKey,
relativePath,
contentSha256: sha256File(absolutePath),
sizeBytes: stat.size,
});
count++;
}
return count;
}