metainspector 5.20.0 → 5.21.1

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 (41) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +20 -0
  3. data/Gemfile +1 -1
  4. data/README.md +157 -6
  5. data/examples/basic_scraping.rb +4 -3
  6. data/examples/faraday_redirect_options.rb +23 -31
  7. data/examples/html_size_limit.rb +17 -0
  8. data/examples/iframes.rb +15 -0
  9. data/examples/image_details.rb +17 -0
  10. data/examples/image_validation.rb +25 -0
  11. data/examples/link_checker.rb +2 -2
  12. data/examples/responsive_images.rb +15 -0
  13. data/examples/spider.rb +2 -2
  14. data/lib/meta_inspector/document.rb +14 -1
  15. data/lib/meta_inspector/http_session.rb +15 -2
  16. data/lib/meta_inspector/image_downloader.rb +48 -3
  17. data/lib/meta_inspector/parser.rb +20 -1
  18. data/lib/meta_inspector/parsers/head_links.rb +18 -3
  19. data/lib/meta_inspector/parsers/iframes.rb +21 -0
  20. data/lib/meta_inspector/parsers/images.rb +194 -26
  21. data/lib/meta_inspector/parsers/texts.rb +2 -2
  22. data/lib/meta_inspector/url_policy.rb +23 -6
  23. data/lib/meta_inspector/version.rb +1 -1
  24. data/lib/meta_inspector.rb +1 -0
  25. data/meta_inspector.gemspec +1 -2
  26. data/spec/document_spec.rb +139 -0
  27. data/spec/examples_spec.rb +206 -0
  28. data/spec/image_download_spec.rb +11 -0
  29. data/spec/image_metadata_spec.rb +110 -0
  30. data/spec/image_validity_spec.rb +195 -0
  31. data/spec/inline_images_spec.rb +75 -0
  32. data/spec/meta_inspector/head_links_spec.rb +69 -0
  33. data/spec/meta_inspector/iframes_spec.rb +50 -0
  34. data/spec/meta_inspector/images_spec.rb +130 -0
  35. data/spec/meta_inspector/texts_spec.rb +50 -0
  36. data/spec/parser_spec.rb +10 -0
  37. data/spec/redirect_headers_spec.rb +143 -0
  38. data/spec/unicode_image_urls_spec.rb +74 -0
  39. data/spec/url_filter_spec.rb +1 -1
  40. metadata +29 -37
  41. data/examples/redirect_web_server.rb +0 -5
@@ -1,6 +1,7 @@
1
1
  require 'stringio'
2
2
  require 'fastimage'
3
3
  require 'timeout'
4
+ require 'base64'
4
5
 
5
6
  module MetaInspector
6
7
  class ImageDownloader
@@ -14,13 +15,39 @@ module MetaInspector
14
15
  @read_timeout = [options[:read_timeout] || TIMEOUT, TIMEOUT].min
15
16
  end
16
17
 
17
- def size(url)
18
+ def size(url, reject_invalid_url: false)
19
+ fetch(url, metadata: false, reject_invalid_url: reject_invalid_url)
20
+ end
21
+
22
+ def metadata(url, reject_invalid_url: false)
23
+ fetch(url, metadata: true, reject_invalid_url: reject_invalid_url)
24
+ end
25
+
26
+ def inline_metadata(url)
27
+ header, payload = url.split(',', 2)
28
+ return nil unless payload && !payload.match?(/%(?![0-9a-fA-F]{2})/)
29
+
30
+ bytes = payload.gsub(/%([0-9a-fA-F]{2})/) { [$1.to_i(16)].pack('C') }.b
31
+ bytes = Base64.strict_decode64(bytes) if header.match?(/;base64\z/i)
32
+ dimensions = FastImage.size(StringIO.new(bytes))
33
+ return nil unless dimensions
34
+
35
+ { dimensions: dimensions, type: FastImage.type(StringIO.new(bytes)), file_size: bytes.bytesize }
36
+ rescue ArgumentError
37
+ nil
38
+ end
39
+
40
+ private
41
+
42
+ def fetch(url, metadata:, reject_invalid_url:)
18
43
  bytes = ''.b
19
44
  received = 0
20
45
  status = nil
