altcha 1.0.0 → 2.0.0.beta1

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.
data/lib/altcha.rb CHANGED
@@ -1,436 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'altcha/version'
4
- require 'openssl'
5
- require 'base64'
6
- require 'uri'
7
- require 'time'
8
-
9
- # Altcha module provides functions for creating and verifying ALTCHA challenges.
10
- module Altcha
11
- # Contains algorithm type definitions for hashing.
12
- module Algorithm
13
- SHA1 = 'SHA-1'
14
- SHA256 = 'SHA-256'
15
- SHA512 = 'SHA-512'
16
- end
17
-
18
- # Default values for challenge generation.
19
- DEFAULT_MAX_NUMBER = 1_000_000
20
- DEFAULT_SALT_LENGTH = 12
21
- DEFAULT_ALGORITHM = Algorithm::SHA256
22
-
23
- # Class representing options for generating a challenge.
24
- class ChallengeOptions
25
- attr_accessor :algorithm, :max_number, :salt_length, :hmac_key, :salt, :number, :expires, :params
26
-
27
- def initialize(algorithm: nil, max_number: nil, salt_length: nil, hmac_key:, salt: nil, number: nil, expires: nil, params: nil)
28
- @algorithm = algorithm
29
- @max_number = max_number
30
- @salt_length = salt_length
31
- @hmac_key = hmac_key
32
- @salt = salt
33
- @number = number
34
- @expires = expires
35
- @params = params
36
- end
37
- end
38
-
39
- # Class representing a challenge with its attributes.
40
- class Challenge
41
- attr_accessor :algorithm, :challenge, :maxnumber, :salt, :signature
42
-
43
- def initialize(algorithm:, challenge:, maxnumber: nil, salt:, signature:)
44
- @algorithm = algorithm
45
- @challenge = challenge
46
- @maxnumber = maxnumber
47
- @salt = salt
48
- @signature = signature
49
- end
50
-
51
- # Converts the Challenge object to a JSON string.
52
- # @param options [Hash] options to customize JSON encoding.
53
- # @return [String] JSON representation of the Challenge object.
54
- def to_json(options = {})
55
- {
56
- algorithm: @algorithm,
57
- challenge: @challenge,
58
- maxnumber: @maxnumber,
59
- salt: @salt,
60
- signature: @signature
61
- }.to_json(options)
62
- end
63
- end
64
-
65
- # Class representing the payload of a challenge.
66
- class Payload
67
- attr_accessor :algorithm, :challenge, :number, :salt, :signature
68
-
69
- def initialize(algorithm:, challenge:, number:, salt:, signature:)
70
- @algorithm = algorithm
71
- @challenge = challenge
72
- @number = number
73
- @salt = salt
74
- @signature = signature
75
- end
76
-
77
- # Converts the Payload object to a JSON string.
78
- # @param options [Hash] options to customize JSON encoding.
79
- # @return [String] JSON representation of the Payload object.
80
- def to_json(options = {})
81
- {
82
- algorithm: @algorithm,
83
- challenge: @challenge,
84
- number: @number,
85
- salt: @salt,
86
- signature: @signature
87
- }.to_json(options)
88
- end
89
-
90
- # Creates a Payload object from a JSON string.
91
- # @param string [String] JSON string to parse.
92
- # @return [Payload] Parsed Payload object.
93
- def self.from_json(string)
94
- data = JSON.parse(string)
95
- new(
96
- algorithm: data['algorithm'],
97
- challenge: data['challenge'],
98
- number: data['number'],
99
- salt: data['salt'],
100
- signature: data['signature']
101
- )
102
- end
103
- end
104
-
105
- # Class representing the payload for server signatures.
106
- class ServerSignaturePayload
107
- attr_accessor :algorithm, :verification_data, :signature, :verified
108
-
109
- def initialize(algorithm:, verification_data:, signature:, verified:)
110
- @algorithm = algorithm
111
- @verification_data = verification_data
112
- @signature = signature
113
- @verified = verified
114
- end
115
-
116
- # Converts the ServerSignaturePayload object to a JSON string.
117
- # @param options [Hash] options to customize JSON encoding.
118
- # @return [String] JSON representation of the ServerSignaturePayload object.
119
- def to_json(options = {})
120
- {
121
- algorithm: @algorithm,
122
- verificationData: @verification_data,
123
- signature: @signature,
124
- verified: @verified
125
- }.to_json(options)
126
- end
127
-
128
- # Creates a ServerSignaturePayload object from a JSON string.
129
- # @param string [String] JSON string to parse.
130
- # @return [ServerSignaturePayload] Parsed ServerSignaturePayload object.
131
- def self.from_json(string)
132
- data = JSON.parse(string)
133
- new(
134
- algorithm: data['algorithm'],
135
- verification_data: data['verificationData'],
136
- signature: data['signature'],
137
- verified: data['verified']
138
- )
139
- end
140
- end
141
-
142
- # Class for verifying server signatures, containing various data points.
143
- class ServerSignatureVerificationData
144
- attr_accessor :classification, :country, :detected_language, :email, :expire, :fields, :fields_hash,
145
- :ip_address, :reasons, :score, :time, :verified
146
-
147
- # Converts the ServerSignatureVerificationData object to a JSON string.
148
- # @param options [Hash] options to customize JSON encoding.
149
- # @return [String] JSON representation of the ServerSignatureVerificationData object.
150
- def to_json(options = {})
151
- {
152
- classification: @classification,
153
- country: @country,
154
- detectedLanguage: @detected_language,
155
- email: @email,
156
- expire: @expire,
157
- fields: @fields,
158
- fieldsHash: @fields_hash,
159
- ipAddress: @ip_address,
160
- reasons: @reasons,
161
- score: @score,
162
- time: @time,
163
- verified: @verified
164
- }.to_json(options)
165
- end
166
- end
167
-
168
- # Class representing the solution to a challenge.
169
- class Solution
170
- attr_accessor :number, :took
171
- end
172
-
173
- # Generates a random byte array of the specified length.
174
- # @param length [Integer] The length of the byte array to generate.
175
- # @return [String] The generated random byte array.
176
- def self.random_bytes(length)
177
- OpenSSL::Random.random_bytes(length)
178
- end
179
-
180
- # Generates a random integer between 0 and the specified maximum (inclusive).
181
- # @param max [Integer] The upper bound for the random integer.
182
- # @return [Integer] The generated random integer.
183
- def self.random_int(max)
184
- rand(max + 1)
185
- end
186
-
187
- # Hashes the input data using the specified algorithm and returns the hexadecimal representation of the hash.
188
- # @param algorithm [String] The hashing algorithm to use (e.g., SHA-1, SHA-256, SHA-512).
189
- # @param data [String] The data to hash.
190
- # @return [String] The hexadecimal representation of the hashed data.
191
- def self.hash_hex(algorithm, data)
192
- hash = hash(algorithm, data)
193
- hash.unpack1('H*')
194
- end
195
-
196
- # Hashes the input data using the specified algorithm.
197
- # @param algorithm [String] The hashing algorithm to use (e.g., SHA-1, SHA-256, SHA-512).
198
- # @param data [String] The data to hash.
199
- # @return [String] The binary hash of the data.
200
- # @raise [ArgumentError] If an unsupported algorithm is specified.
201
- def self.hash(algorithm, data)
202
- case algorithm
203
- when Algorithm::SHA1
204
- OpenSSL::Digest::SHA1.digest(data)
205
- when Algorithm::SHA256
206
- OpenSSL::Digest::SHA256.digest(data)
207
- when Algorithm::SHA512
208
- OpenSSL::Digest::SHA512.digest(data)
209
- else
210
- raise ArgumentError, "Unsupported algorithm: #{algorithm}"
211
- end
212
- end
213
-
214
- # Computes the HMAC of the input data using the specified algorithm and key, and returns the hexadecimal representation.
215
- # @param algorithm [String] The hashing algorithm to use (e.g., SHA-1, SHA-256, SHA-512).
216
- # @param data [String] The data to hash.
217
- # @param key [String] The key for the HMAC.
218
- # @return [String] The hexadecimal representation of the HMAC.
219
- def self.hmac_hex(algorithm, data, key)
220
- hmac = hmac_hash(algorithm, data, key)
221
- hmac.unpack1('H*')
222
- end
223
-
224
- # Computes the HMAC of the input data using the specified algorithm and key.
225
- # @param algorithm [String] The hashing algorithm to use (e.g., SHA-1, SHA-256, SHA-512).
226
- # @param data [String] The data to hash.
227
- # @param key [String] The key for the HMAC.
228
- # @return [String] The binary HMAC of the data.
229
- # @raise [ArgumentError] If an unsupported algorithm is specified.
230
- def self.hmac_hash(algorithm, data, key)
231
- digest_class = case algorithm
232
- when Algorithm::SHA1
233
- OpenSSL::Digest::SHA1
234
- when Algorithm::SHA256
235
- OpenSSL::Digest::SHA256
236
- when Algorithm::SHA512
237
- OpenSSL::Digest::SHA512
238
- else
239
- raise ArgumentError, "Unsupported algorithm: #{algorithm}"
240
- end
241
- OpenSSL::HMAC.digest(digest_class.new, key, data)
242
- end
243
-
244
- # Creates a challenge for the client to solve based on the provided options.
245
- # @param options [ChallengeOptions] Options for generating the challenge.
246
- # @return [Challenge] The generated Challenge object.
247
- def self.create_challenge(options)
248
- algorithm = options.algorithm || DEFAULT_ALGORITHM
249
- max_number = options.max_number || DEFAULT_MAX_NUMBER
250
- salt_length = options.salt_length || DEFAULT_SALT_LENGTH
251
-
252
- params = options.params || {}
253
- params['expires'] = options.expires.to_i if options.expires
254
-
255
- salt = options.salt || random_bytes(salt_length).unpack1('H*')
256
- salt += "?#{URI.encode_www_form(params)}" unless params.empty?
257
- salt += salt.end_with?('&') ? '' : '&'
258
-
259
- number = options.number || random_int(max_number)
260
-
261
- challenge_str = "#{salt}#{number}"
262
- challenge = hash_hex(algorithm, challenge_str)
263
- signature = hmac_hex(algorithm, challenge, options.hmac_key)
264
-
265
- Challenge.new(
266
- algorithm: algorithm,
267
- challenge: challenge,
268
- maxnumber: max_number,
269
- salt: salt,
270
- signature: signature,
271
- )
272
- end
273
-
274
- # Verifies the solution provided by the client.
275
- # @param payload [String, Payload] The payload to verify, either as a base64 encoded JSON string or a Payload instance.
276
- # @param hmac_key [String] The key used for HMAC verification.
277
- # @param check_expires [Boolean] Whether to check if the challenge has expired.
278
- # @return [Boolean] True if the solution is valid, false otherwise.
279
- def self.verify_solution(payload, hmac_key, check_expires = true)
280
- # Attempt to handle payload as a base64 encoded JSON string or as a Payload instance
281
-
282
- # Decode and parse base64 JSON string if it's a String
283
- if payload.is_a?(String)
284
- decoded_payload = Base64.decode64(payload)
285
- payload = Payload.from_json(decoded_payload)
286
-
287
- # Convert payload from hash to Payload if it's a plain object
288
- elsif payload.is_a?(Hash)
289
- payload = Payload.new(
290
- algorithm: payload[:algorithm],
291
- challenge: payload[:challenge],
292
- number: payload[:number],
293
- salt: payload[:salt],
294
- signature: payload[:signature]
295
- )
296
- end
297
-
298
- # Ensure payload is an instance of Payload
299
- return false unless payload.is_a?(Payload)
300
-
301
- required_attributes = %i[algorithm challenge number salt signature]
302
- required_attributes.each do |attr|
303
- value = payload.send(attr)
304
- return false if value.nil? || value.to_s.strip.empty?
305
- end
306
-
307
- # Extract expiration time if checking expiration
308
- if check_expires && payload.salt.include?('?')
309
- expires = URI.decode_www_form(payload.salt.split('?').last).to_h['expires'].to_i
310
- return false if expires && Time.now.to_i > expires
311
- end
312
-
313
- # Convert payload to ChallengeOptions
314
- challenge_options = ChallengeOptions.new(
315
- algorithm: payload.algorithm,
316
- hmac_key: hmac_key,
317
- number: payload.number,
318
- salt: payload.salt
319
- )
320
-
321
- # Create expected challenge and compare with the provided payload
322
- expected_challenge = create_challenge(challenge_options)
323
- expected_challenge.challenge == payload.challenge && expected_challenge.signature == payload.signature
324
- rescue ArgumentError, JSON::ParserError
325
- # Handle specific exceptions for invalid Base64 or JSON
326
- false
327
- end
328
-
329
- # Extracts parameters from the payload's salt.
330
- # @param payload [Payload] The payload containing the salt.
331
- # @return [Hash] Parameters extracted from the payload's salt.
332
- def self.extract_params(payload)
333
- URI.decode_www_form(payload.salt.split('?').last).to_h
334
- end
335
-
336
- # Verifies the hash of form fields.
337
- # @param form_data [Hash] The form data to verify.
338
- # @param fields [Array<String>] The fields to include in the hash.
339
- # @param fields_hash [String] The expected hash of the fields.
340
- # @param algorithm [String] The hashing algorithm to use.
341
- # @return [Boolean] True if the fields hash matches, false otherwise.
342
- def self.verify_fields_hash(form_data, fields, fields_hash, algorithm)
343
- lines = fields.map { |field| form_data[field].to_s }
344
- joined_data = lines.join("\n")
345
- computed_hash = hash_hex(algorithm, joined_data)
346
- computed_hash == fields_hash
347
- end
348
-
349
- # Verifies the server's signature.
350
- # @param payload [String, ServerSignaturePayload] The payload to verify, either as a base64 encoded JSON string or a ServerSignaturePayload instance.
351
- # @param hmac_key [String] The key used for HMAC verification.
352
- # @return [Array<Boolean, ServerSignatureVerificationData>] A tuple where the first element is true if the signature is valid, and the second element is the verification data.
353
- def self.verify_server_signature(payload, hmac_key)
354
- # Decode and parse base64 JSON string if it's a String
355
- if payload.is_a?(String)
356
- decoded_payload = Base64.decode64(payload)
357
- payload = ServerSignaturePayload.from_json(decoded_payload)
358
-
359
- # Convert payload from hash to ServerSignaturePayload if it's a plain object
360
- elsif payload.is_a?(Hash)
361
- payload = ServerSignaturePayload.new(
362
- algorithm: payload[:algorithm],
363
- verification_data: payload[:verification_data],
364
- signature: payload[:signature],
365
- verified: payload[:verified]
366
- )
367
- end
368
-
369
- # Ensure payload is an instance of ServerSignaturePayload
370
- return [false, nil] unless payload.is_a?(ServerSignaturePayload)
371
-
372
- required_attributes = %i[algorithm verification_data signature verified]
373
- required_attributes.each do |attr|
374
- value = payload.send(attr)
375
- return false if value.nil? || value.to_s.strip.empty?
376
- end
377
-
378
- hash_data = hash(payload.algorithm, payload.verification_data)
379
- expected_signature = hmac_hex(payload.algorithm, hash_data, hmac_key)
380
-
381
- params = URI.decode_www_form(payload.verification_data).to_h
382
- verification_data = ServerSignatureVerificationData.new.tap do |v|
383
- v.classification = params['classification'] || nil
384
- v.country = params['country'] || nil
385
- v.detected_language = params['detectedLanguage'] || nil
386
- v.email = params['email'] || nil
387
- v.expire = params['expire'] ? params['expire'].to_i : nil
388
- v.fields = params['fields'] ? params['fields'].split(',') : nil
389
- v.fields_hash = params['fieldsHash'] || nil
390
- v.ip_address = params['ipAddress'] || nil
391
- v.reasons = params['reasons'] ? params['reasons'].split(',') : nil
392
- v.score = params['score'] ? params['score'].to_f : nil
393
- v.time = params['time'] ? params['time'].to_i : nil
394
- v.verified = params['verified'] == 'true'
395
- end
396
-
397
- now = Time.now.to_i
398
- is_verified = payload.verified &&
399
- verification_data.verified &&
400
- (verification_data.expire.nil? || verification_data.expire > now) &&
401
- payload.signature == expected_signature
402
-
403
- [is_verified, verification_data]
404
- rescue ArgumentError, JSON::ParserError => e
405
- # Handle specific exceptions for invalid Base64 or JSON
406
- puts "Error decoding or parsing payload: #{e.message}"
407
- false
408
- end
409
-
410
- # Solves a challenge by iterating over possible solutions.
411
- # @param challenge [String] The challenge to solve.
412
- # @param salt [String] The salt used in the challenge.
413
- # @param algorithm [String] The hashing algorithm used.
414
- # @param max [Integer] The maximum number to try.
415
- # @param start [Integer] The starting number to try.
416
- # @return [Solution, nil] The solution if found, or nil if not.
417
- def self.solve_challenge(challenge, salt, algorithm, max, start)
418
- algorithm ||= Algorithm::SHA256
419
- max ||= DEFAULT_MAX_NUMBER
420
- start ||= 0
421
-
422
- start_time = Time.now
423
-
424
- (start..max).each do |n|
425
- hash = hash_hex(algorithm, "#{salt}#{n}")
426
- if hash == challenge
427
- return Solution.new.tap do |s|
428
- s.number = n
429
- s.took = Time.now - start_time
430
- end
431
- end
432
- end
433
-
434
- nil
435
- end
436
- end
4
+ require 'altcha/v1'
5
+ require 'altcha/v2'
metadata CHANGED
@@ -1,74 +1,95 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: altcha
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.0.0
4
+ version: 2.0.0.beta1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Daniel Regeci
8
8
  autorequire:
