Module: Autonoma::Refs

Defined in:
lib/autonoma/refs.rb

Class Method Summary collapse

Class Method Details

.make_json_safe(obj) ⇒ Object

Recursively convert non-JSON-safe types (Time, DateTime, BigDecimal, etc.) to strings so that JSON.generate does not raise.



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/autonoma/refs.rb', line 52

def self.make_json_safe(obj)
  case obj
  when Hash
    obj.transform_values { |v| make_json_safe(v) }
  when Array
    obj.map { |v| make_json_safe(v) }
  when Time, DateTime
    obj.iso8601(3)
  when Date
    obj.iso8601
  when BigDecimal
    obj.to_s("F")
  when Symbol
    obj.to_s
  else
    obj
  end
end

.sign_refs(payload, secret) ⇒ Object

Sign a refs payload into a 3-part token string.



13
14
15
16
17
18
# File 'lib/autonoma/refs.rb', line 13

def self.sign_refs(payload, secret)
  header = base64url_encode(JSON.generate({ alg: "HS256", typ: "REFS" }))
  body = base64url_encode(JSON.generate(make_json_safe(payload)))
  signature = hmac_sign("#{header}.#{body}", secret)
  "#{header}.#{body}.#{signature}"
end

.verify_refs(token, secret) ⇒ Object

Verify and decode a refs token. Returns the payload hash or raises.



21
22
23
24
25
26
27
28
29
30
31
# File 'lib/autonoma/refs.rb', line 21

def self.verify_refs(token, secret)
  parts = token.split(".")
  raise "malformed token" unless parts.length == 3

  header, body, signature = parts
  expected = hmac_sign("#{header}.#{body}", secret)

  raise "signature mismatch" unless Autonoma.secure_compare(expected, signature)

  JSON.parse(base64url_decode(body))
end