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
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: ba31ea21114c1932ca2dde179a2812f24d429b7420807fec232de65ea1ba824e
4
- data.tar.gz: 99188cbec093cfd1d22cdfd3d31bf181cf193e937f6c7b23a61cb6ed39ba1ca2
3
+ metadata.gz: e84dae185b72b0ea7bec6e573db063bf2a0fe3632d978222f2c00cb2a0111075
4
+ data.tar.gz: 48799a4f6609282828b6161a4333231e0a0d0d762916fedf5e1ab854dc19e074
5
5
  SHA512:
6
- metadata.gz: bc39e09f57cadd29f60e6a41556878d807a629e99de37b6b64b3ebf090d32aeca63d49b38af436fa16e5fff29e4cf5e927d99df5b37f35385ea30165a8de55e3
7
- data.tar.gz: d4a4777631f8c63d238236960148330a3dc7ba0f4ae2ec0b497cc3e03f33a5ca8daca05141dbaaa20a99a54fd933d5a5c9cb7056dd4b84b12c1a515119935574
6
+ metadata.gz: 7af14afd571dc86d85a04e88a85a81b1386919a2b156a40ce5c57d59b4ec7084f9af4a40def4158797530ddeb99aca0406a628bf1f17c1d65dfb3761c3a5108f
7
+ data.tar.gz: e11c0c31565f180b1df73e4c291d4f1840dc1c7be48bbfe7b9507cda3383a593b0412a158edda73099288a7f4d0b3acd28b4b7764fdb21292f00bc9345aae134
data/CHANGELOG.md CHANGED
@@ -1,5 +1,25 @@
1
1
  # MetaInspector Changelog
2
2
 
3
+ ## [Changes in 5.21.1](https://github.com/jaimeiniesta/metainspector/compare/v5.21.0...v5.21.1)
4
+
5
+ * Security: forward only `User-Agent`, `Accept`, `Accept-Language` and `Accept-Encoding` when page redirects change the origin (scheme, host or port), preventing custom credentials from reaching another origin. Apply the policy to GET and HEAD, including headers supplied through `faraday_options`, and keep the initial credentials out of image requests on the redirected origin. Custom headers remain available within the initial origin ([GHSA-mcmp-j8cq-h65f](https://github.com/jaimeiniesta/metainspector/security/advisories/GHSA-mcmp-j8cq-h65f)).
6
+
7
+ ## [Changes in 5.21.0](https://github.com/jaimeiniesta/metainspector/compare/v5.20.0...v5.21.0)
8
+
9
+ * 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).
10
+ * Match favicon `rel` tokens case-insensitively across ASCII whitespace, including `alternate icon`, while rejecting unrelated substrings and retaining legacy `shortcut` links (#548).
11
+ * Match feed, stylesheet and canonical `rel` keywords case-insensitively within ASCII whitespace-separated token lists (#549).
12
+ * Skip whitespace-only metadata in `best_description` so later metadata and paragraph fallbacks are considered (#550).
13
+ * 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).
14
+ * 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).
15
+ * 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).
16
+ * Fix downloading and validating image URLs containing Unicode characters while preserving their original form (#536).
17
+ * 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).
18
+ * 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).
19
+ * Add opt-in `max_html_bytes` to reject oversized HTML before parsing (#273).
20
+ * 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).
21
+ * Add `iframes` to expose each iframe's original attributes, and `iframe_sources` to resolve their source URLs (#222).
22
+
3
23
  ## [Changes in 5.20.0](https://github.com/jaimeiniesta/metainspector/compare/v5.19.0...v5.20.0)
4
24
 
5
25
  * 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
@@ -325,6 +375,14 @@ end
325
375
 
326
376
  By default, MetaInspector will follow redirects (up to a limit of 10).
327
377
 
378
+ Custom headers are retained only on the initial page origin (scheme, host and port).
379
+ For redirects to a different origin, including subdomains, different ports and
380
+ HTTPS-to-HTTP redirects, only `User-Agent`, `Accept`, `Accept-Language` and
381
+ `Accept-Encoding` are forwarded. This applies to GET and HEAD requests and to
382
+ headers supplied through either `headers:` or `faraday_options[:headers]`.
383
+ Credentials from the initial request are also withheld from images on a redirected
384
+ page at a different origin. Image requests retain their generated `Range` header.
385
+
328
386
  If you want to disallow redirects, you can do it like this:
