gologin-commonjs 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/babel.config.json +17 -0
  2. package/dist/README.md +163 -0
  3. package/dist/example.js +35 -0
  4. package/dist/examples/example-amazon-cloud-browser.js +52 -0
  5. package/dist/examples/example-amazon-headless.js +56 -0
  6. package/dist/examples/example-amazon.js +53 -0
  7. package/dist/examples/example-create-custom-profile.js +42 -0
  8. package/dist/examples/example-create-profile.js +43 -0
  9. package/dist/examples/example-custom-args.js +34 -0
  10. package/dist/examples/example-fast-profile-settings.js +59 -0
  11. package/dist/examples/example-gmail.js +82 -0
  12. package/dist/examples/example-iphey.js +19 -0
  13. package/dist/examples/example-local-profile.js +28 -0
  14. package/dist/examples/example-login-walmart.js +38 -0
  15. package/dist/examples/example-startremote.js +29 -0
  16. package/dist/examples/example-stopremote.js +22 -0
  17. package/dist/examples/example-timezone.js +51 -0
  18. package/dist/fonts.js +3339 -0
  19. package/dist/fonts_config +104 -0
  20. package/dist/gologin-browser-ext.zip +0 -0
  21. package/dist/gologin_zeroprofile.b64 +1 -0
  22. package/dist/index.d.ts +61 -0
  23. package/dist/profile_export_example.csv +2 -0
  24. package/dist/run.sh +1 -0
  25. package/dist/src/bookmarks/utils.js +23 -0
  26. package/dist/src/browser/browser-api.js +106 -0
  27. package/dist/src/browser/browser-checker.js +336 -0
  28. package/dist/src/browser/browser-user-data-manager.js +306 -0
  29. package/dist/src/cookies/cookies-manager.js +164 -0
  30. package/dist/src/extensions/extensions-extractor.js +50 -0
  31. package/dist/src/extensions/extensions-manager.js +301 -0
  32. package/dist/src/extensions/user-extensions-manager.js +246 -0
  33. package/dist/src/gologin-api.js +103 -0
  34. package/dist/src/gologin.js +1319 -0
  35. package/dist/src/profile/profile-archiver.js +68 -0
  36. package/dist/src/profile/profile-directories-to-remove.js +71 -0
  37. package/dist/src/utils/browser.js +59 -0
  38. package/dist/src/utils/common.js +60 -0
  39. package/dist/src/utils/constants.js +7 -0
  40. package/dist/src/utils/utils.js +53 -0
  41. package/dist/test.html +1 -0
  42. package/dist/zero_profile.zip +0 -0
  43. package/gologin/.eslintrc.json +290 -0
  44. package/gologin/.sentry-native/a65389b2-9a7d-41ed-7de5-95c4570f0d3d.run.lock +0 -0
  45. package/gologin/README.md +163 -0
  46. package/gologin/example.js +36 -0
  47. package/gologin/examples/example-amazon-cloud-browser.js +44 -0
  48. package/gologin/examples/example-amazon-headless.js +50 -0
  49. package/gologin/examples/example-amazon.js +47 -0
  50. package/gologin/examples/example-create-custom-profile.js +39 -0
  51. package/gologin/examples/example-create-profile.js +40 -0
  52. package/gologin/examples/example-custom-args.js +34 -0
  53. package/gologin/examples/example-fast-profile-settings.js +69 -0
  54. package/gologin/examples/example-gmail.js +67 -0
  55. package/gologin/examples/example-iphey.js +17 -0
  56. package/gologin/examples/example-local-profile.js +26 -0
  57. package/gologin/examples/example-login-walmart.js +35 -0
  58. package/gologin/examples/example-startremote.js +25 -0
  59. package/gologin/examples/example-stopremote.js +20 -0
  60. package/gologin/examples/example-timezone.js +44 -0
  61. package/gologin/fonts.js +3339 -0
  62. package/gologin/fonts_config +104 -0
  63. package/gologin/gologin-browser-ext.zip +0 -0
  64. package/gologin/gologin_zeroprofile.b64 +1 -0
  65. package/gologin/index.d.ts +61 -0
  66. package/gologin/package.json +49 -0
  67. package/gologin/profile_export_example.csv +2 -0
  68. package/gologin/run.sh +1 -0
  69. package/gologin/src/bookmarks/utils.js +16 -0
  70. package/gologin/src/browser/browser-api.js +95 -0
  71. package/gologin/src/browser/browser-checker.js +392 -0
  72. package/gologin/src/browser/browser-user-data-manager.js +335 -0
  73. package/gologin/src/cookies/cookies-manager.js +189 -0
  74. package/gologin/src/extensions/extensions-extractor.js +56 -0
  75. package/gologin/src/extensions/extensions-manager.js +384 -0
  76. package/gologin/src/extensions/user-extensions-manager.js +295 -0
  77. package/gologin/src/gologin-api.js +110 -0
  78. package/gologin/src/gologin.js +1553 -0
  79. package/gologin/src/profile/profile-archiver.js +86 -0
  80. package/gologin/src/profile/profile-directories-to-remove.js +75 -0
  81. package/gologin/src/utils/browser.js +62 -0
  82. package/gologin/src/utils/common.js +76 -0
  83. package/gologin/src/utils/constants.js +1 -0
  84. package/gologin/src/utils/utils.js +49 -0
  85. package/gologin/test.html +1 -0
  86. package/gologin/zero_profile.zip +0 -0
  87. package/package.json +46 -0
  88. package/tes.js +35 -0
