aliyun_intelligent_captcha 0.1.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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 62f0463a50dc9c3494408cb48a92a72bc52ca8d4a4b85377170f705cd0163b6f
4
+ data.tar.gz: d6be4f996f9a11b5458003aec5a42f5a8c52e5469790623ac571d6285a407c93
5
+ SHA512:
6
+ metadata.gz: b552f81e4d2c44024e43c6b1567e077ca743ae1fc6d2bb9c664c02a2046e259ad37e52a8b430532a66e834b86b0c6b8c143e91c6e75a12fbbb1613177656b5f4
7
+ data.tar.gz: b887aa0e96dac79476f505d40327c6c220fd70fed4b729ff0c54828a599f152d7e6b36fa5bae7ac944e84e51d5f874a90a42ade38179aca321288798aa64967e
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ming
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,123 @@
1
+ # Aliyun Intelligent Captcha
2
+
3
+ Ruby gem for verifying Alibaba Cloud intelligent captcha tokens with the `VerifyIntelligentCaptcha` OpenAPI.
4
+
5
+ It has no runtime dependency on the Alibaba Cloud SDK. The client signs requests with Alibaba Cloud ACS3-HMAC-SHA256 and uses Ruby's standard `Net::HTTP`.
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem "aliyun_intelligent_captcha"
13
+ ```
14
+
15
+ Then run:
16
+
17
+ ```sh
18
+ bundle install
19
+ ```
20
+
21
+ ## Rails Configuration
22
+
23
+ Create `config/initializers/aliyun_intelligent_captcha.rb`:
24
+
25
+ ```ruby
26
+ AliyunIntelligentCaptcha.configure do |config|
27
+ config.access_key_id = ENV.fetch("ALIYUN_ACCESS_KEY_ID")
28
+ config.access_key_secret = ENV.fetch("ALIYUN_ACCESS_KEY_SECRET")
29
+ config.scene_id = ENV["ALIYUN_CAPTCHA_SCENE_ID"]
30
+
31
+ # Defaults:
32
+ # config.endpoint = "captcha.cn-shanghai.aliyuncs.com"
33
+ # config.api_version = "2023-03-05"
34
+ # config.open_timeout = 2
35
+ # config.read_timeout = 5
36
+ end
37
+ ```
38
+
39
+ You can also use Rails config:
40
+
41
+ ```ruby
42
+ # config/application.rb
43
+ config.aliyun_intelligent_captcha.access_key_id = ENV["ALIYUN_ACCESS_KEY_ID"]
44
+ config.aliyun_intelligent_captcha.access_key_secret = ENV["ALIYUN_ACCESS_KEY_SECRET"]
45
+ ```
46
+
47
+ ## Usage
48
+
49
+ ```ruby
50
+ result = AliyunIntelligentCaptcha.verify(
51
+ captcha_verify_param: params[:captcha_verify_param],
52
+ remote_ip: request.remote_ip
53
+ )
54
+
55
+ if result.passed?
56
+ # continue
57
+ else
58
+ # reject request
59
+ end
60
+ ```
61
+
62
+ For Rails controllers:
63
+
64
+ ```ruby
65
+ class ApplicationController < ActionController::Base
66
+ include AliyunIntelligentCaptcha::Rails::ControllerHelpers
67
+ end
68
+
69
+ class SessionsController < ApplicationController
70
+ def create
71
+ unless verify_aliyun_intelligent_captcha(params[:captcha_verify_param])
72
+ render status: :unprocessable_entity, json: { error: "captcha_failed" }
73
+ return
74
+ end
75
+
76
+ # sign in
77
+ end
78
+ end
79
+ ```
80
+
81
+ ## Custom Fields
82
+
83
+ Alibaba Cloud may add or rename request fields. Pass additional OpenAPI fields as keyword arguments:
84
+
85
+ ```ruby
86
+ AliyunIntelligentCaptcha.verify(
87
+ captcha_verify_param: params[:captcha_verify_param],
88
+ scene_id: "your_scene_id",
89
+ user_id: current_user.id,
90
+ remote_ip: request.remote_ip
91
+ )
92
+ ```
93
+
94
+ Ruby snake_case keys are converted to Alibaba Cloud CamelCase keys:
95
+
96
+ ```ruby
97
+ captcha_verify_param # => CaptchaVerifyParam
98
+ remote_ip # => RemoteIp
99
+ ```
100
+
101
+ ## Direct Client
102
+
103
+ ```ruby
104
+ client = AliyunIntelligentCaptcha::Client.new(
105
+ access_key_id: "...",
106
+ access_key_secret: "...",
107
+ scene_id: "..."
108
+ )
109
+
110
+ client.verify(captcha_verify_param: "...")
111
+ ```
112
+
113
+ ## Error Handling
114
+
115
+ Network errors and non-2xx responses raise `AliyunIntelligentCaptcha::Error` subclasses:
116
+
117
+ ```ruby
118
+ begin
119
+ result = AliyunIntelligentCaptcha.verify(captcha_verify_param: token)
120
+ rescue AliyunIntelligentCaptcha::ConfigurationError, AliyunIntelligentCaptcha::RequestError => error
121
+ Rails.logger.warn("captcha verify failed: #{error.message}")
122
+ end
123
+ ```
@@ -0,0 +1,142 @@
1
+ # frozen_string_literal: true
2
+
3
+
4
+ require "json"
5
+ require "net/http"
6
+ require "openssl"
7
+ require "securerandom"
8
+ require "time"
9
+ require "uri"
10
+
11
+ require_relative "configuration"
12
+ require_relative "error"
13
+ require_relative "result"
14
+
15
+ module AliyunIntelligentCaptcha
16
+ class Client
17
+ ACTION = "VerifyIntelligentCaptcha"
18
+ CONTENT_TYPE = "application/json; charset=utf-8"
19
+ SIGNATURE_ALGORITHM = "ACS3-HMAC-SHA256"
20
+
21
+ def initialize(access_key_id:,
22
+ access_key_secret:,
23
+ endpoint: Configuration::DEFAULT_ENDPOINT,
24
+ api_version: Configuration::DEFAULT_API_VERSION,
25
+ scene_id: nil,
26
+ open_timeout: Configuration::DEFAULT_OPEN_TIMEOUT,
27
+ read_timeout: Configuration::DEFAULT_READ_TIMEOUT,
28
+ logger: nil,
29
+ http_client: nil)
30
+ @access_key_id = access_key_id
31
+ @access_key_secret = access_key_secret
32
+ @endpoint = endpoint
33
+ @api_version = api_version
34
+ @scene_id = scene_id
35
+ @open_timeout = open_timeout
36
+ @read_timeout = read_timeout
37
+ @logger = logger
38
+ @http_client = http_client
39
+ end
40
+
41
+ def verify(captcha_verify_param:, scene_id: @scene_id, **extra)
42
+ ensure_configured!
43
+
44
+ payload = normalize_payload(
45
+ extra.merge(captcha_verify_param: captcha_verify_param, scene_id: scene_id).compact
46
+ )
47
+ response = perform_request(payload)
48
+ Result.new(body: parse_response(response.body), status: response.code)
49
+ end
50
+
51
+ private
52
+
53
+ def ensure_configured!
54
+ raise ConfigurationError, "access_key_id is required" if blank?(@access_key_id)
55
+ raise ConfigurationError, "access_key_secret is required" if blank?(@access_key_secret)
56
+ end
57
+
58
+ def perform_request(payload)
59
+ uri = URI::HTTPS.build(host: @endpoint, path: "/")
60
+ body = JSON.generate(payload)
61
+ request = Net::HTTP::Post.new(uri)
62
+ request.body = body
63
+ signed_headers(body).each { |key, value| request[key] = value }
64
+
65
+ response = @http_client ? @http_client.call(request, uri) : net_http_request(uri, request)
66
+ validate_response!(response)
67
+ response
68
+ rescue Timeout::Error, SocketError, SystemCallError, OpenSSL::SSL::SSLError => error
69
+ @logger&.warn("[aliyun_intelligent_captcha] request failed: #{error.class}: #{error.message}")
70
+ raise RequestError, error.message
71
+ end
72
+
73
+ def net_http_request(uri, request)
74
+ Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: @open_timeout, read_timeout: @read_timeout) do |http|
75
+ http.request(request)
76
+ end
77
+ end
78
+
79
+ def signed_headers(body)
80
+ content_sha256 = sha256_hex(body)
81
+ headers = {
82
+ "host" => @endpoint,
83
+ "content-type" => CONTENT_TYPE,
84
+ "x-acs-action" => ACTION,
85
+ "x-acs-version" => @api_version,
86
+ "x-acs-date" => Time.now.utc.iso8601,
87
+ "x-acs-signature-nonce" => SecureRandom.uuid,
88
+ "x-acs-content-sha256" => content_sha256
89
+ }
90
+
91
+ headers.merge("Authorization" => authorization(headers, content_sha256))
92
+ end
93
+
94
+ def authorization(headers, content_sha256)
95
+ signed_header_names = headers.keys.map(&:downcase).sort
96
+ canonical_headers = signed_header_names.map { |name| "#{name}:#{headers.fetch(name)}\n" }.join
97
+ signed_headers = signed_header_names.join(";")
98
+ canonical_request = [
99
+ "POST",
100
+ "/",
101
+ "",
102
+ canonical_headers,
103
+ signed_headers,
104
+ content_sha256
105
+ ].join("\n")
106
+ string_to_sign = "#{SIGNATURE_ALGORITHM}\n#{sha256_hex(canonical_request)}"
107
+ signature = OpenSSL::HMAC.hexdigest("SHA256", @access_key_secret, string_to_sign)
108
+
109
+ "#{SIGNATURE_ALGORITHM} Credential=#{@access_key_id},SignedHeaders=#{signed_headers},Signature=#{signature}"
110
+ end
111
+
112
+ def validate_response!(response)
113
+ return if response.code.to_i.between?(200, 299)
114
+
115
+ raise ResponseError, "Aliyun captcha API returned HTTP #{response.code}: #{response.body}"
116
+ end
117
+
118
+ def parse_response(body)
119
+ JSON.parse(body)
120
+ rescue JSON::ParserError => error
121
+ raise ResponseError, "invalid JSON response: #{error.message}"
122
+ end
123
+
124
+ def normalize_payload(payload)
125
+ payload.each_with_object({}) do |(key, value), normalized|
126
+ normalized[camelize(key.to_s)] = value
127
+ end
128
+ end
129
+
130
+ def camelize(value)
131
+ value.split("_").map(&:capitalize).join
132
+ end
133
+
134
+ def sha256_hex(value)
135
+ OpenSSL::Digest::SHA256.hexdigest(value)
136
+ end
137
+
138
+ def blank?(value)
139
+ value.nil? || value.to_s.strip.empty?
140
+ end
141
+ end
142
+ end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AliyunIntelligentCaptcha
4
+ class Configuration
5
+ DEFAULT_ENDPOINT = "captcha.cn-shanghai.aliyuncs.com"
6
+ DEFAULT_API_VERSION = "2023-03-05"
7
+ DEFAULT_OPEN_TIMEOUT = 2
8
+ DEFAULT_READ_TIMEOUT = 5
9
+
10
+ attr_accessor :access_key_id,
11
+ :access_key_secret,
12
+ :endpoint,
13
+ :api_version,
14
+ :scene_id,
15
+ :open_timeout,
16
+ :read_timeout,
17
+ :logger
18
+
19
+ def initialize
20
+ @endpoint = DEFAULT_ENDPOINT
21
+ @api_version = DEFAULT_API_VERSION
22
+ @open_timeout = DEFAULT_OPEN_TIMEOUT
23
+ @read_timeout = DEFAULT_READ_TIMEOUT
24
+ end
25
+
26
+ def to_h
27
+ {
28
+ access_key_id: access_key_id,
29
+ access_key_secret: access_key_secret,
30
+ endpoint: endpoint,
31
+ api_version: api_version,
32
+ scene_id: scene_id,
33
+ open_timeout: open_timeout,
34
+ read_timeout: read_timeout,
35
+ logger: logger
36
+ }
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AliyunIntelligentCaptcha
4
+ class Error < StandardError; end
5
+ class ConfigurationError < Error; end
6
+ class RequestError < Error; end
7
+ class ResponseError < Error; end
8
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AliyunIntelligentCaptcha
4
+ module Rails
5
+ module ControllerHelpers
6
+ def verify_aliyun_intelligent_captcha(captcha_verify_param, **extra)
7
+ AliyunIntelligentCaptcha.verify(
8
+ captcha_verify_param: captcha_verify_param,
9
+ remote_ip: request.remote_ip,
10
+ **extra
11
+ ).passed?
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails/railtie"
4
+
5
+ require_relative "configuration"
6
+ require_relative "rails/controller_helpers"
7
+
8
+ module AliyunIntelligentCaptcha
9
+ class Railtie < Rails::Railtie
10
+ config.aliyun_intelligent_captcha = Configuration.new
11
+
12
+ initializer "aliyun_intelligent_captcha.configure" do |app|
13
+ AliyunIntelligentCaptcha.configure do |config|
14
+ app.config.aliyun_intelligent_captcha.to_h.each do |key, value|
15
+ config.public_send("#{key}=", value)
16
+ end
17
+ end
18
+ AliyunIntelligentCaptcha.reset_client!
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,49 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AliyunIntelligentCaptcha
4
+ class Result
5
+ attr_reader :body, :status
6
+
7
+ def initialize(body:, status:)
8
+ @body = body
9
+ @status = status.to_i
10
+ end
11
+
12
+ def passed?
13
+ truthy?(fetch_value("VerifyResult")) ||
14
+ truthy?(fetch_value("Passed")) ||
15
+ truthy?(fetch_value("Result")) ||
16
+ success_code?
17
+ end
18
+
19
+ def request_id
20
+ fetch_value("RequestId")
21
+ end
22
+
23
+ def code
24
+ fetch_value("Code")
25
+ end
26
+
27
+ def message
28
+ fetch_value("Message")
29
+ end
30
+
31
+ private
32
+
33
+ def fetch_value(key)
34
+ body[key] || body[underscore(key)]
35
+ end
36
+
37
+ def underscore(value)
38
+ value.gsub(/([a-z\d])([A-Z])/, "\\1_\\2").downcase
39
+ end
40
+
41
+ def success_code?
42
+ code.to_s.casecmp("OK").zero? || code.to_s == "200"
43
+ end
44
+
45
+ def truthy?(value)
46
+ value == true || value.to_s.casecmp("true").zero? || value.to_s == "1"
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AliyunIntelligentCaptcha
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "aliyun_intelligent_captcha/client"
4
+ require_relative "aliyun_intelligent_captcha/configuration"
5
+ require_relative "aliyun_intelligent_captcha/error"
6
+ require_relative "aliyun_intelligent_captcha/result"
7
+ require_relative "aliyun_intelligent_captcha/version"
8
+
9
+ require_relative "aliyun_intelligent_captcha/railtie" if defined?(Rails::Railtie)
10
+
11
+ module AliyunIntelligentCaptcha
12
+ class << self
13
+ def configuration
14
+ @configuration ||= Configuration.new
15
+ end
16
+
17
+ def configure
18
+ yield(configuration)
19
+ end
20
+
21
+ def client
22
+ @client ||= Client.new(**configuration.to_h)
23
+ end
24
+
25
+ def reset_client!
26
+ @client = nil
27
+ end
28
+
29
+ def verify(...)
30
+ client.verify(...)
31
+ end
32
+ end
33
+ end
metadata ADDED
@@ -0,0 +1,80 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: aliyun_intelligent_captcha
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - ming
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: minitest
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: '5.0'
19
+ type: :development
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - "~>"
24
+ - !ruby/object:Gem::Version
25
+ version: '5.0'
26
+ - !ruby/object:Gem::Dependency
27
+ name: rake
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - "~>"
31
+ - !ruby/object:Gem::Version
32
+ version: '13.0'
33
+ type: :development
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - "~>"
38
+ - !ruby/object:Gem::Version
39
+ version: '13.0'
40
+ description: A small Ruby/Rails friendly gem for verifying Alibaba Cloud intelligent
41
+ captcha tokens through the VerifyIntelligentCaptcha OpenAPI.
42
+ email:
43
+ - ming@example.com
44
+ executables: []
45
+ extensions: []
46
+ extra_rdoc_files: []
47
+ files:
48
+ - LICENSE.txt
49
+ - README.md
50
+ - lib/aliyun_intelligent_captcha.rb
51
+ - lib/aliyun_intelligent_captcha/client.rb
52
+ - lib/aliyun_intelligent_captcha/configuration.rb
53
+ - lib/aliyun_intelligent_captcha/error.rb
54
+ - lib/aliyun_intelligent_captcha/rails/controller_helpers.rb
55
+ - lib/aliyun_intelligent_captcha/railtie.rb
56
+ - lib/aliyun_intelligent_captcha/result.rb
57
+ - lib/aliyun_intelligent_captcha/version.rb
58
+ homepage: https://github.com/diningcity-group/Aliyun-intelligent-captcha
59
+ licenses:
60
+ - MIT
61
+ metadata:
62
+ allowed_push_host: https://rubygems.org
63
+ rdoc_options: []
64
+ require_paths:
65
+ - lib
66
+ required_ruby_version: !ruby/object:Gem::Requirement
67
+ requirements:
68
+ - - ">="
69
+ - !ruby/object:Gem::Version
70
+ version: '3.0'
71
+ required_rubygems_version: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ requirements: []
77
+ rubygems_version: 4.0.10
78
+ specification_version: 4
79
+ summary: Ruby client for Alibaba Cloud VerifyIntelligentCaptcha.
80
+ test_files: []