fxa.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. const res = await fetch(
  11. `${config.fxa_url}/.well-known/openid-configuration`,
  12. { timeout: 3000 }
  13. );
  14. fxaConfig = await res.json();
  15. fxaConfig.key_scope = KEY_SCOPE;
  16. lastConfigRefresh = Date.now();
  17. return fxaConfig;
  18. }
  19. module.exports = {
  20. getFxaConfig,
  21. verify: async function(token) {
  22. if (!token) {
  23. return null;
  24. }
  25. const c = await getFxaConfig();
  26. try {
  27. const verifyUrl = c.jwks_uri.replace('jwks', 'verify'); //HACK
  28. const result = await fetch(verifyUrl, {
  29. method: 'POST',
  30. headers: { 'Content-Type': 'application/json' },
  31. body: JSON.stringify({ token })
  32. });
  33. const info = await result.json();
  34. if (
  35. info.scope &&
  36. Array.isArray(info.scope) &&
  37. info.scope.includes(KEY_SCOPE)
  38. ) {
  39. return info.user;
  40. }
  41. } catch (e) {
  42. // gulp
  43. }
  44. return null;
  45. }
  46. };