329
387
 
330
388
  ```ruby
@@ -350,6 +408,8 @@ page = MetaInspector.new(url, faraday_options: { redirect: { callback: callback
350
408
 
351
409
  The `faraday_options[:redirect]` hash is passed to the `FollowRedirects` middleware used by `Faraday`, so that we can use all available options.
352
410
  Check them [here](https://github.com/lostisland/faraday_middleware/blob/main/lib/faraday_middleware/response/follow_redirects.rb#L44).
411
+ The origin header policy also applies after your redirect callback runs and when
412
+ `clear_authorization_header: false` is set.
353
413
 
354
414
  ### Filtering request URLs
355
415
 
@@ -379,7 +439,7 @@ rescue MetaInspector::RequestError => error
379
439
  end
380
440
  ```
381
441
 
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.
442
+ 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
443
 
384
444
  If your application accepts arbitrary hostnames, this example rejects addresses in private, loopback, link-local and unspecified ranges, including IPv4-mapped IPv6 addresses:
385
445
 
@@ -501,13 +561,38 @@ While this is generally useful, it can be [tricky](https://github.com/sporkmonge
501
561
 
502
562
  You can disable URL normalization by passing the `normalize_url: false` option.
503
563
 
564
+ ### Inline images
565
+
566
+ By default, image results replace each `data:` URL with its header before the comma,
567
+ for example `data:image/png;base64`. This applies to the image collection, image
568
+ metadata and size results, suggested images, favicon, and `to_hash`; raw `meta_tags`
569
+ are unchanged. Different inline images can have the same displayed header. `best`
570
+ and `largest` skip inline images when these placeholders are used.
571
+
572
+ Pass `inline_image_data: true` to return full data URLs and allow them to compete
573
+ for `best` and `largest`. Base64 and percent-encoded data images are decoded locally
574
+ for dimensions and metadata, without a network request or using the download budget.
575
+ `download_images: false` disables these lookups too.
576
+
504
577
  ### Image downloading
505
578
 
506
579
  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
580
 
508
581
  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
582
 
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.
583
+ To opt in to image type and file size, use:
584
+
585
+ ```ruby
586
+ page.images.with_details
587
+ # => [{ url: "https://example.com/photo.png", width: 640, height: 480,
588
+ # type: :png, file_size: 12345 }]
589
+ ```
590
+
591
+ 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.
592
+
593
+ 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.
594
+
595
+ 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
596
 
512
597
  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
598
 
@@ -526,9 +611,57 @@ page.images.with_size
526
611
 
527
612
  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
613
 
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.
614
+ 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.
615
+
616
+ 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.
617
+
618
+ To discard images that cannot be read by FastImage, opt in to validation:
619
+
620
+ ```ruby
621
+ page = MetaInspector.new('http://example.com',
622
+ download_image_options: { reject_invalid_images: true })
623
+ page.images.to_a # excludes images that failed validation
624
+ page.images.owner_suggested # first suggested image that has not failed validation
625
+ page.images.best # falls back to another suggested or page image
626
+ ```
627
+
628
+ Validation downloads images even when HTML dimensions are present. It applies to
629
+ the image collection, `with_size`, `with_details`, and suggested images; it does
630
+ not validate the favicon. A failed HTTP request, an unsuccessful response, or a
631
+ response whose dimensions FastImage cannot determine is invalid. An image URL that
632
+ uses an unsupported scheme is invalid without a request. Valid `data:` images are decoded locally. URLs
633
+ with non-ASCII characters are normalized before the request; results keep the
634
+ original URL. This is a bounded image-header check, not a guarantee that the
635
+ entire image can be downloaded or decoded.
636
+
637
+ For validity information without filtering the collection, enable
638
+ `fetch_all_image_meta` and call `with_metadata`:
530
639
 
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.
640
+ ```ruby
641
+ page = MetaInspector.new('http://example.com', fetch_all_image_meta: true)
642
+ page.images.with_metadata # [{ url: 'http://example.com/image.png', valid: true }, ...]
643
+ ```
644
+
645
+ Metadata follows the original image collection order and includes invalid entries,
646
+ even when rejection is also enabled. Duplicate `src` values are removed before URLs
647
+ are resolved. `valid` is `true` or `false`
648
+ for a lookup that was attempted, and `nil` when no lookup was made (including an
649
+ unresolvable URL). Without `fetch_all_image_meta`, `with_metadata` does not initiate
650
+ validation and returns `nil` validity values.
651
+
652
+ Both options respect `download_images: false` and `max_image_downloads`. Images
653
+ that cannot be checked because downloads are disabled or the HTTP budget is exhausted
654
+ are retained, with unknown validity. Local data images and URLs found invalid without
655
+ a request do not count toward the limit. Suggested images and collection images share
656
+ the budget in the order they are first queried; repeated URLs reuse their results.
657
+ Consequently the order of API calls can affect which images are checked when a
658
+ limit is set. URL filter errors still propagate to the caller.
659
+
660
+ With either option, `with_details` takes type and file size from these validation
661
+ lookups, so each image is downloaded at most once and shares the same budget.
662
+ Unsupported image URL schemes get `nil` metadata instead of raising; redirects to unsupported schemes still raise. With
663
+ `reject_invalid_images`, `with_details` omits images that failed validation, like
664
+ `with_size`; images that were not checked are kept with `nil` type and file size.
532
665
 
533
666
  ### Caching responses
534
667
 
@@ -552,7 +685,25 @@ Web page scraping is tricky, you can expect to find different exceptions during
552
685
 
553
686
  ## Examples
554
687
 
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:
688
+ Runnable sample scripts live in `examples/`. From the repository root, pass the URL as an argument:
689
+
690
+ ```sh
691
+ bundle exec ruby examples/basic_scraping.rb https://example.com
692
+ ```
693
+
694
+ 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`.
695
+
696
+ * `basic_scraping.rb`: prints the page title, metadata and links, plus the page data as JSON.
697
+ * `spider.rb`: follows internal links using a queue and lists the pages visited.
698
+ * `link_checker.rb`: checks linked pages and reports broken links with their origin.
699
+ * `faraday_redirect_options.rb`: restricts requests to allowed HTTPS hosts with `url_filter:` and logs redirects with a callback.
700
+ * `responsive_images.rb`: lists `img[src]`, `img[srcset]` and `picture source[srcset]` candidates, plus the best image.
701
+ * `image_details.rb <url> [max_downloads]`: prints dimensions, type and file size, largest first; image downloads default to a limit of 10.
702
+ * `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.
703
+ * `iframes.rb`: lists iframe attributes and resolved source URLs without downloading embedded documents.
704
+ * `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.
705
+
706
+ What follows is an example of use from irb:
556
707
 
557
708
  ```ruby
558
709
  $ 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,22 @@ 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
+ # Image requests must keep trusting the initial origin after page redirects.
29
+ @page_origin ||= url.to_s unless image
28
30
  faraday_options = @faraday_options.merge(url: url)
29
31
  redirects = (faraday_options.delete(:redirect) || {}).dup
32
+ if protect_redirect_callback && redirects[:callback]
33
+ callback = redirects[:callback]
34
+ redirects[:callback] = lambda do |*args|
35
+ begin
36
+ callback.call(*args)
37
+ rescue StandardError => error
38
+ raise URLPolicy::Failure.new(error)
39
+ end
40
+ end
41
+ end
30
42
  Faraday.new(faraday_options) do |faraday|
31
43
  unless image
32
44
  faraday.request :retry, max: @retries
@@ -37,7 +49,8 @@ module MetaInspector
37
49
  faraday.use Faraday::FollowRedirects::Middleware, **redirects
38
50
  faraday.use :cookie_jar
39
51
  end
40
- faraday.use URLPolicy, @url_filter, image ? origin : nil
52
+ faraday.use URLPolicy, @url_filter, image ? origin : nil,
53
+ request_origin: @page_origin || origin
41
54
  if !image && @cache.is_a?(Hash)
42
55
  cache_options = @cache.dup
43
56
  cache_options[:serializer] ||= Marshal