Sha256: 773495bd6402b937b128c391b75b35a4bcf194b61947f6669ae99810c29bd648

Contents?: true

Size: 2 KB

Versions: 13

Compression:

Stored size: 2 KB

Contents

# frozen_string_literal: true

require "addressable/uri"
require "dry-initializer"
require "email_address"
require "ipaddr"
require "public_suffix"

module Mihari
  class TypeChecker
    extend Dry::Initializer

    param :data

    def initialize(*args, **kwargs)
      super

      raise ArgumentError if data.is_a?(Hash)
    end

    # @return [Boolean]
    def hash?
      md5? || sha1? || sha256? || sha512?
    end

    # @return [Boolean]
    def ip?
      IPAddr.new data
      true
    rescue IPAddr::InvalidAddressError => _e
      false
    end

    # @return [Boolean]
    def domain?
      uri = Addressable::URI.parse("http://#{data}")
      uri.host == data && PublicSuffix.valid?(uri.host)
    rescue Addressable::URI::InvalidURIError => _e
      false
    end

    # @return [Boolean]
    def url?
      uri = Addressable::URI.parse(data)
      uri.scheme && uri.host && uri.path && PublicSuffix.valid?(uri.host)
    rescue Addressable::URI::InvalidURIError => _e
      false
    end

    # @return [Boolean]
    def mail?
      EmailAddress.valid? data, host_validation: :syntax
    end

    # @return [String, nil]
    def type
      return "hash" if hash?
      return "ip" if ip?
      return "domain" if domain?
      return "url" if url?
      return "mail" if mail?
    end

    # @return [String, nil]
    def detailed_type
      return "md5" if md5?
      return "sha1" if sha1?
      return "sha256" if sha256?
      return "sha512" if sha512?

      type
    end

    # @return [String, nil]
    def self.type(data)
      new(data).type
    end

    # @return [String, nil]
    def self.detailed_type(data)
      new(data).detailed_type
    end

    private

    # @return [Boolean]
    def md5?
      data.match?(/^[A-Fa-f0-9]{32}$/)
    end

    # @return [Boolean]
    def sha1?
      data.match?(/^[A-Fa-f0-9]{40}$/)
    end

    # @return [Boolean]
    def sha256?
      data.match?(/^[A-Fa-f0-9]{64}$/)
    end

    # @return [Boolean]
    def sha512?
      data.match?(/^[A-Fa-f0-9]{128}$/)
    end
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
mihari-3.12.0 lib/mihari/type_checker.rb
mihari-3.11.0 lib/mihari/type_checker.rb
mihari-3.10.1 lib/mihari/type_checker.rb
mihari-3.10.0 lib/mihari/type_checker.rb
mihari-3.9.2 lib/mihari/type_checker.rb
mihari-3.9.1 lib/mihari/type_checker.rb
mihari-3.9.0 lib/mihari/type_checker.rb
mihari-3.8.1 lib/mihari/type_checker.rb
mihari-3.8.0 lib/mihari/type_checker.rb
mihari-3.7.2 lib/mihari/type_checker.rb
mihari-3.7.1 lib/mihari/type_checker.rb
mihari-3.7.0 lib/mihari/type_checker.rb
mihari-3.6.1 lib/mihari/type_checker.rb