Class: Shugoi::TokenSigner
- Inherits:
-
Object
- Object
- Shugoi::TokenSigner
- Defined in:
- lib/shugoi/token_signer.rb
Constant Summary collapse
- GRANT_TTL_MS =
60_000
Instance Method Summary collapse
-
#initialize(secret) ⇒ TokenSigner
constructor
A new instance of TokenSigner.
- #sign(site_key, timestamp = Utils.now_ms) ⇒ Object
- #verify_render_grant(mid, grant, token, ip, expected_site_key) ⇒ Object
- #verify_token(token) ⇒ Object
Constructor Details
#initialize(secret) ⇒ TokenSigner
Returns a new instance of TokenSigner.
5 6 7 |
# File 'lib/shugoi/token_signer.rb', line 5 def initialize(secret) @secret = secret.to_s end |
Instance Method Details
#sign(site_key, timestamp = Utils.now_ms) ⇒ Object
9 10 11 12 13 14 15 |
# File 'lib/shugoi/token_signer.rb', line 9 def sign(site_key, = Utils.now_ms) return "" if @secret.empty? nonce = SecureRandom.hex(8) payload = [site_key, .to_i, nonce].join(":") sig = Utils.hmac_hex(@secret, payload) "#{payload}:#{sig}" end |
#verify_render_grant(mid, grant, token, ip, expected_site_key) ⇒ Object
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/shugoi/token_signer.rb', line 17 def verify_render_grant(mid, grant, token, ip, expected_site_key) return true if @secret.empty? # fail-safe : pas de secret → pas de vérification return false if grant.to_s.empty? || mid.to_s.empty? return false unless mid.to_s.match?(/\A[a-f0-9]{64}\z/) ts_str, sig = grant.to_s.split(":", 2) return false if ts_str.nil? || sig.nil? ts = Utils.base36_decode(ts_str) return false if ts.zero? && ts_str != "0" return false if Utils.now_ms - (ts * 1000) > GRANT_TTL_MS return false if expected_site_key.to_s.empty? payload = "render-grant:#{[expected_site_key, mid, token.to_s, ip.to_s, ts_str].join(':')}" expected = Utils.hmac_hex(@secret, payload) Utils.secure_equals(sig, expected) end |
#verify_token(token) ⇒ Object
35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/shugoi/token_signer.rb', line 35 def verify_token(token) parts = token.to_s.split(":") return false unless parts.length == 4 && parts[3].length == 64 return false if @secret.empty? site_key, , nonce, sig = parts ts = .to_i return false if ts.zero? return false if Utils.now_ms - ts > 120_000 # TOKEN_TTL payload = [site_key, , nonce].join(":") expected = Utils.hmac_hex(@secret, payload) Utils.secure_equals(sig, expected) end |