sourcebot/packages/crypto/src/index.ts
Michael Sukkarieh 31114a9d95
add concept of secrets (#180)
* add @sourcebot/schemas package

* migrate things to use the schemas package

* Dockerfile support

* add secret table to schema

* Add concept of connection manager

* Rename Config->Connection

* Handle job failures

* Add join table between repo and connection

* nits

* create first version of crypto package

* add crypto package as deps to others

* forgot to add package changes

* add server action for adding and listing secrets, create test page for it

* add secrets page to nav menu

* add secret to config and support fetching it in backend

* reset secret form on successful submission

* add toast feedback for secrets form

* add instructions for adding encryption key to dev instructions

* add encryption key support in docker file

* add delete secret button

* fix nits from pr review

---------

Co-authored-by: bkellam <bshizzle1234@gmail.com>
2025-01-27 14:07:07 -08:00

35 lines
1.1 KiB
TypeScript

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 } {
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 decrypt(iv: string, encryptedText: string): string {
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;
}