Class: RhoHubAccount

Inherits:
Object show all
Defined in:
lib/build/RhoHubAccount.rb

Constant Summary collapse

@@token_preamble_len =
16
@@token_size =
50
@@min_update_interval =
60*60*24
@@token_file_name =
'token'
@@salt_file_name =
'salt'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeRhoHubAccount

Returns a new instance of RhoHubAccount.



250
251
252
# File 'lib/build/RhoHubAccount.rb', line 250

def initialize()
  self.clear()
end

Instance Attribute Details

#changedObject (readonly)

Returns the value of attribute changed.



248
249
250
# File 'lib/build/RhoHubAccount.rb', line 248

def changed
  @changed
end

#ivObject

Returns the value of attribute iv.



247
248
249
# File 'lib/build/RhoHubAccount.rb', line 247

def iv
  @iv
end

#saltObject

Returns the value of attribute salt.



68
69
70
# File 'lib/build/RhoHubAccount.rb', line 68

def salt
  @salt
end

#token_preamble_lenObject (readonly)

Returns the value of attribute token_preamble_len.



68
69
70
# File 'lib/build/RhoHubAccount.rb', line 68

def token_preamble_len
  @token_preamble_len
end

#token_sizeObject (readonly)

Returns the value of attribute token_size.



68
69
70
# File 'lib/build/RhoHubAccount.rb', line 68

def token_size
  @token_size
end

Class Method Details

.bin_to_hex(s) ⇒ Object



85
86
87
# File 'lib/build/RhoHubAccount.rb', line 85

def bin_to_hex(s)
  s.unpack('H*').first
end

.check_field(field, salt, iv) ⇒ Object



149
150
151
152
153
154
155
156
# File 'lib/build/RhoHubAccount.rb', line 149

def check_field(field, salt, iv)
  decode = decode_val(field, salt, iv)
  len = CRC32.calc_a("token").length
  code = decode.slice(0, decode.length - len)
  code_hash = decode.slice(decode.length - len, len)

  return code, code_hash == CRC32.calc_a(code)
end

.decode_val(decodeable, salt, iv) ⇒ Object



110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/build/RhoHubAccount.rb', line 110

def decode_val(decodeable, salt, iv)
  cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc")
  cipher.decrypt

  cipher.key = Digest::SHA2.hexdigest(salt)
  cipher.iv = iv

  # and decrypt it
  decrypted = cipher.update(decodeable)
  decrypted << cipher.final

  decrypted
end

.decode_validate_token_old(token_hash, salt) ⇒ Object



158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/build/RhoHubAccount.rb', line 158

def decode_validate_token_old(token_hash, salt)
  code = 0
  result = {}

  result[:token] = nil
  result[:lt] = 0
  result[:ft] = nil

  if !token_hash.nil?
    message = HashBase64.safe_decode(token_hash)

    if !(message["iv"].nil? || message["token"].nil?)
      result[:iv] = message["iv"]

      decrypted = decode_val(message["token"], salt, message["iv"])

      tokenlen = decrypted.length - @@token_preamble_len - Digest::SHA2.hexdigest("token").length
      tok = decrypted.slice(@@token_preamble_len, tokenlen)

      if is_valid_token?(tok)
        token_hash = decrypted.slice(tokenlen + @@token_preamble_len,decrypted.length)

        if token_hash != Digest::SHA2.hexdigest(tok)
          return nil
        else
          result[:token] = tok
        end
      else
        return nil
      end

      if !(message["lt"].nil?)
        code, is_correct = check_field(message["lt"], salt, message["iv"])

        if is_correct
          result[:lt] = code.unpack('l<').first
        end
      end

      if !(message["ft"].nil? || message["ft"].empty?)
        code, is_correct = check_field(message["ft"], salt, message["iv"])

        if is_correct
          result[:ft] = code
        end
      end
    else
      return nil
    end
  else
    return nil
  end

  result
end

.encode_token_old(token, salt, token_preamble_len, iv = nil, subscription = nil) ⇒ Object



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/build/RhoHubAccount.rb', line 124

def encode_token_old(token, salt, token_preamble_len, iv = nil, subscription = nil)
  #random preamble
  token_code = generate_preamble(token_preamble_len)
  token_code << token
  token_code << Digest::SHA2.hexdigest(token)

  encrypted, iv = encode_val(token_code, salt, iv)

  curr_time = [Time.now.to_i].pack('l<')
  time_code = curr_time + CRC32.calc_a(curr_time)

  time, iv = encode_val(time_code, salt, iv)

  if !(subscription.nil? || subscription.empty?)
    sub_code_crc = subscription + CRC32.calc_a(subscription)
    sub_code, iv = encode_val(sub_code_crc, salt, iv)
  else
    sub_code = ""
  end

  message = HashBase64.safe_encode({:iv => iv, :token => encrypted, :lt => time, :ft => sub_code})

  JSON.generate(message)
end

.encode_val(encodeable, salt, iv = nil) ⇒ Object



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/build/RhoHubAccount.rb', line 93

