github-token.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { createTokenAuth } from '@octokit/auth-token';
  2. import got from 'got';
  3. import { ElectronReleaseRepo } from './types';
  4. const cachedTokens = Object.create(null);
  5. async function ensureToken (repo: ElectronReleaseRepo) {
  6. if (!cachedTokens[repo]) {
  7. cachedTokens[repo] = await (async () => {
  8. const { ELECTRON_GITHUB_TOKEN, SUDOWOODO_EXCHANGE_URL, SUDOWOODO_EXCHANGE_TOKEN } = process.env;
  9. if (ELECTRON_GITHUB_TOKEN) {
  10. return ELECTRON_GITHUB_TOKEN;
  11. }
  12. if (SUDOWOODO_EXCHANGE_URL && SUDOWOODO_EXCHANGE_TOKEN) {
  13. const resp = await got.post(SUDOWOODO_EXCHANGE_URL + '?repo=' + repo, {
  14. headers: {
  15. Authorization: SUDOWOODO_EXCHANGE_TOKEN
  16. },
  17. throwHttpErrors: false
  18. });
  19. if (resp.statusCode !== 200) {
  20. console.error('bad sudowoodo exchange response code:', resp.statusCode);
  21. throw new Error('non-200 status code received from sudowoodo exchange function');
  22. }
  23. try {
  24. return JSON.parse(resp.body).token;
  25. } catch {
  26. // Swallow as the error could include the token
  27. throw new Error('Unexpected error parsing sudowoodo exchange response');
  28. }
  29. }
  30. throw new Error('Could not find or fetch a valid GitHub Auth Token');
  31. })();
  32. }
  33. }
  34. export const createGitHubTokenStrategy = (repo: ElectronReleaseRepo) => () => {
  35. let tokenAuth: ReturnType<typeof createTokenAuth> | null = null;
  36. async function ensureTokenAuth (): Promise<ReturnType<typeof createTokenAuth>> {
  37. if (!tokenAuth) {
  38. await ensureToken(repo);
  39. tokenAuth = createTokenAuth(cachedTokens[repo]);
  40. }
  41. return tokenAuth;
  42. }
  43. async function auth () {
  44. return await (await ensureTokenAuth())();
  45. }
  46. const hook: ReturnType<typeof createTokenAuth>['hook'] = async (...args) => {
  47. const a = (await ensureTokenAuth());
  48. return (a as any).hook(...args);
  49. };
  50. auth.hook = hook;
  51. return auth;
  52. };