Skip to content

Instantly share code, notes, and snippets.

@steven-tey
Created March 27, 2023 03:05
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save steven-tey/994ae6be0da254ebbdf28d06623874ec to your computer and use it in GitHub Desktop.
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
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")
);
}
@itsbrex
Copy link

itsbrex commented Apr 5, 2023

Thanks for sharing this @steven-tey! 🙏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment