/** * Helper script to create a live API key for local development * Usage: node scripts/create-live-api-key.js */ require('dotenv').config(); const crypto = require('crypto'); const { query, connectDB } = require('../src/database/connection'); function generateApiKey(type = 'live') { const prefix = type === 'test' ? 'vf_test_' : 'vf_live_'; return prefix + crypto.randomBytes(24).toString('hex'); } async function createLiveApiKey() { try { await connectDB(); console.log('āœ… Connected to database'); // Get a user to attach the key to. Prefer an existing user, otherwise create one. let userRes = await query('SELECT id FROM users ORDER BY id LIMIT 1'); let userId; if (userRes.rows.length === 0) { console.log('No users found. Creating a default local user...'); const bcrypt = require('bcryptjs'); const passwordHash = await bcrypt.hash('localpass123', 10); const userResult = await query( `INSERT INTO users (email, password_hash, company_name, plan, monthly_quota, quota_reset_date, is_active) VALUES ($1, $2, $3, $4, $5, DATE(NOW() + INTERVAL '1 month'), true) RETURNING id`, ['local@example.com', passwordHash, 'Local Dev', 'dev', 100000] ); userId = userResult.rows[0].id; console.log('Created user id:', userId); } else { userId = userRes.rows[0].id; console.log('Using existing user id:', userId); } // Deactivate any existing live keys for that user (optional) await query('UPDATE api_keys SET is_active = false WHERE user_id = $1 AND key_prefix = $2', [userId, 'vf_live_']); // Generate new live API key const apiKey = generateApiKey('live'); const keyHash = crypto.createHash('sha256').update(apiKey).digest('hex'); await query( `INSERT INTO api_keys (user_id, key_prefix, key_hash, key_hint, name, is_test_key, is_active) VALUES ($1, $2, $3, $4, $5, false, true)`, [userId, 'vf_live_', keyHash, apiKey.slice(-4), 'Local Live Key'] ); console.log('\nāœ… Live API Key Created Successfully!\n'); console.log('Key:'); console.log(apiKey); console.log('\nUse this in your request header:'); console.log('Header: x-api-key'); console.log('Value:', apiKey); process.exit(0); } catch (error) { console.error('āŒ Error creating live API key:', error.message); console.error(error); process.exit(1); } } createLiveApiKey();