get-url-hash.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import got from 'got';
  2. import * as url from 'node:url';
  3. const HASHER_FUNCTION_HOST = 'electron-artifact-hasher.azurewebsites.net';
  4. const HASHER_FUNCTION_ROUTE = '/api/HashArtifact';
  5. export async function getUrlHash (targetUrl: string, algorithm = 'sha256', attempts = 3) {
  6. const options = {
  7. code: process.env.ELECTRON_ARTIFACT_HASHER_FUNCTION_KEY!,
  8. targetUrl,
  9. algorithm
  10. };
  11. const search = new url.URLSearchParams(options);
  12. const functionUrl = url.format({
  13. protocol: 'https:',
  14. hostname: HASHER_FUNCTION_HOST,
  15. pathname: HASHER_FUNCTION_ROUTE,
  16. search: search.toString()
  17. });
  18. try {
  19. const resp = await got(functionUrl, {
  20. throwHttpErrors: false
  21. });
  22. if (resp.statusCode !== 200) {
  23. console.error('bad hasher function response:', resp.body.trim());
  24. throw new Error('non-200 status code received from hasher function');
  25. }
  26. if (!resp.body) throw new Error('Successful lambda call but failed to get valid hash');
  27. return resp.body.trim();
  28. } catch (err) {
  29. if (attempts > 1) {
  30. const { response } = err as any;
  31. if (response?.body) {
  32. console.error(`Failed to get URL hash for ${targetUrl} - we will retry`, {
  33. statusCode: response.statusCode,
  34. body: JSON.parse(response.body)
  35. });
  36. } else {
  37. console.error(`Failed to get URL hash for ${targetUrl} - we will retry`, err);
  38. }
  39. return getUrlHash(targetUrl, algorithm, attempts - 1);
  40. }
  41. throw err;
  42. }
  43. };