fxa.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. const fetch = require('node-fetch');
  2. const config = require('./config');
  3. const KEY_SCOPE = config.fxa_key_scope;
  4. let fxaConfig = null;
  5. let lastConfigRefresh = 0;
  6. async function getFxaConfig() {
  7. if (fxaConfig && Date.now() - lastConfigRefresh < 1000 * 60 * 5) {
  8. return fxaConfig;
  9. }
  10. try {
  11. const res = await fetch(
  12. `${config.fxa_url}/.well-known/openid-configuration`,
  13. { timeout: 3000 }
  14. );
  15. fxaConfig = await res.json();
  16. fxaConfig.key_scope = KEY_SCOPE;
  17. lastConfigRefresh = Date.now();
  18. } catch (e) {
  19. // continue with previous fxaConfig
  20. }
  21. return fxaConfig;
  22. }
  23. module.exports = {
  24. getFxaConfig,
  25. verify: async function(token) {
  26. if (!token) {
  27. return null;
  28. }
  29. const c = await getFxaConfig();
  30. try {
  31. const verifyUrl = c.jwks_uri.replace('jwks', 'verify'); //HACK
  32. const result = await fetch(verifyUrl, {
  33. method: 'POST',
  34. headers: { 'Content-Type': 'application/json' },
  35. body: JSON.stringify({ token })
  36. });
  37. const info = await result.json();
  38. if (
  39. info.scope &&
  40. Array.isArray(info.scope) &&
  41. info.scope.includes(KEY_SCOPE)
  42. ) {
  43. return info.user;
  44. }
  45. } catch (e) {
  46. // gulp
  47. }
  48. return null;
  49. }
  50. };