46
+ headers = nil
47
+ completed = false
21
48
  stop = Object.new
22
49
  Timeout.timeout(TIMEOUT) do
23
- session = @session.build(url, image: true, origin: @origin.url)
50
+ session = @session.build(url, image: true, origin: @origin.url, protect_redirect_callback: reject_invalid_url)
24
51
  catch(stop) do
25
52
  session.get do |request|
26
53
  request.headers['Range'] = "bytes=0-#{MAX_BYTES - 1}"
@@ -29,6 +56,7 @@ module MetaInspector
29
56
  request.options.timeout = @read_timeout
30
57
  request.options.on_data = proc do |chunk, _total, env|
31
58
  status = env.status
59
+ headers = env.response_headers
32
60
  remaining = MAX_BYTES - received
33
61
  received += chunk.bytesize
34
62
  # Count redirect bodies too, across the entire lookup.
@@ -40,14 +68,31 @@ module MetaInspector
40
68
  throw stop if received >= MAX_BYTES
41
69
  end
42
70
  end
71
+ completed = true
43
72
  end
44
73
  end
45
- FastImage.size(StringIO.new(bytes)) if status && (200..299).cover?(status)
74
+ return unless status && (200..299).cover?(status)
75
+
76
+ dimensions = FastImage.size(StringIO.new(bytes))
77
+ return dimensions unless metadata
78
+
79
+ { dimensions: dimensions, type: FastImage.type(StringIO.new(bytes)),
80
+ file_size: file_size(status, headers, completed, bytes.bytesize) }
46
81
  rescue URLPolicy::Failure => failure
47
82
  raise failure.original
48
83
  rescue Faraday::TimeoutError, Faraday::ConnectionFailed, Faraday::SSLError,
49
84
  Faraday::FollowRedirects::RedirectLimitReached, URI::InvalidURIError, Timeout::Error
50
85
  nil
51
86
  end
87
+
88
+ def file_size(status, headers, completed, bytesize)
89
+ value = if status == 206
90
+ headers['content-range'].to_s[/\Abytes \d+-\d+\/(\d+)\z/i, 1]
91
+ elsif status == 200 && (headers['content-encoding'].nil? || headers['content-encoding'] == 'identity')
92
+ length = headers['content-length']
93
+ length.nil? && completed ? bytesize.to_s : length.to_s[/\A\d+\z/]
94
+ end
95
+ value.to_i if value
96
+ end
52
97
  end
53
98
  end
@@ -10,13 +10,18 @@ module MetaInspector
10
10
  class Parser
11
11
  def initialize(document, options = {})
12
12
  @document = document
13
+ @max_html_bytes = options[:max_html_bytes]
13
14
  @head_links_parser = MetaInspector::Parsers::HeadLinksParser.new(self)
14
15
  @meta_tag_parser = MetaInspector::Parsers::MetaTagsParser.new(self)
15
16
  @links_parser = MetaInspector::Parsers::LinksParser.new(self)
16
17
  @download_images = options[:download_images]
17
18
  @images_parser = MetaInspector::Parsers::ImagesParser.new(self, download_images: @download_images,
18
19
  max_image_downloads: options[:max_image_downloads],
20
+ download_image_options: options[:download_image_options],
21
+ fetch_all_image_meta: options[:fetch_all_image_meta],
22
+ inline_image_data: options[:inline_image_data],
19
23
  image_downloader: options[:image_downloader])
24
+ @iframes_parser = MetaInspector::Parsers::IframesParser.new(self)
20
25
  @texts_parser = MetaInspector::Parsers::TextsParser.new(self)
21
26
 
22
27
  parsed # parse early so we can fail early
@@ -28,12 +33,26 @@ module MetaInspector
28
33
  delegate [:head_links, :stylesheets, :canonicals, :feeds, :feed] => :@head_links_parser
29
34
  delegate [:links, :base_url] => :@links_parser
30
35
  delegate :images => :@images_parser
36
+ delegate [:iframes, :iframe_sources] => :@iframes_parser
31
37
  delegate [:language, :title, :best_title, :author, :best_author, :description, :best_description,
32
38
  :h1, :h2, :h3, :h4, :h5, :h6] => :@texts_parser
33
39
 
