#!/bin/bash set -e echo "Generating JWT keys from JWT_SECRET..." # Load environment variables if [ -f .env ]; then export $(cat .env | grep -v '^#' | xargs) else echo "Error: .env file not found" exit 1 fi # Validate required environment variable if [ -z "$JWT_SECRET" ]; then echo "Error: JWT_SECRET not set" exit 1 fi echo "Using JWT_SECRET (first 8 chars): ${JWT_SECRET:0:8}..." echo "Using JWT_ISSUER: ${JWT_ISSUER:-madbase}..." # Create a temporary TypeScript script to generate keys cat > /tmp/generate_keys.ts << 'EOF' import jwt from 'jsonwebtoken'; const secret = process.env.JWT_SECRET || ''; const issuer = process.env.JWT_ISSUER || 'madbase'; if (!secret) { console.error('JWT_SECRET not provided'); process.exit(1); } const exp = Math.floor(Date.now() / 1000) + 60 * 60 * 24 * 7; // 7 days from now const anonPayload = { sub: 'anon', role: 'anon', iss: issuer, iat: Math.floor(Date.now() / 1000), exp: exp }; const servicePayload = { sub: 'service_role', role: 'service_role', iss: issuer, iat: Math.floor(Date.now() / 1000), exp: exp }; const anonKey = jwt.sign(anonPayload, secret, { algorithm: 'HS256' }); const serviceKey = jwt.sign(servicePayload, secret, { algorithm: 'HS256' }); console.log('Generated Keys:'); console.log(`MADBASE_ANON_KEY=${anonKey}`); console.log(`MADBASE_SERVICE_ROLE_KEY=${serviceKey}`); EOF # Run the script using ts-node or node if command -v tsx &> /dev/null; then JWT_SECRET="$JWT_SECRET" JWT_ISSUER="${JWT_ISSUER:-madbase}" tsx /tmp/generate_keys.ts elif command -v ts-node &> /dev/null; then JWT_SECRET="$JWT_SECRET" JWT_ISSUER="${JWT_ISSUER:-madbase}" ts-node /tmp/generate_keys.ts else echo "Error: tsx or ts-node not found. Please install one of them:" echo " npm install -g tsx" echo " npm install -g ts-node" exit 1 fi # Clean up rm /tmp/generate_keys.ts echo "" echo "To update your .env file with these keys, run:" echo " scripts/generate_jwt_keys.sh | grep 'MADBASE_ANON_KEY=' | cut -d'=' -f2- | xargs -I {} sed -i '' 's/^MADBASE_ANON_KEY=.*/MADBASE_ANON_KEY={}/' .env" echo " scripts/generate_jwt_keys.sh | grep 'MADBASE_SERVICE_ROLE_KEY=' | cut -d'=' -f2- | xargs -I {} sed -i '' 's/^MADBASE_SERVICE_ROLE_KEY=.*/MADBASE_SERVICE_ROLE_KEY={}/' .env"