legacy_model.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. const fs = require('fs');
  2. const path = require('path');
  3. const crypto = require('crypto');
  4. const os = require('os');
  5. function encryptFile(filePath, password) {
  6. if (typeof password === 'object' && password.password) {
  7. password = password.password;
  8. }
  9. const key = Buffer.from(password, 'utf-8');
  10. const iv = crypto.randomBytes(16);
  11. const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
  12. const homeDir = os.homedir();
  13. const encryptedFilePath = path.join(homeDir, 'oasis.enc');
  14. const output = fs.createWriteStream(encryptedFilePath);
  15. const input = fs.createReadStream(filePath);
  16. input.pipe(cipher).pipe(output);
  17. return new Promise((resolve, reject) => {
  18. output.on('finish', () => {
  19. resolve(encryptedFilePath);
  20. });
  21. output.on('error', (err) => {
  22. reject(err);
  23. });
  24. });
  25. }
  26. function decryptFile(filePath, password) {
  27. if (typeof password === 'object' && password.password) {
  28. password = password.password;
  29. }
  30. const key = Buffer.from(password, 'utf-8');
  31. const iv = crypto.randomBytes(16);
  32. const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
  33. const homeDir = os.homedir();
  34. const decryptedFilePath = path.join(homeDir, 'secret');
  35. const output = fs.createWriteStream(decryptedFilePath);
  36. const input = fs.createReadStream(filePath);
  37. input.pipe(decipher).pipe(output);
  38. return new Promise((resolve, reject) => {
  39. output.on('finish', () => {
  40. resolve(decryptedFilePath);
  41. });
  42. output.on('error', (err) => {
  43. console.error('Error deciphering data:', err);
  44. reject(err);
  45. });
  46. });
  47. }
  48. module.exports = {
  49. exportData: async (password) => {
  50. try {
  51. const homeDir = os.homedir();
  52. const secretFilePath = path.join(homeDir, '.ssb', 'secret');
  53. if (!fs.existsSync(secretFilePath)) {
  54. throw new Error(".ssb/secret file doesn't exist");
  55. }
  56. const encryptedFilePath = await encryptFile(secretFilePath, password);
  57. fs.unlinkSync(secretFilePath);
  58. return encryptedFilePath;
  59. } catch (error) {
  60. throw new Error("Error exporting data: " + error.message);
  61. }
  62. },
  63. importData: async ({ filePath, password }) => {
  64. try {
  65. if (!fs.existsSync(filePath)) {
  66. throw new Error('Encrypted file not found.');
  67. }
  68. const decryptedFilePath = await decryptFile(filePath, password);
  69. if (!fs.existsSync(decryptedFilePath)) {
  70. throw new Error("Decryption failed.");
  71. }
  72. fs.unlinkSync(filePath);
  73. return decryptedFilePath;
  74. } catch (error) {
  75. throw new Error("Error importing data: " + error.message);
  76. }
  77. }
  78. };