9
9
  bindir: exe
10
10
  cert_chain: []
11
- date: 2025-12-14 00:00:00.000000000 Z
11
+ date: 2026-04-04 00:00:00.000000000 Z
12
12
  dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: base64
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
13
27
  - !ruby/object:Gem::Dependency
14
28
  name: bundler
15
29
  requirement: !ruby/object:Gem::Requirement
16
30
  requirements:
17
31
  - - "~>"
18
32
  - !ruby/object:Gem::Version
19
- version: 4.0.1
33
+ version: '4.0'
20
34
  type: :development
21
35
  prerelease: false
22
36
  version_requirements: !ruby/object:Gem::Requirement
23
37
  requirements:
24
38
  - - "~>"
25
39
  - !ruby/object:Gem::Version
26
- version: 4.0.1
40
+ version: '4.0'
27
41
  - !ruby/object:Gem::Dependency
28
42
  name: rake
29
43
  requirement: !ruby/object:Gem::Requirement
30
44
  requirements:
31
45
  - - "~>"
32
46
  - !ruby/object:Gem::Version
33
- version: 13.3.1
47
+ version: '13.3'
34
48
  type: :development
35
49
  prerelease: false
36
50
  version_requirements: !ruby/object:Gem::Requirement
37
51
  requirements:
