metainspector 5.21.2 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +37 -0
  3. data/README.md +215 -48
  4. data/lib/meta_inspector/attempt_timeout.rb +40 -0
  5. data/lib/meta_inspector/document.rb +101 -68
  6. data/lib/meta_inspector/errors.rb +5 -1
  7. data/lib/meta_inspector/html_encoding.rb +183 -0
  8. data/lib/meta_inspector/http_session.rb +74 -45
  9. data/lib/meta_inspector/image_downloader.rb +37 -24
  10. data/lib/meta_inspector/parser.rb +144 -34
  11. data/lib/meta_inspector/parsers/base.rb +7 -2
  12. data/lib/meta_inspector/parsers/head_links.rb +20 -28
  13. data/lib/meta_inspector/parsers/iframes.rb +2 -3
  14. data/lib/meta_inspector/parsers/images.rb +119 -70
  15. data/lib/meta_inspector/parsers/links.rb +19 -9
  16. data/lib/meta_inspector/parsers/meta_tags.rb +22 -31
  17. data/lib/meta_inspector/parsers/texts.rb +43 -33
  18. data/lib/meta_inspector/request.rb +67 -55
  19. data/lib/meta_inspector/url.rb +43 -19
  20. data/lib/meta_inspector/url_policy.rb +18 -11
  21. data/lib/meta_inspector/version.rb +1 -1
  22. data/lib/meta_inspector.rb +14 -13
  23. data/lib/metainspector.rb +1 -1
  24. data/meta_inspector.gemspec +1 -1
  25. data/spec/document_spec.rb +154 -56
  26. data/spec/meta_inspector/content_type_spec.rb +47 -0
  27. data/spec/meta_inspector/head_links_spec.rb +3 -3
  28. data/spec/meta_inspector/images_spec.rb +82 -1
  29. data/spec/meta_inspector/links_spec.rb +98 -2
  30. data/spec/meta_inspector/meta_inspector_spec.rb +3 -25
  31. data/spec/meta_inspector/meta_tags_spec.rb +53 -0
  32. data/spec/meta_inspector/texts_spec.rb +140 -3
  33. data/spec/meta_inspector/timeouts_spec.rb +107 -0
  34. data/spec/noscript_spec.rb +179 -0
  35. data/spec/parser_spec.rb +380 -10
  36. data/spec/query_string_spec.rb +125 -0
  37. data/spec/request_errors_spec.rb +91 -0
  38. data/spec/request_spec.rb +28 -10
  39. data/spec/response_encoding_spec.rb +487 -0
  40. data/spec/url_filter_spec.rb +2 -1
  41. data/spec/url_spec.rb +37 -0
  42. metadata +10 -2
@@ -3,28 +3,33 @@ module MetaInspector
3
3
  class LinksParser < Base
4
4
  delegate [:parsed, :url, :scheme, :host] => :@main_parser
5
5
 
6
+ HTTP_LINK = /^http(s)?:\/\//i
7
+ private_constant :HTTP_LINK
8
+
6
9
  def links
7
10
  self
8
11
  end
9
12
 
10
- # Returns all links found, unprocessed
13
+ # Returns all links found, unprocessed.
14
+ # Matches <a> by local name: in the HTML5 tree, links inside inline
15
+ # <svg> or <math> are in another namespace, and '//a' would miss them.
11
16
  def raw
12
- @raw ||= cleanup(parsed.search('//a/@href')).compact.uniq
17
+ @raw ||= cleanup(parsed.xpath('//*[local-name()="a"]/@href')).compact.uniq
13
18
  end
14
19
 
15
- # Returns all links found, unrelavitized and absolutified
20
+ # Returns all links found, absolutified
16
21
  def all
17
22
  @all ||= raw.map { |link| URL.absolutify(link, base_url) }.compact.uniq
18
23
  end
19
24
 
20
25
  # Returns all HTTP links found
21
26
  def http
