Module: Altcha::V1

Defined in:
lib/altcha/v1.rb

Overview

V1 proof-of-work: find a number N such that SHA256(salt+N) equals the challenge hash.

Defined Under Namespace

Modules: Algorithm Classes: Challenge, ChallengeOptions, Payload, ServerSignaturePayload, ServerSignatureVerificationData, Solution

Constant Summary collapse

DEFAULT_MAX_NUMBER =
1_000_000
DEFAULT_SALT_LENGTH =
12
DEFAULT_ALGORITHM =
Algorithm::SHA256

Class Method Summary collapse

Class Method Details

.create_challenge(options) ⇒ Object



195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# File 'lib/altcha/v1.rb', line 195

def self.create_challenge(options)
  algorithm   = options.algorithm   || DEFAULT_ALGORITHM
  max_number  = options.max_number  || DEFAULT_MAX_NUMBER
  salt_length = options.salt_length || DEFAULT_SALT_LENGTH

  params = options.params || {}
  params['expires'] = options.expires.to_i if options.expires

  salt = options.salt || random_bytes(salt_length).unpack1('H*')
  salt += "?#{URI.encode_www_form(params)}" unless params.empty?
  salt += salt.end_with?('&') ? '' : '&'

  number    = options.number || random_int(max_number)
  challenge = hash_hex(algorithm, "#{salt}#{number}")
  signature = hmac_hex(algorithm, challenge, options.hmac_key)

  Challenge.new(
    algorithm: algorithm,
    challenge: challenge,
    maxnumber: max_number,
    salt:      salt,
    signature: signature
  )
end

.extract_params(payload) ⇒ Object



258
259
260
# File 'lib/altcha/v1.rb', line 258

def self.extract_params(payload)
  URI.decode_www_form(payload.salt.split('?').last).to_h
end

.hash(algorithm, data) ⇒ Object



172
173
174
175
176
177
178
179
# File 'lib/altcha/v1.rb', line 172

def self.hash(algorithm, data)
  case algorithm
  when Algorithm::SHA1   then OpenSSL::Digest::SHA1.digest(data)
  when Algorithm::SHA256 then OpenSSL::Digest::SHA256.digest(data)
  when Algorithm::SHA512 then OpenSSL::Digest::SHA512.digest(data)
  else raise ArgumentError, "Unsupported algorithm: #{algorithm}"
  end
end

.hash_hex(algorithm, data) ⇒ Object



168
169
170
# File 'lib/altcha/v1.rb', line 168

def self.hash_hex(algorithm, data)
  hash(algorithm, data).unpack1('H*')
end

.hmac_hash(algorithm, data, key) ⇒ Object



185
186
187
188
189
190
191
192
193
# File 'lib/altcha/v1.rb', line 185

def self.hmac_hash(algorithm, data, key)
  digest_class = case algorithm
                 when Algorithm::SHA1   then OpenSSL::Digest::SHA1
                 when Algorithm::SHA256 then OpenSSL::Digest::SHA256
                 when Algorithm::SHA512 then OpenSSL::Digest::SHA512
                 else raise ArgumentError, "Unsupported algorithm: #{algorithm}"
                 end
  OpenSSL::HMAC.digest(digest_class.new, key, data)
end

.hmac_hex(algorithm, data, key) ⇒ Object



181
182
183
# File 'lib/altcha/v1.rb', line 181

def self.hmac_hex(algorithm, data, key)
  hmac_hash(algorithm, data, key).unpack1('H*')
end

.random_bytes(length) ⇒ Object


Module-level functions



160
161
162
# File 'lib/altcha/v1.rb', line 160

def self.random_bytes(length)
  OpenSSL::Random.random_bytes(length)
end

.random_int(max) ⇒ Object



164
165
166
# File 'lib/altcha/v1.rb', line 164

def self.random_int(max)
  rand(max + 1)
end

.solve_challenge(challenge, salt, algorithm, max, start) ⇒ Object



318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
# File 'lib/altcha/v1.rb', line 318

