#!/bin/bash

###############################################################################
# Frontend Security Audit Script
#
# Comprehensive security testing for Global Gala Next.js/React frontend apps
# Tests: XSS, data exposure, token security, dependency vulnerabilities,
#        client-side validation bypass, API integration security
#
# Usage: ./scripts/frontend-security-audit.sh
###############################################################################

set -eo pipefail

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Counters
PASS=0
FAIL=0
WARN=0
CRITICAL=0

# Configuration
FRONTEND_PATH="/Users/charlie/code/showprima-frontend"
TICKETING_APP="${FRONTEND_PATH}/apps/ticketing"
ADMIN_APP="${FRONTEND_PATH}/apps/admin"
TICKETING_URL="http://localhost:3002"
ADMIN_URL="http://localhost:3001"

# Logging
info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

pass() {
    echo -e "${GREEN}[PASS]${NC} $1"
    ((PASS++))
}

fail() {
    echo -e "${RED}[FAIL]${NC} $1"
    ((FAIL++))
}

warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
    ((WARN++))
}

critical() {
    echo -e "${RED}[CRITICAL]${NC} $1"
    ((CRITICAL++))
    ((FAIL++))
}

header() {
    echo ""
    echo -e "${BLUE}===================================================${NC}"
    echo -e "${BLUE}$1${NC}"
    echo -e "${BLUE}===================================================${NC}"
    echo ""
}

###############################################################################
# 1. Dependency Security
###############################################################################

header "1. Dependency Security Scanning"

info "Running npm audit on frontend workspace..."
cd "$FRONTEND_PATH"

# Check if node_modules exists
if [ ! -d "node_modules" ]; then
    warn "node_modules not found. Run 'npm install' first."
else
    # Run npm audit and capture results
    AUDIT_OUTPUT=$(npm audit --audit-level=moderate 2>&1 || true)

    if echo "$AUDIT_OUTPUT" | grep -q "found 0 vulnerabilities"; then
        pass "No npm vulnerabilities found"
    elif echo "$AUDIT_OUTPUT" | grep -qi "critical"; then
        critical "Critical npm vulnerabilities detected!"
        echo "$AUDIT_OUTPUT" | grep -i "critical" || true
    elif echo "$AUDIT_OUTPUT" | grep -qi "high"; then
        fail "High severity npm vulnerabilities detected"
        echo "$AUDIT_OUTPUT" | grep -i "high" || true
    elif echo "$AUDIT_OUTPUT" | grep -qi "moderate"; then
        warn "Moderate npm vulnerabilities detected"
    else
        pass "npm audit completed with low/no vulnerabilities"
    fi
fi

###############################################################################
# 2. Sensitive Data Exposure in Source Code
###############################################################################

header "2. Sensitive Data Exposure Detection"

info "Scanning for hardcoded API keys, tokens, and secrets..."

# Search for common secret patterns
SECRET_PATTERNS=(
    "api[_-]?key"
    "api[_-]?secret"
    "access[_-]?token"
    "auth[_-]?token"
    "secret[_-]?key"
    "private[_-]?key"
    "stripe[_-]?key"
    "sk_live"
    "pk_live"
    "password\s*=\s*['\"]"
    "AKIA[0-9A-Z]{16}" # AWS keys
)

FOUND_SECRETS=0
for pattern in "${SECRET_PATTERNS[@]}"; do
    if grep -riE "$pattern" "$TICKETING_APP/src" "$ADMIN_APP/src" 2>/dev/null | grep -v "node_modules" | grep -v ".next" | grep -v "test" | grep -q .; then
        ((FOUND_SECRETS++))
        warn "Potential secret found matching pattern: $pattern"
    fi
done

if [ $FOUND_SECRETS -eq 0 ]; then
    pass "No hardcoded secrets detected in source code"
else
    fail "Found $FOUND_SECRETS potential secret patterns in source code"
fi

###############################################################################
# 3. Console Log Exposure
###############################################################################

header "3. Console Log & Debug Statement Detection"

info "Checking for console.log statements in production code..."

# Count console.log occurrences (excluding test files)
CONSOLE_LOGS=$(grep -rn "console\.log\|console\.warn\|console\.error\|console\.debug" "$TICKETING_APP/src" "$ADMIN_APP/src" 2>/dev/null | grep -v "node_modules" | grep -v ".next" | grep -v ".spec" | grep -v ".test" | wc -l || echo "0")

