-
Notifications
You must be signed in to change notification settings - Fork 0
Add secure encryption, storage, and retrieval of Twitter and Telegram credentials using Redis #10
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
9070e63
Implement environment variable encryption and storage in Redis
jackcooper20 e089521
Refactor encryption methods to use AES-GCM and improve environment va…
jackcooper20 746e489
Refactor environment variable handling: switch to Redis for Twitter a…
jackcooper20 4adaa3e
Refactor encryption handling: encapsulate key retrieval in a function…
jackcooper20 0d37d8c
Refactor environment variable handling: update variable names for con…
jackcooper20 6de3c32
Refactor showEnvVariables: replace dynamic import of decrypt function…
jackcooper20 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
import * as crypto from 'crypto'; | ||
|
||
const SCHEME = 'v1'; | ||
const ALGORITHM = 'aes-256-gcm'; | ||
const IV_LENGTH = 12; // per NIST recommendation for GCM | ||
|
||
// Use a strong key in production, ideally from a secure source | ||
let KEY: Buffer | null = null; | ||
function getKey(): Buffer { | ||
const k = process.env.ENCRYPTION_KEY; | ||
if (!k) throw new Error('ENCRYPTION_KEY environment variable must be set'); | ||
if (!/^[0-9a-fA-F]{64}$/.test(k)) { | ||
throw new Error('ENCRYPTION_KEY must be a 64-hex-char (256-bit) value'); | ||
} | ||
if (!KEY) KEY = Buffer.from(k, 'hex'); | ||
return KEY; | ||
} | ||
|
||
|
||
export function encrypt(text: string): string { | ||
const iv = crypto.randomBytes(IV_LENGTH); | ||
const cipher = crypto.createCipheriv(ALGORITHM, getKey(), iv); | ||
const ciphertext = Buffer.concat([cipher.update(text, 'utf8'), cipher.final()]); | ||
const tag = cipher.getAuthTag(); | ||
return `${SCHEME}:${iv.toString('hex')}:${tag.toString('hex')}:${ciphertext.toString('hex')}`; | ||
} | ||
|
||
|
||
export function decrypt(text: string): string { | ||
const parts = text.split(':'); | ||
if (parts.length !== 4) throw new Error('Invalid payload format'); | ||
const [scheme, ivHex, tagHex, dataHex] = parts; | ||
if (scheme !== SCHEME) throw new Error(`Unsupported scheme: ${scheme}`); | ||
const iv = Buffer.from(ivHex, 'hex'); | ||
const tag = Buffer.from(tagHex, 'hex'); | ||
const data = Buffer.from(dataHex, 'hex'); | ||
const decipher = crypto.createDecipheriv(ALGORITHM, getKey(), iv); | ||
decipher.setAuthTag(tag); | ||
const plaintext = Buffer.concat([decipher.update(data), decipher.final()]); | ||
return plaintext.toString('utf8'); | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
// Utility string functions | ||
|
||
/** | ||
* Masks a string for display, showing only the first and last 4 characters. | ||
* Example: abcd1234efgh5678 -> abcd…5678 | ||
*/ | ||
export function mask(v: string): string { | ||
if (!v) return ''; | ||
return v.length <= 8 ? '********' : `${v.slice(0, 4)}…${v.slice(-4)}`; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
import { encrypt } from '../lib/encryption'; | ||
import { createClient } from 'redis'; | ||
import fs from 'fs'; | ||
import path from 'path'; | ||
|
||
const redisClient = createClient({ url: process.env.REDIS_URL }); | ||
|
||
async function ensureRedisConnected() { | ||
if (!redisClient.isOpen) { | ||
await redisClient.connect(); | ||
} | ||
} | ||
|
||
async function moveEnvToRedis() { | ||
const envVars: Record<string, string> = {}; | ||
const EXCLUDE = new Set(['ENCRYPTION_KEY']); | ||
for (const [key, value] of Object.entries(process.env)) { | ||
if (!value || EXCLUDE.has(key)) continue; | ||
envVars[key] = value; | ||
} | ||
await ensureRedisConnected(); | ||
// Define which keys belong to which service | ||
const twitterKeys = ['TWITTER_AUTH_TOKEN', 'TWITTER_BEARER', 'TWITTER_CSRF_TOKEN']; | ||
const telegramKeys = ['TELEGRAM_API_ID', 'TELEGRAM_API_HASH', 'TELEGRAM_TG_CHANNEL']; | ||
|
||
// Encrypt each value individually and store as an object | ||
const twitterAccount: Record<string, string> = {}; | ||
const telegramAccount: Record<string, string> = {}; | ||
const otherVars: Record<string, string> = {}; | ||
|
||
for (const [key, value] of Object.entries(envVars)) { | ||
if (twitterKeys.includes(key)) { | ||
twitterAccount[key] = encrypt(value); | ||
} else if (telegramKeys.includes(key)) { | ||
telegramAccount[key] = encrypt(value); | ||
} else { | ||
otherVars[key] = encrypt(value); | ||
} | ||
} | ||
|
||
if (Object.keys(twitterAccount).length) { | ||
let twitterArr: any[] = []; | ||
const existing = await redisClient.get('twitter-accounts'); | ||
if (existing) { | ||
try { | ||
twitterArr = JSON.parse(existing); | ||
} catch { } | ||
} | ||
twitterArr.push(twitterAccount); | ||
await redisClient.set('twitter-accounts', JSON.stringify(twitterArr)); | ||
} | ||
if (Object.keys(telegramAccount).length) { | ||
let telegramArr: any[] = []; | ||
const existing = await redisClient.get('telegram-accounts'); | ||
if (existing) { | ||
try { | ||
telegramArr = JSON.parse(existing); | ||
} catch { } | ||
} | ||
telegramArr.push(telegramAccount); | ||
await redisClient.set('telegram-accounts', JSON.stringify(telegramArr)); | ||
} | ||
if (Object.keys(otherVars).length) { | ||
await redisClient.set('env-variables', JSON.stringify(otherVars)); | ||
} | ||
console.log('Moved and individually encrypted env variables to Redis (twitter-accounts, telegram-accounts, env-variables as objects).'); | ||
} | ||
|
||
moveEnvToRedis().then(() => process.exit(0)); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
import { createClient } from 'redis'; | ||
import { mask } from '../lib/utils/string'; | ||
import { decrypt } from '../lib/encryption'; | ||
|
||
|
||
async function showEnvVariables() { | ||
const redisClient = createClient({ url: process.env.REDIS_URL }); | ||
const decryptFlag = process.argv.includes('--decrypt'); | ||
let decryptFn: ((v: string) => string) | null = null; | ||
if (decryptFlag) { | ||
decryptFn = decrypt; | ||
} | ||
await redisClient.connect(); | ||
await showAccounts(redisClient, decryptFlag, decryptFn); | ||
await redisClient.quit(); | ||
} | ||
|
||
// Unified function to show both Twitter and Telegram accounts | ||
type AccountRecord = Record<string, string> | { error: string }; | ||
|
||
async function showAccounts( | ||
redisClient: ReturnType<typeof createClient>, | ||
decryptFlag: boolean, | ||
decryptFn: ((v: string) => string) | null | ||
) { | ||
const services: { name: string; key: string }[] = [ | ||
{ name: 'Twitter', key: 'twitter-accounts' }, | ||
{ name: 'Telegram', key: 'telegram-accounts' } | ||
]; | ||
for (const service of services) { | ||
const raw = await redisClient.get(service.key); | ||
console.log(`\n${service.name} Accounts:`); | ||
if (raw) { | ||
let accounts: AccountRecord[]; | ||
try { | ||
accounts = JSON.parse(raw) as AccountRecord[]; | ||
} catch (e) { | ||
accounts = [{ error: 'Failed to parse' }]; | ||
} | ||
accounts.forEach((acc, idx) => { | ||
console.log(`Account ${idx + 1}:`); | ||
Object.entries(acc).forEach(([k, v]) => { | ||
const shown = decryptFlag && decryptFn ? decryptFn(v as string) : mask(v as string); | ||
console.log(` ${k}: ${shown}`); | ||
}); | ||
tasin2610 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
}); | ||
} else { | ||
console.log(' (none)'); | ||
} | ||
} | ||
tasin2610 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
showEnvVariables(); | ||
|
||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.