def encode_val(encodeable, salt, iv = nil)
  cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc")
  cipher.encrypt
  cipher.key = Digest::SHA2.hexdigest(salt)

  if iv.nil?
    iv = cipher.random_iv
  end
  cipher.iv = iv

  #random preamble
  encrypted = cipher.update(encodeable)
  encrypted << cipher.final

  return encrypted, iv
end

.env_safe_decode64(env_val_name) ⇒ Object



214
215
216
217
218
219
220
221
222
223
224
225
226
# File 'lib/build/RhoHubAccount.rb', line 214

def env_safe_decode64(env_val_name)
  res = nil
  val = ENV[env_val_name]
  if !val.nil?
    begin
      res = JSON.parse(Base64.decode64(val))
    rescue
      res = nil
    end
  end

  res
end

.generate_preamble(len) ⇒ Object



80
81
82
83
# File 'lib/build/RhoHubAccount.rb', line 80

def generate_preamble(len)
  range = ((48..57).to_a+(65..90).to_a+(97..122).to_a)
  ([nil]*len).map { range.sample.chr }.join
end

.hex_to_bin(s) ⇒ Object



89
90
91
# File 'lib/build/RhoHubAccount.rb', line 89

def hex_to_bin(s)
  s.scan(/../).map { |x| x.hex }.pack('c*')
end

.is_valid_token?(token) ⇒ Boolean

Returns:

  • (Boolean)


71
72
73
74
75
76
77
78
# File 'lib/build/RhoHubAccount.rb', line 71

