aboutsummaryrefslogtreecommitdiffstats
path: root/packages/main/src/userAgent.ts
blob: 298e5652c3fc0eef68e32ac9e99c2cd8bbaac041 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
 * Copyright (C)  2021-2022 Kristóf Marussy <kristof@marussy.com>
 *
 * This file is part of Sophie.
 *
 * Sophie is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * SPDX-License-Identifier: AGPL-3.0-only
 */

/**
 * @file Based on the javascript code snippet available at
 * https://github.com/GoogleChrome/developer.chrome.com/blob/c33f7f4f2964e7deb28aee44de745c3725b70063/site/en/docs/privacy-sandbox/user-agent/snippets/index.md
 *
 * Used under the Apache 2.0 license according to
 * https://github.com/GoogleChrome/developer.chrome.com/blob/c33f7f4f2964e7deb28aee44de745c3725b70063/LICENSE
 */

const electronUAParts = / (sophie|Electron)\/[^\s]+/g;
const chromeUAs = /^Mozilla\/5\.0 \(((?<platform>Lin|Win|Mac|X11; C|X11; L)+[^\)]+)\) AppleWebKit\/537.36 \(KHTML, like Gecko\) Chrome\/(?<major>\d+)[\d\.]+(?<mobile>[ Mobile]*) Safari\/537\.36$/;
const unifiedPlatform = {
  'Lin': 'Linux; Android 10; K',
  'Win': 'Windows NT 10.0; Win64; x64',
  'Mac': 'Macintosh; Intel Mac OS X 10_15_7',
  'X11; C': 'X11; CrOS x86_64',
  'X11; L': 'X11; Linux x86_64',
};

/**
 * Reduces the information exposed in the user-agent string.
 *
 * @param userAgent The original user-agent string.
 * @returns The reduces user-agent string.
 * @see https://developer.chrome.com/docs/privacy-sandbox/user-agent/
 */
export function reduceUserAgent(userAgent: string): string {
  const userAgentWithoutElectron = userAgent.replaceAll(electronUAParts, '');
  const matched = chromeUAs.exec(userAgentWithoutElectron) as unknown as {
    groups: {
      platform: 'Lin' | 'Win' | 'Mac' | 'X11; C' | 'X11; L',
      major: string,
      mobile: string,
    }
  };
  if (matched) {
    return `Mozilla/5.0 (${unifiedPlatform[matched.groups.platform]}) ` +
      `AppleWebKit/537.36 (KHTML, like Gecko) ` +
      `Chrome/${matched.groups.major}.0.0.0${matched.groups.mobile} Safari/537.36`
  }
  return userAgentWithoutElectron;
}