user-agent.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import { app } from 'electron';
  2. const REMOVE_CHROME_COMPONENT_PATTERNS = [
  3. /^https:\/\/accounts\.google\.com(\/|$)/,
  4. ];
  5. const CHROME_COMPONENT_PATTERN = / Chrome\\?.([^\s]+)/g;
  6. const COMPONENTS_TO_REMOVE = [
  7. / Electron\\?.([^\s]+)/g,
  8. ` ${app.name}/${app.getVersion()}`,
  9. ];
  10. // TODO(sentialx): script to update stable Chrome version?
  11. const COMPONENTS_TO_REPLACE: [string | RegExp, string][] = [
  12. [CHROME_COMPONENT_PATTERN, ' Chrome/87.0.4280.88'],
  13. ];
  14. const urlMatchesPatterns = (url: string, patterns: RegExp[]) =>
  15. patterns.some((pattern) => url.match(pattern));
  16. /**
  17. * Checks if a given url is suitable for removal of Chrome
  18. * component from the user agent string.
  19. * @param url
  20. */
  21. const shouldRemoveChromeString = (url: string) =>
  22. urlMatchesPatterns(url, REMOVE_CHROME_COMPONENT_PATTERNS);
  23. export const getUserAgentForURL = (userAgent: string, url: string) => {
  24. let componentsToRemove = [...COMPONENTS_TO_REMOVE];
  25. // For accounts.google.com, we remove Chrome/*.* component
  26. // from the user agent, to fix compatibility issues on Google Sign In.
  27. // WATCH: https://developers.googleblog.com/2020/08/guidance-for-our-effort-to-block-less-secure-browser-and-apps.html
  28. if (shouldRemoveChromeString(url)) {
  29. componentsToRemove = [...componentsToRemove, CHROME_COMPONENT_PATTERN];
  30. }
  31. // Replace the components.
  32. [
  33. // Convert components to remove to pairs.
  34. ...componentsToRemove.map((x): [string | RegExp, string] => [x, '']),
  35. ...COMPONENTS_TO_REPLACE,
  36. ].forEach((x) => (userAgent = userAgent.replace(x[0], x[1])));
  37. return userAgent;
  38. };