import { readFile, writeFile } from "fs/promises"; import { existsSync } from "fs"; import { getFilePath } from "./storage"; import { encryptBuffer, decryptBuffer } from "./filecrypto"; import { prisma } from "./prisma"; // Chiffrement/déchiffrement explicite d'un fichier (action groupée "chiffrer/déchiffrer"). // Format auto-porté géré par filecrypto. Le flag File.isEncrypted indique l'état sur disque. export async function encryptFile(fileId: string): Promise { const file = await prisma.file.findUnique({ where: { id: fileId } }); if (!file || file.isEncrypted) return false; const filePath = getFilePath(file.storagePath); if (!existsSync(filePath)) return false; const plain = await readFile(filePath); await writeFile(filePath, encryptBuffer(plain)); await prisma.file.update({ where: { id: fileId }, data: { isEncrypted: true, encryptionIV: "v2" }, }); return true; } export async function decryptFile(fileId: string): Promise { const file = await prisma.file.findUnique({ where: { id: fileId } }); if (!file) return null; const filePath = getFilePath(file.storagePath); if (!existsSync(filePath)) return null; const raw = await readFile(filePath); return file.isEncrypted ? decryptBuffer(raw) : raw; } export async function removeEncryption(fileId: string): Promise { const file = await prisma.file.findUnique({ where: { id: fileId } }); if (!file || !file.isEncrypted) return false; const filePath = getFilePath(file.storagePath); if (!existsSync(filePath)) return false; const raw = await readFile(filePath); await writeFile(filePath, decryptBuffer(raw)); await prisma.file.update({ where: { id: fileId }, data: { isEncrypted: false, encryptionIV: null }, }); return true; }