|
| 1 | +import { NextResponse } from 'next/server'; |
| 2 | +import { getNetworkStatusState, updateNetworkStatusState } from '@/lib/db'; |
| 3 | +import { |
| 4 | + buildHealthSummaryEmbed, |
| 5 | + buildStatusChangeEmbed, |
| 6 | + buildWebhookPayload, |
| 7 | + sendDiscordWebhook, |
| 8 | + canSendAlert, |
| 9 | + shouldAlert, |
| 10 | +} from '@/lib/discord'; |
| 11 | +import { checkRateLimit, getClientIp, addRateLimitHeaders } from '@/lib/rate-limit'; |
| 12 | +import type { ApiResponse, HealthStatus, DiscordNotificationType, NetworkHealth } from '@/lib/types'; |
| 13 | + |
| 14 | +// Environment variables |
| 15 | +const DISCORD_WEBHOOK_URL = process.env.DISCORD_WEBHOOK_URL; |
| 16 | +const DISCORD_WEBHOOK_SECRET = process.env.DISCORD_WEBHOOK_SECRET; |
| 17 | + |
| 18 | +// Rate limit: 5 requests per minute (Discord webhook rate limit is 30/min) |
| 19 | +const RATE_LIMIT_CONFIG = { limit: 5, windowSeconds: 60 }; |
| 20 | + |
| 21 | +interface WebhookRequestBody { |
| 22 | + type?: 'scheduled' | 'status_check'; |
| 23 | + force?: boolean; |
| 24 | +} |
| 25 | + |
| 26 | +interface WebhookResponseData { |
| 27 | + sent: boolean; |
| 28 | + type: DiscordNotificationType; |
| 29 | + status: HealthStatus; |
| 30 | + score: number; |
| 31 | +} |
| 32 | + |
| 33 | +/** |
| 34 | + * Fetch network health from the internal API |
| 35 | + * This reuses the existing health endpoint logic |
| 36 | + */ |
| 37 | +async function fetchNetworkHealth(baseUrl: string): Promise<NetworkHealth | null> { |
| 38 | + try { |
| 39 | + const response = await fetch(`${baseUrl}/api/health`, { |
| 40 | + next: { revalidate: 0 }, // Don't cache |
| 41 | + }); |
| 42 | + |
| 43 | + if (!response.ok) return null; |
| 44 | + |
| 45 | + const data = await response.json(); |
| 46 | + if (!data.success || !data.data) return null; |
| 47 | + |
| 48 | + return data.data as NetworkHealth; |
| 49 | + } catch { |
| 50 | + return null; |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +export async function POST(request: Request) { |
| 55 | + // Verify webhook URL is configured |
| 56 | + if (!DISCORD_WEBHOOK_URL) { |
| 57 | + console.error('DISCORD_WEBHOOK_URL not configured'); |
| 58 | + return NextResponse.json<ApiResponse<never>>( |
| 59 | + { success: false, error: 'Discord webhook not configured' }, |
| 60 | + { status: 500 } |
| 61 | + ); |
| 62 | + } |
| 63 | + |
| 64 | + // Verify authorization |
| 65 | + const authHeader = request.headers.get('authorization'); |
| 66 | + if (!DISCORD_WEBHOOK_SECRET) { |
| 67 | + console.error('DISCORD_WEBHOOK_SECRET not configured'); |
| 68 | + return NextResponse.json<ApiResponse<never>>( |
| 69 | + { success: false, error: 'Webhook secret not configured' }, |
| 70 | + { status: 500 } |
| 71 | + ); |
| 72 | + } |
| 73 | + |
| 74 | + if (authHeader !== `Bearer ${DISCORD_WEBHOOK_SECRET}`) { |
| 75 | + return NextResponse.json<ApiResponse<never>>( |
| 76 | + { success: false, error: 'Unauthorized' }, |
| 77 | + { status: 401 } |
| 78 | + ); |
| 79 | + } |
| 80 | + |
| 81 | + // Rate limiting |
| 82 | + const clientIp = getClientIp(request); |
| 83 | + const rateLimitResult = checkRateLimit(`discord-webhook:${clientIp}`, RATE_LIMIT_CONFIG); |
| 84 | + |
| 85 | + if (!rateLimitResult.success) { |
| 86 | + const response = NextResponse.json<ApiResponse<never>>( |
| 87 | + { success: false, error: 'Rate limit exceeded' }, |
| 88 | + { status: 429 } |
| 89 | + ); |
| 90 | + return addRateLimitHeaders(response, rateLimitResult); |
| 91 | + } |
| 92 | + |
| 93 | + try { |
| 94 | + // Parse request body |
| 95 | + let body: WebhookRequestBody = { type: 'scheduled' }; |
| 96 | + try { |
| 97 | + body = await request.json(); |
| 98 | + } catch { |
| 99 | + // Default to scheduled if no body |
| 100 | + } |
| 101 | + |
| 102 | + // Determine base URL for internal API calls |
| 103 | + const baseUrl = |
| 104 | + process.env.URL || |
| 105 | + process.env.DEPLOY_URL || |
| 106 | + `${request.headers.get('x-forwarded-proto') || 'https'}://${request.headers.get('host')}`; |
| 107 | + |
| 108 | + // Fetch current network health |
| 109 | + const currentHealth = await fetchNetworkHealth(baseUrl); |
| 110 | + |
| 111 | + if (!currentHealth) { |
| 112 | + return NextResponse.json<ApiResponse<never>>( |
| 113 | + { success: false, error: 'Failed to fetch network health' }, |
| 114 | + { status: 500 } |
| 115 | + ); |
| 116 | + } |
| 117 | + |
| 118 | + // Get previous state |
| 119 | + const previousState = await getNetworkStatusState(); |
| 120 | + |
| 121 | + let shouldSendWebhook = false; |
| 122 | + let notificationType: DiscordNotificationType = 'scheduled'; |
| 123 | + let embed; |
| 124 | + |
| 125 | + if (body.type === 'scheduled' || body.force) { |
| 126 | + // Scheduled update - always send summary |
| 127 | + embed = buildHealthSummaryEmbed(currentHealth); |
| 128 | + shouldSendWebhook = true; |
| 129 | + } else { |
| 130 | + // Status check - only alert on changes |
| 131 | + if (previousState) { |
| 132 | + const alertCheck = shouldAlert( |
| 133 | + previousState.status, |
| 134 | + previousState.network_score, |
| 135 | + previousState.active_nodes, |
| 136 | + currentHealth |
| 137 | + ); |
| 138 | + |
| 139 | + // Check cooldown |
| 140 | + if (alertCheck.shouldAlert && canSendAlert(previousState.last_alert_sent)) { |
| 141 | + shouldSendWebhook = true; |
| 142 | + notificationType = alertCheck.type; |
| 143 | + embed = buildStatusChangeEmbed(previousState.status, currentHealth, notificationType); |
| 144 | + } |
| 145 | + } else { |
| 146 | + // No previous state - this is the first run, just update state without alerting |
| 147 | + shouldSendWebhook = false; |
| 148 | + } |
| 149 | + } |
| 150 | + |
| 151 | + // Send to Discord if needed |
| 152 | + let webhookResult: { success: boolean; error?: string } = { success: true }; |
| 153 | + if (shouldSendWebhook && embed) { |
| 154 | + // Mention @everyone only for offline status |
| 155 | + const mentionEveryone = currentHealth.status === 'offline'; |
| 156 | + const payload = buildWebhookPayload(embed, mentionEveryone); |
| 157 | + webhookResult = await sendDiscordWebhook(DISCORD_WEBHOOK_URL, payload); |
| 158 | + } |
| 159 | + |
| 160 | + // Update state in database |
| 161 | + await updateNetworkStatusState( |
| 162 | + currentHealth.status, |
| 163 | + currentHealth.network_score ?? 0, |
| 164 | + currentHealth.active_nodes, |
| 165 | + shouldSendWebhook && webhookResult.success |
| 166 | + ); |
| 167 | + |
| 168 | + const response = NextResponse.json<ApiResponse<WebhookResponseData>>({ |
| 169 | + success: webhookResult.success, |
| 170 | + data: { |
| 171 | + sent: shouldSendWebhook && webhookResult.success, |
| 172 | + type: notificationType, |
| 173 | + status: currentHealth.status, |
| 174 | + score: currentHealth.network_score ?? 0, |
| 175 | + }, |
| 176 | + ...(webhookResult.error && { error: webhookResult.error }), |
| 177 | + }); |
| 178 | + |
| 179 | + return addRateLimitHeaders(response, rateLimitResult); |
| 180 | + } catch (error) { |
| 181 | + console.error('Discord webhook error:', error); |
| 182 | + return NextResponse.json<ApiResponse<never>>( |
| 183 | + { |
| 184 | + success: false, |
| 185 | + error: error instanceof Error ? error.message : 'Unknown error', |
| 186 | + }, |
| 187 | + { status: 500 } |
| 188 | + ); |
| 189 | + } |
| 190 | +} |
| 191 | + |
| 192 | +// GET endpoint for health check |
| 193 | +export async function GET() { |
| 194 | + const configured = Boolean(DISCORD_WEBHOOK_URL && DISCORD_WEBHOOK_SECRET); |
| 195 | + |
| 196 | + return NextResponse.json<ApiResponse<{ configured: boolean }>>({ |
| 197 | + success: true, |
| 198 | + data: { configured }, |
| 199 | + }); |
| 200 | +} |
0 commit comments