Spaces:
Sleeping

olokaflow / apps /server /src /db /crypto.ts
phucsd's picture
Fix HF connection tester + Dual-Key Decrypt + Full Vault Hydration
3ec3c9b verified
Raw History Blame Contribute Delete
2.43 kB
import crypto from 'node:crypto';
const DEFAULT_SECRET = 'olokaflow-default-master-secret-change-in-production-2026';
const MASTER_SECRET = process.env.OLOKA_MASTER_KEY || DEFAULT_SECRET;
const KEY = crypto.scryptSync(MASTER_SECRET, 'olokaflow-salt-v1', 32);
const DEFAULT_KEY = crypto.scryptSync(DEFAULT_SECRET, 'olokaflow-salt-v1', 32);
const PREFIX = 'enc:v1:';
export function encryptSecret(plainText: string): string {
if (!plainText || !plainText.trim()) return '';
if (plainText.startsWith(PREFIX)) return plainText;
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', KEY, iv);
const encrypted = Buffer.concat([cipher.update(plainText, 'utf8'), cipher.final()]);
const authTag = cipher.getAuthTag();
return `${PREFIX}${iv.toString('base64')}:${authTag.toString('base64')}:${encrypted.toString('base64')}`;
}
function tryDecryptWithKey(payload: string, key: Buffer): string {
const raw = payload.slice(PREFIX.length);
const [ivB64, tagB64, dataB64] = raw.split(':');
if (!ivB64 || !tagB64 || !dataB64) return '';
const iv = Buffer.from(ivB64, 'base64');
const authTag = Buffer.from(tagB64, 'base64');
const encrypted = Buffer.from(dataB64, 'base64');
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
decipher.setAuthTag(authTag);
const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()]);
return decrypted.toString('utf8');
}
export function decryptSecret(payload: string): string {
if (!payload || !payload.trim()) return '';
if (!payload.startsWith(PREFIX)) return payload;
try {
return tryDecryptWithKey(payload, KEY);
} catch {
try {
return tryDecryptWithKey(payload, DEFAULT_KEY);
} catch {
return '';
}
}
}
export function maskSecret(secret: string): string {
const plain = decryptSecret(secret);
if (!plain) return '';
if (plain.length <= 8) return '••••••••';
return `${plain.slice(0, 4)}••••••${plain.slice(-4)}`;
}
export function isMaskedOrEmptySecret(input?: string | null): boolean {
if (!input || !input.trim()) return true;
const trimmed = input.trim();
return trimmed.includes('••••') || trimmed === 'configured' || trimmed === '***';
}
export function hashPassword(password: string): string {
const salt = 'olokaflow-auth-v1';
return crypto.scryptSync(password, salt, 64).toString('hex');
}