metainspector 5.19.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 (43) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +21 -0
  3. data/Gemfile +1 -1
  4. data/README.md +214 -9
  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 +23 -4
  15. data/lib/meta_inspector/http_session.rb +75 -0
  16. data/lib/meta_inspector/image_downloader.rb +98 -0
  17. data/lib/meta_inspector/parser.rb +22 -2
  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 +196 -27
  21. data/lib/meta_inspector/parsers/texts.rb +2 -2
  22. data/lib/meta_inspector/request.rb +17 -39
  23. data/lib/meta_inspector/url_policy.rb +68 -0
  24. data/lib/meta_inspector/version.rb +1 -1
  25. data/lib/meta_inspector.rb +1 -0
  26. data/meta_inspector.gemspec +1 -2
  27. data/spec/document_spec.rb +139 -0
  28. data/spec/examples_spec.rb +206 -0
  29. data/spec/image_download_spec.rb +125 -0
  30. data/spec/image_metadata_spec.rb +110 -0
  31. data/spec/image_validity_spec.rb +195 -0
  32. data/spec/inline_images_spec.rb +75 -0
  33. data/spec/meta_inspector/head_links_spec.rb +69 -0
  34. data/spec/meta_inspector/iframes_spec.rb +50 -0
  35. data/spec/meta_inspector/images_spec.rb +130 -0
  36. data/spec/meta_inspector/meta_inspector_spec.rb +58 -7
  37. data/spec/meta_inspector/texts_spec.rb +50 -0
  38. data/spec/parser_spec.rb +10 -0
  39. data/spec/request_spec.rb +1 -1
  40. data/spec/unicode_image_urls_spec.rb +74 -0
  41. data/spec/url_filter_spec.rb +206 -0
  42. metadata +32 -36
  43. data/examples/redirect_web_server.rb +0 -5
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 5bc16dfdcdd22661ba7bb196d4db8750a5fa4d48d054197982768fa7fac44835
4
- data.tar.gz: ce356b1f0f2511069ff96329e775e3581282d68d395c4dada93a9275e5dd4aa6
3
+ metadata.gz: 486be410cc1d8f68b50d6f61ed2bb158487e2461dfcdda8d2287647d447313c9
4
+ data.tar.gz: da722ae3063738ed07aa0287bfdb4102ba2c000ec9cf29d9b7b82e245b7e5f2e
5
5
  SHA512:
