security-helpers (3).js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // server/security-helpers.js
  2. /**
  3. * Security helper functions for decrypting database credentials
  4. */
  5. const crypto = require('crypto');
  6. // The secret key used for decryption (same as in your encryption script)
  7. const SECRET_KEY = 'KEY';
  8. // Known encrypted values from your test-encrypt-server-code.js output
  9. const encryptedValues = {
  10. dbHost: 'dbHost',
  11. dbName: 'dbName',
  12. dbTable: 'dbTable',
  13. dbUsername: 'dbUsername',
  14. dbPassword: 'dbPassword'
  15. };
  16. /**
  17. * Decrypt an encrypted string
  18. */
  19. function decryptValue(encryptedText) {
  20. try {
  21. const parts = encryptedText.split(':');
  22. if (parts.length !== 3) return null; // Not our encrypted format
  23. const iv = Buffer.from(parts[0], 'hex');
  24. const authTag = Buffer.from(parts[1], 'hex');
  25. const encryptedData = parts[2];
  26. const decipher = crypto.createDecipheriv('aes-256-gcm', Buffer.from(SECRET_KEY, 'hex'), iv);
  27. decipher.setAuthTag(authTag);
  28. let decrypted = decipher.update(encryptedData, 'hex', 'utf8');
  29. decrypted += decipher.final('utf8');
  30. return decrypted;
  31. } catch (error) {
  32. // If decryption fails, it's probably not our encrypted value
  33. return null;
  34. }
  35. }
  36. /**
  37. * Process function body to replace encrypted credentials with decrypted values
  38. */
  39. function processEncryptedCredentials(functionBody) {
  40. if (!functionBody) return functionBody;
  41. let processedBody = functionBody;
  42. // Check for dynamic pattern matches first (hex:hex:hex)
  43. const encryptionPattern = /['"]([0-9a-f]+:[0-9a-f]+:[0-9a-f]+)['"]/g;
  44. let match;
  45. while ((match = encryptionPattern.exec(functionBody)) !== null) {
  46. const potentialEncrypted = match[1];
  47. const decrypted = decryptValue(potentialEncrypted);
  48. if (decrypted) {
  49. // Replace in the function body, keeping the quotes that surrounded it
  50. const fullMatch = match[0];
  51. const replacement = fullMatch[0] + decrypted + fullMatch[fullMatch.length - 1];
  52. processedBody = processedBody.replace(fullMatch, replacement);
  53. }
  54. }
  55. // Also check for known encrypted values
  56. Object.entries(encryptedValues).forEach(([key, encryptedValue]) => {
  57. if (processedBody.includes(encryptedValue)) {
  58. const decrypted = decryptValue(encryptedValue);
  59. if (decrypted) {
  60. processedBody = processedBody.replace(
  61. new RegExp(`['"]${encryptedValue}['"]`, 'g'),
  62. `"${decrypted}"`
  63. );
  64. }
  65. }
  66. });
  67. return processedBody;
  68. }
  69. module.exports = {
  70. decryptValue,
  71. processEncryptedCredentials,
  72. encryptedValues
  73. };