Skip to Content

Ruby on Rails

Pour intégrer ProxyTracer dans une application Rails avec une efficacité maximale, nous contournons complètement la couche du contrôleur et construisons un Rack Middleware personnalisé. Cela intercepte la requête HTTP brute avant qu'elle n'entre dans le routeur Rails.

Intergiciel Rack

Cet intergiciel exploite l'objet natif Rack::Request pour extraire l'IP en toute sécurité (en gérant automatiquement les en-têtes usurpés) et utilise la bibliothèque standard Net::HTTP de Ruby pour imposer un délai d'attente strict.

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 end

Configuration

Pour activer la protection globalement, insérez l'intergiciel dans votre pile d'applications à l'intérieur 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 end
Last updated on