data-primals-engine 1.5.0 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +35 -0
  2. package/client/src/AddWidgetTypeModal.jsx +47 -43
  3. package/client/src/App.jsx +2 -6
  4. package/client/src/App.scss +12 -0
  5. package/client/src/AssistantChat.jsx +363 -323
  6. package/client/src/AssistantChat.scss +27 -10
  7. package/client/src/Dashboard.jsx +480 -396
  8. package/client/src/Dashboard.scss +1 -1
  9. package/client/src/DashboardHtmlViewItem.jsx +147 -0
  10. package/client/src/DashboardView.jsx +654 -569
  11. package/client/src/DataEditor.jsx +10 -3
  12. package/client/src/DataLayout.jsx +805 -755
  13. package/client/src/DataLayout.scss +14 -0
  14. package/client/src/DataTable.jsx +39 -75
  15. package/client/src/Dialog.scss +1 -1
  16. package/client/src/Field.jsx +2057 -1825
  17. package/client/src/FlexViewCard.jsx +44 -0
  18. package/client/src/HistoryDialog.jsx +47 -14
  19. package/client/src/HtmlViewBuilderModal.jsx +91 -0
  20. package/client/src/HtmlViewBuilderModal.scss +18 -0
  21. package/client/src/HtmlViewCard.jsx +44 -0
  22. package/client/src/HtmlViewCard.scss +35 -0
  23. package/client/src/KanbanCard.jsx +1 -2
  24. package/client/src/ModelCreator.jsx +5 -4
  25. package/client/src/ModelCreatorField.jsx +51 -4
  26. package/client/src/ModelList.jsx +92 -53
  27. package/client/src/Notification.jsx +136 -136
  28. package/client/src/Notification.scss +0 -18
  29. package/client/src/Pagination.jsx +5 -3
  30. package/client/src/RelationField.jsx +354 -258
  31. package/client/src/RelationSelectorWidget.jsx +173 -0
  32. package/client/src/contexts/ModelContext.jsx +10 -1
  33. package/client/src/contexts/UIContext.jsx +72 -63
  34. package/client/src/filter.js +262 -212
  35. package/client/src/hooks/useValidation.js +75 -0
  36. package/client/src/translations.js +24 -24
  37. package/package.json +2 -1
  38. package/src/constants.js +1 -1
  39. package/src/defaultModels.js +1596 -1544
  40. package/src/i18n.js +710 -10
  41. package/src/modules/assistant/assistant.js +148 -18
  42. package/src/modules/bucket.js +2 -1
  43. package/src/modules/data/data.core.js +118 -92
  44. package/src/modules/data/data.history.js +531 -492
  45. package/src/modules/data/data.js +3 -53
  46. package/src/modules/data/data.operations.js +77 -26
  47. package/src/modules/data/data.relations.js +686 -686
  48. package/src/modules/data/data.routes.js +1879 -1821
  49. package/src/modules/data/data.validation.js +81 -2
  50. package/src/modules/file.js +247 -238
  51. package/src/packs.js +5482 -5478
  52. package/test/data.integration.test.js +1115 -1060
@@ -2,6 +2,7 @@ import {Event} from "../../events.js";
2
2
  import i18n from "../../i18n.js";
3
3
  import {allowedFields, maxFileSize, maxModelNameLength, maxStringLength} from "../../constants.js";
4
4
  import {getDefaultForType} from "../../data.js";
5
+ import { generateRegexFromMask } from './data.core.js';
5
6
 
6
7
  import {dataTypes} from "./data.operations.js";
7
8
  import {Logger} from "../../gameObject.js";