40
+ # Deprecated compatibility shortcut; remove in 6.0.
41
+ def favicon
42
+ warn 'DEPRECATION WARNING: page.favicon is deprecated and will be removed in 6.0. ' \
43
+ 'Use page.images.favicon instead.'
44
+ images.favicon
45
+ end
46
+
34
47
  # Returns the whole parsed document
35
48
  def parsed
36
- @parsed ||= Nokogiri::HTML(@document.to_s)
49
+ @parsed ||= begin
50
+ html = @document.to_s
51
+ if @max_html_bytes && html.bytesize > @max_html_bytes
52
+ raise MetaInspector::ParserError, "HTML is #{html.bytesize} bytes, exceeding the limit of #{@max_html_bytes} bytes"
53
+ end
54
+ Nokogiri::HTML(html)
55
+ end
37
56
  end
38
57
  end
39
58
  end
@@ -21,16 +21,17 @@ module MetaInspector
21
21
  end
22
22
 
23
23
  def stylesheets
24
- @stylesheets ||= head_links.select { |hl| hl[:rel] == 'stylesheet' }
24
+ @stylesheets ||= head_links.select { |hl| rel_includes?(hl[:rel], 'stylesheet') }
25
25
  end
26
26
 
27
27
  def canonicals
28
- @canonicals ||= head_links.select { |hl| hl[:rel] == 'canonical' }
28
+ @canonicals ||= head_links.select { |hl| rel_includes?(hl[:rel], 'canonical') }
29
29
  end
30
30
 
31
31
  def feeds
32
32
  @feeds ||=
33
- parsed.search("//link[@rel='alternate']").map do |link|
33
+ parsed.search('//link[@rel]').map do |link|
34
+ next unless rel_includes?(link['rel'], 'alternate')
34
35
  next if !KNOWN_FEED_TYPES.include?(link["type"]) || link["href"].to_s.strip == ''
35
36
 
36
37
  {
@@ -40,6 +41,20 @@ module MetaInspector
40
41
  }
41
42
  end.compact
42
43
  end
44
+
45
+ # Deprecated compatibility method; remove in 6.0.
46
+ def feed
47
+ warn 'DEPRECATION WARNING: page.feed is deprecated and will be removed in 6.0. ' \
48
+ 'Use page.feeds instead.'
49
+ first_feed = feeds.find { |link| %r{/(rss|atom)\+xml$}i.match?(link[:type]) }
50
+ first_feed && first_feed[:href]
51
+ end
52
+
53
+ private
54
+
55
+ def rel_includes?(rel, keyword)
56
+ rel.to_s.downcase(:ascii).split(/[ \t\n\f\r]+/).include?(keyword)
57
+ end
43
58
  end
44
59
  end
45
60
  end
@@ -0,0 +1,21 @@
1
+ module MetaInspector
2
+ module Parsers
3
+ class IframesParser < Base
4
+ delegate [:parsed, :base_url] => :@main_parser
5
+ def iframes
6
+ @iframes ||= parsed.search('//iframe').map do |iframe|
7
+ iframe.attributes.each_with_object({}) do |(name, attribute), result|
8
+ result[name.to_sym] = attribute.value
9
+ end
10
+ end
11
+ end
12
+
13
+ def iframe_sources
14
+ iframes.map do |attributes|
15
+ src = attributes[:src].to_s.strip
16
+ URL.absolutify(src, base_url, normalize: false) unless src.empty?
17
+ end
18
+ end
19
+ end
20
+ end
21
+ end
@@ -1,4 +1,5 @@
1
1
  require_relative '../image_downloader'
2
+ require 'strscan'
2
3
 
3
4
  module MetaInspector
4
5
  module Parsers
@@ -12,6 +13,12 @@ module MetaInspector
12
13
  @image_downloader = options[:image_downloader]
13
14
  @download_images = options[:download_images]
14
15
  @max_image_downloads = options[:max_image_downloads]
16
+ @reject_invalid_images = (options[:download_image_options] || {})[:reject_invalid_images]
17
+ @fetch_all_image_meta = options[:fetch_all_image_meta]
18
+ @inline_image_data = options[:inline_image_data]
19
+ @image_sizes = {}
20
+ @image_metadata = {}
21
+ @download_attempts = 0
15
22
  super(main_parser)
