Class: Dubhe::Policy

Inherits:
Object
  • Object
show all
Defined in:
lib/dubhe/policy.rb,
sig/dubhe.rbs

Defined Under Namespace

Classes: Denied

Constant Summary collapse

Result =

Returns:

  • (Object)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(profile: :feed) ⇒ Policy

Returns a new instance of Policy.

Parameters:

  • profile: (Symbol) (defaults to: :feed)


14
15
16
# File 'lib/dubhe/policy.rb', line 14

def initialize(profile: :feed)
  @profile = profile
end

Instance Attribute Details

#profile ⇒ Object (readonly)

Returns the value of attribute profile.



12
13
14
# File 'lib/dubhe/policy.rb', line 12

def profile
  @profile
end

Instance Method Details

#apply(input, base_url: nil, allow_remote_images: false, on_blocked: nil) ⇒ Object

Parameters:

  • input (String)
  • base_url: (String, nil) (defaults to: nil)
  • allow_remote_images: (Boolean) (defaults to: false)

Returns:

  • (Object)


18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/dubhe/policy.rb', line 18

def apply(input, base_url: nil, allow_remote_images: false, on_blocked: nil)
  urls = []
  profile_options = Jabbah::Sanitize::PROFILES.fetch(profile.to_sym, Jabbah::Sanitize::DEFAULT).merge(
    allow_remote_images: allow_remote_images)
  document = Jabbah::Sanitize.clean(input, profile: profile_options, base_url: base_url,
    on_blocked: lambda do |url|
      urls << url
      on_blocked&.call(url)
    end,
    allow: Jabbah::Sanitize::DEFAULT)
  Result.new(html: document.to_html, document: document, blocked_count: urls.length)
end

#external_url?(url) ⇒ Boolean

Returns:

  • (Boolean)


51
52
53
54
55
56
# File 'lib/dubhe/policy.rb', line 51

def external_url?(url)
  scheme = URI.parse(url.to_s).scheme.to_s.downcase
  %w[http https mailto].include?(scheme)
rescue URI::InvalidURIError
  false
end

#resolve_local(root, path) ⇒ String

Parameters:

  • root (String)
  • path (String)

Returns:

  • (String)


31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/dubhe/policy.rb', line 31

def resolve_local(root, path)
  root_path = Pathname.new(root.to_s).expand_path
  raise Denied, "source root does not exist: #{root}" unless root_path.directory?

  candidate = root_path.join(path.to_s).cleanpath
  root_real = root_path.realpath
  candidate_real = candidate.realpath
  return candidate_real.to_s if candidate_real == root_real || candidate_real.to_s.start_with?("#{root_real}#{File::SEPARATOR}")

  raise Denied, "path escapes source root: #{path}"
rescue Errno::ENOENT
  # Check the nearest existing parent so a new path cannot escape via .. .
  parent = candidate
  parent = parent.parent until parent.exist? || parent.root?
  parent_real = parent.realpath
  return candidate.to_s if parent_real == root_real || parent_real.to_s.start_with?("#{root_real}#{File::SEPARATOR}")

  raise Denied, "path escapes source root: #{path}"
end