def self.solve_challenge(challenge, salt, algorithm, max, start)
  algorithm  ||= DEFAULT_ALGORITHM
  max        ||= DEFAULT_MAX_NUMBER
  start      ||= 0
  start_time   = Time.now

  (start..max).each do |n|
    if hash_hex(algorithm, "#{salt}#{n}") == challenge
      return Solution.new.tap do |s|
        s.number = n
        s.took   = Time.now - start_time
      end
    end
  end

  nil
end

.verify_fields_hash(form_data, fields, fields_hash, algorithm) ⇒ Object



262
263
264
265
266
# File 'lib/altcha/v1.rb', line 262

def self.verify_fields_hash(form_data, fields, fields_hash, algorithm)
  lines       = fields.map { |field| form_data[field].to_s }
  joined_data = lines.join("\n")
  hash_hex(algorithm, joined_data) == fields_hash
end

.verify_server_signature(payload, hmac_key) ⇒ Object



268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
# File 'lib/altcha/v1.rb', line 268

def self.verify_server_signature(payload, hmac_key)
  if payload.is_a?(String)
    payload = ServerSignaturePayload.from_json(Base64.decode64(payload))
  elsif payload.is_a?(Hash)
    payload = ServerSignaturePayload.new(
      algorithm:         payload[:algorithm],
      verification_data: payload[:verification_data],
      signature:         payload[:signature],
      verified:          payload[:verified]
    )
  end

  return [false, nil] unless payload.is_a?(ServerSignaturePayload)

  %i[algorithm verification_data signature verified].each do |attr|
    value = payload.send(attr)
    return false if value.nil? || value.to_s.strip.empty?
  end

  hash_data         = hash(payload.algorithm, payload.verification_data)
  expected_signature = hmac_hex(payload.algorithm, hash_data, hmac_key)

  params = URI.decode_www_form(payload.verification_data).to_h
  verification_data = ServerSignatureVerificationData.new.tap do |v|
    v.classification    = params['classification']
    v.country           = params['country']
    v.detected_language = params['detectedLanguage']
    v.email             = params['email']
    v.expire            = params['expire']&.to_i
    v.fields            = params['fields']&.split(',')
    v.fields_hash       = params['fieldsHash']
    v.ip_address        = params['ipAddress']
    v.reasons           = params['reasons']&.split(',')
    v.score             = params['score']&.to_f
    v.time              = params['time']&.to_i
    v.verified          = params['verified'] == 'true'
  end

  now = Time.now.to_i
  is_verified = payload.verified &&
                verification_data.verified &&
                (verification_data.expire.nil? || verification_data.expire > now) &&
                payload.signature == expected_signature

  [is_verified, verification_data]
rescue ArgumentError, JSON::ParserError => e
  puts "Error decoding or parsing payload: #{e.message}"
  false
end

.verify_solution(payload, hmac_key, check_expires = true) ⇒ Object



220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
# File 'lib/altcha/v1.rb', line 220

def self.verify_solution(payload, hmac_key, check_expires = true)
  if payload.is_a?(String)
    payload = Payload.from_json(Base64.decode64(payload))
  elsif payload.is_a?(Hash)
    payload = Payload.new(
      algorithm: payload[:algorithm],
      challenge: payload[:challenge],
      number:    payload[:number],
      salt:      payload[:salt],
      signature: payload[:signature]
    )
  end

  return false unless payload.is_a?(Payload)

  %i[algorithm challenge number salt signature].each do |attr|
    value = payload.send(attr)
    return false if value.nil? || value.to_s.strip.empty?
  end

  if check_expires && payload.salt.include?('?')
    expires = URI.decode_www_form(payload.salt.split('?').last).to_h['expires'].to_i
    return false if expires && Time.now.to_i > expires
  end

  expected = create_challenge(
    ChallengeOptions.new(
      algorithm: payload.algorithm,
      hmac_key:  hmac_key,
      number:    payload.number,
      salt:      payload.salt
    )
  )
  expected.challenge == payload.challenge && expected.signature == payload.signature
rescue ArgumentError, JSON::ParserError
  false
end