if [ "$CONSOLE_LOGS" -gt 50 ]; then
    warn "Found $CONSOLE_LOGS console.log statements (should be removed in production builds)"
elif [ "$CONSOLE_LOGS" -gt 0 ]; then
    info "Found $CONSOLE_LOGS console statements (ensure they're removed in production builds)"
    pass "Console logging within acceptable limits"
else
    pass "No console.log statements found"
fi

###############################################################################
# 4. XSS Vulnerability Detection
###############################################################################

header "4. XSS Vulnerability Detection"

info "Scanning for dangerous React patterns (dangerouslySetInnerHTML)..."

DANGEROUS_HTML=$(grep -rn "dangerouslySetInnerHTML" "$TICKETING_APP/src" "$ADMIN_APP/src" 2>/dev/null | grep -v "node_modules" | wc -l || echo "0")

if [ "$DANGEROUS_HTML" -gt 0 ]; then
    warn "Found $DANGEROUS_HTML uses of dangerouslySetInnerHTML - ensure content is sanitized"
else
    pass "No dangerouslySetInnerHTML usage found"
fi

info "Checking for eval() usage..."
EVAL_USAGE=$(grep -rn "\beval\(" "$TICKETING_APP/src" "$ADMIN_APP/src" 2>/dev/null | grep -v "node_modules" | wc -l || echo "0")

if [ "$EVAL_USAGE" -gt 0 ]; then
    fail "Found $EVAL_USAGE uses of eval() - potential XSS vulnerability"
else
    pass "No eval() usage found"
fi

###############################################################################
# 5. Local Storage Security
###############################################################################

header "5. Local Storage & Session Storage Security"

info "Checking for sensitive data storage in localStorage..."

# Check for JWT/token storage in localStorage
LOCAL_STORAGE_PATTERNS=(
    "localStorage\.setItem.*token"
    "localStorage\.setItem.*jwt"
    "localStorage\.setItem.*auth"
    "sessionStorage\.setItem.*token"
    "sessionStorage\.setItem.*password"
)

INSECURE_STORAGE=0
for pattern in "${LOCAL_STORAGE_PATTERNS[@]}"; do
    if grep -riE "$pattern" "$TICKETING_APP/src" "$ADMIN_APP/src" 2>/dev/null | grep -v "node_modules" | grep -q .; then
        ((INSECURE_STORAGE++))
        warn "Potentially insecure storage pattern: $pattern"
    fi
done

if [ $INSECURE_STORAGE -eq 0 ]; then
    pass "No sensitive data stored in localStorage/sessionStorage"
else
    fail "Found $INSECURE_STORAGE instances of sensitive data in browser storage (use httpOnly cookies)"
fi

###############################################################################
# 6. API Endpoint Security
###############################################################################

header "6. API Endpoint Security & Configuration"

info "Testing CORS configuration on frontend apps..."

# Test CORS on ticketing app
CORS_RESPONSE=$(curl -s -X OPTIONS "$TICKETING_URL" \
    -H "Origin: https://malicious-site.com" \
    -H "Access-Control-Request-Method: POST" \
    -o /dev/null -w "%{http_code}" 2>/dev/null || echo "000")

if [ "$CORS_RESPONSE" = "000" ]; then
    warn "Ticketing app not running at $TICKETING_URL (start with 'npm run dev')"
else
    pass "Ticketing app is accessible"
fi

###############################################################################
# 7. Client-Side Validation Bypass Detection
###############################################################################

header "7. Client-Side Validation Security"

info "Checking for client-only validation without backend verification..."

# Search for form validation patterns
VALIDATION_PATTERNS=$(grep -rn "required\|validation\|validate" "$TICKETING_APP/src" "$ADMIN_APP/src" 2>/dev/null | grep -v "node_modules" | wc -l || echo "0")

if [ "$VALIDATION_PATTERNS" -gt 0 ]; then
    info "Found form validation code - ensure backend validates all inputs"
    pass "Client-side validation present (verify backend validation exists)"
else
    warn "Limited client-side validation detected"
fi

###############################################################################
# 8. Environment Variable Exposure
###############################################################################

header "8. Environment Variable Security"

info "Checking for exposed environment variables in build output..."

# Check .env files for public exposure
if [ -f "$TICKETING_APP/.env" ]; then
    warn "Ticketing app has .env file - ensure it's in .gitignore"