@@ -11,6 +12,63 @@ let engine, logger;
11
12
  export function onInit(defaultEngine) {
12
13
  engine = defaultEngine;
13
14
  logger = engine.getComponent(Logger);
15
+
16
+ Event.Listen("OnValidateModelStructure", async (modelStructure) =>{
17
+
18
+ const objectKeys = Object.keys(modelStructure);
19
+
20
+ if( objectKeys.find(o => !["name", "_user", "icon", "history", "locked", "_id", "description", "maxRequestData", "fields", "tags"].includes(o)) ){
21
+ throw new Error(i18n.t('api.model.invalidStructure'));
22
+ }
23
+
24
+ // Vérification du type de name
25
+ if (typeof modelStructure.name !== 'string' || !modelStructure.name) {
26
+ throw new Error(i18n.t("api.validate.requiredFieldString", ["name"]));
27
+ }
28
+
29
+ // Vérification du type de description
30
+ if (typeof modelStructure.description !== 'string') {
31
+ throw new Error(i18n.t("api.validate.fieldString", ["description"]));
32
+ }
33
+
34
+ // Vérification de la présence et du type du tableau fields
35
+ if (!Array.isArray(modelStructure.fields)) {
36
+ throw new Error(i18n.t('api.validate.fieldArray', ["fields"]));
37
+ }
38
+
39
+ // Vérification de la présence et du type du tableau fields
40
+ if (typeof(modelStructure.tags) !== 'undefined' && (!Array.isArray(modelStructure.tags) || modelStructure.tags.some(tag => typeof tag !== 'string'))) {
41
+ throw new Error(i18n.t('api.validate.fieldArray', ["tags"]));
42
+ //todo: fieldStringArray trad
43
+ }
44
+
45
+ // Vérification de chaque champ dans le tableau fields
46
+ for (const field of modelStructure.fields) {
47
+ validateField(field);
48
+ }
49
+
50
+ if (modelStructure.constraints) {
51
+ if (!Array.isArray(modelStructure.constraints)) {
52
+ throw new Error('Model "constraints" property must be an array.');
53
+ }
54
+ const fieldNames = new Set(modelStructure.fields.map(f => f.name));
55
+ for (const constraint of modelStructure.constraints) {
56
+ if (constraint.type === 'unique') {
57
+ if (!constraint.name || !Array.isArray(constraint.keys) || constraint.keys.length === 0) {
58
+ throw new Error('Unique constraint must have a "name" and a non-empty "keys" array.');
59
+ }
60
+ for (const key of constraint.keys) {
61
+ if (!fieldNames.has(key)) {
62
+ throw new Error(`Constraint key "${key}" in constraint "${constraint.name}" does not exist as a field in the model.`);
63
+ }
64
+ }
65
+ }
66
+ }
67
+ }
68
+
69
+ return true; // La structure du modèle est valide
70
+ }, "event", "system");
71
+
14
72
  }
15
73
 
