danielberkompas/ex_twilio

RTC Capability Grants

stavro opened this issue · 1 comments

I noticed ExTwilio has support for signing call tokens, I'd like to expand this to support video & rtc calling as well.

To leverage the creation of tokens for Video (docs), tokens must be signed with a grant of rtc.

Ruby implementation: https://github.com/twilio/twilio-ruby/blob/0a945ccc1c536c711745b26b0023b1a75b132450/lib/twilio-ruby/util/access_token.rb#L55-L71

Documentation on Capability signing: https://www.twilio.com/docs/api/client/capability-token-spec

Minimal working token generation for RTC video chats:

  def twilio_token(identity) do
    sid = System.get_env("TWILIO_ACCOUNT_SID")
    api_key = System.get_env("TWILIO_API_KEY")
    api_secret = System.get_env("TWILIO_API_KEY_SECRET")
    rtc_profile_sid = System.get_env("TWILIO_RTC_PROFILE_SID")
    now = epoch_ts()
    exp = now + 3600

    payload = %{
      "jti" => "#{api_key}-#{now}",
      "iss" => api_key,
      "sub" => sid,
      "exp" => exp,
      "grants" => %{
        "identity" => identity,
        "rtc" => %{
          "configuration_profile_sid" => rtc_profile_sid
        }
      }
    }

    payload
    |> Joken.token()
    |> Joken.with_header_arg("cty", "twilio-fpa;v=1")
    |> Joken.with_signer(Joken.hs256(api_secret))
    |> Joken.sign()
    |> Joken.get_compact()
  end

  defp epoch_ts() do
    epoch = {{1970, 1, 1}, {0, 0, 0}}
    epoch_i = :calendar.datetime_to_gregorian_seconds(epoch)
    now_i = :calendar.datetime_to_gregorian_seconds(:calendar.universal_time)
    now_i - epoch_i
  end