Files

68 lines
1.6 KiB
Ruby
Raw Permalink Normal View History

2024-09-07 01:30:34 +03:00
# frozen_string_literal: true
module DownloadUtils
2025-12-10 09:13:55 +02:00
LOCALHOSTS = Set[
'0.0.0.0',
'127.0.0.1',
'127.0.1.1',
'localhost',
'localhost.localdomain',
'::1',
'[::1]',
'ip6-localhost',
'ip6-loopback',
'127.0.0.0',
'127.255.255.255',
'::',
'0:0:0:0:0:0:0:1',
'[0:0:0:0:0:0:0:1]',
'0000:0000:0000:0000:0000:0000:0000:0001',
'[0000:0000:0000:0000:0000:0000:0000:0001]',
'::0',
'0::0',
'::ffff:127.0.0.1',
'[::ffff:127.0.0.1]',
'::ffff:7f00:1',
'[::ffff:7f00:1]',
'local',
'localhost.local',
'ip6-localnet',
'ip6-allnodes',
'ip6-allrouters'
].freeze
2024-09-07 01:30:34 +03:00
UnableToDownload = Class.new(StandardError)
module_function
2026-02-14 07:57:53 +02:00
def call(url, validate: Docuseal.multitenant?)
2025-02-24 13:24:16 +02:00
uri = begin
URI(url)
rescue URI::Error
Addressable::URI.parse(url).normalize
end
2024-09-07 01:30:34 +03:00
2026-02-14 07:57:53 +02:00
validate_uri!(uri) if validate
2024-09-07 01:30:34 +03:00
2026-02-14 07:57:53 +02:00
resp = conn(validate:).get(uri)
2024-09-07 01:30:34 +03:00
2025-02-24 13:24:16 +02:00
raise UnableToDownload, "Error loading: #{uri}" if resp.status >= 400
2024-09-07 01:30:34 +03:00
resp
end
2025-12-10 09:13:55 +02:00
def validate_uri!(uri)
2026-02-16 08:08:41 +02:00
raise UnableToDownload, "Error loading: #{uri}. Only HTTPS is allowed." if uri.scheme != 'https' ||
[443, nil].exclude?(uri.port)
2025-12-10 09:13:55 +02:00
raise UnableToDownload, "Error loading: #{uri}. Can't download from localhost." if uri.host.in?(LOCALHOSTS)
end
2026-02-14 07:57:53 +02:00
def conn(validate: Docuseal.multitenant?)
2024-09-07 01:30:34 +03:00
Faraday.new do |faraday|
2025-12-10 09:13:55 +02:00
faraday.response :follow_redirects, callback: lambda { |_, new_env|
2026-02-14 07:57:53 +02:00
validate_uri!(new_env[:url]) if validate
2025-12-10 09:13:55 +02:00
}
2024-09-07 01:30:34 +03:00
end
end
end