22
- @http ||= all.select { |link| link =~ /^http(s)?:\/\//i}
27
+ @http ||= all.grep(HTTP_LINK)
23
28
  end
24
29
 
25
30
  # Returns all non-HTTP links found
26
31
  def non_http
27
- @non_http ||= all.select { |link| link !~ /^http(s)?:\/\//i}
32
+ @non_http ||= all.grep_v(HTTP_LINK)
28
33
  end
29
34
 
30
35
  # Returns all internal HTTP links found
@@ -48,13 +53,18 @@ module MetaInspector
48
53
  # or the url of the document if no <base> tag was found.
49
54
  # Relative base hrefs are resolved against the document URL.
50
55
  def base_url
51
- current_base_href = base_href.to_s.strip.empty? ? nil : URL.absolutify(base_href, url)
52
- current_base_href || url
56
+ return url if base_href.to_s.strip.empty?
57
+
58
+ URL.absolutify(base_href, url) || url
53
59
  end
54
60
 
55
- # Returns the value of the href attribute on the <base /> tag, if exists
61
+ # Returns the value of the href attribute on the <base /> tag, if exists.
62
+ # Memoized, nil included, as it's needed once per link, image, iframe
63
+ # and head link, and searching the whole document every time is slow.
56
64
  def base_href
57
- parsed.search('base').first.attributes['href'].value rescue nil
65
+ return @base_href if defined?(@base_href)
66
+
67
+ @base_href = parsed.search('base').first&.attributes&.[]('href')&.value
58
68
  end
59
69
  end
60
70
  end
@@ -5,17 +5,21 @@ module MetaInspector
5
5
 
6
6
  def meta_tags
7
7
  {
8
- 'name' => meta_tags_by('name'),
9
- 'http-equiv' => meta_tags_by('http-equiv'),
10
- 'property' => meta_tags_by('property'),
11
- 'charset' => [charset_from_meta_charset]
8
+ 'name' => meta_tags_by('name'),
9
+ 'http-equiv' => meta_tags_by('http-equiv'),
10
+ 'property' => meta_tags_by('property'),
11
+ 'charset' => [charset_from_meta_charset]
12
12
  }
13
13
  end
14
14
 
15
+ # Like meta_tags, with only the first value of each tag
15
16
  def meta_tag
16
- convert_each_array_to_first_element_on meta_tags
17
+ meta_tags.transform_values do |values|
18
+ values.is_a?(Hash) ? values.transform_values(&:first) : values.first
19
+ end
17
20
  end
18
21
 
22
+ # meta_tag merged into one Hash: name, then http-equiv, then property
19
23
  def meta
20
24
  meta_tag['name']
21
25
  .merge(meta_tag['http-equiv'])
@@ -33,40 +37,27 @@ module MetaInspector
33
37
  private
34
38
 
35
39
  def charset_from_meta_charset
36
- parsed.css('meta[charset]')[0].attributes['charset'].value rescue nil
40
+ parsed.at_css('meta[charset]')&.attributes&.[]('charset')&.value
37
41
  end
38
42
 
39
43
  def charset_from_meta_content_type
40
- parsed.css("meta[http-equiv='Content-Type']")[0]
41
- .attributes['content'].value.split(';')[1].split('=')[1] rescue nil
42
- end
43
-
44
- def meta_tags_by(attribute)
45
- hash = {}
46
- parsed.css("meta[@#{attribute}]").map do |tag|
47
- name = tag.attributes[attribute].value.downcase rescue nil
48
- content = tag.attributes['content'].value rescue nil
49
-
50
- if name && content
51
- hash[name] ||= []
52
- hash[name] << content
53
- end
44
+ tag = parsed.css('meta[http-equiv]').find do |meta|
45
+ meta['http-equiv'].casecmp('Content-Type').zero?
54
46
  end
55
- hash
47
+ return unless tag
48
+
49
+ tag['content'].to_s[/;\s*charset\s*=\s*["']?([^;\s"']+)/i, 1]
56
50
  end
57
51
 
58
- def convert_each_array_to_first_element_on(hash)
59
- hash.each_pair do |k, v|
60
- hash[k] = if v.is_a?(Hash)
61
- convert_each_array_to_first_element_on(v)
62
- elsif v.is_a?(Array)
63
- v.first
64
- else
65
- v
66
- end
52
+ # Returns every content of the meta tags with that attribute, keyed by
53
+ # its lowercased value
54
+ def meta_tags_by(attribute)
55
+ parsed.css("meta[@#{attribute}]").each_with_object({}) do |tag, contents|
56
+ name = tag.attributes[attribute]&.value&.downcase
57
+ content = tag.attributes['content']&.value
58
+ (contents[name] ||= []) << content if name && content
67
59
  end
68
60
  end
69
-
70
61
  end
71
62
  end
72
63
  end
@@ -5,14 +5,15 @@ module MetaInspector
5
5
 
6
6
  # Returns the declared HTML language, or nil when missing or blank
7
7
  def language
8
- value = parsed.at_css('html')&.[]('lang')&.strip
9
- value unless value.to_s.empty?
8
+ stripped_presence(parsed.at_css('html')&.[]('lang'))
10
9
  end
11
10
 
12
- # Returns the parsed document title, from the content of the <title> tag
13
- # within the <head> section.
11
+ # Returns the content of the first <title> tag within the <head> section,
12
+ # without surrounding whitespace, or nil when missing or blank
14
13
  def title
15
- @title ||= parsed.css('head title').inner_text rescue nil
14
+ return @title if defined?(@title)
15
+
16
+ @title = stripped_presence(parsed.at_css('head title')&.inner_text)
16
17
  end
17
18
 
18
19
  def best_title
@@ -30,7 +31,7 @@ module MetaInspector
30
31
  def h3
31
32
  @h3 ||= find_heading('h3')
32
33
  end
33
-
34
+
34
35
  def h4
35
36
  @h4 ||= find_heading('h4')
36
37
  end
@@ -59,12 +60,16 @@ module MetaInspector
59
60
  @best_author ||= find_best_author
60
61
  end
61
62
 
62
- # Returns the meta description, if present
63
+ # Returns the meta description without surrounding whitespace, or nil when
64
+ # missing or blank
63
65
  def description
64
- @description ||= meta['description']
66
+ return @description if defined?(@description)
67
+
68
+ @description = stripped_presence(meta['description'])
65
69
  end
66
70
 
67
- # A description getter that returns the first non-blank description
71
+ # A description getter that returns the first non-blank description,
72
+ # without surrounding whitespace,
68
73
  # from the following candidates:
69
74
  # - the standard meta description
70
75
  # - the og:description meta tag
@@ -76,40 +81,46 @@ module MetaInspector
76
81
 
77
82
  private
78
83
 
84
+ def stripped_presence(text)
85
+ text = text&.strip
86
+ text unless text.nil? || text.empty?
87
+ end
88
+
89
+ # Strips the text and collapses its inner whitespace into single spaces
90
+ def squish(text)
91
+ text.strip.gsub(/\s+/, ' ')
92
+ end
93
+
79
94
  def find_heading(heading)
80
- parsed.css(heading).map { |tag| tag.inner_text.strip.gsub(/\s+/, ' ') }.reject(&:empty?)
95
+ parsed.css(heading).map { |tag| squish(tag.inner_text) }.reject(&:empty?)
96
+ end
97
+
98
+ # Returns the first candidate, String or node, with non-blank text, squished
99
+ def first_squished_text(candidates)
100
+ texts = candidates.flatten.compact.map { |c| squish(c.respond_to?(:inner_text) ? c.inner_text : c) }
101
+ texts.find { |text| !text.empty? }
81
102
  end
82
103
 
83
104
  # Look for candidates per list of priority
84
105
  def find_best_title
85
- candidates = [
86
- meta['title'],
87
- meta['og:title'],
88
- parsed.css('head title'),
89
- parsed.css('body title'),
90
- parsed.css('h1').first,
91
- meta['parsely-title']
92
- ]
93
- candidates.flatten!
94
- candidates.compact!
95
- candidates.map! { |c| (c.respond_to? :inner_text) ? c.inner_text : c }
96
- candidates.map! { |c| c.strip.gsub(/\s+/, ' ') }
97
- candidates.find { |c| !c.to_s.empty? }
106
+ first_squished_text([
107
+ meta['title'],
108
+ meta['og:title'],
109
+ parsed.css('head title'),
110
+ parsed.css('body title'),
111
+ parsed.css('h1').first,
112
+ meta['parsely-title']
113
+ ])
98
114
  end
99
115
 
100
116
  def find_best_author
101
- candidates = [
117
+ first_squished_text([
102
118
  meta['author'],
103
119
  parsed.css('a[rel="author"]').first,
104
120
  parsed.css('address').first,
105
121
  meta['twitter:creator'],
106
122
  meta['parsely-author']
107
- ]
108
- candidates.flatten!
109
- candidates.compact!
110
- candidates.map! { |c| (c.respond_to? :inner_text) ? c.inner_text : c }
111
- candidates.map! { |c| c.strip.gsub(/\s+/, ' ') }
112
- candidates.find { |c| !c.to_s.empty? }
123
+ ])
113
124
  end
114
125
 
115
126
  def find_best_description
@@ -119,13 +130,12 @@ module MetaInspector
119
130
  meta['twitter:description'],
120
131
  secondary_description
121
132
  ]
122
- candidates.find { |x| !x.to_s.strip.empty? }
133
+ candidates.filter_map { |candidate| stripped_presence(candidate) }.first
123
134
  end
124
135
 
125
136
  # Look for the first <p> block with 120 characters or more
126
137
  def secondary_description
127
- first_long_paragraph = parsed.search('//p[string-length() >= 120]').first
128
- first_long_paragraph ? first_long_paragraph.text : ''
138
+ parsed.at_xpath('//p[string-length() >= 120]')&.text
129
139
  end
130
140
  end
131
141
  end
@@ -1,35 +1,39 @@
1
- require 'timeout'
2
1
  require_relative 'http_session'
2
+ require_relative 'html_encoding'
3
3
 
4
4
  module MetaInspector
5
-
6
5
  # Makes the request to the server
7
6
  class Request
8
7
  def initialize(initial_url, options = {})
9
- @url = initial_url
10
-
8
+ @url = initial_url
11
9
  URLPolicy.validate!(@url.url)
12
10
 
13
- @allow_redirections = options[:allow_redirections]
14
- @head_first = options[:head_first]
11
+ @allow_redirections = options[:allow_redirections]
12
+ @head_first = options[:head_first]
15
13
  @allow_non_html_content = options[:allow_non_html_content]
16
- @connection_timeout = options[:connection_timeout]
17
- @read_timeout = options[:read_timeout]
18
- @encoding = options[:encoding]
19
- @http_session = options[:http_session] || HttpSession.new(options)
14
+ @connection_timeout = options[:connection_timeout]
15
+ @read_timeout = options[:read_timeout]
16
+ @encoding = options[:encoding]
17
+ @http_session = options[:http_session] || HttpSession.new(options)
20
18
 
21
- response # request early so we can fail early
19
+ response # request early so we can fail early
22
20
  end
23
21
 
24
22
  extend Forwardable
25
23
  delegate :url => :@url
26
24
 
25
+ # Responses without a Content-Type are treated as HTML.
26
+ def self.html_content_type?(content_type)
27
+ content_type.nil? || content_type == 'text/html'
28
+ end
29
+
27
30
  def read
28
31
  return unless response
32
+
29
33
  body = response.body
30
- body = body.encode!(@encoding, @encoding, :invalid => :replace) if @encoding
31
- body.tr("\000", '')
32
- rescue ArgumentError => e
34
+ check_content_encoding!(body)
35
+ to_utf8(with_declared_encoding(body)).tr("\000", '')
36
+ rescue ArgumentError, EncodingError => e
33
37
  raise MetaInspector::RequestError.new(e)
34
38
  end
35
39
 
@@ -41,40 +45,23 @@ module MetaInspector
41
45
  @response ||= fetch
42
46
  rescue URLPolicy::Failure => failure
43
47
  raise failure.original
44
- rescue Faraday::TimeoutError => e
48
+ rescue Faraday::TimeoutError, AttemptTimeout::Expired => e
45
49
  raise MetaInspector::TimeoutError.new(e)
46
- rescue Faraday::ConnectionFailed, Faraday::SSLError, URI::InvalidURIError, Faraday::FollowRedirects::RedirectLimitReached => e
50
+ rescue Faraday::ConnectionFailed, Faraday::SSLError, URI::InvalidURIError, URI::InvalidComponentError,
51
+ Faraday::FollowRedirects::RedirectLimitReached, Zlib::Error => e
47
52
  raise MetaInspector::RequestError.new(e)
48
53
  end
49
54
 
50
55
  private
51
56
 
52
- # Once per process: apps fetch many pages with the same options, and a warning
53
- # per request would flood their logs
54
- def self.warn_faraday_http_cache_deprecation
55
- return if @faraday_http_cache_deprecation_warned
56
-
57
- @faraday_http_cache_deprecation_warned = true
58
- warn 'DEPRECATION WARNING: the top-level faraday_http_cache option is deprecated and will be removed ' \
59
- 'in the next major version. Pass it inside faraday_options instead: ' \
60
- 'faraday_options: { faraday_http_cache: { store: cache } }'
61
- end
62
-
63
57
  def fetch
64
- Timeout::timeout(fatal_timeout) do
65
- session = @http_session.build(url)
66
-
67
- check_head_content_type(session) if @head_first
68
- response = perform_request(session, :get)
58
+ session = @http_session.build(url)
69
59
 
70
- if @allow_redirections
71
- @url.url = response.env.url.to_s
72
- end
60
+ check_head_content_type(session) if @head_first
61
+ response = perform_request(session, :get)
73
62
 
74
- response
75
- end
76
- rescue Timeout::Error => e
77
- raise MetaInspector::TimeoutError.new(e)
63
+ @url.url = response.env.url.to_s if @allow_redirections
64
+ response
78
65
  end
79
66
 
80
67
  def check_head_content_type(session)
@@ -82,31 +69,56 @@ module MetaInspector
82
69
  return unless head_response.success?
83
70
 
84
71
  type = response_content_type(head_response)
85
- if !@allow_non_html_content && !type.nil? && type != 'text/html'
86
- fail MetaInspector::NonHtmlError.new "The url provided contains #{type} content instead of text/html content"
72
+ raise NonHtmlError.for(type) unless @allow_non_html_content || self.class.html_content_type?(type)
73
+ end
74
+
75
+ # Tags the body with its encoding, from highest to lowest precedence: a
76
+ # byte-order mark for encodings that aren't ASCII-compatible, the encoding:
77
+ # option, then the HTTP charset. The adapter tags the body only with HTTP
78
+ # charsets Ruby knows, so labels such as "x-sjis" are resolved here.
79
+ def with_declared_encoding(body)
80
+ if body.encoding == Encoding::BINARY
81
+ charset = HtmlEncoding.resolve(HtmlEncoding.charset_param(response.headers['content-type']))
82
+ body = body.dup.force_encoding(charset) if charset
83
+ end
84
+ body = body.dup.force_encoding(@encoding) if @encoding
85
+ bom_encoding = HtmlEncoding.byte_order_mark_encoding(body)
86
+ body = body.dup.force_encoding(bom_encoding) if bom_encoding && !Encoding.find(bom_encoding).ascii_compatible?
87
+ body
88
+ end
89
+
90
+ # Replaces invalid bytes with U+FFFD, as browsers do, so one bad byte
91
+ # doesn't make the whole page fail. Binary bodies are decoded later by the parser.
92
+ def to_utf8(body)
93
+ body = HtmlEncoding.normalize(body)
94
+ if body.encoding.ascii_compatible?
95
+ body.scrub
96
+ else
97
+ body.encode(Encoding::UTF_8, invalid: :replace, undef: :replace)
87
98
  end
88
99
  end
89
100
 
101
+ # The compression middleware removes Content-Encoding once it has decoded the
102
+ # body. If it's still there, the body is compressed bytes, not HTML (#597).
103
+ def check_content_encoding!(body)
104
+ return if body.empty?
105
+
106
+ header = response.headers['content-encoding'].to_s
107
+ encodings = header.split(',').map { |value| value.strip.downcase }.reject(&:empty?) - ['identity']
108
+ return if encodings.empty?
109
+
110
+ raise MetaInspector::RequestError, "Unsupported Content-Encoding: #{header.strip}"
111
+ end
112
+
90
113
  def response_content_type(response)
91
- response.headers['content-type']&.split(';')&.first
114
+ response.headers['content-type']&.split(';')&.first&.strip&.downcase
92
115
  end
93
116
 
94
117
  def perform_request(session, method)
95
118
  session.public_send(method) do |req|
96
- req.options.timeout = @connection_timeout
97
- req.options.open_timeout = @read_timeout
119
+ req.options.open_timeout = @connection_timeout
120
+ req.options.timeout = @read_timeout
98
121
  end
99
122
  end
100
-
101
- # Timeouts when connecting / reading a request are handled by Faraday, but in the
102
- # case of URLs that respond with streaming, Faraday will never return. In that case,
103
- # we'll resort to our own timeout
104
- #
105
- # https://github.com/jaimeiniesta/metainspector/issues/188
106
- # https://github.com/lostisland/faraday/issues/602
107
- #
108
- def fatal_timeout
109
- (@connection_timeout || 0) + (@read_timeout || 0) + 1
110
- end
111
123
  end
112
124
  end
@@ -2,42 +2,47 @@ require 'addressable/uri'
2
2
 
3
3
  module MetaInspector
4
4
  class URL
5
- attr_reader :url
5
+ WELL_KNOWN_TRACKING_PARAMS = %w[utm_source utm_medium utm_term utm_content utm_campaign]
6
6
 
7
- def initialize(initial_url, options = {})
8
- options = self.class.defaults.merge(options)
7
+ attr_reader :url
9
8
 
10
- @normalize = options[:normalize]
9
+ def self.defaults
10
+ { normalize: true }
11
+ end
11
12
 
13
+ def initialize(initial_url, options = {})
14
+ @normalize = self.class.defaults.merge(options)[:normalize]
12
15
  self.url = initial_url
13
16
  end
14
17
 
15
18
  def scheme
16
- parsed(url) ? parsed(url).scheme : nil
19
+ parsed(url)&.scheme
17
20
  end
18
21
 
19
22
  def host
20
- parsed(url) ? parsed(url).host : nil
23
+ parsed(url)&.host
21
24
  end
22
25
 
23
26
  def root_url
24
27
  "#{scheme}://#{host}/"
25
28
  end
26
29
 
27
- WELL_KNOWN_TRACKING_PARAMS = %w( utm_source utm_medium utm_term utm_content utm_campaign )
28
-
29
30
  def tracked?
30
- u = parsed(url)
31
- return false unless u.query_values
32
- found_tracking_params = WELL_KNOWN_TRACKING_PARAMS & u.query_values.keys
33
- return found_tracking_params.any?
31
+ query_values = parsed(url).query_values
32
+ return false unless query_values
33
+
34
+ WELL_KNOWN_TRACKING_PARAMS.intersect?(query_values.keys)
34
35
  end
35
36
 
37
+ # Removes only the tracking key=value pairs, keeping the rest of the
38
+ # query string as written: order, repeated keys and encoding.
36
39
  def untracked_url
37
40
  u = parsed(url)
38
- return url unless u.query_values
39
- query_values = u.query_values.delete_if { |key, _| WELL_KNOWN_TRACKING_PARAMS.include? key }
40
- u.query_values = query_values.length > 0 ? query_values : nil
41
+ return url unless u.query
42
+ params = u.query.split('&', -1)
43
+ kept = params.reject { |param| tracking_param?(param) }
44
+ return url if kept.length == params.length
45
+ u.query = kept.empty? ? nil : kept.join('&')
41
46
  u.to_s
42
47
  end
43
48
 
@@ -62,16 +67,35 @@ module MetaInspector
62
67
  MetaInspector::URL.new(url, options).url
63
68
  else
64
69
  uri = Addressable::URI.join(base_url, url)
65
- options[:normalize] ? uri.normalize.to_s : uri.to_s
70
+ options[:normalize] ? normalize(uri) : uri.to_s
66
71
  end
67
72
  rescue MetaInspector::ParserError, Addressable::URI::InvalidURIError, ArgumentError
68
73
  nil
69
74
  end
70
75
 
76
+ # Addressable's normalization, except for the query: reserved characters such
77
+ # as ";" or "[]" and existing escapes are kept as written, since changing them
78
+ # can change the resource (RFC 3986, 2.2). Only what can't be sent is escaped.
79
+ def self.normalize(uri)
80
+ normalized = uri.normalize
81
+ normalized.query = escape_query(uri.query) if uri.query
82
+ normalized.to_s
83
+ end
84
+
85
+ # Bytes allowed in a query by RFC 3986 (pchar, "/" and "?"), plus "[]" and
86
+ # "%" when it starts an escape. Browsers send "[]" unescaped too.
87
+ QUERY_UNSAFE = /%(?![0-9A-Fa-f]{2})|[^A-Za-z0-9\-._~!$&'()*+,;=:@\/?\[\]%]/n
88
+ private_constant :QUERY_UNSAFE
89
+
90
+ def self.escape_query(query)
91
+ query.b.gsub(QUERY_UNSAFE) { |byte| format('%%%02X', byte.ord) }.force_encoding(Encoding::UTF_8)
92
+ end
93
+
71
94
  private
72
95
 
73
- def self.defaults
74
- { :normalize => true }
96
+ def tracking_param?(param)
97
+ key = Addressable::URI.unencode_component(param.split('=', 2).first)
98
+ WELL_KNOWN_TRACKING_PARAMS.include?(key)
75
99
  end
76
100
 
77
101
  # Adds 'http' as default scheme, if there is none
@@ -82,7 +106,7 @@ module MetaInspector
82
106
  # Normalize url to deal with characters that should be encoded,
83
107
  # add trailing slash, convert to downcase...
84
108
  def normalized(url)
85
- Addressable::URI.parse(url).normalize.to_s
109
+ self.class.normalize(Addressable::URI.parse(url))
86
110
  rescue Addressable::URI::InvalidURIError => e
87
111
  raise MetaInspector::ParserError.new(e)
88
112
  end
@@ -21,7 +21,7 @@ module MetaInspector
21
21
  raise InvalidURL, 'URL must be HTTP or HTTPS'
22
22
  end
23
23
  uri
24
- rescue URI::InvalidURIError => error
24
+ rescue URI::InvalidURIError, URI::InvalidComponentError => error
25
25
  raise InvalidURL.new(error)
26
26
  end
27
27
 
@@ -34,28 +34,35 @@ module MetaInspector
34
34
  @allowed_headers = @image_origin ? IMAGE_HEADERS : PAGE_HEADERS
35
35
  end
36
36
 
37
+ # Keeps only the PAGE_HEADERS or IMAGE_HEADERS on requests that leave the
38
+ # trusted origin, so credentials and cookies aren't sent elsewhere, sends image lookups that leave the page's origin with a Referer,
39
+ # and applies the url_filter.
37
40
  def call(env)
38
41
  uri = self.class.validate!(env.url)
39
42
  cross_image_origin = @image_origin && origin(uri) != origin(@image_origin)
40
43
  if cross_image_origin || (@request_origin && origin(uri) != origin(@request_origin))
41
44
  env.request_headers.delete_if { |key, _| !@allowed_headers.include?(key.downcase) }
42
45
  end
43
- if cross_image_origin
44
- unless @image_origin.scheme == 'https' && uri.scheme == 'http'
45
- referer = @image_origin.dup
46
- referer.userinfo = nil
47
- referer.path = '/'
48
- referer.query = nil
49
- referer.fragment = nil
50
- env.request_headers['Referer'] = referer.to_s
51
- end
52
- end
46
+ add_referer(env, uri) if cross_image_origin
53
47
  check_filter(uri) if @filter
54
48
  @app.call(env)
55
49
  end
56
50
 
57
51
  private
58
52
 
53
+ # Sends the page's origin, as browsers do by default, except on a
54
+ # downgrade from HTTPS to HTTP.
55
+ def add_referer(env, uri)
56
+ return if @image_origin.scheme == 'https' && uri.scheme == 'http'
57
+
58
+ referer = @image_origin.dup
59
+ referer.userinfo = nil
60
+ referer.path = '/'
61
+ referer.query = nil
62
+ referer.fragment = nil
63
+ env.request_headers['Referer'] = referer.to_s
64
+ end
65
+
59
66
  def origin(uri)
60
67
  [uri.scheme.downcase, uri.hostname.downcase, uri.port]
61
68
  end
@@ -1,3 +1,3 @@
1
1
  module MetaInspector
2
- VERSION = '5.21.2'
2
+ VERSION = '6.0.0'
3
3
  end
@@ -1,17 +1,18 @@
1
1
  require 'forwardable'
2
- require File.expand_path(File.join(File.dirname(__FILE__), 'meta_inspector/errors'))
3
- require File.expand_path(File.join(File.dirname(__FILE__), 'meta_inspector/request'))
4
- require File.expand_path(File.join(File.dirname(__FILE__), 'meta_inspector/url'))
5
- require File.expand_path(File.join(File.dirname(__FILE__), 'meta_inspector/parser'))
6
- require File.expand_path(File.join(File.dirname(__FILE__), 'meta_inspector/parsers/base'))
7
- require File.expand_path(File.join(File.dirname(__FILE__), 'meta_inspector/parsers/images'))
8
- require File.expand_path(File.join(File.dirname(__FILE__), 'meta_inspector/parsers/iframes'))
9
- require File.expand_path(File.join(File.dirname(__FILE__), 'meta_inspector/parsers/links'))
10
- require File.expand_path(File.join(File.dirname(__FILE__), 'meta_inspector/parsers/head_links'))
11
- require File.expand_path(File.join(File.dirname(__FILE__), 'meta_inspector/parsers/meta_tags'))
12
- require File.expand_path(File.join(File.dirname(__FILE__), 'meta_inspector/parsers/texts'))
13
- require File.expand_path(File.join(File.dirname(__FILE__), 'meta_inspector/document'))
14
- require File.expand_path(File.join(File.dirname(__FILE__), 'meta_inspector/version'))
2
+ require_relative 'meta_inspector/version'
3
+ require_relative 'meta_inspector/errors'
4
+ require_relative 'meta_inspector/url'
5
+ require_relative 'meta_inspector/request'
6
+ require_relative 'meta_inspector/image_downloader'
7
+ require_relative 'meta_inspector/parser'
8
+ require_relative 'meta_inspector/parsers/base'
9
+ require_relative 'meta_inspector/parsers/images'
10
+ require_relative 'meta_inspector/parsers/iframes'
11
+ require_relative 'meta_inspector/parsers/links'
12
+ require_relative 'meta_inspector/parsers/head_links'
13
+ require_relative 'meta_inspector/parsers/meta_tags'
14
+ require_relative 'meta_inspector/parsers/texts'
15
+ require_relative 'meta_inspector/document'
15
16
 
16
17
  module MetaInspector
17
18
  extend self
data/lib/metainspector.rb CHANGED
@@ -1 +1 @@
1
- require File.expand_path(File.join(File.dirname(__FILE__), './meta_inspector'))
1
+ require_relative 'meta_inspector'