|
|
@@ -0,0 +1,53 @@
|
|
|
+import { FastifyRequest } from 'fastify'
|
|
|
+
|
|
|
+export function getClientIP(request: FastifyRequest): string {
|
|
|
+ const xForwardedFor = request.headers['x-forwarded-for']
|
|
|
+ if (xForwardedFor) {
|
|
|
+ const ips = Array.isArray(xForwardedFor) ? xForwardedFor[0] : xForwardedFor
|
|
|
+ const firstIP = ips.split(',')[0].trim()
|
|
|
+ if (firstIP && firstIP !== '127.0.0.1' && firstIP !== '::1') {
|
|
|
+ return firstIP
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ const xRealIP = request.headers['x-real-ip']
|
|
|
+ if (xRealIP) {
|
|
|
+ const realIP = Array.isArray(xRealIP) ? xRealIP[0] : xRealIP
|
|
|
+ if (realIP && realIP !== '127.0.0.1' && realIP !== '::1') {
|
|
|
+ return realIP
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ if (request.ip && request.ip !== '127.0.0.1' && request.ip !== '::1') {
|
|
|
+ return request.ip
|
|
|
+ }
|
|
|
+
|
|
|
+ const cfConnectingIP = request.headers['cf-connecting-ip'] // Cloudflare
|
|
|
+ if (cfConnectingIP) {
|
|
|
+ const cfIP = Array.isArray(cfConnectingIP) ? cfConnectingIP[0] : cfConnectingIP
|
|
|
+ if (cfIP && cfIP !== '127.0.0.1' && cfIP !== '::1') {
|
|
|
+ return cfIP
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ const xClientIP = request.headers['x-client-ip']
|
|
|
+ if (xClientIP) {
|
|
|
+ const clientIP = Array.isArray(xClientIP) ? xClientIP[0] : xClientIP
|
|
|
+ if (clientIP && clientIP !== '127.0.0.1' && clientIP !== '::1') {
|
|
|
+ return clientIP
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ return 'unknown'
|
|
|
+}
|
|
|
+
|
|
|
+export function isValidIP(ip: string): boolean {
|
|
|
+ if (!ip || ip === 'unknown' || ip === '127.0.0.1' || ip === '::1') {
|
|
|
+ return false
|
|
|
+ }
|
|
|
+
|
|
|
+ const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
|
|
|
+ const ipv6Regex = /^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/
|
|
|
+
|
|
|
+ return ipv4Regex.test(ip) || ipv6Regex.test(ip)
|
|
|
+}
|