@@ -0,0 +1,336 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = exports.BrowserChecker = void 0;
7
+ var _child_process = require("child_process");
8
+ var _decompress = _interopRequireDefault(require("decompress"));
9
+ var _decompressUnzip = _interopRequireDefault(require("decompress-unzip"));
10
+ var _fs = require("fs");
11
+ var _https = require("https");
12
+ var _os = require("os");
13
+ var _path = require("path");
14
+ var _progress = _interopRequireDefault(require("progress"));
15
+ var _readline = require("readline");
16
+ var _util = _interopRequireDefault(require("util"));
17
+ var _utils = require("../utils/utils.js");
18
+ var _common = require("../utils/common.js");
19
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
20
+ const exec = _util.default.promisify(_child_process.exec);
21
+ const {
22
+ access,
23
+ mkdir,
24
+ readdir,
25
+ rmdir,
26
+ unlink,
27
+ copyFile,
28
+ readlink,
29
+ symlink,
30
+ lstat,
31
+ rename,
32
+ writeFile
33
+ } = _fs.promises;
34
+ const PLATFORM = process.platform;
35
+ const ARCH = process.arch;
36
+ const VERSION_FILE = 'latest-version.txt';
37
+ const WIN_FOLDERSIZE_FILE = 'foldersize.txt';
38
+ const WIN_FOLDERSIZE_FILE_LINK = `https://orbita-browser-windows.gologin.com/${WIN_FOLDERSIZE_FILE}`;
39
+ const BROWSER_ARCHIVE_NAME = `orbita-browser-latest.${PLATFORM === 'win32' ? 'zip' : 'tar.gz'}`;
40
+ const MAC_HASH_FILE = 'hashfile.mtree';
41
+ const DEB_HASH_FILE = 'hashfile.txt';
42
+ const WIN_HASH_FILE = DEB_HASH_FILE;
43
+ const MAC_HASHFILE_LINK = `https://orbita-browser-mac.gologin.com/${MAC_HASH_FILE}`;
44
+ const DEB_HASHFILE_LINK = `https://orbita-browser-linux.gologin.com/${DEB_HASH_FILE}`;
45
+ const WIN_HASHFILE_LINK = `https://orbita-browser-windows.gologin.com/${WIN_HASH_FILE}`;
46
+ const MAC_ARM_HASHFILE_LINK = `https://orbita-browser-mac-arm.gologin.com/${MAC_HASH_FILE}`;
47
+ const FAIL_SUM_MATCH_MESSAGE = 'hash_sum_not_matched';
48
+ const EXTRACTED_FOLDER = 'extracted-browser';
49
+ class BrowserChecker {
50
+ #homedir;
51
+ #browserPath;
52
+ #executableFilePath;
53
+ #skipOrbitaHashChecking = false;
54
+ constructor(skipOrbitaHashChecking) {
55
+ this.#skipOrbitaHashChecking = skipOrbitaHashChecking;
56
+ this.#homedir = (0, _os.homedir)();
57
+ this.#browserPath = (0, _path.join)(this.#homedir, '.gologin', 'browser');
58
+ let executableFilePath = (0, _path.join)(this.#browserPath, 'orbita-browser', 'chrome');
59
+ if (PLATFORM === 'darwin') {
60
+ const orbitaFolderName = (0, _utils.findLatestBrowserVersionDirectory)(this.#browserPath);
61
+ if (orbitaFolderName === 'error') {
62
+ throw Error('Orbita folder not found in this directory: ' + this.#browserPath);
63
+ }
64
+ executableFilePath = (0, _path.join)(this.#browserPath, orbitaFolderName, 'Orbita-Browser.app', 'Contents', 'MacOS', 'Orbita');
65
+ } else if (PLATFORM === 'win32') {
66
+ executableFilePath = (0, _path.join)(this.#browserPath, 'orbita-browser', 'chrome.exe');
67
+ }
68
+ this.#executableFilePath = executableFilePath;
69
+ // console.log('executableFilePath:', executableFilePath);
70
+ }
71
+ async checkBrowser(autoUpdateBrowser = false, checkBrowserUpdate = true) {
72
+ const browserFolderExists = await access(this.#executableFilePath).then(() => true).catch(() => false);
73
+ const {
74
+ latestVersion: browserLatestVersion,
75
+ browserDownloadUrl
76
+ } = await this.getLatestBrowserVersion();
77
+ if (!browserFolderExists) {
78
+ return this.downloadBrowser(browserLatestVersion, browserDownloadUrl);
79
+ }
80
+ const currentVersionReq = await this.getCurrentVersion();
81
+ const currentVersion = (currentVersionReq?.stdout || '').replace(/(\r\n|\n|\r)/gm, '');
82
+ if (browserLatestVersion === currentVersion || !checkBrowserUpdate) {
83
+ return;
84
+ }
85
+ if (autoUpdateBrowser) {
86
+ return this.downloadBrowser(browserLatestVersion, browserDownloadUrl);
87
+ }
88
+ return new Promise(resolve => {
89
+ const rl = (0, _readline.createInterface)(process.stdin, process.stdout);
90
+ const timeout = setTimeout(() => {
91
+ console.log(`\nContinue with current ${currentVersion} version.`);
92
+ resolve();
93
+ }, 10000);
94
+ rl.question(`New Orbita ${browserLatestVersion} is available. Update? [y/n] `, answer => {
95
+ clearTimeout(timeout);
96
+ rl.close();
97
+ if (answer && answer[0].toString().toLowerCase() === 'y') {
98
+ return this.downloadBrowser(browserLatestVersion, browserDownloadUrl).then(() => resolve());
99
+ }
100
+ console.log(`Continue with current ${currentVersion} version.`);
101
+ resolve();
102
+ });
103
+ });
104
+ }
105
+ async downloadBrowser(latestVersion, browserDownloadUrl) {
106
+ await this.deleteOldArchives(true);
107
+ await mkdir(this.#browserPath, {
108
+ recursive: true
109
+ });
110
+ const pathStr = (0, _path.join)(this.#browserPath, BROWSER_ARCHIVE_NAME);
111
+ await this.downloadBrowserArchive(browserDownloadUrl, pathStr);
112
+ await this.checkBrowserArchive(pathStr);
113
+ await this.extractBrowser();
114
+ await this.checkBrowserSum(latestVersion);
115
+ console.log('Orbita hash checked successfully');
116
+ await this.replaceBrowser();
117
+ await this.addLatestVersion(latestVersion).catch(() => null);
118
+ await this.deleteOldArchives();
119
+ console.log('Orbita updated successfully');
120
+ }
121
+ addLatestVersion(latestVersion) {
122
+ return mkdir((0, _path.join)(this.#browserPath, 'orbita-browser', 'version'), {
123
+ recursive: true
124
+ }).then(() => writeFile((0, _path.join)(this.#browserPath, 'orbita-browser', 'version', 'latest-version.txt'), latestVersion));
125
+ }
126
+ downloadBrowserArchive(link, pathStr) {
127
+ return new Promise((resolve, reject) => {
128
+ const writableStream = (0, _fs.createWriteStream)(pathStr);
129
+ writableStream.on('error', async err => {
130
+ await unlink(pathStr);
131
+ reject(err);
132
+ });
133
+ writableStream.on('finish', () => resolve());
134
+ const req = (0, _https.get)(link, {
135
+ timeout: 15 * 1000
136
+ }, res => {
137
+ const len = parseInt(res.headers['content-length'], 10);
138
+ const formattedLen = len / 1024 / 1024;
139
+ const bar = new _progress.default('Orbita downloading [:bar] :rate/mps :downloadedMb/:fullMbMB :percent :etas', {
140
+ complete: '=',
141
+ incomplete: ' ',
142
+ width: 30,
143
+ total: Math.round(formattedLen)
144
+ });
145
+ let downloadedMb = 0;
146
+ res.on('data', chunk => {
147
+ const formattedChunckLenght = chunk.length / 1024 / 1024;
148
+ downloadedMb += formattedChunckLenght;
149
+ bar.tick(formattedChunckLenght, {
150
+ fullMb: formattedLen.toFixed(2),
151
+ downloadedMb: downloadedMb.toFixed(2)
152
+ });
153
+ });
154
+ res.on('end', () => {
155
+ bar.tick(bar.total, {
156
+ fullMb: formattedLen.toFixed(2),
157
+ downloadedMb: formattedLen.toFixed(2)
158
+ });
159
+ console.log('\nDownload completed');
160
+ writableStream.end();
161
+ });
162
+ res.pipe(writableStream);
163
+ });
164
+ req.on('error', err => writableStream.destroy(err));
165
+ req.end();
166
+ });
167
+ }
168
+ async checkBrowserArchive(pathStr) {
169
+ console.log('Checking Orbita archive');
170
+ try {
171
+ await access(pathStr);
172
+ } catch (e) {
173
+ throw new Error('Archive has not been found. Please run script again.');
174
+ }
175
+ }
176
+ async extractBrowser() {
177
+ console.log('Extracting Orbita');
178
+ await mkdir((0, _path.join)(this.#browserPath, EXTRACTED_FOLDER), {
179
+ recursive: true
180
+ });
181
+ if (PLATFORM === 'win32') {
182
+ return (0, _decompress.default)((0, _path.join)(this.#browserPath, BROWSER_ARCHIVE_NAME), (0, _path.join)(this.#browserPath, EXTRACTED_FOLDER), {
183
+ plugins: [(0, _decompressUnzip.default)()],
184
+ filter: file => !file.path.endsWith('/')
185
+ });
186
+ }
187
+ return exec(`tar xzf ${(0, _path.join)(this.#browserPath, BROWSER_ARCHIVE_NAME)} --directory ${(0, _path.join)(this.#browserPath, EXTRACTED_FOLDER)}`);
188
+ }
189
+ async downloadHashFile(latestVersion) {
190
+ let hashLink = DEB_HASHFILE_LINK;
191
+ let resultPath = (0, _path.join)(this.#browserPath, DEB_HASH_FILE);
192
+ if (PLATFORM === 'darwin') {
193
+ hashLink = MAC_HASHFILE_LINK;
194
+ if (ARCH === 'arm64') {
195
+ hashLink = MAC_ARM_HASHFILE_LINK;
196
+ }
197
+ resultPath = (0, _path.join)(this.#browserPath, MAC_HASH_FILE);
198
+ }
199
+ if (latestVersion) {
200
+ const [majorVer] = latestVersion.split('.');
201
+ hashLink = hashLink.replace('hashfile.', `hashfile-${majorVer}.`);
202
+ }
203
+ const writableStream = (0, _fs.createWriteStream)(resultPath);
204
+ writableStream.on('error', async err => {
205
+ await unlink(resultPath);
206
+ throw err;
207
+ });
208
+ await new Promise(resolve => (0, _https.get)(hashLink, {
209
+ timeout: 10 * 1000
210
+ }, res => {
211
+ res.on('end', () => {
212
+ console.log('Hashfile downloading completed');
213
+ writableStream.end();
214
+ resolve();
215
+ });
216
+ res.pipe(writableStream);
217
+ }).on('error', err => writableStream.destroy(err)));
218
+ const hashFile = PLATFORM === 'darwin' ? MAC_HASH_FILE : DEB_HASH_FILE;
219
+ const hashFilePath = (0, _path.join)(this.#browserPath, hashFile);
220
+ return access(hashFilePath);
221
+ }
222
+ async checkBrowserSum(latestVersion) {
223
+ if (this.#skipOrbitaHashChecking) {
224
+ return Promise.resolve();
225
+ }
226
+ console.log('Orbita hash checking');
227
+ if (PLATFORM === 'win32') {
228
+ return Promise.resolve();
229
+ }
230
+ await this.downloadHashFile(latestVersion);
231
+ if (PLATFORM === 'darwin') {
232
+ const calculatedHash = await exec(`mtree -p ${(0, _path.join)(this.#browserPath, EXTRACTED_FOLDER, 'Orbita-Browser.app')} < ${(0, _path.join)(this.#browserPath, MAC_HASH_FILE)} || echo ${FAIL_SUM_MATCH_MESSAGE}`);
233
+ const checkedRes = (calculatedHash || '').toString().trim();
234
+ if (checkedRes.includes(FAIL_SUM_MATCH_MESSAGE)) {
235
+ throw new Error('Error in sum matching. Please run script again.');
236
+ }
237
+ return;
238
+ }
239
+ const hashFileContent = await exec(`cat ${(0, _path.join)(this.#browserPath, DEB_HASH_FILE)}`);
240
+ let serverRes = (hashFileContent.stdout || '').toString().trim();
241
+ serverRes = serverRes.split(' ')[0];
242
+ const calculateLocalBrowserHash = await exec(`cd ${(0, _path.join)(this.#browserPath, EXTRACTED_FOLDER)} && find orbita-browser -type f -print0 | sort -z | \
243
+ xargs -0 sha256sum > ${this.#browserPath}/calculatedFolderSha.txt`);
244
+ const localHashContent = await exec(`cd ${this.#browserPath} && sha256sum calculatedFolderSha.txt`);
245
+ let userRes = (localHashContent.stdout || '').toString().trim();
246
+ userRes = userRes.split(' ')[0];
247
+ if (userRes !== serverRes) {
248
+ throw new Error('Error in sum matching. Please run script again.');
249
+ }
250
+ }
251
+ async replaceBrowser() {
252
+ console.log('Copy Orbita to target path');
253
+ if (PLATFORM === 'darwin') {
254
+ return rename((0, _path.join)(this.#browserPath, EXTRACTED_FOLDER), (0, _path.join)(this.#browserPath, 'orbita-browser'));
255
+ }
256
+ const targetBrowserPath = (0, _path.join)(this.#browserPath, 'orbita-browser');
257
+ await this.deleteDir(targetBrowserPath);
258
+ await this.copyDir((0, _path.join)(this.#browserPath, EXTRACTED_FOLDER, 'orbita-browser'), targetBrowserPath);
259
+ }
260
+ async deleteOldArchives(deleteCurrentBrowser = false) {
261
+ if (deleteCurrentBrowser) {
262
+ return this.deleteDir((0, _path.join)(this.#browserPath, 'orbita-browser'));
263
+ }
264
+ await this.deleteDir((0, _path.join)(this.#browserPath, EXTRACTED_FOLDER));
265
+ return readdir(this.#browserPath).then(files => {
266
+ const promises = [];
267
+ files.forEach(filename => {
268
+ if (filename.match(/(txt|dylib|mtree)/)) {
269
+ promises.push(unlink((0, _path.join)(this.#browserPath, filename)));
270
+ }
271
+ });
272
+ return Promise.all(promises);
273
+ }).catch(e => {
274
+ console.log(`Error in deleting old archives. ${e.message}`);
275
+ return Promise.resolve();
276
+ });
277
+ }
278
+ async copyDir(src, dest) {
279
+ await mkdir(dest);
280
+ const files = await readdir(src);
281
+ for (let i = 0; i < files.length; i++) {
282
+ const current = await lstat((0, _path.join)(src, files[i]));
283
+ if (current.isDirectory()) {
284
+ await this.copyDir((0, _path.join)(src, files[i]), (0, _path.join)(dest, files[i]));
285
+ } else if (current.isSymbolicLink()) {
286
+ const symlinkObj = await readlink((0, _path.join)(src, files[i]));
287
+ await symlink(symlinkObj, (0, _path.join)(dest, files[i]));
288
+ } else {
289
+ await copyFile((0, _path.join)(src, files[i]), (0, _path.join)(dest, files[i]));
290
+ }
291
+ }
292
+ }
293
+ getCurrentVersion() {
294
+ let command = `if [ -f ${(0, _path.join)(this.#browserPath, 'orbita-browser', 'version')} ]; then cat ${(0, _path.join)(this.#browserPath, 'orbita-browser', 'version')}; else echo 0.0.0; fi`;
295
+ if (PLATFORM === 'win32') {
296
+ command = `if exist "${(0, _path.join)(this.#browserPath, 'orbita-browser', 'version')}" (type "${(0, _path.join)(this.#browserPath, 'orbita-browser', 'version')}") else (echo 0.0.0)`;
297
+ } else if (PLATFORM === 'darwin') {
298
+ command = `if [ -f ${(0, _path.join)(this.#browserPath, 'orbita-browser', 'version', VERSION_FILE)} ]; then cat ${(0, _path.join)(this.#browserPath, 'orbita-browser', 'version', VERSION_FILE)}; else echo 0.0.0; fi`;
299
+ }
300
+ return exec(command);
301
+ }
302
+ getLatestBrowserVersion() {
303
+ const userOs = (0, _common.getOS)();
304
+ return new Promise(resolve => (0, _https.get)(`${_common.API_URL}/gologin-global-settings/latest-browser-info?os=${userOs}`, {
305
+ timeout: 15 * 1000,
306
+ headers: {
307
+ 'Content-Type': 'application/json',
308
+ 'User-Agent': 'gologin-api'
309
+ }
310
+ }, res => {
311
+ res.setEncoding('utf8');
312
+ let resultResponse = '';
313
+ res.on('data', data => resultResponse += data);
314
+ res.on('end', () => {
315
+ resolve(JSON.parse(resultResponse.trim()));
316
+ });
317
+ }).on('error', err => resolve('')));
318
+ }
319
+ get getOrbitaPath() {
320
+ return this.#executableFilePath;
321
+ }
322
+ async deleteDir(path = '') {
323
+ if (!path) {
324
+ return;
325
+ }
326
+ const directoryExists = await access(path).then(() => true).catch(() => false);
327
+ if (!directoryExists) {
328
+ return;
329
+ }
330
+ return rmdir(path, {
331
+ recursive: true
332
+ });
333
+ }
334
+ }
335
+ exports.BrowserChecker = BrowserChecker;
336
+ var _default = exports.default = BrowserChecker;
@@ -0,0 +1,306 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.uploadCookies = exports.setOriginalExtPaths = exports.setExtPathsAndRemoveDeleted = exports.recalculateId = exports.downloadFonts = exports.downloadCookies = exports.copyFontsConfigFile = exports.composeFonts = void 0;
7
+ var _crypto = require("crypto");
8
+ var _fs = require("fs");
9
+ var _os = require("os");
10
+ var _path = require("path");
11
+ var _url = require("url");
12
+ var _requestretry = _interopRequireDefault(require("requestretry"));
13
+ var _fonts = require("../../fonts.js");
14
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
15
+ const {
16
+ access,
17
+ readFile,
18
+ writeFile,
19
+ mkdir,
20
+ readdir,
21
+ copyFile,
22
+ rename
23
+ } = _fs.promises;
24
+ const _filename = (0, _url.fileURLToPath)(require('url').pathToFileURL(__filename).toString());
25
+ const _dirname = (0, _path.dirname)(_filename);
26
+ const FONTS_URL = 'https://fonts.gologin.com/';
27
+ const FONTS_DIR_NAME = 'fonts';
28
+ const HOMEDIR = (0, _os.homedir)();
29
+ const BROWSER_PATH = (0, _path.join)(HOMEDIR, '.gologin', 'browser');
30
+ const OS_PLATFORM = process.platform;
31
+ const DEFAULT_ORBITA_EXTENSIONS_NAMES = ['Google Hangouts', 'Chromium PDF Viewer', 'CryptoTokenExtension', 'Web Store'];
32
+ const GOLOGIN_BASE_FOLDER_NAME = '.gologin';
33
+ const GOLOGIN_TEST_FOLDER_NAME = '.gologin_test';
34
+ const osPlatform = process.platform;
35
+ const downloadCookies = ({
36
+ profileId,
37
+ ACCESS_TOKEN,
38
+ API_BASE_URL
39
+ }) => _requestretry.default.get(`${API_BASE_URL}/browser/${profileId}/cookies`, {
40
+ headers: {
41
+ Authorization: `Bearer ${ACCESS_TOKEN}`,
42
+ 'user-agent': 'gologin-api'
43
+ },
44
+ json: true,
45
+ maxAttempts: 3,
46
+ retryDelay: 2000,
47
+ timeout: 10 * 1000
48
+ }).catch(e => {
49
+ console.log(e);
50
+ return {
51
+ body: []
52
+ };
53
+ });
54
+ exports.downloadCookies = downloadCookies;
55
+ const uploadCookies = ({
56
+ cookies = [],
57
+ profileId,
58
+ ACCESS_TOKEN,
59
+ API_BASE_URL
60
+ }) => _requestretry.default.post(`${API_BASE_URL}/browser/${profileId}/cookies/?encrypted=true`, {
61
+ headers: {
62
+ Authorization: `Bearer ${ACCESS_TOKEN}`,
63
+ 'User-Agent': 'gologin-api'
64
+ },
65
+ json: cookies,
66
+ maxAttempts: 3,
67
+ retryDelay: 2000,
68
+ timeout: 20 * 1000
69
+ }).catch(e => {
70
+ console.log(e);
71
+ return e;
72
+ });
73
+ exports.uploadCookies = uploadCookies;
74
+ const downloadFonts = async (fontsList = [], profilePath) => {
75
+ if (!fontsList.length) {
76
+ return;
77
+ }
78
+ const browserFontsPath = (0, _path.join)(BROWSER_PATH, FONTS_DIR_NAME);
79
+ await mkdir(browserFontsPath, {
80
+ recursive: true
81
+ });
82
+ const files = await readdir(browserFontsPath);
83
+ const fontsToDownload = fontsList.filter(font => !files.includes(font));
84
+ let promises = fontsToDownload.map(font => _requestretry.default.get(FONTS_URL + font, {
85
+ maxAttempts: 5,
86
+ retryDelay: 2000,
87
+ timeout: 30 * 1000
88
+ }).pipe((0, _fs.createWriteStream)((0, _path.join)(browserFontsPath, font))));
89
+ if (promises.length) {
90
+ await Promise.all(promises);
91
+ }
92
+ promises = fontsList.map(font => copyFile((0, _path.join)(browserFontsPath, font), (0, _path.join)(profilePath, FONTS_DIR_NAME, font)));
93
+ await Promise.all(promises);
94
+ };
95
+ exports.downloadFonts = downloadFonts;
96
+ const composeFonts = async (fontsList = [], profilePath, differentOs = false) => {
97
+ if (!(fontsList.length && profilePath)) {
98
+ return;
99
+ }
100
+ const fontsToDownload = _fonts.fontsCollection.filter(elem => fontsList.includes(elem.value)).reduce((res, elem) => res.concat(elem.fileNames || []), []);
101
+ if (differentOs && !fontsToDownload.length) {
102
+ throw new Error('No fonts to download found. Use getAvailableFonts() method and set some fonts from this list');
103
+ }
104
+ fontsToDownload.push('LICENSE.txt');
105
+ fontsToDownload.push('OFL.txt');
106
+ const pathToFontsDir = (0, _path.join)(profilePath, FONTS_DIR_NAME);
107
+ const fontsDirExists = await access(pathToFontsDir).then(() => true, () => false);
108
+ if (fontsDirExists) {
109
+ (0, _fs.rmdirSync)(pathToFontsDir, {
110
+ recursive: true
111
+ });
112
+ }
113
+ await mkdir(pathToFontsDir, {
114
+ recursive: true
115
+ });
116
+ await downloadFonts(fontsToDownload, profilePath);
117
+ if (OS_PLATFORM === 'linux') {
118
+ await copyFontsConfigFile(profilePath);
119
+ }
120
+ };
121
+ exports.composeFonts = composeFonts;
122
+ const copyFontsConfigFile = async profilePath => {
123
+ if (!profilePath) {
124
+ return;
125
+ }
126
+ const fileContent = await readFile((0, _path.resolve)(_dirname, '..', '..', 'fonts_config'), 'utf-8');
127
+ const result = fileContent.replace(/\$\$GOLOGIN_FONTS\$\$/g, (0, _path.join)(profilePath, FONTS_DIR_NAME));
128
+ const defaultFolderPath = (0, _path.join)(profilePath, 'Default');
129
+ await mkdir(defaultFolderPath, {
130
+ recursive: true
131
+ });
132
+ await writeFile((0, _path.join)(defaultFolderPath, 'fonts_config'), result);
133
+ };
134
+ exports.copyFontsConfigFile = copyFontsConfigFile;
135
+ const setExtPathsAndRemoveDeleted = (settings = {}, profileExtensionsCheckRes = [], profileId = '') => {
136
+ const formattedLocalExtArray = profileExtensionsCheckRes.map(el => {
137
+ const [extFolderName = ''] = el.split(_path.sep).reverse();
138
+ const [originalId] = extFolderName.split('@');
139
+ if (!originalId) {
140
+ return null;
141
+ }
142
+ return {
143
+ path: el,
144
+ originalId
145
+ };
146
+ }).filter(Boolean);
147
+ const extensionsSettings = settings.extensions?.settings || {};
148
+ const extensionsEntries = Object.entries(extensionsSettings);
149
+ const promises = extensionsEntries.map(async extensionObj => {
150
+ let [extensionId, currentExtSettings = {}] = extensionObj;
151
+ const extName = currentExtSettings.manifest?.name || '';
152
+ let extPath = currentExtSettings.path || '';
153
+ let originalId = '';
154
+ const isExtensionToBeDeleted = ['resources', 'passwords-ext', 'cookies-ext'].some(substring => extPath.includes(substring)) && [GOLOGIN_BASE_FOLDER_NAME, GOLOGIN_TEST_FOLDER_NAME].some(substring => extPath.includes(substring)) || DEFAULT_ORBITA_EXTENSIONS_NAMES.includes(extName) && [GOLOGIN_BASE_FOLDER_NAME, GOLOGIN_TEST_FOLDER_NAME].some(substring => extPath.includes(substring));
155
+ if (isExtensionToBeDeleted) {
156
+ delete extensionsSettings[extensionId];
157
+ return;
158
+ }
159
+ if (osPlatform === 'win32') {
160
+ extPath = extPath.replace(/\//g, '\\');
161
+ } else {
162
+ extPath = extPath.replace(/\\/g, '/');
163
+ }
164
+ extensionsSettings[extensionId].path = extPath;
165
+ const splittedPath = extPath.split(_path.sep);
166
+ const isExtensionManageable = ['chrome-extensions', 'user-extensions'].some(substring => extPath.includes(substring)) && [GOLOGIN_BASE_FOLDER_NAME, GOLOGIN_TEST_FOLDER_NAME].some(substring => extPath.includes(substring));
167
+ if (isExtensionManageable) {
168
+ const [extFolderName] = extPath.split(_path.sep).reverse();
169
+ [originalId] = extFolderName.split('@');
170
+ } else if (splittedPath.length === 2) {
171
+ [originalId] = splittedPath;
172
+ }
173
+ if (isExtensionManageable || splittedPath.length === 2) {
174
+ const isExtensionInProfileSettings = formattedLocalExtArray.find(el => el.path.includes(originalId));
175
+ if (!isExtensionInProfileSettings) {
176
+ delete extensionsSettings[extensionId];
177
+ return;
178
+ }
179
+ }
180
+ const localExtObj = originalId && formattedLocalExtArray.find(el => el.path.includes(originalId));
181
+ if (!localExtObj) {
182
+ return;
183
+ }
184
+ const initialExtName = extensionId;
185
+ extensionId = await recalculateId({
186
+ localExtObj,
187
+ extensionId,
188
+ extensionsSettings,
189
+ currentExtSettings
190
+ });
191
+ if (initialExtName !== extensionId) {
192
+ const profilePath = (0, _path.join)((0, _os.tmpdir)(), `gologin_profile_${profileId}`);
193
+ const extSyncFolder = (0, _path.join)(profilePath, 'Default', 'Sync Extension Settings', initialExtName);
194
+ const newSyncFolder = (0, _path.join)(profilePath, 'Default', 'Sync Extension Settings', extensionId);
195
+ await rename(extSyncFolder, newSyncFolder).catch(() => null);
196
+ }
197
+ if (localExtObj.path.endsWith('.zip')) {
198
+ localExtObj.path = localExtObj.path.replace('.zip', '');
199
+ }
200
+ extensionsSettings[extensionId].path = localExtObj.path || '';
201
+ });
202
+ return Promise.all(promises).then(() => extensionsSettings);
203
+ };
204
+ exports.setExtPathsAndRemoveDeleted = setExtPathsAndRemoveDeleted;
205
+ const setOriginalExtPaths = async (settings = {}, originalExtensionsFolder = '') => {
206
+ if (!originalExtensionsFolder) {
207
+ return null;
208
+ }
209
+ const extensionsSettings = settings.extensions?.settings || {};
210
+ const extensionsEntries = Object.entries(extensionsSettings);
211
+ const originalExtensionsList = await readdir(originalExtensionsFolder).catch(() => []);
212
+ if (!originalExtensionsList.length) {
213
+ return null;
214
+ }
215
+ const promises = originalExtensionsList.map(async originalId => {
216
+ const extFolderPath = (0, _path.join)(originalExtensionsFolder, originalId);
217
+ const extFolderContent = await readdir(extFolderPath);
218
+ if (!extFolderPath.length) {
219
+ return {};
220
+ }
221
+ if (extFolderContent.includes('manifest.json')) {
222
+ return {
223
+ originalId,
224
+ path: (0, _path.join)(originalExtensionsFolder, originalId)
225
+ };
226
+ }
227
+ const [version] = extFolderContent;
228
+ return {
229
+ originalId,
230
+ path: (0, _path.join)(originalExtensionsFolder, originalId, version)
231
+ };
232
+ });
233
+ const originalExtPaths = await Promise.all(promises);
234
+ extensionsEntries.forEach(extensionObj => {
235
+ const [extensionsId] = extensionObj;
236
+ const extPath = extensionsSettings[extensionsId].path;
237
+ if (!/chrome-extensions/.test(extPath)) {
238
+ return;
239
+ }
240
+ const originalExtPath = originalExtPaths.find(el => el.originalId === extensionsId);
241
+ if (!originalExtPath) {
242
+ return;
243
+ }
244
+ extensionsSettings[extensionsId].path = originalExtPath.path || '';
245
+ });
246
+ return extensionsSettings;
247
+ };
248
+ exports.setOriginalExtPaths = setOriginalExtPaths;
249
+ const recalculateId = async ({
250
+ localExtObj,
251
+ extensionId,
252
+ extensionsSettings,
253
+ currentExtSettings
254
+ }) => {
255
+ if (currentExtSettings.manifest?.key) {
256
+ return extensionId;
257
+ }
258
+ const manifestFilePath = (0, _path.join)(localExtObj.path, 'manifest.json');
259
+ const manifestString = await readFile(manifestFilePath, {
260
+ encoding: 'utf8'
261
+ }).catch(() => ({}));
262
+ if (!manifestString) {
263
+ return extensionId;
264
+ }
265
+ let manifestObject;
266
+ try {
267
+ manifestObject = JSON.parse(manifestString);
268
+ } catch {
269
+ return extensionId;
270
+ }
271
+ if (manifestObject.key) {
272
+ return extensionId;
273
+ }
274
+ let encoding = 'utf8';
275
+ if (osPlatform === 'win32') {
276
+ encoding = 'utf16le';
277
+ }
278
+ const extPathToEncode = Buffer.from(localExtObj.path, encoding);
279
+ const hexEncodedPath = (0, _crypto.createHash)('sha256').update(extPathToEncode).digest('hex');
280
+ const newId = hexEncodedPath.split('').slice(0, 32).map(symbol => extIdEncoding[symbol]).join('');
281
+ if (extensionId !== newId) {
282
+ delete extensionsSettings[extensionId];
283
+ extensionsSettings[newId] = currentExtSettings;
284
+ extensionId = newId;
285
+ }
286
+ return extensionId;
287
+ };
288
+ exports.recalculateId = recalculateId;
289
+ const extIdEncoding = {
290
+ 0: 'a',
291
+ 1: 'b',
292
+ 2: 'c',
293
+ 3: 'd',
294
+ 4: 'e',
295
+ 5: 'f',
296
+ 6: 'g',
297
+ 7: 'h',
298
+ 8: 'i',
299
+ 9: 'j',
300
+ a: 'k',
301
+ b: 'l',
302
+ c: 'm',
303
+ d: 'n',
304
+ e: 'o',
305
+ f: 'p'
306
+ };