fi

if [ -f "$ADMIN_APP/.env" ]; then
    warn "Admin app has .env file - ensure it's in .gitignore"
fi

# Check for NEXT_PUBLIC_ prefix usage
PUBLIC_ENV_VARS=$(grep -rn "NEXT_PUBLIC_" "$TICKETING_APP/.env.local" "$ADMIN_APP/.env.local" 2>/dev/null | wc -l || echo "0")

if [ "$PUBLIC_ENV_VARS" -gt 0 ]; then
    info "Found $PUBLIC_ENV_VARS NEXT_PUBLIC_ variables (these will be exposed to browser)"
    pass "Public env variables properly prefixed"
else
    pass "No public environment variables found"
fi

###############################################################################
# 9. Build Security
###############################################################################

header "9. Build & Production Security"

info "Checking for source maps in production builds..."

# Check if .next exists
if [ -d "$TICKETING_APP/.next" ]; then
    SOURCE_MAPS=$(find "$TICKETING_APP/.next" -name "*.map" 2>/dev/null | wc -l || echo "0")

    if [ "$SOURCE_MAPS" -gt 0 ]; then
        warn "Found $SOURCE_MAPS source map files (should be disabled in production)"
    else
        pass "No source maps in build output"
    fi
else
    info "No .next build directory found (run 'npm run build' to test)"
fi

###############################################################################
# 10. TypeScript Security
###############################################################################

header "10. TypeScript Type Safety"

info "Checking for TypeScript strict mode..."

# Check tsconfig.json for strict mode
if [ -f "$TICKETING_APP/tsconfig.json" ]; then
    if grep -q '"strict":\s*true' "$TICKETING_APP/tsconfig.json"; then
        pass "TypeScript strict mode enabled in ticketing app"
    else
        warn "TypeScript strict mode not enabled (recommended for type safety)"
    fi
fi

# Check for 'any' type usage
ANY_USAGE=$(grep -rn ": any\|as any" "$TICKETING_APP/src" "$ADMIN_APP/src" 2>/dev/null | grep -v "node_modules" | grep -v ".next" | wc -l || echo "0")

if [ "$ANY_USAGE" -gt 50 ]; then
    warn "Found $ANY_USAGE uses of 'any' type (reduces type safety)"
elif [ "$ANY_USAGE" -gt 0 ]; then
    info "Found $ANY_USAGE uses of 'any' type (within acceptable limits)"
    pass "TypeScript type coverage is good"
else
    pass "Excellent TypeScript type coverage (no 'any' usage)"
fi

###############################################################################
# 11. Third-Party Script Security
###############################################################################

header "11. Third-Party Script & CDN Security"

info "Checking for external script loading..."

# Search for external script tags
EXTERNAL_SCRIPTS=$(grep -rn "<script src=\"http" "$TICKETING_APP" "$ADMIN_APP" 2>/dev/null | grep -v "node_modules" | wc -l || echo "0")

if [ "$EXTERNAL_SCRIPTS" -gt 0 ]; then
    warn "Found $EXTERNAL_SCRIPTS external script references - ensure integrity checks (SRI) are used"
else
    pass "No external scripts detected"
fi

###############################################################################
# 12. Clickjacking Protection
###############################################################################

header "12. Clickjacking & UI Redress Protection"

info "Testing for X-Frame-Options / CSP frame-ancestors..."

if [ "$CORS_RESPONSE" != "000" ]; then
    FRAME_PROTECTION=$(curl -s -I "$TICKETING_URL" 2>/dev/null | grep -i "x-frame-options\|content-security-policy" || echo "")

    if [ -n "$FRAME_PROTECTION" ]; then
        pass "Frame protection headers detected"
    else
        warn "No X-Frame-Options or CSP frame-ancestors header (add to prevent clickjacking)"
    fi
fi

###############################################################################
# 13. Authentication Token Security
###############################################################################

header "13. Authentication & Token Security"

info "Checking JWT handling security..."

# Search for JWT decode/storage patterns
JWT_PATTERNS=$(grep -rn "jwt\|jsonwebtoken\|decode" "$TICKETING_APP/src" "$ADMIN_APP/src" 2>/dev/null | grep -v "node_modules" | wc -l || echo "0")