16
23
  end
17
24
 
@@ -22,7 +29,7 @@ module MetaInspector
22
29
  # Returns the Facebook Open Graph image, Twitter image, Parsely image or
23
30
  # the largest image in the image collection
24
31
  def best
25
- owner_suggested || largest
32
+ suggested_image(skip_inline: !@inline_image_data) || largest
26
33
  end
27
34
 
28
35
  # Returns the parsed image from Facebook's open graph property tags
@@ -30,36 +37,62 @@ module MetaInspector
30
37
  # See doc at http://developers.facebook.com/docs/opengraph/
31
38
  # If none found, tries with Twitter image, then Parsely image
32
39
  def owner_suggested
33
- suggested_img = content_of(meta['og:image']) || content_of(meta['twitter:image']) ||
34
- content_of(meta['parsely-image-url'])
35
- URL.absolutify(suggested_img, base_url, normalize: false) if suggested_img
40
+ result_url(suggested_image)
41
+ end
42
+
43
+ # Returns validity for each image URL; nil means no lookup was performed.
44
+ def with_metadata
45
+ absolutified_images.map do |url|
46
+ { url: result_url(url), valid: @fetch_all_image_meta && url ? image_validity(url) : nil }
47
+ end
36
48
  end
37
49
 
38
50
  # Returns an array of [img_url, width, height] sorted by image area (width * height)
39
51
  def with_size
40
52
  @with_size ||= begin
41
- img_nodes = parsed.search('//img').select{ |img_node| img_node['src'] }
42
- imgs_with_size = img_nodes.map do |img_node|
43
- [URL.absolutify(img_node['src'], base_url, normalize: false), img_node['width'], img_node['height']]
53
+ imgs_with_size = unique_image_candidates
54
+ if @download_images && @reject_invalid_images
55
+ imgs_with_size.reject! { |url, width, height| image_validity(url) == false }
44
56
  end
45
- imgs_with_size.reject! { |url, width, height| url.nil? || url.empty? }
46
- imgs_with_size.uniq! { |url, width, height| url }
47
- download_attempts = 0
48
- imgs_with_size.map! do |url, width, height|
57
+ imgs_with_size.map! do |url, width, height, _responsive|
49
58
  if width.nil? || height.nil?
50
- if @download_images && (@max_image_downloads.nil? || download_attempts < @max_image_downloads)
51
- download_attempts += 1
52
- width, height = @image_downloader.size(url)
53
- else
54
- width, height = [0, 0]
55
- end
59
+ width, height = image_size(url) || [0, 0]
56
60
  end
57
- [url, width.to_i, height.to_i]
61
+ [result_url(url), width.to_i, height.to_i]
58
62
  end
59
63
  imgs_with_size.sort_by { |url, width, height| -(width.to_i * height.to_i) }
60
64
  end
61
65
  end
62
66
 
67
+ # Returns image details sorted by area. Metadata lookups are opt-in.
68
+ # With validation enabled, details reuse the validation lookups.
69
+ def with_details
70
+ @with_details ||= begin
71
+ attempts = 0
72
+ images = unique_image_candidates.filter_map do |url, width, height, _responsive|
73
+ metadata = nil
74
+ if validating_images?
75
+ next if @reject_invalid_images && image_validity(url) == false
76
+
77
+ metadata = image_metadata(url)
78
+ elsif @download_images
79
+ if data_image_url?(url)
80
+ metadata = image_metadata(url)
81
+ elsif http_image_url?(url) && (@max_image_downloads.nil? || attempts < @max_image_downloads)
82
+ attempts += 1
83
+ metadata = @image_downloader.metadata(encoded_url(url))
84
+ end
85
+ end
86
+ downloaded_width, downloaded_height = metadata && metadata[:dimensions]
87
+ width ||= downloaded_width
88
+ height ||= downloaded_height
89
+ { url: result_url(url), width: width.to_i, height: height.to_i,
90
+ type: metadata && metadata[:type], file_size: metadata && metadata[:file_size] }
91
+ end
92
+ images.sort_by { |image| -(image[:width] * image[:height]) }
93
+ end
94
+ end
95
+
63
96
  # Returns the largest image from the image collection,
64
97
  # filtered for images that are more square than 10:1 or 1:10