def is_valid_token?(token)
  if !token.nil? && !token.empty?
    res = /([0-9a-f]{#{@@token_size}})/.match(token)
    return !res.nil? && !res[1].nil?
  end

  false
end

.remove_account_files(token_folder) ⇒ Object



228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
# File 'lib/build/RhoHubAccount.rb', line 228

def (token_folder)
  token_file = File.join(token_folder, @@token_file_name)
  salt_file = File.join(token_folder, @@salt_file_name)

  files = [token_file, salt_file]

  begin
    files.each do |f_name|
      if File.exists?(f_name)
        File.delete(f_name)
      end
    end
  rescue => e
    puts "could not delete token files"
    raise
  end
end

Instance Method Details

#clearObject



254
255
256
257
258
259
260
261
262
263
264
# File 'lib/build/RhoHubAccount.rb', line 254

def clear()
  @iv = nil
  @salt = SecureRandom.urlsafe_base64(32)
  @info = {
    :subscription => nil,
    :token => nil,
    :time => 0,
    :server => nil
  }
  @changed = true
end

#encode_token_for_envObject



407
408
409
410
411
412
413
414
415
416
# File 'lib/build/RhoHubAccount.rb', line 407

def encode_token_for_env()
  HashBase64.safe_encode(
    JSON.generate(
      {
        "token" => self.token,
        "subscription" => self.subscription
      }
    )
  )
end

#is_outdatedObject



387
388
389
# File 'lib/build/RhoHubAccount.rb', line 387

def is_outdated()
  (@info[:time] - Time.now.to_i > @@min_update_interval) || @changed
end

#is_valid_subscription?Boolean

Returns:

  • (Boolean)


306
307
308
# File 'lib/build/RhoHubAccount.rb', line 306

def is_valid_subscription?()
  remaining_subscription_time() > 0
end

#is_valid_token?Boolean

Returns:

  • (Boolean)


293
294
295
# File 'lib/build/RhoHubAccount.rb', line 293

def is_valid_token?()
  !(@info[:token].nil? || @info[:token].empty?)
end

#read_token_from_envObject



395
396
397
398
399
400
401
402
403
404
405
# File 'lib/build/RhoHubAccount.rb', line 395

def read_token_from_env()
  packed = self.class.env_safe_decode64('RHOMOBILE_USER_INFO')
  if !packed.nil?
    self.token = packed["token"]
    self.time = Time.now.to_i
    self.subscription = packed["subscription"]
    @changed = false
  end

  !packed.nil? && self.is_valid_token?()
end

#read_token_from_files(token_folder) ⇒ Object



418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
# File 'lib/build/RhoHubAccount.rb', line 418

def read_token_from_files(token_folder)
  result = false

  token_file = File.join(token_folder, @@token_file_name)
  salt_file = File.join(token_folder, @@salt_file_name)

  if File.exists?(token_file)
    begin
      data = JSON.parse(File.read(token_file))

      if !data["lt"].nil? || data["salt"].nil?
        if File.exists?(salt_file)
          salt = File.read(salt_file)

          result = self.class.decode_validate_token_old(data, salt)

          # changed will be automatically updated
          if !result.nil?
            @iv = result[:iv]
            @salt = salt
            self.token = result[:token]
            self.time = result[:lt]
            self.subscription = result[:ft]
          end

          result = true
        end
      else

        message = HashBase64.safe_decode(data)

        if !(message["iv"].nil? || message["data"].nil? || message["salt"].nil?)
          decrypted = self.class.decode_val(message["data"], message["salt"], message["iv"])

          data_len = decrypted.length - @@token_preamble_len - Digest::SHA2.hexdigest("data").length
          data = decrypted.slice(@@token_preamble_len, data_len)

          data_hash = decrypted.slice(data_len + @@token_preamble_len,decrypted.length)

          if data_hash == Digest::SHA2.hexdigest(data)
            packed = JSON.parse(data)
            packed.each do |key, value|
              case key
              when "token"
                self.token = value
              when "time"
                self.time = value
              when "subscription"
                self.subscription = value
              when "server"
                self.server = value
              else
                raise "Unknown key #{key} in config"
              end
            end

            @changed = false

            result = true
          end
        end
      end
    rescue Exception => e
      puts "exception! #{e.inspect}"
      self.clear
    end
  end

  result
end

#remaining_subscription_timeObject



310
311
312
313
314
315
316
317
318
319
320
321
322
# File 'lib/build/RhoHubAccount.rb', line 310

def remaining_subscription_time()
  diff = 0

  if !(@info[:subscription].nil? || @info[:subscription].empty?)
    begin
      diff = [0,(JSON.parse(@info[:subscription])["tokenValidUntil"]).to_i - Time.now.to_i].max
    rescue Exception => e
      diff = 0
    end
  end

  diff
end

#remaining_timeObject



391
392
393
# File 'lib/build/RhoHubAccount.rb', line 391

def remaining_time()
  [0,@info[:time] + @@min_update_interval - Time.now.to_i].max
end

#save_token(token_folder) ⇒ Object



489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
# File 'lib/build/RhoHubAccount.rb', line 489

def save_token(token_folder)
  result = false

  self.time = Time.now.to_i

  payload = JSON.generate(@info)
  data = self.class.generate_preamble(@@token_preamble_len) + payload + Digest::SHA2.hexdigest(payload)

  encrypted, @iv = self.class.encode_val(data, @salt)

  message = {
    :iv => @iv,
    :salt => @salt,
    :data => encrypted
  }

  packed = JSON.generate(HashBase64.safe_encode(message))

  File.open(File.join(token_folder, @@token_file_name),"w") { |f| f.write(packed) }

  @changed = false
end

#serverObject



266
267
268
# File 'lib/build/RhoHubAccount.rb', line 266

def server()
  @info[:server].nil? ? "" : @info[:server]
end

#server=(value) ⇒ Object



270
271
272
273
274
275
276
# File 'lib/build/RhoHubAccount.rb', line 270

def server=(value)
  if value != @info[:server]
    @changed = true
  end

  @info[:server] = value
end

#subsciption_planObject



334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
# File 'lib/build/RhoHubAccount.rb', line 334

def subsciption_plan()
  text = "free" 

  begin
    resp = JSON.parse(subscription)
    unsigned = subscription.gsub(/"signature":"[^"]*"/, '"signature":""')
    hash = Digest::SHA1.hexdigest(unsigned)

    if (resp["signature"] == Digest::SHA1.hexdigest(unsigned))
      if !(resp["features"].nil? && resp["features"]["plan"].nil?)
        text = resp["features"]["plan"]
      end
    else
      text = "invalid"
    end
  rescue Exception => e
  end

  text
end

#subscriptionObject



297
298
299
# File 'lib/build/RhoHubAccount.rb', line 297

def subscription()
  @info[:subscription]
end

#subscription=(value) ⇒ Object



301
302
303
304
# File 'lib/build/RhoHubAccount.rb', line 301

def subscription=(value)
  @changed = @changed || value != @info[:subscription]
  @info[:subscription] = value
end

#subscription_levelObject



355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
# File 'lib/build/RhoHubAccount.rb', line 355

def subscription_level()
  level = -1

  if is_valid_subscription?()
    case subsciption_plan()
    when "premium"
      level = 2
    when "gold"
      level = 2
    when "enterprise"
      level = 1
    when "silver"
      level = 1
    when "free"
      level = 0
    else
      level = -1
    end
  end

  level
end

#timeObject



378
379
380
# File 'lib/build/RhoHubAccount.rb', line 378

def time()
  @info[:time]
end

#time=(value) ⇒ Object



382
383
384
385
# File 'lib/build/RhoHubAccount.rb', line 382

def time=(value)
  @changed = @changed || value != @info[:time]
  @info[:time] = value
end

#to_boolean(s) ⇒ Object



324
325
326
327
328
329
330
331
332
# File 'lib/build/RhoHubAccount.rb', line 324

def to_boolean(s)
  if s.kind_of?(String)
    !!(s =~ /^(true|t|yes|y|1)$/i)
  elsif s.kind_of?(TrueClass)
    true
  else
    false
  end
end

#tokenObject



278
279
280
# File 'lib/build/RhoHubAccount.rb', line 278

def token()
  @info[:token]
end

#token=(value) ⇒ Object



282
283
284
285
286
287
288
289
290
291
# File 'lib/build/RhoHubAccount.rb', line 282

def token=(value)
  new_val = self.class.is_valid_token?(value) ? value : nil
  # reset time because token was changed
  if new_val != @info[:token]
    @changed = true
    @info[:time] = 0
  end

  @info[:token] = new_val
end