12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- // server/security-helpers.js
- /**
- * Security helper functions for decrypting database credentials
- */
- const crypto = require('crypto');
- // The secret key used for decryption (same as in your encryption script)
- const SECRET_KEY = 'KEY';
- // Known encrypted values from your test-encrypt-server-code.js output
- const encryptedValues = {
- dbHost: 'dbHost',
- dbName: 'dbName',
- dbTable: 'dbTable',
- dbUsername: 'dbUsername',
- dbPassword: 'dbPassword'
- };
- /**
- * Decrypt an encrypted string
- */
- function decryptValue(encryptedText) {
- try {
- const parts = encryptedText.split(':');
- if (parts.length !== 3) return null; // Not our encrypted format
-
- const iv = Buffer.from(parts[0], 'hex');
- const authTag = Buffer.from(parts[1], 'hex');
- const encryptedData = parts[2];
-
- const decipher = crypto.createDecipheriv('aes-256-gcm', Buffer.from(SECRET_KEY, 'hex'), iv);
- decipher.setAuthTag(authTag);
-
- let decrypted = decipher.update(encryptedData, 'hex', 'utf8');
- decrypted += decipher.final('utf8');
-
- return decrypted;
- } catch (error) {
- // If decryption fails, it's probably not our encrypted value
- return null;
- }
- }
- /**
- * Process function body to replace encrypted credentials with decrypted values
- */
- function processEncryptedCredentials(functionBody) {
- if (!functionBody) return functionBody;
-
- let processedBody = functionBody;
-
- // Check for dynamic pattern matches first (hex:hex:hex)
- const encryptionPattern = /['"]([0-9a-f]+:[0-9a-f]+:[0-9a-f]+)['"]/g;
- let match;
-
- while ((match = encryptionPattern.exec(functionBody)) !== null) {
- const potentialEncrypted = match[1];
- const decrypted = decryptValue(potentialEncrypted);
-
- if (decrypted) {
- // Replace in the function body, keeping the quotes that surrounded it
- const fullMatch = match[0];
- const replacement = fullMatch[0] + decrypted + fullMatch[fullMatch.length - 1];
- processedBody = processedBody.replace(fullMatch, replacement);
- }
- }
-
- // Also check for known encrypted values
- Object.entries(encryptedValues).forEach(([key, encryptedValue]) => {
- if (processedBody.includes(encryptedValue)) {
- const decrypted = decryptValue(encryptedValue);
- if (decrypted) {
- processedBody = processedBody.replace(
- new RegExp(`['"]${encryptedValue}['"]`, 'g'),
- `"${decrypted}"`
- );
- }
- }
- });
-
- return processedBody;
- }
- module.exports = {
- decryptValue,
- processEncryptedCredentials,
- encryptedValues
- };
|