65
98
  def largest
@@ -67,7 +100,7 @@ module MetaInspector
67
100
  imgs_with_size = with_size.dup
68
101
  imgs_with_size.keep_if do |url, width, height|
69
102
  ratio = width.to_f / height.to_f
70
- ratio > 0.1 && ratio < 10
103
+ (@inline_image_data || !data_image_url?(url)) && ratio > 0.1 && ratio < 10
71
104
  end
72
105
  url, width, height = imgs_with_size.first
73
106
  url
@@ -76,25 +109,160 @@ module MetaInspector
76
109
 
77
110
  # Return favicon url if exist
78
111
  def favicon
79
- query = '//link[@rel="icon" or contains(@rel, "shortcut")]'
80
- value = parsed.xpath(query)[0].attributes['href'].value
81
- @favicon ||= URL.absolutify(value, base_url, normalize: false)
112
+ link = parsed.xpath('//link[@rel]').find do |node|
113
+ # Keep legacy shortcut-only links while matching whole, ASCII-insensitive tokens.
114
+ node['rel'].tr('A-Z', 'a-z').split(/[ \t\n\f\r]+/).any? { |rel| rel == 'icon' || rel == 'shortcut' }
115
+ end
116
+ value = link.attributes['href'].value
117
+ @favicon ||= result_url(URL.absolutify(value, base_url, normalize: false))
82
118
  rescue
83
119
  nil
84
120
  end
85
121
 
86
122
  private
87
123
 
124
+ def result_url(url)
125
+ return url if url.nil? || @inline_image_data || !data_image_url?(url)
126
+
127
+ url.split(',', 2).first
128
+ end
129
+
130
+ def suggested_image(skip_inline: false)
131
+ ['og:image', 'twitter:image', 'parsely-image-url'].each do |key|
132
+ value = content_of(meta[key])
133
+ next unless value
134
+
135
+ url = URL.absolutify(value, base_url, normalize: false)
136
+ next if url.nil? || (skip_inline && data_image_url?(url))
137
+ next if @download_images && @reject_invalid_images && image_validity(url) == false
138
+
139
+ return url
140
+ end
141
+ nil
142
+ end
143
+
144
+ def unique_image_candidates
145
+ candidates = {}
146
+ image_candidates.each do |url, width, height, responsive|
147
+ next if url.nil? || url.empty?
148
+
149
+ previous = candidates[url]
150
+ if previous.nil? || ((previous[1].nil? || previous[2].nil?) && width && height)
151
+ candidates[url] = [url, width, height, responsive]
152
+ end
153
+ end
154
+ candidates.values
155
+ end
156
+
88
157
  def images_collection
89
- @images_collection ||= absolutified_images
158
+ @images_collection ||= if @download_images && @reject_invalid_images
159
+ absolutified_images.reject { |url| url && image_validity(url) == false }.map { |url| result_url(url) }
160
+ else
161
+ absolutified_images.map { |url| result_url(url) }
162
+ end
163
+ end
164
+
165
+ def image_size(url)
166
+ return @image_sizes[url] if @image_sizes.key?(url)
167
+ return nil unless @download_images
168
+
169
+ if data_image_url?(url)
170
+ metadata = @image_downloader.inline_metadata(url)
171
+ @image_metadata[url] = metadata
172
+ return @image_sizes[url] = metadata && metadata[:dimensions]
173
+ end
174
+ return @image_sizes[url] = nil unless http_image_url?(url)
175
+ return nil unless @max_image_downloads.nil? || @download_attempts < @max_image_downloads
176
+
177
+ unless validating_images?
178
+ @download_attempts += 1
179
+ return @image_sizes[url] = @image_downloader.size(encoded_url(url))
180
+ end
181
+
182
+ request_url = encoded_url(url)
183
+ @download_attempts += 1
184
+ # Metadata comes from the same download and lets with_details reuse it.
185
+ metadata = @image_downloader.metadata(request_url, reject_invalid_url: true)
186
+ @image_metadata[url] = metadata
187
+ @image_sizes[url] = metadata && metadata[:dimensions]
188
+ end
189
+
190
+ def image_metadata(url)
191
+ image_size(url)
192
+ @image_metadata[url]
193
+ end
194
+
195
+ def validating_images?
196
+ @reject_invalid_images || @fetch_all_image_meta
197
+ end
198
+
199
+ # Normalizes non-ASCII URLs for the request; results keep the original.
200
+ # A URL that cannot be normalized is returned as is, so URL validation
201
+ # rejects it instead of Addressable raising.
202
+ def encoded_url(url)
203
+ url.ascii_only? ? url : URL.new(url).url
204
+ rescue StandardError
205
+ url
206
+ end
207
+
208
+ def image_validity(url)
209
+ image_size(url)
210
+ return nil unless @image_sizes.key?(url)
211
+
212
+ !@image_sizes[url].nil?
213
+ end
214
+
215
+ def data_image_url?(url)
216
+ url.match?(/\Adata:/i)
217
+ end
218
+
219
+ def http_image_url?(url)
220
+ URLPolicy.validate!(encoded_url(url))
221
+ true
222
+ rescue URLPolicy::InvalidURL
223
+ false
90
224
  end
