Spaces:
Sleeping

File size: 2,428 Bytes
9713441
 
3ec3c9b
 
9713441
 
3ec3c9b
9713441
 
 
 
 
 
 
 
 
 
 
 
 
 
3ec3c9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9713441
 
 
 
 
3ec3c9b
9713441
3ec3c9b
 
 
 
 
9713441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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');
}