16
74
  export async function validateModelStructure(modelStructure) {
@@ -104,13 +162,23 @@ export const validateField = (field) => {
104
162
  case 'code':
105
163
  if (field.type === 'code')
106
164
  allowedFieldTest(['maxlength', 'language', 'conditionBuilder', 'targetModel']);
107
- else if (['string_t', 'string'].includes(field.type))
108
- allowedFieldTest(['maxlength', 'multiline']);
165
+ else if (['string_t', 'string'].includes(field.type)) {
166
+ allowedFieldTest(['maxlength', 'multiline', 'mask', 'replacement']);
167
+ }
109
168
  else
110
169
  allowedFieldTest(['maxlength']);
111
170
  if (field.maxlength !== undefined && typeof field.maxlength !== 'number') {
112
171
  throw new Error(i18n.t('api.validate.fieldNumber', "L'attribut '{{0}}' doit être un nombre.", ["maxlength"]));
113
172
  }
173
+ if (field.mask !== undefined && typeof field.mask !== 'string') {
174
+ throw new Error(i18n.t('api.validate.fieldString', "Le champ '{{0}}' doit être une chaîne de caractères.", ["mask"]));
175
+ }
176
+ if (field.replacement !== undefined && typeof field.replacement !== 'object') {
177
+ throw new Error(i18n.t('api.validate.fieldObject', "L'attribut '{{0}}' doit être un objet.", ["replacement"]));
178
+ }
179
+ if (field.mask && !field.replacement) {
180
+ throw new Error(i18n.t('api.validate.missingField', "L'attribut 'replacement' est requis quand 'mask' est défini."));
181
+ }
114
182
  break;
115
183
  case 'model':
116
184
  case 'modelField':
@@ -241,6 +309,17 @@ export async function validateModelData(doc, model, isPatch = false) {
241
309
  const fieldDef = model.fields.find(f => f.name === fieldName);
242
310
  if (!fieldDef) continue; // On ignore les champs supplémentaires
243
311
 
312
+ // Validation du masque si défini
313
+ if (fieldDef.mask && value) {
314
+ const regexString = generateRegexFromMask(fieldDef.mask, fieldDef.replacement);
315
+ if (regexString) {
316
+ const regex = new RegExp(regexString);
317
+ if (!regex.test(value)) {
318
+ throw new Error(i18n.t('api.field.maskValidationFailed', { field: fieldName, value: value, mask: fieldDef.mask }));
319
+ }
320
+ }
321
+ }
322
+
244
323
  const validator = dataTypes[fieldDef.type]?.validate;
245
324
  const valid = validator && validator(value, fieldDef);
246
325
  const realValidation = await Event.Trigger('OnDataValidate', "event", "system", value, fieldDef, doc);
@@ -1,239 +1,248 @@
1
-
2
- // Nouvelle fonction pour ajouter un fichier privé
3
- import {maxPrivateFileSize, megabytes} from "../constants.js";
4
- import {isLocalUser} from "../data.js";
5
- import i18n from "../../src/i18n.js";
6
- import {getCollection} from "./mongodb.js";
7
- import {getFileExtension, isGUID, uuidv4} from "../core.js";
8
- import path from "node:path";
9
- import process from "node:process";
10
- import fs from "node:fs";
11
- import { checkServerCapacity} from "./data/index.js";
12
- import crypto from "node:crypto";
13
- import * as tar from "tar";
14
- import {promisify} from "node:util";
15
- import {calculateTotalUserStorageUsage, hasPermission} from "./user.js";
16
- import {Logger} from "../gameObject.js";
17
- import {deleteFromS3, getUserS3Config, uploadToS3} from "./bucket.js";
18
- import {Config} from "../config.js";
19
-
20
- const pbkdf2Async = promisify(crypto.pbkdf2);
21
-
22
- let engine, logger;
23
- const fsPromises = fs.promises;
24
-
25
- // Encryption settings
26
- const algorithm = 'aes-256-cbc'; // Algorithm to use
27
- const iterations = 100000; // Number of iterations for PBKDF2
28
- const keyLength = 32; // Key length for AES-256
29
- const ivLength = 16; // IV length for AES
30
-
31
- // Function to derive a key and IV from a passphrase and salt
32
- async function deriveKeyAndIV(password, salt) {
33
- const key = await pbkdf2Async(password, salt, iterations, keyLength, 'sha256');
34
- // L'IV n'est plus dérivé ici.
35
- return { key };
36
- }
37
-
38
-
39
- export const unzip = async (file) => {
40
- await tar.extract({ file: file, gzip: true, sync: true });
41
- }
42
-
43
- export const zip = async (filename) => {
44
- await tar.create({ gzip: true, sync: true, file: filename+'.gz' }, [filename])
45
- }
46
- export const addFile = async (file, user) => {
47
- if (!file) throw new Error("Le fichier est requis");
48
-
49
- const m = Config.Get('maxPrivateFileSize', maxPrivateFileSize);
50
- if (file.size > m) {
51
- throw new Error(`La taille du fichier dépasse la limite autorisée (${m / megabytes} Mo).`);
52
- }
53
-
54
- if (user.username !== 'demo' && isLocalUser(user) && !await hasPermission(["API_ADMIN", "API_UPLOAD_FILE"], user)) {
55
- throw new Error(i18n.t("api.permission.uploadFile"));
56
- }
57
-
58
- const incomingDataSize = file.size;
59
-
60
- const userStorageLimit = await engine.userProvider.getUserStorageLimit(user);
61
- const currentStorageUsage = await calculateTotalUserStorageUsage(user);
62
-
63
- if (currentStorageUsage + incomingDataSize > userStorageLimit) {
64
- throw new Error(i18n.t("api.data.storageLimitExceeded", { limit: Math.round(userStorageLimit / megabytes) }));
65
- }
66
-
67
- const serverCapacity = await checkServerCapacity(incomingDataSize);
68
- if (!serverCapacity.isSufficient) {
69
- throw new Error(i18n.t("api.data.serverStorageFull", "Le serveur a atteint sa capacité de stockage maximale. Veuillez réessayer plus tard."));
70
- }
71
-
72
- // Générer un GUID pour le fichier
73
- const guid = uuidv4();
74
- const s3Config = await getUserS3Config(user);
75
- const extension = getFileExtension(file.name);
76
- const newFilename = `${guid}.${extension}`;
77
-
78
- const fileData = {
79
- guid: guid,
80
- filename: file.name,
81
- size: file.size,
82
- mimeType: file.type,
83
- createdAt: new Date(),
84
- user: user.username,
85
- mainUser: user._user
86
- };
87
-
88
- if (s3Config && s3Config.bucketName && s3Config.accessKeyId && s3Config.secretAccessKey) { // Correction: bucketName au lieu de bucket
89
- try {
90
- // Correction: Appel manquant à la fonction de téléversement
91
- await uploadToS3(s3Config, file.path, newFilename);
92
-
93
- fileData.storage = 's3';
94
- fileData.filename = newFilename; // Le nom sur S3
95
- logger.info(`Fichier ${newFilename} téléversé sur le bucket S3 ${s3Config.bucketName}.`);
96
- } catch (error) {
97
- logger.info(`Le téléversement S3 a échoué pour ${file.name}: ${error.message}`, 'error');
98
- throw new Error("Le téléversement S3 a échoué.");
99
- } finally {
100
- // Nettoyer le fichier temporaire uploadé par express-formidable
101
- await fsPromises.unlink(file.path).catch(e => logger.info(`Échec de la suppression du fichier temporaire ${file.path}: ${e.message}`, 'error'));
102
- }
103
- } else {
104
- // Sauvegarde locale
105
- const uploadDir = path.join(process.cwd(), "uploads", "private");
106
- if (!fs.existsSync(uploadDir)) {
107
- fs.mkdirSync(uploadDir, { recursive: true });
108
- }
109
- const newPath = path.join(uploadDir, newFilename);
110
-
111
- try {
112
- // express-formidable place déjà le fichier dans un répertoire temporaire. Nous n'avons qu'éplacer.
113
- await fsPromises.rename(file.path, newPath);
114
- fileData.storage = 'local';
115
- fileData.filename = newFilename; // Le nom dans le dossier uploads
116
- fileData.path = newPath; // Le chemin complet pour les fichiers locaux
117
- logger.info(`Fichier ${newFilename} sauvegardé localement dans ${newPath}.`);
118
- } catch (error) {
119
- logger.info(`Le déplacement du fichier local a échoué pour ${file.name}: ${error.message}`, 'error');
120
- // Essayer de nettoyer le fichier temporaire même si le renommage échoue
121
- await fsPromises.unlink(file.path).catch(e => logger.info(`Échec de la suppression du fichier temporaire ${file.path}: ${e.message}`, 'error'));
122
- throw new Error("Le stockage du fichier local a échoué.");
123
- }
124
- }
125
-
126
- const filesCollection = await getCollection("files");
127
- await filesCollection.insertOne(fileData);
128
-
129
- return guid;
130
- };
131
-
132
- /**
133
- * Récupère les métadonnées d'un fichier depuis la base de données.
134
- * @param {string} guid - Le GUID du fichier.
135
- * @returns {Promise<object|null>} L'objet de métadonnées du fichier ou null si non trouvé.
136
- */
137
- export const getFile = async (guid) => {
138
- const filesCollection = await getCollection("files");
139
- return await filesCollection.findOne({ guid });
140
- };
141
-
142
- export const removeFile = async (guid, user) => {
143
- if (!guid) return false;
144
- if (!isGUID(guid)) throw new Error("Le GUID du fichier n'est pas valide.");
145
-
146
- const fileData = await getFile(guid);
147
- if (!fileData) {
148
- logger.info(`Tentative de suppression d'un fichier inexistant avec le GUID : ${guid}`, 'warn');
149
- return;
150
- }
151
-
152
- if (fileData.storage === 's3') {
153
- const s3Config = await getUserS3Config(user);
154
- if (s3Config && s3Config.bucketName) { // Correction: bucketName au lieu de bucket
155
- try {
156
- await deleteFromS3(s3Config, fileData.filename);
157
- logger.info(`Fichier ${fileData.filename} supprimé du bucket S3 ${s3Config.bucketName}.`);
158
- } catch (error) {
159
- logger.info(`La suppression S3 a échoué pour ${fileData.filename}: ${error.message}`, 'error');
160
- throw new Error("La suppression S3 a échoué.");
161
- }
162
- } else {
163
- logger.info(`Configuration S3 non trouvée pour l'utilisateur, impossible de supprimer le fichier ${fileData.filename} de S3.`, 'error');
164
- throw new Error("Configuration S3 non trouvée, impossible de supprimer le fichier.");
165
- }
166
- } else if (fileData.storage === 'local') {
167
- try {
168
- if (fileData.path && fs.existsSync(fileData.path)) {
169
- await fsPromises.unlink(fileData.path);
170
- logger.info(`Fichier local ${fileData.path} supprimé.`);
171
- } else {
172
- logger.info(`Fichier local non trouvé au chemin ${fileData.path}, mais suppression de l'enregistrement en BDD.`, 'warn');
173
- }
174
- } catch (error) {
175
- logger.info(`La suppression du fichier local a échoué pour ${fileData.path}: ${error.message}`, 'error');
176
- throw new Error("La suppression du fichier local a échoué.");
177
- }
178
- }
179
-
180
- const filesCollection = await getCollection("files");
181
- await filesCollection.deleteOne({ guid });
182
- };
183
-
184
-
185
-
186
-
187
- // Function to encrypt the file content
188
- export async function encryptFile(filePath, password) {
189
- try {
190
- const salt = crypto.randomBytes(16);
191
- const iv = crypto.randomBytes(ivLength);
192
-
193
- // On ne dérive que la clé
194
- const { key } = await deriveKeyAndIV(password, salt);
195
-
196
- const fileData = await fs.promises.readFile(filePath);
197
- const cipher = crypto.createCipheriv(algorithm, key, iv);
198
- const encryptedData = Buffer.concat([cipher.update(fileData), cipher.final()]);
199
-
200
- // On it : [salt][iv][données chiffrées]
201
- await fs.promises.writeFile(filePath, Buffer.concat([salt, iv, encryptedData]));
202
-
203
- console.log('File encrypted successfully.', filePath);
204
- } catch (error) {
205
- console.error('Error during encryption:', error.message);
206
- }
207
- }
208
- // Function to decrypt the file content
209
- export async function decryptFile(filePath, password) {
210
- try {
211
- const fileData = await fs.promises.readFile(filePath);
212
-
213
- // Extraire le sel, l'IV et les données
214
- const salt = fileData.slice(0, 16);
215
- // NOUVEAU: Extraire l'IV qui suit le sel
216
- const iv = fileData.slice(16, 16 + ivLength);
217
- const encryptedData = fileData.slice(16 + ivLength);
218
-
219
- // On dérive la même clé en utilisant le sel extrait
220
- const { key } = await deriveKeyAndIV(password, salt);
221
-
222
- // On utilise l'IV extrait pour le déchiffrement
223
- const decipher = crypto.createDecipheriv(algorithm, key, iv);
224
- const decryptedData = Buffer.concat([decipher.update(encryptedData), decipher.final()]);
225
-
226
- await fs.promises.writeFile(filePath, decryptedData);
227
-
228
- console.log('File decrypted successfully.');
229
- } catch (error) {
230
- console.error('Error during decryption:', error.message);
231
- // Relancer l'erreur peut être utile pour que l'appelant sache que ça a échoué
232
- throw new Error(`Decryption failed: ${error.message}`);
233
- }
234
- }
235
-
236
- export async function onInit(defaultEngine) {
237
- engine = defaultEngine;
238
- logger = engine.getComponent(Logger);
1
+
2
+ // Nouvelle fonction pour ajouter un fichier privé
3
+ import {maxPrivateFileSize, megabytes} from "../constants.js";
4
+ import {isLocalUser} from "../data.js";
5
+ import i18n from "../../src/i18n.js";
6
+ import {getCollection} from "./mongodb.js";
7
+ import {getFileExtension, isGUID, uuidv4} from "../core.js";
8
+ import path from "node:path";
9
+ import process from "node:process";
10
+ import fs from "node:fs";
11
+ import { checkServerCapacity} from "./data/index.js";
12
+ import crypto from "node:crypto";
13
+ import * as tar from "tar";
14
+ import {promisify} from "node:util";
15
+ import {calculateTotalUserStorageUsage, hasPermission} from "./user.js";
16
+ import {Logger} from "../gameObject.js";
17
+ import {deleteFromS3, getUserS3Config, uploadToS3} from "./bucket.js";
18
+ import {Config} from "../config.js";
19
+
20
+ const pbkdf2Async = promisify(crypto.pbkdf2);
21
+
22
+ let engine, logger;
23
+ const fsPromises = fs.promises;
24
+
25
+ // Encryption settings
26
+ const algorithm = 'aes-256-cbc'; // Algorithm to use
27
+ const iterations = 100000; // Number of iterations for PBKDF2
28
+ const keyLength = 32; // Key length for AES-256
29
+ const ivLength = 16; // IV length for AES
30
+
31
+ // Function to derive a key and IV from a passphrase and salt
32
+ async function deriveKeyAndIV(password, salt) {
33
+ const key = await pbkdf2Async(password, salt, iterations, keyLength, 'sha256');
34
+ // L'IV n'est plus dérivé ici.
35
+ return { key };
36
+ }
37
+
38
+
39
+ export const unzip = async (file) => {
40
+ await tar.extract({ file: file, gzip: true, sync: true });
41
+ }
42
+
43
+ export const zip = async (filename) => {
44
+ await tar.create({ gzip: true, sync: true, file: filename+'.gz' }, [filename])
45
+ }
46
+ export const addFile = async (file, user) => {
47
+ if (!file) throw new Error("Le fichier est requis");
48
+
49
+ // Rendre compatible avec formidable v2 (path, name, type) et v3 (filepath, originalFilename, mimetype)
50
+ const filePath = file.path || file.filepath;
51
+ const originalName = file.name || file.originalFilename;
52
+ const mimeType = file.type || file.mimetype;
53
+
54
+ if (!filePath || !originalName) {
55
+ throw new Error("Les informations du fichier (nom, chemin) sont incomplètes.");
56
+ }
57
+
58
+ const m = Config.Get('maxPrivateFileSize', maxPrivateFileSize);
59
+ if (file.size > m) {
60
+ throw new Error(`La taille du fichier dépasse la limite autorisée (${m / megabytes} Mo).`);
61
+ }
62
+
63
+ if (user.username !== 'demo' && isLocalUser(user) && !await hasPermission(["API_ADMIN", "API_UPLOAD_FILE"], user)) {
64
+ throw new Error(i18n.t("api.permission.uploadFile"));
65
+ }
66
+
67
+ const incomingDataSize = file.size;
68
+
69
+ const userStorageLimit = await engine.userProvider.getUserStorageLimit(user);
70
+ const currentStorageUsage = await calculateTotalUserStorageUsage(user);
71
+
72
+ if (currentStorageUsage + incomingDataSize > userStorageLimit) {
73
+ throw new Error(i18n.t("api.data.storageLimitExceeded", { limit: Math.round(userStorageLimit / megabytes) }));
74
+ }
75
+
76
+ const serverCapacity = await checkServerCapacity(incomingDataSize);
77
+ if (!serverCapacity.isSufficient) {
78
+ throw new Error(i18n.t("api.data.serverStorageFull", "Le serveur a atteint sa capacité de stockage maximale. Veuillez réessayer plus tard."));
79
+ }
80
+
81
+ // Générer un GUID pour le fichier
82
+ const guid = uuidv4();
83
+ const s3Config = await getUserS3Config(user);
84
+ const extension = getFileExtension(originalName);
85
+ const newFilename = `${guid}.${extension}`;
86
+
87
+ const fileData = {
88
+ guid: guid,
89
+ name: originalName, // Nom original du fichier
90
+ filename: newFilename, // Nom du fichier stocké (GUID + extension)
91
+ size: file.size,
92
+ mimeType: mimeType,
93
+ createdAt: new Date(),
94
+ user: user.username,
95
+ mainUser: user._user
96
+ };
97
+
98
+ if (s3Config && s3Config.bucketName && s3Config.accessKeyId && s3Config.secretAccessKey) {
99
+ try {
100
+ await uploadToS3(s3Config, filePath, newFilename);
101
+
102
+ fileData.storage = 's3';
103
+ logger.info(`Fichier ${newFilename} téléversé sur le bucket S3 ${s3Config.bucketName}.`);
104
+ } catch (error) {
105
+ logger.error(`Le téléversement S3 a échoué pour ${originalName}: ${error.message}`, error);
106
+ throw new Error("Le téléversement S3 a échoué.");
107
+ } finally {
108
+ // Nettoyer le fichier temporaire uploadé par express-formidable
109
+ await fsPromises.unlink(filePath).catch(e => logger.warn(`Échec de la suppression du fichier temporaire ${filePath}: ${e.message}`));
110
+ }
111
+ } else {
112
+ // Sauvegarde locale
113
+ const uploadDir = path.join(process.cwd(), "uploads", "private");
114
+ if (!fs.existsSync(uploadDir)) {
115
+ fs.mkdirSync(uploadDir, { recursive: true });
116
+ }
117
+ const newPath = path.join(uploadDir, newFilename);
118
+
119
+ try {
120
+ // Utiliser copyFile puis unlink au lieu de rename pour éviter les erreurs cross-device (EXDEV)
121
+ // qui peuvent survenir dans des environnements conteneurisés comme GitHub Actions.
122
+ await fsPromises.copyFile(filePath, newPath);
123
+ await fsPromises.unlink(filePath);
124
+ fileData.storage = 'local';
125
+ fileData.path = newPath; // Le chemin complet pour les fichiers locaux
126
+ logger.info(`Fichier ${newFilename} sauvegardé localement dans ${newPath}.`);
127
+ } catch (error) {
128
+ logger.error(`Le stockage du fichier local a échoué pour ${originalName}: ${error.message}`, error);
129
+ // Essayer de nettoyer le fichier temporaire même si le renommage échoue
130
+ await fsPromises.unlink(filePath).catch(e => logger.warn(`Échec de la suppression du fichier temporaire ${filePath}: ${e.message}`));
131
+ throw new Error("Le stockage du fichier local a échoué.");
132
+ }
133
+ }
134
+
135
+ const filesCollection = await getCollection("files");
136
+ await filesCollection.insertOne(fileData);
137
+
138
+ return guid;
139
+ };
140
+
141
+ /**
142
+ * Récupère les métadonnées d'un fichier depuis la base de données.
143
+ * @param {string} guid - Le GUID du fichier.
144
+ * @returns {Promise<object|null>} L'objet de métadonnées du fichier ou null si non trouvé.
145
+ */
146
+ export const getFile = async (guid) => {
147
+ const filesCollection = await getCollection("files");
148
+ return await filesCollection.findOne({ guid });
149
+ };
150
+
151
+ export const removeFile = async (guid, user) => {
152
+ if (!guid) return false;
153
+ if (!isGUID(guid)) throw new Error("Le GUID du fichier n'est pas valide.");
154
+
155
+ const fileData = await getFile(guid);
156
+ if (!fileData) {
157
+ logger.info(`Tentative de suppression d'un fichier inexistant avec le GUID : ${guid}`, 'warn');
158
+ return;
159
+ }
160
+
161
+ if (fileData.storage === 's3') {
162
+ const s3Config = await getUserS3Config(user);
163
+ if (s3Config && s3Config.bucketName) { // Correction: bucketName au lieu de bucket
164
+ try {
165
+ await deleteFromS3(s3Config, fileData.filename);
166
+ logger.info(`Fichier ${fileData.filename} supprimé du bucket S3 ${s3Config.bucketName}.`);
167
+ } catch (error) {
168
+ logger.info(`La suppression S3 a échoué pour ${fileData.filename}: ${error.message}`, 'error');
169
+ throw new Error("La suppression S3 a échoué.");
170
+ }
171
+ } else {
172
+ logger.info(`Configuration S3 non trouvée pour l'utilisateur, impossible de supprimer le fichier ${fileData.filename} de S3.`, 'error');
173
+ throw new Error("Configuration S3 non trouvée, impossible de supprimer le fichier.");
174
+ }
175
+ } else if (fileData.storage === 'local') {
176
+ try {
177
+ if (fileData.path && fs.existsSync(fileData.path)) {
178
+ await fsPromises.unlink(fileData.path);
179
+ logger.info(`Fichier local ${fileData.path} supprimé.`);
180
+ } else {
181
+ logger.info(`Fichier local non trouvé au chemin ${fileData.path}, mais suppression de l'enregistrement en BDD.`, 'warn');
182
+ }
183
+ } catch (error) {
184
+ logger.info(`La suppression du fichier local a échoué pour ${fileData.path}: ${error.message}`, 'error');
185
+ throw new Error("La suppression du fichier local a échoué.");
186
+ }
187
+ }
188
+
189
+ const filesCollection = await getCollection("files");
190
+ await filesCollection.deleteOne({ guid });
191
+ };
192
+
193
+
194
+
195
+
196
+ // Function to encrypt the file content
197
+ export async function encryptFile(filePath, password) {
198
+ try {
199
+ const salt = crypto.randomBytes(16);
200
+ const iv = crypto.randomBytes(ivLength);
201
+
202
+ // On ne dérive que la clé
203
+ const { key } = await deriveKeyAndIV(password, salt);
204
+
205
+ const fileData = await fs.promises.readFile(filePath);
206
+ const cipher = crypto.createCipheriv(algorithm, key, iv);
207
+ const encryptedData = Buffer.concat([cipher.update(fileData), cipher.final()]);
208
+
209
+ // On it : [salt][iv][données chiffrées]
210
+ await fs.promises.writeFile(filePath, Buffer.concat([salt, iv, encryptedData]));
211
+
212
+ console.log('File encrypted successfully.', filePath);
213
+ } catch (error) {
214
+ console.error('Error during encryption:', error.message);
215
+ }
216
+ }
217
+ // Function to decrypt the file content
218
+ export async function decryptFile(filePath, password) {
219
+ try {
220
+ const fileData = await fs.promises.readFile(filePath);
221
+
222
+ // Extraire le sel, l'IV et les données
223
+ const salt = fileData.slice(0, 16);
224
+ // NOUVEAU: Extraire l'IV qui suit le sel
225
+ const iv = fileData.slice(16, 16 + ivLength);
226
+ const encryptedData = fileData.slice(16 + ivLength);
227
+
228
+ // On dérive la même clé en utilisant le sel extrait
229
+ const { key } = await deriveKeyAndIV(password, salt);
230
+
231
+ // On utilise l'IV extrait pour le déchiffrement
232
+ const decipher = crypto.createDecipheriv(algorithm, key, iv);
233
+ const decryptedData = Buffer.concat([decipher.update(encryptedData), decipher.final()]);
234
+
235
+ await fs.promises.writeFile(filePath, decryptedData);
236
+
237
+ console.log('File decrypted successfully.');
238
+ } catch (error) {
239
+ console.error('Error during decryption:', error.message);
240
+ // Relancer l'erreur peut être utile pour que l'appelant sache que ça a échoué
241
+ throw new Error(`Decryption failed: ${error.message}`);
242
+ }
243
+ }
244
+
245
+ export async function onInit(defaultEngine) {
246
+ engine = defaultEngine;
247
+ logger = engine.getComponent(Logger);
239
248
  }