// scripts/keygen.js const fs = require('fs'); const path = require('path'); const crypto = require('crypto'); const envPath = path.join(__dirname, '../.env'); const force = process.argv.includes('--force'); let envContent = ''; let exists = false; let alreadySet = false; if (fs.existsSync(envPath)) { envContent = fs.readFileSync(envPath, 'utf8'); exists = true; alreadySet = /^BITSTREAM_API_SECRET=.+/m.test(envContent); } if (alreadySet && !force) { console.warn('BITSTREAM_API_SECRET already exists in .env!'); console.warn('If you want to overwrite it, run: npm run keygen --force / yarn keygen --force'); process.exit(1); } const key = crypto.randomBytes(32).toString('hex'); let newEnvContent = ''; if (exists) { // Remove any existing BITSTREAM_API_SECRET line newEnvContent = envContent.replace(/^BITSTREAM_API_SECRET=.*$/m, '').trim(); if (newEnvContent.length > 0 && !newEnvContent.endsWith('\n')) newEnvContent += '\n'; newEnvContent += `BITSTREAM_API_SECRET=${key}\n`; } else { newEnvContent = `# Bitstream API Secret\nBITSTREAM_API_SECRET=${key}\n`; } fs.writeFileSync(envPath, newEnvContent, 'utf8'); console.log('Your new Bitstream API secret key:'); console.log(key); console.log('\nThe key has been written to .env as BITSTREAM_API_SECRET.'); if (alreadySet && force) { console.log('Previous BITSTREAM_API_SECRET was overwritten.'); }