6
- metadata.gz: 6a669057baeb8107c8ae6940f4323f60664982fa3c8c74ce4f029b434ebfe227436c743a6b6041acbcddfdc2ea7fb38704a6126d3204b18479a8ca81b2b63a0e
7
- data.tar.gz: 123f1cbb41fd5492307d96e316b17c91fc4f17d523a12f9fd865be49a3de31d8b932ceae6365bc7e1f6f49fd9721f8626eb9a8b5bbcbf9d86b2e972aedaa1544
6
+ metadata.gz: b5249e8927148dc832343679a72474ad8396772dfa00c4657c856406b88619897947cbcc3e2423b77a60b2585357f19a6519c0fe8b49abc88147fa8fba1fe80b
7
+ data.tar.gz: b2285a8dd0fb31f48c702b0623b40b93fbd5d626812074b761e25293f240b56685a97c8497570d0306b53222840927c3e020c11f953b73ef71aee064deb2ecbe
data/CHANGELOG.md CHANGED
@@ -1,5 +1,26 @@
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
+
19
+ ## [Changes in 5.20.0](https://github.com/jaimeiniesta/metainspector/compare/v5.19.0...v5.20.0)
20
+
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)).
22
+ * Accept `faraday_http_cache` inside `faraday_options`, which used to raise `NameError`. The top-level `faraday_http_cache` option still works but is deprecated: it prints a warning once per process. Passing both raises `ArgumentError` (#373).
23
+
3
24
  ## [Changes in 5.19.0](https://github.com/jaimeiniesta/metainspector/compare/v5.18.1...v5.19.0)
4
25
 
5
26
  * Security: stop modifying the `faraday_options` hash passed to MetaInspector. When the same hash was reused, its `redirect` options were deleted after the first request, so a redirect `callback` used to block private hosts only ran once and later requests followed any redirect ([GHSA-mm2p-6q2v-7ph5](https://github.com/jaimeiniesta/metainspector/security/advisories/GHSA-mm2p-6q2v-7ph5)). Frozen option hashes no longer raise `FrozenError`.
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
@@ -341,8 +391,7 @@ And even customize what to do in between each redirect:
341
391
 
342
392
  ```ruby
343
393
  callback = proc do |previous_response, next_request|
344
-   ip_address = Resolv.getaddress(next_request.url.host)
345
- raise 'Invalid address' if IPAddr.new(ip_address).private?
394
+ puts "Following redirect to #{next_request.url}"
346
395
  end
347
396
 
348
397
  page = MetaInspector.new(url, faraday_options: { redirect: { callback: callback } })
@@ -352,6 +401,63 @@ page = MetaInspector.new(url, faraday_options: { redirect: { callback: callback
352
401
  The `faraday_options[:redirect]` hash is passed to the `FollowRedirects` middleware used by `Faraday`, so that we can use all available options.
353
402
  Check them [here](https://github.com/lostisland/faraday_middleware/blob/main/lib/faraday_middleware/response/follow_redirects.rb#L44).
354
403
 
404
+ ### Filtering request URLs
405
+
406
+ Use `url_filter:` to decide which destinations MetaInspector may request. The filter receives a Ruby `URI` and runs before the initial page request, the optional HEAD request, image size downloads, and every redirect destination. Only HTTP and HTTPS requests are supported.
407
+
408
+ For example, allow HTTPS requests to two known hosts:
409
+
410
+ ```ruby
411
+ allowed_hosts = %w[example.com images.example.com]
412
+
413
+ filter = proc do |uri|
414
+ uri.scheme == 'https' && allowed_hosts.include?(uri.hostname)
415
+ end
416
+
417
+ page = MetaInspector.new('https://example.com', url_filter: filter)
418
+ page.images.largest # Image requests and their redirects use the same filter.
419
+ ```
420
+
421
+ A truthy return value permits the request. Returning `false` or `nil` raises `MetaInspector::RequestError` before contacting the rejected destination. This also applies when an image request is rejected:
422
+
423
+ ```ruby
424
+ begin
425
+ page = MetaInspector.new(url, url_filter: filter)
426
+ page.images.largest
427
+ rescue MetaInspector::RequestError => error
428
+ warn error.message
429
+ end
430
+ ```
431
+
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.
433
+
434
+ If your application accepts arbitrary hostnames, this example rejects addresses in private, loopback, link-local and unspecified ranges, including IPv4-mapped IPv6 addresses:
435
+
436
+ ```ruby
437
+ require 'ipaddr'
438
+ require 'resolv'
439
+
440
+ zero_network = IPAddr.new('0.0.0.0/8')
441
+
442
+ filter = proc do |uri|
443
+ addresses = Resolv.getaddresses(uri.hostname)
444
+
445
+ !addresses.empty? && addresses.all? do |address|
446
+ ip = IPAddr.new(address)
447
+ ip = ip.native if ip.ipv4_mapped?
448
+
449
+ !(ip.private? || ip.loopback? || ip.link_local? ||
450
+ ip.to_i.zero? || zero_network.include?(ip))
451
+ end
452
+ end
453
+
454
+ page = MetaInspector.new(url, url_filter: filter)
455
+ ```
456
+
457
+ DNS resolution in this example happens separately from the connection, so it cannot prevent DNS rebinding. Use network egress restrictions as well when processing untrusted URLs. The example covers the listed ranges; applications may need additional address or port restrictions.
458
+
459
+ The existing redirect `callback` keeps its two arguments and runs only on redirects. Move destination validation from that callback to `url_filter:` to cover initial URLs as well as redirects, for both pages and images.
460
+
355
461
  ### Headers
356
462
 
357
463
  By default, the following headers are set:
@@ -445,9 +551,40 @@ While this is generally useful, it can be [tricky](https://github.com/sporkmonge
445
551
 
446
552
  You can disable URL normalization by passing the `normalize_url: false` option.
447
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
+
448
567
  ### Image downloading
449
568
 
450
- When you ask for the largest image on the page with `page.images.largest`, it will be determined by its height and width attributes on the HTML markup, and also by downloading a small portion of each image using the [fastimage](https://github.com/sdsykes/fastimage) gem. This is really fast as it doesn't download the entire images, normally just the headers of the image files.
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.
570
+
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.
572
+
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`.
586
+
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.
451
588
 
452
589
  If you want to disable this, you can specify it like this:
453
590
 
@@ -464,19 +601,69 @@ page.images.with_size
464
601
 
465
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.
466
603
 
467
- 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.
468
607
 
469
- 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.
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.
626
+
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.
470
655
 
471
656
  ### Caching responses
472
657
 
473
- MetaInspector can be configured to use [Faraday::HttpCache](https://github.com/plataformatec/faraday-http-cache) to cache page responses. For that you should pass the `faraday_http_cache` option with at least the `:store` key, for example:
658
+ MetaInspector can be configured to use [Faraday::HttpCache](https://github.com/plataformatec/faraday-http-cache) to cache page responses. For that you should pass the `faraday_http_cache` option inside `faraday_options`, with at least the `:store` key, for example:
474
659
 
475
660
  ```ruby
476
661
  cache = ActiveSupport::Cache.lookup_store(:file_store, '/tmp/cache')
477
- page = MetaInspector.new('http://example.com', faraday_http_cache: { store: cache })
662
+ page = MetaInspector.new('http://example.com', faraday_options: { faraday_http_cache: { store: cache } })
478
663
  ```
479
664
 
665
+ The top-level `faraday_http_cache` option still works, but it is deprecated and prints a warning, once per process. Passing it in both places raises an `ArgumentError`.
666
+
480
667
  ## Exception Handling
481
668
 
482
669
  Web page scraping is tricky, you can expect to find different exceptions during the request of the page or the parsing of its contents. MetaInspector will encapsulate these exceptions on these main errors:
@@ -488,7 +675,25 @@ Web page scraping is tricky, you can expect to find different exceptions during
488
675
 
489
676
  ## Examples
490
677
 
491
- 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:
492
697
 
493
698
  ```ruby
494
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,9 +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
- # * faraday_options: an optional hash of options to pass to Faraday on the request
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
22
+ # * url_filter: callable receiving a URI before each request; false/nil rejects it
23
+ # * faraday_options: an optional hash of options to pass to Faraday on the request.
24
+ # Its faraday_http_cache key configures response caching with Faraday::HttpCache
25
+ # * faraday_http_cache: deprecated, use faraday_options: { faraday_http_cache: ... }
19
26
  def initialize(initial_url, options = {})
20
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
21
32
  @max_image_downloads = options[:max_image_downloads]
22
33
  unless @max_image_downloads.nil? || (@max_image_downloads.is_a?(Integer) && @max_image_downloads >= 0)
23
34
  raise ArgumentError, 'max_image_downloads must be a non-negative Integer or nil'
@@ -37,8 +48,10 @@ module MetaInspector
37
48
  @normalize_url = options[:normalize_url]
38
49
  @faraday_options = options[:faraday_options]
39
50
  @faraday_http_cache = options[:faraday_http_cache]
51
+ @http_session = MetaInspector::HttpSession.new(options)
40
52
  @url = MetaInspector::URL.new(initial_url, normalize: @normalize_url)
41
- @request = MetaInspector::Request.new(@url, allow_redirections: @allow_redirections,
53
+ @request = MetaInspector::Request.new(@url, http_session: @http_session,
54
+ allow_redirections: @allow_redirections,
42
55
  head_first: options[:head_first],
43
56
  allow_non_html_content: @allow_non_html_content,
44
57
  connection_timeout: @connection_timeout,
@@ -49,7 +62,12 @@ module MetaInspector
49
62
  faraday_options: @faraday_options,
50
63
  faraday_http_cache: @faraday_http_cache) unless @document
51
64
  @parser = MetaInspector::Parser.new(self, download_images: @download_images,
52
- max_image_downloads: @max_image_downloads)
65
+ max_html_bytes: max_html_bytes,
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],
70
+ image_downloader: MetaInspector::ImageDownloader.new(@http_session, @url, options))
53
71
  end
54
72
 
55
73
  extend Forwardable
@@ -60,7 +78,7 @@ module MetaInspector
60
78
 
61
79
  delegate [:parsed, :language, :title, :best_title, :author, :best_author,
62
80
  :h1, :h2, :h3, :h4, :h5, :h6, :description, :best_description, :links,
63
- :images, :feeds, :feed, :charset, :meta_tags,
81
+ :images, :iframes, :iframe_sources, :feeds, :feed, :charset, :meta_tags,
64
82
  :meta_tag, :meta, :favicon,
65
83
  :head_links, :stylesheets, :canonicals] => :@parser
66
84
 
@@ -86,6 +104,7 @@ module MetaInspector
86
104
  'h6' => h6,
87
105
  'links' => links.to_hash,
88
106
  'images' => images.to_a,
107
+ 'iframes' => iframes,
89
108
  'charset' => charset,
90
109
  'feeds' => feeds,
91
110
  'content_type' => content_type,