-
Notifications
You must be signed in to change notification settings - Fork 275
Expand file tree
/
Copy pathindex.ts
More file actions
68 lines (49 loc) · 1.95 KB
/
index.ts
File metadata and controls
68 lines (49 loc) · 1.95 KB
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
import crypto from 'crypto';
import { SOURCEBOT_ENCRYPTION_KEY } from './environment';
const algorithm = 'aes-256-cbc';
const ivLength = 16; // 16 bytes for CBC
const generateIV = (): Buffer => {
return crypto.randomBytes(ivLength);
};
export function encrypt(text: string): { iv: string; encryptedData: string } {
if (!SOURCEBOT_ENCRYPTION_KEY) {
throw new Error('Encryption key is not set');
}
const encryptionKey = Buffer.from(SOURCEBOT_ENCRYPTION_KEY, 'ascii');
const iv = generateIV();
const cipher = crypto.createCipheriv(algorithm, encryptionKey, iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
return { iv: iv.toString('hex'), encryptedData: encrypted };
}
export function hashSecret(text: string): string {
if (!SOURCEBOT_ENCRYPTION_KEY) {
throw new Error('Encryption key is not set');
}
return crypto.createHmac('sha256', SOURCEBOT_ENCRYPTION_KEY).update(text).digest('hex');
}
export function generateApiKey(): { key: string; hash: string } {
if (!SOURCEBOT_ENCRYPTION_KEY) {
throw new Error('Encryption key is not set');
}
const secret = crypto.randomBytes(32).toString('hex');
const hash = hashSecret(secret);
return {
key: `sourcebot-${secret}`,
hash,
};
}
export function decrypt(iv: string, encryptedText: string): string {
if (!SOURCEBOT_ENCRYPTION_KEY) {
throw new Error('Encryption key is not set');
}
const encryptionKey = Buffer.from(SOURCEBOT_ENCRYPTION_KEY, 'ascii');
const ivBuffer = Buffer.from(iv, 'hex');
const encryptedBuffer = Buffer.from(encryptedText, 'hex');
const decipher = crypto.createDecipheriv(algorithm, encryptionKey, ivBuffer);
let decrypted = decipher.update(encryptedBuffer, undefined, 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
// Export token utilities
export { getTokenFromConfig } from './tokenUtils.js';