38
52
  - - "~>"
39
53
  - !ruby/object:Gem::Version
40
- version: 13.3.1
54
+ version: '13.3'
41
55
  - !ruby/object:Gem::Dependency
42
56
  name: rspec
43
57
  requirement: !ruby/object:Gem::Requirement
44
58
  requirements:
45
59
  - - "~>"
46
60
  - !ruby/object:Gem::Version
47
- version: '3.0'
61
+ version: '3.13'
48
62
  type: :development
49
63
  prerelease: false
50
64
  version_requirements: !ruby/object:Gem::Requirement
51
65
  requirements:
52
66
  - - "~>"
53
67
  - !ruby/object:Gem::Version
54
- version: '3.0'
68
+ version: '3.13'
55
69
  description: A lightweight library for creating and verifying ALTCHA challenges.
56
70
  email:
57
71
  executables: []
58
72
  extensions: []
59
73
  extra_rdoc_files: []
60
74
  files:
75
+ - ".github/workflows/publish.yml"
61
76
  - ".gitignore"
62
77
  - ".rspec"
78
+ - CODE_OF_CONDUCT.md
79
+ - CONTRIBUTING.md
63
80
  - Gemfile
64
81
  - Gemfile.lock
65
82
  - LICENSE.txt
66
83
  - README.md
67
84
  - Rakefile
85
+ - SECURITY.md
68
86
  - altcha.gemspec
69
87
  - bin/console
70
88
  - bin/setup
89
+ - examples/server.rb
71
90
  - lib/altcha.rb
91
+ - lib/altcha/v1.rb
92
+ - lib/altcha/v2.rb
72
93
  - lib/altcha/version.rb
73
94
  homepage: https://altcha.org
74
95
  licenses:
@@ -82,14 +103,14 @@ required_ruby_version: !ruby/object:Gem::Requirement
82
103
  requirements:
83
104
  - - ">="
84
105
  - !ruby/object:Gem::Version
85
- version: '0'
106
+ version: '2.7'
86
107
  required_rubygems_version: !ruby/object:Gem::Requirement
87
108
  requirements:
88
109
  - - ">="
89
110
  - !ruby/object:Gem::Version
90
111
  version: '0'
91
112
  requirements: []
92
- rubygems_version: 3.5.11
113
+ rubygems_version: 3.5.22
93
114
  signing_key:
94
115
  specification_version: 4
95
116
  summary: ALTCHA Library