|
| 1 | +/** |
| 2 | + * GitHub IP allowlist for webhook endpoint protection. |
| 3 | + * |
| 4 | + * Fetches GitHub's webhook IP ranges from api.github.com/meta, |
| 5 | + * caches them, and checks incoming requests against the allowlist. |
| 6 | + * Falls back to hardcoded ranges if the API is unreachable. |
| 7 | + */ |
| 8 | + |
| 9 | +// Hardcoded fallback — GitHub webhook IPs as of 2026-03. |
| 10 | +// Update periodically or rely on the live fetch. |
| 11 | +const FALLBACK_CIDRS = [ |
| 12 | + "140.82.112.0/20", |
| 13 | + "185.199.108.0/22", |
| 14 | + "192.30.252.0/22", |
| 15 | + "143.55.64.0/20", |
| 16 | +]; |
| 17 | + |
| 18 | +const CACHE_KEY = "https://api.github.com/meta#hooks"; |
| 19 | +const CACHE_TTL_SECONDS = 3600; // 1 hour |
| 20 | + |
| 21 | +/** In-memory cache for the current isolate lifetime */ |
| 22 | +let memCache: { cidrs: string[]; expiresAt: number } | null = null; |
| 23 | + |
| 24 | +/** |
| 25 | + * Parse an IPv4 CIDR and return [networkInt, maskInt]. |
| 26 | + * Returns null for IPv6 or invalid input. |
| 27 | + */ |
| 28 | +function parseIPv4CIDR(cidr: string): [number, number] | null { |
| 29 | + const match = cidr.match(/^(\d+\.\d+\.\d+\.\d+)\/(\d+)$/); |
| 30 | + if (!match) return null; |
| 31 | + const ip = match[1]; |
| 32 | + const prefix = parseInt(match[2], 10); |
| 33 | + if (prefix < 0 || prefix > 32) return null; |
| 34 | + |
| 35 | + const parts = ip.split(".").map(Number); |
| 36 | + if (parts.some((p) => p < 0 || p > 255)) return null; |
| 37 | + |
| 38 | + const ipInt = (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]; |
| 39 | + const mask = prefix === 0 ? 0 : (~0 << (32 - prefix)) >>> 0; |
| 40 | + return [ipInt >>> 0, mask]; |
| 41 | +} |
| 42 | + |
| 43 | +/** Parse an IPv4 address to a 32-bit unsigned integer. Returns null for IPv6. */ |
| 44 | +function parseIPv4(ip: string): number | null { |
| 45 | + const parts = ip.split("."); |
| 46 | + if (parts.length !== 4) return null; |
| 47 | + const nums = parts.map(Number); |
| 48 | + if (nums.some((n) => isNaN(n) || n < 0 || n > 255)) return null; |
| 49 | + return ((nums[0] << 24) | (nums[1] << 16) | (nums[2] << 8) | nums[3]) >>> 0; |
| 50 | +} |
| 51 | + |
| 52 | +/** Check if an IPv4 address matches any of the given CIDRs. */ |
| 53 | +function ipMatchesCIDRs(ip: string, cidrs: string[]): boolean { |
| 54 | + const ipInt = parseIPv4(ip); |
| 55 | + if (ipInt === null) { |
| 56 | + // IPv6 — check string prefix match against IPv6 CIDRs |
| 57 | + // For now, allow IPv6 through (GitHub rarely sends webhooks via IPv6) |
| 58 | + return true; |
| 59 | + } |
| 60 | + |
| 61 | + for (const cidr of cidrs) { |
| 62 | + const parsed = parseIPv4CIDR(cidr); |
| 63 | + if (!parsed) continue; // skip IPv6 CIDRs |
| 64 | + const [network, mask] = parsed; |
| 65 | + if ((ipInt & mask) === (network & mask)) return true; |
| 66 | + } |
| 67 | + return false; |
| 68 | +} |
| 69 | + |
| 70 | +/** |
| 71 | + * Fetch GitHub webhook IP ranges, with Cache API + in-memory caching. |
| 72 | + * Falls back to hardcoded ranges on failure. |
| 73 | + */ |
| 74 | +async function getGitHubHookCIDRs(): Promise<string[]> { |
| 75 | + // 1. Check in-memory cache |
| 76 | + if (memCache && Date.now() < memCache.expiresAt) { |
| 77 | + return memCache.cidrs; |
| 78 | + } |
| 79 | + |
| 80 | + // 2. Check Cache API |
| 81 | + try { |
| 82 | + const cache = caches.default; |
| 83 | + const cached = await cache.match(CACHE_KEY); |
| 84 | + if (cached) { |
| 85 | + const data = await cached.json() as { hooks?: string[] }; |
| 86 | + if (data.hooks?.length) { |
| 87 | + memCache = { cidrs: data.hooks, expiresAt: Date.now() + CACHE_TTL_SECONDS * 1000 }; |
| 88 | + return data.hooks; |
| 89 | + } |
| 90 | + } |
| 91 | + } catch { |
| 92 | + // Cache API may not be available in some environments |
| 93 | + } |
| 94 | + |
| 95 | + // 3. Fetch from GitHub |
| 96 | + try { |
| 97 | + const res = await fetch("https://api.github.com/meta", { |
| 98 | + headers: { "User-Agent": "github-webhook-mcp" }, |
| 99 | + }); |
| 100 | + if (res.ok) { |
| 101 | + const data = await res.json() as { hooks?: string[] }; |
| 102 | + if (data.hooks?.length) { |
| 103 | + // Store in Cache API |
| 104 | + try { |
| 105 | + const cache = caches.default; |
| 106 | + await cache.put( |
| 107 | + CACHE_KEY, |
| 108 | + new Response(JSON.stringify(data), { |
| 109 | + headers: { |
| 110 | + "Content-Type": "application/json", |
| 111 | + "Cache-Control": `max-age=${CACHE_TTL_SECONDS}`, |
| 112 | + }, |
| 113 | + }), |
| 114 | + ); |
| 115 | + } catch { |
| 116 | + // Cache write failure is non-fatal |
| 117 | + } |
| 118 | + |
| 119 | + memCache = { cidrs: data.hooks, expiresAt: Date.now() + CACHE_TTL_SECONDS * 1000 }; |
| 120 | + return data.hooks; |
| 121 | + } |
| 122 | + } |
| 123 | + } catch { |
| 124 | + // Network failure — fall through to hardcoded |
| 125 | + } |
| 126 | + |
| 127 | + // 4. Fallback |
| 128 | + return FALLBACK_CIDRS; |
| 129 | +} |
| 130 | + |
| 131 | +/** |
| 132 | + * Check if the request comes from a GitHub webhook IP. |
| 133 | + * Returns true if allowed, false if blocked. |
| 134 | + * |
| 135 | + * Skips the check when CF-Connecting-IP is absent (local dev). |
| 136 | + */ |
| 137 | +export async function isGitHubWebhookIP(request: Request): Promise<boolean> { |
| 138 | + const clientIP = request.headers.get("CF-Connecting-IP"); |
| 139 | + |
| 140 | + // In local dev (wrangler dev), CF-Connecting-IP may be absent — allow through |
| 141 | + if (!clientIP) return true; |
| 142 | + |
| 143 | + const cidrs = await getGitHubHookCIDRs(); |
| 144 | + return ipMatchesCIDRs(clientIP, cidrs); |
| 145 | +} |
0 commit comments