91
225
 
92
226
  def absolutified_images
93
- parsed_images.map { |i| URL.absolutify(i, base_url, normalize: false) }
227
+ image_candidates.map(&:first).uniq
228
+ end
229
+
230
+ def image_candidates
231
+ @image_candidates ||= parsed.xpath('//img | //picture/source').flat_map do |node|
232
+ candidates = []
233
+ src = node['src'].to_s.strip if node.name == 'img'
234
+ candidates << [src, node['width'], node['height']] if src && !src.empty?
235
+ srcset_urls(node['srcset']).each { |url| candidates << [url, nil, nil, true] }
236
+ candidates.map do |url, width, height, responsive|
237
+ [URL.absolutify(url, base_url, normalize: false), width, height, responsive]
238
+ end
239
+ end
240
+ end
241
+
242
+ def srcset_urls(value)
243
+ scanner = StringScanner.new(value.to_s)
244
+ urls = []
245
+ until scanner.eos?
246
+ scanner.skip(/[\t\n\f\r ,]+/)
247
+ break if scanner.eos?
248
+
249
+ url = scanner.scan(/[^\t\n\f\r ]+/)
250
+ if url.end_with?(',')
251
+ url = url.sub(/,+\z/, '')
252
+ descriptor = ''
253
+ else
254
+ scanner.skip(/[\t\n\f\r ]+/)
255
+ descriptor = scanner.scan(/(?:[^,(]|\([^)]*(?:\)|\z))*/).strip
256
+ scanner.skip(/,/)
257
+ end
258
+ urls << url if !url.empty? && valid_srcset_descriptor?(descriptor)
259
+ end
260
+ urls
94
261
  end
95
262
 
96
- def parsed_images
97
- cleanup(parsed.search('//img/@src'))
263
+ def valid_srcset_descriptor?(descriptor)
264
+ descriptor.empty? || (descriptor.match?(/\A\d+w\z/) && descriptor.to_i > 0) ||
265
+ (descriptor.match?(/\A(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?x\z/) && descriptor.to_f >= 0)
98
266
  end
99
267
 
100
268
  def content_of(content)
@@ -64,7 +64,7 @@ module MetaInspector
64
64
  @description ||= meta['description']
65
65
  end
66
66
 
67
- # A description getter that returns the first non-nill description
67
+ # A description getter that returns the first non-blank description
68
68
  # from the following candidates:
69
69
  # - the standard meta description
70
70
  # - the og:description meta tag
@@ -119,7 +119,7 @@ module MetaInspector
119
119
  meta['twitter:description'],
120
120
  secondary_description
121
121
  ]
122
- candidates.find { |x| !x.to_s.empty? }
122
+ candidates.find { |x| !x.to_s.strip.empty? }
123
123
  end
124
124
 
125
125
  # Look for the first <p> block with 120 characters or more
@@ -1,6 +1,8 @@
1
1
  module MetaInspector
2
2
  # Runs inside redirect handling, before cache access or the network adapter.
3
3
  class URLPolicy < Faraday::Middleware
4
+ class InvalidURL < MetaInspector::RequestError; end
5
+
4
6
  class Failure < StandardError
5
7
  attr_reader :original
6
8
 
@@ -10,28 +12,43 @@ module MetaInspector
10
12
  end
