#!/usr/bin/env node /** * Script to generate a private key for OAuth JWT signing * Run with: node --loader tsx scripts/generate-key.ts * Or add to package.json: "setup:key": "tsx scripts/generate-key.ts" */ import { generateClientAssertionKey } from '@atcute/oauth-crypto'; import { writeFileSync, readFileSync, existsSync } from 'fs'; import { join } from 'path'; import { randomUUID } from 'crypto'; async function generateKey() { console.log('Generating OAuth private key...'); // Generate EC key for client assertions (OAuth) const jwk = await generateClientAssertionKey(); // Add a kid (key ID) if not present - required by atcute if (!jwk.kid) { jwk.kid = randomUUID(); } const jwkString = JSON.stringify(jwk); const envPath = join(process.cwd(), '.env'); const envLocalPath = join(process.cwd(), '.env.local'); // Read existing .env content let envContent = ''; if (existsSync(envPath)) { envContent = readFileSync(envPath, 'utf-8'); } // Check if PRIVATE_KEY_JWK already exists in .env (uncommented) const keyLineRegex = /^PRIVATE_KEY_JWK=\{/m; if (keyLineRegex.test(envContent)) { console.log('āš ļø PRIVATE_KEY_JWK already exists in .env'); console.log(' To regenerate, remove the existing line first or delete the value'); console.log(' Run: sed -i.bak \'/^PRIVATE_KEY_JWK=/d\' .env'); return; } // Add the key to .env const keyLine = `\nPRIVATE_KEY_JWK=${jwkString}\n`; writeFileSync(envPath, envContent + keyLine, 'utf-8'); console.log('āœ… Private key generated and saved to .env'); console.log(' IMPORTANT: Keep this key secure and never commit it to version control!'); console.log(' Add .env to your .gitignore if not already present'); // Update .env.example with placeholder const envExamplePath = join(process.cwd(), '.env.example'); if (existsSync(envExamplePath)) { let exampleContent = readFileSync(envExamplePath, 'utf-8'); if (!exampleContent.includes('PRIVATE_KEY_JWK=')) { exampleContent += '\nPRIVATE_KEY_JWK={"kty":"...generated by setup:key script..."}\n'; writeFileSync(envExamplePath, exampleContent, 'utf-8'); console.log('āœ… Updated .env.example with placeholder'); } } console.log('\nšŸ“ Next steps:'); console.log(' 1. Ensure PUBLIC_BASE_URL is set in .env'); console.log(' 2. For production, use HTTPS and update PUBLIC_BASE_URL'); console.log(' 3. Run your dev server: npm run dev'); } generateKey().catch(err => { console.error('Error generating key:', err); process.exit(1); });