metainspector 5.20.0 → 5.21.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 (40) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +16 -0
  3. data/Gemfile +1 -1
  4. data/README.md +147 -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 +11 -1
  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 +12 -2
  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/unicode_image_urls_spec.rb +74 -0
  38. data/spec/url_filter_spec.rb +1 -1
  39. metadata +27 -36
  40. data/examples/redirect_web_server.rb +0 -5
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: ba31ea21114c1932ca2dde179a2812f24d429b7420807fec232de65ea1ba824e
4
- data.tar.gz: 99188cbec093cfd1d22cdfd3d31bf181cf193e937f6c7b23a61cb6ed39ba1ca2
3
+ metadata.gz: 486be410cc1d8f68b50d6f61ed2bb158487e2461dfcdda8d2287647d447313c9
4
+ data.tar.gz: da722ae3063738ed07aa0287bfdb4102ba2c000ec9cf29d9b7b82e245b7e5f2e
5
5
  SHA512:
6
- metadata.gz: bc39e09f57cadd29f60e6a41556878d807a629e99de37b6b64b3ebf090d32aeca63d49b38af436fa16e5fff29e4cf5e927d99df5b37f35385ea30165a8de55e3
7
- data.tar.gz: d4a4777631f8c63d238236960148330a3dc7ba0f4ae2ec0b497cc3e03f33a5ca8daca05141dbaaa20a99a54fd933d5a5c9cb7056dd4b84b12c1a515119935574
6
+ metadata.gz: b5249e8927148dc832343679a72474ad8396772dfa00c4657c856406b88619897947cbcc3e2423b77a60b2585357f19a6519c0fe8b49abc88147fa8fba1fe80b
7
+ data.tar.gz: b2285a8dd0fb31f48c702b0623b40b93fbd5d626812074b761e25293f240b56685a97c8497570d0306b53222840927c3e020c11f953b73ef71aee064deb2ecbe
data/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # MetaInspector Changelog
2
2
 