11
13
  end
12
14
 
13
- IMAGE_HEADERS = %w[user-agent accept accept-language accept-encoding range].freeze
15
+ PAGE_HEADERS = %w[user-agent accept accept-language accept-encoding].freeze
16
+ IMAGE_HEADERS = (PAGE_HEADERS + %w[range]).freeze
14
17
 
15
18
  def self.validate!(value)
16
19
  uri = URI.parse(value.to_s)
17
20
  unless uri.is_a?(URI::HTTP) && uri.hostname && !uri.hostname.empty?
18
- raise MetaInspector::RequestError, 'URL must be HTTP or HTTPS'
21
+ raise InvalidURL, 'URL must be HTTP or HTTPS'
19
22
  end
20
23
  uri
21
24
  rescue URI::InvalidURIError => error
22
- raise MetaInspector::RequestError.new(error)
25
+ raise InvalidURL.new(error)
23
26
  end
24
27
 
25
- def initialize(app, filter, image_origin = nil)
28
+ def initialize(app, filter, image_origin = nil, request_origin: nil)
26
29
  super(app)
27
30
  @filter = filter
28
31
  @image_origin = image_origin && self.class.validate!(image_origin)
32
+ @request_origin = request_origin && self.class.validate!(request_origin)
33
+ @request_origin ||= @image_origin
34
+ @allowed_headers = @image_origin ? IMAGE_HEADERS : PAGE_HEADERS
29
35
  end
30
36
 
31
37
  def call(env)
32
38
  uri = self.class.validate!(env.url)
33
- if @image_origin && origin(uri) != origin(@image_origin)
34
- env.request_headers.delete_if { |key, _| !IMAGE_HEADERS.include?(key.downcase) }
39
+ cross_image_origin = @image_origin && origin(uri) != origin(@image_origin)
40
+ if cross_image_origin || (@request_origin && origin(uri) != origin(@request_origin))
41
+ env.request_headers.delete_if { |key, _| !@allowed_headers.include?(key.downcase) }
42
+ 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
35
52
  end
36
53
  check_filter(uri) if @filter
37
54
  @app.call(env)
@@ -1,3 +1,3 @@
1
1
  module MetaInspector
2
- VERSION = '5.20.0'
2
+ VERSION = '5.21.1'
3
3
  end
@@ -5,6 +5,7 @@ require File.expand_path(File.join(File.dirname(__FILE__), 'meta_inspector/url')
5
5
  require File.expand_path(File.join(File.dirname(__FILE__), 'meta_inspector/parser'))
6
6
  require File.expand_path(File.join(File.dirname(__FILE__), 'meta_inspector/parsers/base'))
7
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'))
8
9
  require File.expand_path(File.join(File.dirname(__FILE__), 'meta_inspector/parsers/links'))
9
10
  require File.expand_path(File.join(File.dirname(__FILE__), 'meta_inspector/parsers/head_links'))
10
11
  require File.expand_path(File.join(File.dirname(__FILE__), 'meta_inspector/parsers/meta_tags'))
@@ -24,6 +24,7 @@ Gem::Specification.new do |gem|
24
24
  gem.add_dependency 'faraday-http-cache', '>= 2.8', '< 4.0'
25
25
  gem.add_dependency 'faraday-retry', '~> 2.0'
26
26
  gem.add_dependency 'addressable', '~> 2.9.1'
27
+ gem.add_dependency 'base64', '~> 0.3'
27
28
  gem.add_dependency 'fastimage', '~> 2.2'
28
29
  gem.add_dependency 'nesty', '~> 1.0'
29
30
 
@@ -31,8 +32,6 @@ Gem::Specification.new do |gem|
31
32
  gem.add_development_dependency 'webmock', '~> 3.17'
32
33
  gem.add_development_dependency 'rake', '~> 13.0'
33
34
  gem.add_development_dependency 'pry', '~> 0.14'
34
- gem.add_development_dependency 'puma', '~> 8.0', '>= 8.0.2'
35
35
  gem.add_development_dependency 'rubocop', '~> 1.34'
36
36
  gem.add_development_dependency 'resolv', '~> 0.8'
37
- gem.add_development_dependency 'sinatra', '~> 4.2'
38
37
  end