Ruby on Rails
Para integrar ProxyTracer en una aplicación Rails con la máxima eficiencia, omitimos la capa de controladores por completo y construimos un Rack Middleware personalizado. Este intercepta la solicitud HTTP en bruto antes de que ingrese al enrutador de Rails.
Middleware Rack
Este middleware utiliza el objeto nativo Rack::Request para extraer la IP con seguridad (gestionando automáticamente encabezados falsificados) y utiliza la biblioteca estándar Net::HTTP de Ruby para imponer un estricto tiempo de espera.
require 'net/http'
require 'json'
class ProxyTracerMiddleware
def initialize(app)
@app = app
@api_key = ENV['PROXYTRACER_API_KEY']
end
def call(env)
# 1. Extract the IP (Rack automatically sanitizes X-Forwarded-For)
request = Rack::Request.new(env)
ip = request.ip
# Skip local development
if ip && !['127.0.0.1', '::1'].include?(ip)
begin
uri = URI("https://api.proxytracer.com/v1/check/#{ip}")
req = Net::HTTP::Get.new(uri)
req['Authorization'] = "Bearer #{@api_key}"
# 2. Query ProxyTracer API with a strict 500ms timeout
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true, read_timeout: 0.5) do |http|
http.request(req)
end
if response.is_a?(Net::HTTPSuccess)
data = JSON.parse(response.body)
# 3. Drop the connection immediately if a proxy is detected
if data['proxy'] == true
return [
403,
{ 'Content-Type' => 'application/json' },
['{"error": "Access Denied: VPN or Proxy detected."}']
]
end
end
rescue StandardError => e
# Fail open: Log the error and allow the request to proceed
Rails.logger.error("ProxyTracer validation failed: #{e.message}")
end
end
# 4. Traffic is clean, proceed down the Rack stack to the Rails router
@app.call(env)
end
endConfiguración
Para activar la protección de manera global, inserta el middleware en tu pila de aplicación dentro de config/application.rb:
module YourApp
class Application < Rails::Application
# ...
# Insert it high up in the stack to reject bad traffic early
config.middleware.insert_before Rack::Sendfile, ProxyTracerMiddleware
# ...
end
endLast updated on