Skip to Content

Ruby on Rails

Um ProxyTracer mit maximaler Effizienz in eine Rails-Anwendung zu integrieren, umgehen wir die Controller-Schicht vollständig und erstellen eine benutzerdefinierte Rack-Middleware. Dadurch wird die reine HTTP-Anforderung abgefangen, bevor sie in den Rails-Router gelangt.

Rack-Middleware

Diese Middleware nutzt das native Rack::Request-Objekt, um die IP sicher zu extrahieren (und verarbeitet gefälschte Header automatisch), und verwendet Rubys Standardbibliothek Net::HTTP, um ein strenges Timeout zu erzwingen.

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

Konfiguration

Um den Schutz global zu aktivieren, fügen Sie die Middleware in den Anwendungsstack in config/application.rb ein:

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