Class: Shugoi::Rack::Middleware

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

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ Middleware

Returns a new instance of Middleware.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/shugoi/rack/middleware.rb', line 7

def initialize(app, options = {})
  @app = app
  @config = Config.new(options)
  @disk_path_option = options[:disk_path]
  @api_client = ApiClient.new(@config.base_url, debug: @config.debug)
  @api_internal = ApiClient.new(@config.internal_url, debug: @config.debug)
  @guard_cache = GuardCache.new(@api_client)
  @config_cache = ConfigCache.new(@api_internal, @config.signing_secret)
  @token_signer = TokenSigner.new(@config.signing_secret)
  @html_store = HtmlStore.new(disk_path: disk_path)
  @pow = Pow.new(@config.signing_secret, @config.pow_difficulty, @config.pow_ttl_ms)
  @skeleton = SkeletonGenerator.new(@config, @guard_cache, @config_cache, @token_signer)
  @guard_injector = GuardInjector.new(@config, @token_signer, @html_store, @skeleton)
  @render = RenderHandler.new(@config, @token_signer, @html_store, @config_cache, @pow)
  @render_endpoint = RenderEndpoint.new(@render, @pow)
  @core = Core.new(@config, @pow, @api_client, @config_cache)
  @csp = Csp.build(site_key: @config.site_key, api_origin: Csp.origin_of(@config.base_url),
                   extra_directives: @config.extra_directives, split_render: @config.split_render)
  @response_processor = ResponseProcessor.new(@config, @csp, @pow, @core.bot_policy, @guard_injector)
end

Instance Method Details

#call(env) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/shugoi/rack/middleware.rb', line 28

def call(env)
  path = env["PATH_INFO"].to_s
  query = parse_query(env["QUERY_STRING"].to_s)
  method = env["REQUEST_METHOD"].to_s.upcase

  if path.end_with?("/__shugoi/render")
    return method_not_allowed unless %w[GET HEAD].include?(method)
    return @render_endpoint.call(env, query)
  end

  return method_not_allowed if path == "/__sg_challenge" && !%w[GET HEAD].include?(method)

  if @config.auto_inject && @config.site_key
    cfg = @config_cache.fetch(@config.site_key)
    return @app.call(env) if cfg[:skip_paths].include?(path)
  end

  ctx = build_ctx(env, query)
  decision = @core.evaluate(ctx)

  if decision
    headers = {}
    headers["content-security-policy"] = @csp if @config.csp_enabled
    h = headers.merge(decision.headers || {})
    h["content-type"] = decision.content_type
    return [decision.status, h, [decision.body]]
  end

  status, response_headers, body = @app.call(env)
  @response_processor.call(status, response_headers, body, ctx.merge(path: path), query)
end