3
+ ## [Changes in 5.21.0](https://github.com/jaimeiniesta/metainspector/compare/v5.20.0...v5.21.0)
4
+
5
+ * Restore working `page.feed` and `page.favicon` compatibility methods with deprecation warnings and removal scheduled for 6.0. `feed` returns the first RSS/Atom URL (or `nil`), and `favicon` returns `images.favicon`. Migrate to `page.feeds` and `page.images.favicon` (#547).
6
+ * Match favicon `rel` tokens case-insensitively across ASCII whitespace, including `alternate icon`, while rejecting unrelated substrings and retaining legacy `shortcut` links (#548).
7
+ * Match feed, stylesheet and canonical `rel` keywords case-insensitively within ASCII whitespace-separated token lists (#549).
8
+ * Skip whitespace-only metadata in `best_description` so later metadata and paragraph fallbacks are considered (#550).
9
+ * Example scripts run from any directory and are verified in the test suite. New examples for responsive images, image details, image validation, iframes and `max_html_bytes`; the unused redirect test server is removed (#538).
10
+ * Decode `data:` images locally and treat other unsupported image schemes as unknown without consuming the download budget; URL-filter rejections and redirects to unsupported schemes still raise (#544).
11
+ * Image results now omit `data:` URL payloads by default, including in `to_a` and `to_hash`. Set `inline_image_data: true` to retain full URLs; otherwise `best` and `largest` skip inline images (#545).
12
+ * Fix downloading and validating image URLs containing Unicode characters while preserving their original form (#536).
13
+ * Include responsive image candidates from `img[srcset]` and `picture source[srcset]`, alongside `img[src]`, with resolved, deduplicated URLs in document order. All candidates are included regardless of media conditions or device density; responsive candidates use downloaded dimensions for ranking (#269).
14
+ * Add opt-in image validation with `download_image_options: { reject_invalid_images: true }` to omit invalid collection and suggested images, allowing `images.best` to fall back to another image. Use `fetch_all_image_meta: true` and `images.with_metadata` for validity information without filtering. Both options respect download controls and share a cached validation budget; unchecked images retain unknown validity (#271).
15
+ * Add opt-in `max_html_bytes` to reject oversized HTML before parsing (#273).
16
+ * Add opt-in `images.with_details` to report image type and file size alongside dimensions (#268). When image validation is enabled, it reuses the validation lookups and, with `reject_invalid_images`, omits images that failed validation instead of raising for non-HTTP URLs. Validation now normalizes non-ASCII image URLs before requesting them, and URLs found invalid without a request no longer count toward `max_image_downloads` (#537).
17
+ * Add `iframes` to expose each iframe's original attributes, and `iframe_sources` to resolve their source URLs (#222).
18
+
3
19
  ## [Changes in 5.20.0](https://github.com/jaimeiniesta/metainspector/compare/v5.19.0...v5.20.0)
4
20
 
5
21
  * Security: route image size downloads through Faraday so they respect configured network and redirect controls. Add optional `url_filter:` to validate the initial page URL, HEAD requests, image URLs and every redirect destination before requesting them. Returning `false` or `nil` blocks the request with `MetaInspector::RequestError`; filter exceptions propagate. Only HTTP(S) requests are supported ([GHSA-6vgc-f9v5-8939](https://github.com/jaimeiniesta/metainspector/security/advisories/GHSA-6vgc-f9v5-8939)).
data/Gemfile CHANGED
@@ -1,4 +1,4 @@
1
- source "http://rubygems.org"
1
+ source "https://rubygems.org"
2
2
 
3
3
  # Specify your gem's dependencies in MetaInspector.gemspec
4
4
  gemspec
data/README.md CHANGED
@@ -81,6 +81,11 @@ page.canonicals # an array of hashes of all head/links where rel='canon
81
81
  page.feeds # Get rss or atom links in meta data fields as array of hash in the form { href: "...", title: "...", type: "..." }
82
82
  ```
83
83
 
84
+ `page.feed` is a deprecated compatibility method that returns the first RSS or
85
+ Atom feed's absolute URL, or `nil` if none is found. It skips JSON feeds. Each
86
+ call emits a deprecation warning. Use `page.feeds` instead; `page.feed` is
87
+ scheduled for removal in **6.0**.
88
+
84
89
  ### Texts
85
90
 
86
91
  ```ruby
@@ -127,17 +132,47 @@ page.links.external # every external link found on the page as an absolute
127
132
  ### Images
128
133
 
129
134
  ```ruby
130
- page.images # enumerable collection, with every img found on the page as an absolute URL
135
+ page.images # enumerable collection of image URLs found on the page
131
136
  page.images.with_size # a sorted array (by descending area) of [image_url, width, height]
137
+ page.images.with_details # image hashes with dimensions, type and file size (downloads images)
132
138
  page.images.best # Most relevant image from og:image, twitter:image, or parsely-image-url; falls back to page.images.largest
133
139
  page.images.favicon # absolute URL to the favicon
134
140
  ```
135
141
 
142
+ `page.favicon` is a deprecated shortcut for `page.images.favicon`, returning the
143
+ same URL or `nil`. Each call emits a deprecation warning. Use
144
+ `page.images.favicon` instead; `page.favicon` is scheduled for removal in **6.0**.
145
+
146
+ The collection includes `img[src]`, `img[srcset]`, and `source[srcset]` inside
147
+ `picture`, resolved to absolute URLs and deduplicated. Elements appear in document
148
+ order; for each `img`, `src` comes before its `srcset` candidates, which retain
149
+ their listed order. All candidates are included regardless of media conditions or
150
+ device density. Responsive candidates use their downloaded dimensions for ranking;
151
+ the `img` element's width and height apply only to its `src` fallback. By default,
152
+ non-HTTP responsive URLs remain in the collection but cannot be downloaded for sizing.
153
+
136
154
  `images.owner_suggested` tries `og:image`, `twitter:image`, and `parsely-image-url`
137
155
  in that order, skipping empty or whitespace-only values. Relative image URLs are
138
156
  resolved against the document's base URL. `images.best` uses this suggested image
139
157
  before falling back to the largest suitable image on the page.
140
158
 
159
+ ### Iframes
160
+
161
+ ```ruby
162
+ page.iframes # array of attribute hashes, one per iframe
163
+ page.iframe_sources # resolved source URLs, one per iframe
164
+ ```
165
+
166
+ Each hash contains the original attributes of an `<iframe>`, keyed by symbol;
167
+ for example, `src` remains as written and boolean attributes such as
168
+ `allowfullscreen` have an empty string value. HTML entities are decoded by the parser.
169
+ Both arrays follow document order and retain duplicates. `iframe_sources` strips
170
+ surrounding whitespace and resolves each `src` against the document's base URL
171
+ without normalizing it. It contains `nil` for a missing, blank, or unresolvable
172
+ source. These methods inspect iframe elements in the page; they do not download
173
+ or inspect the embedded documents. `to_hash['iframes']` contains the attribute
174
+ hashes.
175
+
141
176
  ### Meta tags
142
177
 
143
178
  When it comes to meta tags, you have several options:
@@ -297,6 +332,21 @@ You can specify 2 different timeouts when requesting a page:
297
332
 
298
333
  Both timeouts default to 20 seconds each.
299
334
 
335
+ These timeouts apply to fetching, not to parsing HTML. To avoid parsing large
336
+ documents, set `max_html_bytes` to a non-negative integer:
337
+
338
+ ```ruby
339
+ page = MetaInspector.new(url, max_html_bytes: 2 * 1024 * 1024)
340
+ ```
341
+
342
+ The default is `nil` (no limit). HTML larger than the limit raises
343
+ `MetaInspector::ParserError` before parsing, including HTML passed with the
344
+ `document` option. The limit is measured in bytes after fetching and processing
345
+ the response, so it does not limit download size or memory used for the response.
346
+ It also does not guarantee a parsing deadline: even a small document can be
347
+ slow to parse. Ruby's `Timeout.timeout` cannot reliably interrupt Nokogiri's
348
+ native parser; use a separately supervised process if a hard deadline is needed.
349
+
300
350
  You can also specify the number of `retries`, which defaults to 3.
301
351
 
302
352
  For example, this will time out after 10 seconds waiting for a connection, or after 5 seconds waiting
@@ -379,7 +429,7 @@ rescue MetaInspector::RequestError => error
379
429
  end
380
430
  ```
381
431
 
382
- Exceptions raised by your filter propagate to the caller. The filter is optional: MetaInspector does not block private IP addresses by default. It applies to outgoing requests, including image downloads from HTML passed with `document:`. Reading image URLs with `images.to_a` or `images.owner_suggested` does not download them or run the filter.
432
+ Exceptions raised by your filter propagate to the caller. The filter is optional: MetaInspector does not block private IP addresses by default. It applies to outgoing requests, including image downloads from HTML passed with `document:`. Reading image URLs with `images.to_a` or `images.owner_suggested` does not download them or run the filter unless invalid-image rejection is enabled.
383
433
 
384
434
  If your application accepts arbitrary hostnames, this example rejects addresses in private, loopback, link-local and unspecified ranges, including IPv4-mapped IPv6 addresses:
385
435
 
@@ -501,13 +551,38 @@ While this is generally useful, it can be [tricky](https://github.com/sporkmonge
501
551
 
502
552
  You can disable URL normalization by passing the `normalize_url: false` option.
503
553
 
554
+ ### Inline images
555
+
556
+ By default, image results replace each `data:` URL with its header before the comma,
557
+ for example `data:image/png;base64`. This applies to the image collection, image
558
+ metadata and size results, suggested images, favicon, and `to_hash`; raw `meta_tags`
559
+ are unchanged. Different inline images can have the same displayed header. `best`
560
+ and `largest` skip inline images when these placeholders are used.
561
+
562
+ Pass `inline_image_data: true` to return full data URLs and allow them to compete
563
+ for `best` and `largest`. Base64 and percent-encoded data images are decoded locally
564
+ for dimensions and metadata, without a network request or using the download budget.
565
+ `download_images: false` disables these lookups too.
566
+
504
567
  ### Image downloading
505
568
 
506
569
  Image downloading is enabled by default. `page.images.with_size` and `page.images.largest` fetch images with missing HTML dimensions; `page.images.best` also does this when there is no preferred metadata image. The page controls these image URLs, which may point to other hosts.
507
570
 
508
571
  Image requests use Faraday with the page's proxy, TLS, headers and redirect settings, and respect [`url_filter:`](#filtering-request-urls). Downloaded bytes are passed to [fastimage](https://github.com/sdsykes/fastimage) to determine dimensions. Dimensions already present in HTML are preserved without downloading the image.
509
572
 
510
- Custom page headers are preserved for images on the same origin (scheme, host and port). Requests to other origins, including image redirects, send only standard image request headers such as `User-Agent` and `Accept`; they do not receive page credentials or arbitrary custom headers.
573
+ To opt in to image type and file size, use:
574
+
575
+ ```ruby
576
+ page.images.with_details
577
+ # => [{ url: "https://example.com/photo.png", width: 640, height: 480,
578
+ # type: :png, file_size: 12345 }]
579
+ ```
580
+
581
+ The array is sorted by descending image area and contains one entry per valid, unique image URL. `type` is a FastImage symbol, or `nil` if it cannot be identified. `file_size` is the total in bytes: the `Content-Length` of an unencoded 200 response, the total in a 206 `Content-Range`, or the byte count of a fully downloaded unencoded 200 response without a `Content-Length`. It is `nil` when the total is unavailable; a partial download's byte count is never used as the total. Servers can report inaccurate lengths. Failed requests return `nil` for both fields; URL policy errors still propagate. Each HTML dimension is preserved when present; a missing dimension is obtained from the image or becomes zero if it cannot be determined.
582
+
583
+ Metadata lookup attempts downloads even when HTML dimensions are present, subject to `download_images`, `max_image_downloads`, and the same request restrictions and byte/time limits described below. The limit counts attempts in HTML order, including failures. Results are cached separately from `with_size`; calling both methods can download an image twice and each method applies the limit independently. When `reject_invalid_images` or `fetch_all_image_meta` is enabled, `with_details` reuses the validation lookups instead, as described below.
584
+
585
+ Custom page headers are preserved for images on the same origin (scheme, host and port). Requests to other origins, including image redirects, send only standard image request headers such as `User-Agent` and `Accept`; they do not receive page credentials or arbitrary custom headers. They also send a `Referer` containing only the page origin, except when an HTTPS page requests an HTTP image. The page path, query, fragment and credentials are never included in this cross-origin `Referer`.
511
586
 
512
587
  Each size lookup stops at a 256 KiB response body budget or a two-second overall timeout, including redirects. If the dimensions cannot be determined within these limits, they remain `[0, 0]`. Streamed image responses are not stored in the HTTP response cache, and failed image requests are not retried.
513
588
 
@@ -526,9 +601,57 @@ page.images.with_size
526
601
 
527
602
  The default is `nil` (unlimited). The option accepts a non-negative integer or `nil`; `0` disables image downloads. `download_images: false` always disables downloads, regardless of the limit.
528
603
 
529
- The limit counts image size lookup attempts in HTML order, after excluding unparseable URLs and duplicates. Images with both HTML dimensions already present do not consume the limit, and those dimensions are preserved even after the limit is reached. Failed lookups count toward the limit. Images with incomplete dimensions that are not downloaded remain in `images.with_size` with dimensions `[0, 0]`, matching the behavior when downloads are disabled.
604
+ By default, the limit counts image size lookup attempts in HTML order, after excluding unparseable URLs and duplicates. Images with both HTML dimensions already present do not consume the limit, and those dimensions are preserved even after the limit is reached. Failed lookups count toward the limit. Images with incomplete dimensions that are not downloaded remain in `images.with_size` with dimensions `[0, 0]`, matching the behavior when downloads are disabled.
605
+
606
+ By default, the limit leaves `images.to_a` unchanged, but can affect `images.largest` and the largest-image fallback in `images.best`, since images with unknown dimensions cannot be ranked by size. Size lookup results are cached per document, so repeated calls reuse the same results. This limits size lookup attempts, not elapsed time or HTTP requests made while following image redirects.
607
+
608
+ To discard images that cannot be read by FastImage, opt in to validation:
609
+
610
+ ```ruby
611
+ page = MetaInspector.new('http://example.com',
612
+ download_image_options: { reject_invalid_images: true })
613
+ page.images.to_a # excludes images that failed validation
614
+ page.images.owner_suggested # first suggested image that has not failed validation
615
+ page.images.best # falls back to another suggested or page image
616
+ ```
617
+
618
+ Validation downloads images even when HTML dimensions are present. It applies to
619
+ the image collection, `with_size`, `with_details`, and suggested images; it does
620
+ not validate the favicon. A failed HTTP request, an unsuccessful response, or a
621
+ response whose dimensions FastImage cannot determine is invalid. An image URL that
622
+ uses an unsupported scheme is invalid without a request. Valid `data:` images are decoded locally. URLs
623
+ with non-ASCII characters are normalized before the request; results keep the
624
+ original URL. This is a bounded image-header check, not a guarantee that the
625
+ entire image can be downloaded or decoded.
530
626
 
531
- The limit leaves `images.to_a` unchanged, but can affect `images.largest` and the largest-image fallback in `images.best`, since images with unknown dimensions cannot be ranked by size. Size lookup results are cached per document, so repeated calls reuse the same results. This limits size lookup attempts, not elapsed time or HTTP requests made while following image redirects.
627
+ For validity information without filtering the collection, enable
628
+ `fetch_all_image_meta` and call `with_metadata`:
629
+
630
+ ```ruby
631
+ page = MetaInspector.new('http://example.com', fetch_all_image_meta: true)
632
+ page.images.with_metadata # [{ url: 'http://example.com/image.png', valid: true }, ...]
633
+ ```
634
+
635
+ Metadata follows the original image collection order and includes invalid entries,
636
+ even when rejection is also enabled. Duplicate `src` values are removed before URLs
637
+ are resolved. `valid` is `true` or `false`
638
+ for a lookup that was attempted, and `nil` when no lookup was made (including an
639
+ unresolvable URL). Without `fetch_all_image_meta`, `with_metadata` does not initiate
640
+ validation and returns `nil` validity values.
641
+
642
+ Both options respect `download_images: false` and `max_image_downloads`. Images
643
+ that cannot be checked because downloads are disabled or the HTTP budget is exhausted
644
+ are retained, with unknown validity. Local data images and URLs found invalid without
645
+ a request do not count toward the limit. Suggested images and collection images share
646
+ the budget in the order they are first queried; repeated URLs reuse their results.
647
+ Consequently the order of API calls can affect which images are checked when a
648
+ limit is set. URL filter errors still propagate to the caller.
649
+
650
+ With either option, `with_details` takes type and file size from these validation
651
+ lookups, so each image is downloaded at most once and shares the same budget.
652
+ Unsupported image URL schemes get `nil` metadata instead of raising; redirects to unsupported schemes still raise. With
653
+ `reject_invalid_images`, `with_details` omits images that failed validation, like
654
+ `with_size`; images that were not checked are kept with `nil` type and file size.
532
655
 
533
656
  ### Caching responses
534
657
 
@@ -552,7 +675,25 @@ Web page scraping is tricky, you can expect to find different exceptions during
552
675
 
553
676
  ## Examples
554
677
 
555
- You can find some sample scripts on the `examples` folder, including a basic scraping and a spider that will follow external links using a queue. What follows is an example of use from irb:
678
+ Runnable sample scripts live in `examples/`. From the repository root, pass the URL as an argument:
679
+
680
+ ```sh
681
+ bundle exec ruby examples/basic_scraping.rb https://example.com
682
+ ```
683
+
684
+ You can also run them from inside `examples/`, for example `bundle exec ruby basic_scraping.rb https://example.com`. If no URL is supplied, the scripts prompt for one, except `faraday_redirect_options.rb`, which defaults to `https://example.com`.
685
+
686
+ * `basic_scraping.rb`: prints the page title, metadata and links, plus the page data as JSON.
687
+ * `spider.rb`: follows internal links using a queue and lists the pages visited.
688
+ * `link_checker.rb`: checks linked pages and reports broken links with their origin.
689
+ * `faraday_redirect_options.rb`: restricts requests to allowed HTTPS hosts with `url_filter:` and logs redirects with a callback.
690
+ * `responsive_images.rb`: lists `img[src]`, `img[srcset]` and `picture source[srcset]` candidates, plus the best image.
691
+ * `image_details.rb <url> [max_downloads]`: prints dimensions, type and file size, largest first; image downloads default to a limit of 10.
692
+ * `image_validation.rb <url> [max_downloads]`: reports image validity, filters invalid candidates and prints the best image; image downloads default to a limit of 10, with remaining images reported as not checked.
693
+ * `iframes.rb`: lists iframe attributes and resolved source URLs without downloading embedded documents.
694
+ * `html_size_limit.rb <url> [max_bytes]`: skips HTML over the byte limit (default: 2 MiB). The limit applies after download and does not bound parse time.
695
+
696
+ What follows is an example of use from irb:
556
697
 
557
698
  ```ruby
558
699
  $ irb
@@ -2,9 +2,10 @@
2
2
  #
3
3
  # Usage example:
4
4
  #
5
- # ruby basic_scraping.rb jaimeiniesta.com
5
+ # bundle exec ruby examples/basic_scraping.rb jaimeiniesta.com
6
6
 
7
- require '../lib/metainspector'
7
+ require 'json'
8
+ require_relative '../lib/metainspector'
8
9
  puts "Using MetaInspector #{MetaInspector::VERSION}"
9
10
 
10
11
  # Get the starting URL
@@ -33,4 +34,4 @@ page.links.non_http.each do |link|
33
34
  end
34
35
 
35
36
  puts "\nto_hash..."
36
- puts page.to_hash
37
+ puts JSON.pretty_generate(page.to_hash)
@@ -1,42 +1,34 @@
1
- # A MetaInspector example that runs a callback in between redirects.
2
- # The callback raises an exception if the redirection points to a URL that resolves into a private IP address.
3
- # This is one way of triggering a known security exploit called server-side request forgery (SSRF).
1
+ # Allow only explicitly trusted HTTPS hosts, including on redirects and image
2
+ # requests. A redirect callback can also observe redirects, but it is not a
3
+ # substitute for url_filter: it does not check the initial request.
4
4
  #
5
- # To properly run this example you need a server which redirects to a service like nip.io.
6
- # The easiest way to achieve that is running the examples/redirect_web_server.rb server in one terminal window,
7
- # and calling its address with this example in another terminal window.
5
+ # Usage from the repository root:
6
+ # bundle exec ruby examples/faraday_redirect_options.rb https://example.com
8
7
  #
9
- # Usage example:
10
- # In terminal #1:
11
- # ruby redirect_web_server.rb
12
- #
13
- # In terminal #2:
14
- # ruby faraday_redirect_options.rb http://127.0.0.1:4567
8
+ # Choose hosts under your control for your application. A hostname allowlist
9
+ # alone does not prevent DNS rebinding or compromised DNS; use network egress
10
+ # restrictions as well when processing untrusted URLs.
11
+
12
+ require_relative '../lib/metainspector'
15
13
 
16
- require 'resolv'
17
- require '../lib/metainspector'
18
- puts "Using MetaInspector #{MetaInspector::VERSION}"
14
+ url = ARGV[0] || 'https://example.com'
15
+ allowed_hosts = %w[example.com www.example.com]
19
16
 
20
- # Get the starting URL
21
- url = ARGV[0] || (puts "Enter an url"; gets.strip)
17
+ filter = proc do |uri|
18
+ uri.scheme == 'https' && allowed_hosts.include?(uri.hostname)
19
+ end
22
20
 
23
- # redirect options to be passed along to Faraday::FollowRedirects::Middleware
24
- redirects_opts = {
21
+ redirect_options = {
25
22
  limit: 5,
26
- callback: proc do |_old_response, new_response|
27
- ip_address = Resolv.getaddress(new_response.url.host)
28
- raise 'Invalid address' if IPAddr.new(ip_address).private?
23
+ callback: proc do |old_response, new_request|
24
+ puts "Redirect: #{old_response.url} -> #{new_request.url}"
29
25
  end
30
26
  }
31
27
 
32
28
  begin
33
- page = MetaInspector.new(url, faraday_options: { redirect: redirects_opts })
34
- rescue StandardError => e
35
- puts e.message
36
- else
37
- puts "\nScraping #{page.url} returned these results:"
38
- puts "\nTITLE: #{page.title}"
39
-
40
- puts "\nto_hash..."
41
- puts page.to_hash
29
+ page = MetaInspector.new(url, url_filter: filter, faraday_options: { redirect: redirect_options })
30
+ puts "Using MetaInspector #{MetaInspector::VERSION}"
31
+ puts "Scraping #{page.url} returned title: #{page.title}"
32
+ rescue MetaInspector::RequestError => error
33
+ warn error.message
42
34
  end
@@ -0,0 +1,17 @@
1
+ # Skip HTML larger than max_bytes (default: 2 MiB).
2
+ # The limit applies after download and does not bound parse time.
3
+ #
4
+ # Usage from the repository root:
5
+ # bundle exec ruby examples/html_size_limit.rb <url> [max_bytes]
6
+
7
+ require_relative '../lib/metainspector'
8
+
9
+ url = ARGV[0] || (puts "Enter a url"; gets.strip)
10
+ max_bytes = Integer(ARGV[1] || 2 * 1024 * 1024)
11
+
12
+ begin
13
+ page = MetaInspector.new(url, max_html_bytes: max_bytes)
14
+ puts "TITLE: #{page.title}"
15
+ rescue MetaInspector::ParserError => error
16
+ puts "Skipped: #{error.message}"
17
+ end
@@ -0,0 +1,15 @@
1
+ # List iframe attributes and resolved source URLs. Embedded documents are not downloaded.
2
+ #
3
+ # Usage from the repository root:
4
+ # bundle exec ruby examples/iframes.rb <url>
5
+
6
+ require_relative '../lib/metainspector'
7
+
8
+ url = ARGV[0] || (puts "Enter a url"; gets.strip)
9
+ page = MetaInspector.new(url)
10
+
11
+ puts "#{page.iframes.size} iframes found..."
12
+ page.iframes.zip(page.iframe_sources).each do |attributes, source|
13
+ puts " ==> #{source || '(no source)'}"
14
+ puts attributes.map { |name, value| "#{name}=#{value.inspect}" }.join(' ')
15
+ end
@@ -0,0 +1,17 @@
1
+ # Download images to report dimensions, type and file size, largest first.
2
+ # Image downloads are bounded by max_downloads (default: 10).
3
+ #
4
+ # Usage from the repository root:
5
+ # bundle exec ruby examples/image_details.rb <url> [max_downloads]
6
+
7
+ require_relative '../lib/metainspector'
8
+
9
+ url = ARGV[0] || (puts "Enter a url"; gets.strip)
10
+ max_downloads = Integer(ARGV[1] || 10)
11
+ page = MetaInspector.new(url, max_image_downloads: max_downloads)
12
+
13
+ page.images.with_details.each do |image|
14
+ type = image[:type] || 'unknown type'
15
+ size = image[:file_size] ? "#{image[:file_size]} bytes" : 'unknown size'
16
+ puts "#{image[:url]} #{image[:width]}x#{image[:height]} #{type}, #{size}"
17
+ end
@@ -0,0 +1,25 @@
1
+ # Validate image candidates and omit invalid images from the results.
2
+ # Image downloads are bounded by max_downloads (default: 10); images beyond
3
+ # the limit remain in the results and are reported as not checked.
4
+ #
5
+ # Usage from the repository root:
6
+ # bundle exec ruby examples/image_validation.rb <url> [max_downloads]
7
+
8
+ require_relative '../lib/metainspector'
9
+
10
+ VALIDITY = { true => 'valid', false => 'invalid', nil => 'not checked' }.freeze
11
+
12
+ url = ARGV[0] || (puts "Enter a url"; gets.strip)
13
+ max_downloads = Integer(ARGV[1] || 10)
14
+ page = MetaInspector.new(url, max_image_downloads: max_downloads,
15
+ download_image_options: { reject_invalid_images: true }, fetch_all_image_meta: true)
16
+
17
+ page.images.with_metadata.each do |image|
18
+ puts " ==> #{image[:url]}: #{VALIDITY[image[:valid]]}"
19
+ end
20
+
21
+ puts "#{page.images.to_a.size} images remain after validation..."
22
+ page.images.to_a.each do |image|
23
+ puts " ==> #{image}"
24
+ end
25
+ puts "BEST: #{page.images.best}"
@@ -2,9 +2,9 @@
2
2
  #
3
3
  # Usage example:
4
4
  #
5
- # ruby link_checker.rb example.com
5
+ # bundle exec ruby examples/link_checker.rb example.com
6
6
 
7
- require '../lib/metainspector'
7
+ require_relative '../lib/metainspector'
8
8
  puts "Using MetaInspector #{MetaInspector::VERSION}"
9
9
 
10
10
  class BrokenLinkChecker
@@ -0,0 +1,15 @@
1
+ # List image candidates from img[src], img[srcset] and picture source[srcset].
2
+ #
3
+ # Usage from the repository root:
4
+ # bundle exec ruby examples/responsive_images.rb <url>
5
+
6
+ require_relative '../lib/metainspector'
7
+
8
+ url = ARGV[0] || (puts "Enter a url"; gets.strip)
9
+ page = MetaInspector.new(url)
10
+
11
+ puts "#{page.images.to_a.size} image candidates found..."
12
+ page.images.to_a.each do |image|
13
+ puts " ==> #{image}"
14
+ end
15
+ puts "BEST: #{page.images.best}"
data/examples/spider.rb CHANGED
@@ -2,9 +2,9 @@
2
2
  #
3
3
  # Usage example:
4
4
  #
5
- # ruby spider.rb example.com
5
+ # bundle exec ruby examples/spider.rb example.com
6
6
 
7
- require '../lib/metainspector'
7
+ require_relative '../lib/metainspector'
8
8
  puts "Using MetaInspector #{MetaInspector::VERSION}"
9
9
 
10
10
  # Two arrays, one for the scraping queue and one for the visited links
@@ -15,12 +15,20 @@ module MetaInspector
15
15
  # * normalize_url: true by default
16
16
  # * download_images: fetch missing image dimensions. Defaults to true
17
17
  # * max_image_downloads: maximum image size lookups, or nil for unlimited
18
+ # * download_image_options: supports reject_invalid_images (default false)
19
+ # * inline_image_data: return full data URLs in image results (default false)
20
+ # * fetch_all_image_meta: enable image validity metadata (default false)
21
+ # * max_html_bytes: maximum HTML size before parsing, or nil for unlimited
18
22
  # * url_filter: callable receiving a URI before each request; false/nil rejects it
19
23
  # * faraday_options: an optional hash of options to pass to Faraday on the request.
20
24
  # Its faraday_http_cache key configures response caching with Faraday::HttpCache
21
25
  # * faraday_http_cache: deprecated, use faraday_options: { faraday_http_cache: ... }
22
26
  def initialize(initial_url, options = {})
23
27
  options = defaults.merge(options)
28
+ max_html_bytes = options[:max_html_bytes]
29
+ unless max_html_bytes.nil? || (max_html_bytes.is_a?(Integer) && max_html_bytes >= 0)
30
+ raise ArgumentError, 'max_html_bytes must be a non-negative Integer or nil'
31
+ end
24
32
  @max_image_downloads = options[:max_image_downloads]
25
33
  unless @max_image_downloads.nil? || (@max_image_downloads.is_a?(Integer) && @max_image_downloads >= 0)
26
34
  raise ArgumentError, 'max_image_downloads must be a non-negative Integer or nil'
@@ -54,7 +62,11 @@ module MetaInspector
54
62
  faraday_options: @faraday_options,
55
63
  faraday_http_cache: @faraday_http_cache) unless @document
56
64
  @parser = MetaInspector::Parser.new(self, download_images: @download_images,
65
+ max_html_bytes: max_html_bytes,
57
66
  max_image_downloads: @max_image_downloads,
67
+ download_image_options: options[:download_image_options],
68
+ fetch_all_image_meta: options[:fetch_all_image_meta],
69
+ inline_image_data: options[:inline_image_data],
58
70
  image_downloader: MetaInspector::ImageDownloader.new(@http_session, @url, options))
59
71
  end
60
72
 
@@ -66,7 +78,7 @@ module MetaInspector
66
78
 
67
79
  delegate [:parsed, :language, :title, :best_title, :author, :best_author,
68
80
  :h1, :h2, :h3, :h4, :h5, :h6, :description, :best_description, :links,
69
- :images, :feeds, :feed, :charset, :meta_tags,
81
+ :images, :iframes, :iframe_sources, :feeds, :feed, :charset, :meta_tags,
70
82
  :meta_tag, :meta, :favicon,
71
83
  :head_links, :stylesheets, :canonicals] => :@parser
72
84
 
@@ -92,6 +104,7 @@ module MetaInspector
92
104
  'h6' => h6,
93
105
  'links' => links.to_hash,
94
106
  'images' => images.to_a,
107
+ 'iframes' => iframes,
95
108
  'charset' => charset,
96
109
  'feeds' => feeds,
97
110
  'content_type' => content_type,
@@ -23,10 +23,20 @@ module MetaInspector
23
23
  @faraday_options = (options[:faraday_options] || {}).except(:faraday_http_cache)
24
24
  end
25
25
 
26
- def build(url, image: false, origin: nil)
26
+ def build(url, image: false, origin: nil, protect_redirect_callback: false)
27
27
  URLPolicy.validate!(url)
28
28
  faraday_options = @faraday_options.merge(url: url)
29
29
  redirects = (faraday_options.delete(:redirect) || {}).dup
30
+ if protect_redirect_callback && redirects[:callback]
31
+ callback = redirects[:callback]
32
+ redirects[:callback] = lambda do |*args|
33
+ begin
34
+ callback.call(*args)
35
+ rescue StandardError => error
36
+ raise URLPolicy::Failure.new(error)
37
+ end
38
+ end
39
+ end
30
40
  Faraday.new(faraday_options) do |faraday|
31
41
  unless image
32
42
  faraday.request :retry, max: @retries
@@ -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