Class: Shugoi::ResponseProcessor

Inherits:
Object
  • Object
show all
Defined in:
lib/shugoi/response_processor.rb

Instance Method Summary collapse

Constructor Details

#initialize(config, csp, pow, bot_policy, guard_injector) ⇒ ResponseProcessor

Returns a new instance of ResponseProcessor.



3
4
5
6
7
8
9
# File 'lib/shugoi/response_processor.rb', line 3

def initialize(config, csp, pow, bot_policy, guard_injector)
  @config = config
  @csp = csp
  @pow = pow
  @bot_policy = bot_policy
  @guard_injector = guard_injector
end

Instance Method Details

#call(status, headers, body, context, query) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/shugoi/response_processor.rb', line 11

def call(status, headers, body, context, query)
  headers = headers.each_with_object({}) { |(key, value), result| result[key.to_s.downcase] = value }
  headers["content-security-policy"] = Csp.merge(headers["content-security-policy"], @csp) if @config.csp_enabled
  proof = query["sg_proof"]
  headers["set-cookie"] = @pow.sg_ok_cookie(proof, context[:ip].to_s, context[:ua].to_s) if proof
  return [status, headers, body] unless @config.auto_inject && @config.split_render
  return [status, headers, body] if @bot_policy.trusted?(context[:ua].to_s, context[:ip].to_s)
  return [status, headers, body] if @config.allowlisted?(context[:path].to_s)

  html = body.respond_to?(:each) ? body.each.to_a.join : body.to_s
  return [status, headers, body] unless html.include?("<html")
  unless headers["content-type"].to_s.empty? || headers["content-type"].to_s.include?("text/html")
    return [status, headers,
            body]
  end

  begin
    body = [@guard_injector.call(html)]
    headers["content-type"] = "text/html; charset=utf-8"
  rescue StandardError => e
    warn("[shugoi] inject error: #{e.message}") if @config.debug
  end
  [status, headers, body]
end