Created
March 27, 2023 03:05
-
-
Save steven-tey/994ae6be0da254ebbdf28d06623874ec to your computer and use it in GitHub Desktop.
Typescript code to verify if an incoming request's IP address is from OpenAI's CIDR block
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function ipToInt(ip: string) { | |
return ip.split(".").reduce((acc, octet) => (acc << 8) + parseInt(octet), 0); | |
} | |
function isIpInCIDR(ip: string, cidr: string) { | |
const [cidrIp, prefixLength] = cidr.split("/"); | |
const mask = -1 << (32 - parseInt(prefixLength)); | |
const ipInt = ipToInt(ip); | |
const cidrIpInt = ipToInt(cidrIp); | |
const networkAddress = cidrIpInt & mask; | |
const broadcastAddress = networkAddress | ~mask; | |
return ipInt >= networkAddress && ipInt <= broadcastAddress; | |
} | |
export default function validChatGPTIp(ip: string) { | |
// verify both CIDR blocks from the docs: https://platform.openai.com/docs/plugins/production/ip-egress-ranges | |
return ( | |
isIpInCIDR(ip, "23.102.140.112/28") || isIpInCIDR(ip, "23.98.142.176/28") | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for sharing this @steven-tey! 🙏