if [ "$JWT_PATTERNS" -gt 0 ]; then
    info "Found JWT handling code - verify tokens stored in httpOnly cookies, not localStorage"
    pass "JWT implementation detected (verify secure storage)"
else
    info "No client-side JWT handling detected"
fi

###############################################################################
# 14. Form Security
###############################################################################

header "14. Form Security & CSRF Protection"

info "Checking for CSRF token implementation..."

CSRF_PATTERNS=$(grep -rn "csrf\|_token" "$TICKETING_APP/src" "$ADMIN_APP/src" 2>/dev/null | grep -v "node_modules" | wc -l || echo "0")

if [ "$CSRF_PATTERNS" -gt 0 ]; then
    pass "CSRF protection implementation found"
else
    warn "No CSRF protection detected (verify Laravel backend handles this)"
fi

###############################################################################
# 15. Secure HTTP Headers
###############################################################################

header "15. HTTP Security Headers"

if [ "$CORS_RESPONSE" != "000" ]; then
    info "Checking security headers on frontend apps..."

    HEADERS=$(curl -s -I "$TICKETING_URL" 2>/dev/null)

    # Check for various security headers
    if echo "$HEADERS" | grep -qi "x-content-type-options"; then
        pass "X-Content-Type-Options header present"
    else
        warn "X-Content-Type-Options header missing (add: nosniff)"
    fi

    if echo "$HEADERS" | grep -qi "x-xss-protection"; then
        pass "X-XSS-Protection header present"
    else
        warn "X-XSS-Protection header missing"
    fi

    if echo "$HEADERS" | grep -qi "strict-transport-security"; then
        pass "HSTS header present"
    else
        info "HSTS header missing (add when deployed with HTTPS)"
    fi

    if echo "$HEADERS" | grep -qi "content-security-policy"; then
        pass "Content-Security-Policy header present"
    else
        warn "CSP header missing (recommended for XSS protection)"
    fi
fi

###############################################################################
# Summary
###############################################################################

header "Security Audit Summary"

echo ""
echo -e "${GREEN}Passed:${NC}    $PASS tests"
echo -e "${YELLOW}Warnings:${NC}  $WARN tests"
echo -e "${RED}Failed:${NC}    $FAIL tests"
echo -e "${RED}Critical:${NC}  $CRITICAL tests"
echo ""

# Calculate score
TOTAL=$((PASS + WARN + FAIL))
if [ $TOTAL -eq 0 ]; then
    SCORE=0
else
    SCORE=$(( (PASS * 100) / TOTAL ))
fi

echo "Security Score: $SCORE/100"

# Grade
if [ $CRITICAL -gt 0 ]; then
    echo -e "${RED}Grade: F (CRITICAL VULNERABILITIES FOUND)${NC}"
    EXIT_CODE=2
elif [ $SCORE -ge 90 ]; then
    echo -e "${GREEN}Grade: A (Excellent)${NC}"
    EXIT_CODE=0
elif [ $SCORE -ge 80 ]; then
    echo -e "${GREEN}Grade: B (Good)${NC}"
    EXIT_CODE=0
elif [ $SCORE -ge 70 ]; then
    echo -e "${YELLOW}Grade: C (Acceptable)${NC}"
    EXIT_CODE=0
elif [ $SCORE -ge 60 ]; then
    echo -e "${YELLOW}Grade: D (Needs Improvement)${NC}"
    EXIT_CODE=1
else
    echo -e "${RED}Grade: F (Failing)${NC}"
    EXIT_CODE=1
fi

echo ""
echo "Recommendations:"
echo "================"

if [ $CRITICAL -gt 0 ]; then
    echo "🚨 CRITICAL: Fix critical vulnerabilities immediately before deployment"
fi

if [ $FAIL -gt 5 ]; then
    echo "⚠️  Address failed security checks before production deployment"
fi

if [ $WARN -gt 0 ]; then
    echo "💡 Review warnings and implement recommended security enhancements"
fi

echo "✅ Run 'npm audit fix' to automatically fix dependency vulnerabilities"
echo "✅ Ensure all client-side validation is backed by server-side validation"
echo "✅ Use httpOnly cookies for sensitive tokens, never localStorage"
echo "✅ Implement Content Security Policy (CSP) headers"
echo "✅ Add integrity checks (SRI) for all third-party scripts"

echo ""
echo "Report generated: $(date)"
echo ""

exit $EXIT_CODE
