gologin-commonjs 2.1.13 → 3.0.0

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 (36) hide show
  1. package/dist/src/gologin.js +299 -248
  2. package/dist/src/utils/timezone.js +21 -0
  3. package/gologin/.eslintrc.json +290 -0
  4. package/gologin/package.json +1 -1
  5. package/gologin/src/gologin.js +671 -395
  6. package/gologin/src/utils/timezone.js +470 -0
  7. package/package.json +3 -1
  8. package/tes.js +2 -1
  9. package/tsconfig.json +23 -0
  10. package/types/fonts.d.ts +21 -0
  11. package/types/{bookmarks → src/bookmarks}/utils.d.ts +0 -1
  12. package/types/src/browser/browser-api.d.ts +10 -0
  13. package/types/{browser → src/browser}/browser-checker.d.ts +1 -2
  14. package/types/{browser → src/browser}/browser-user-data-manager.d.ts +0 -1
  15. package/types/{cookies → src/cookies}/cookies-manager.d.ts +7 -3
  16. package/types/{extensions → src/extensions}/extensions-extractor.d.ts +0 -1
  17. package/types/{extensions → src/extensions}/extensions-manager.d.ts +4 -7
  18. package/types/{extensions → src/extensions}/user-extensions-manager.d.ts +1 -2
  19. package/types/src/gologin-api.d.ts +17 -0
  20. package/types/{gologin.d.ts → src/gologin.d.ts} +18 -35
  21. package/types/{profile → src/profile}/profile-archiver.d.ts +1 -2
  22. package/types/{profile → src/profile}/profile-directories-to-remove.d.ts +0 -1
  23. package/types/{utils → src/utils}/browser.d.ts +0 -1
  24. package/types/src/utils/common.d.ts +10 -0
  25. package/types/{utils → src/utils}/constants.d.ts +0 -1
  26. package/types/src/utils/timezone.d.ts +1 -0
  27. package/types/{utils → src/utils}/utils.d.ts +0 -1
  28. package/types/src/utils/zero-profile-bookmarks.d.ts +41 -0
  29. package/types/src/utils/zero-profile-preferences.d.ts +219 -0
  30. package/dist/fonts_config +0 -104
  31. package/dist/gologin-browser-ext.zip +0 -0
  32. package/dist/gologin_zeroprofile.b64 +0 -1
  33. package/dist/index.d.ts +0 -61
  34. package/dist/zero_profile.zip +0 -0
  35. package/types/browser/browser-api.d.ts +0 -10
  36. package/types/utils/common.d.ts +0 -10
@@ -28,6 +28,7 @@ var _path = require("path");
28
28
  var _requestretry = _interopRequireDefault(require("requestretry"));
29
29
  var _rimraf = _interopRequireDefault(require("rimraf"));
30
30
  var _socksProxyAgent = require("socks-proxy-agent");
31
+ var _url = require("url");
31
32
  var _fonts = require("../fonts.js");
32
33
  var _utils = require("./bookmarks/utils.js");
33
34
  var _browserApi = require("./browser/browser-api.js");
@@ -43,6 +44,7 @@ var _utils2 = require("./utils/utils.js");
43
44
  var _gologinApi = require("./gologin-api.js");
44
45
  var _zeroProfileBookmarks = require("./utils/zero-profile-bookmarks.js");
45
46
  var _zeroProfilePreferences = require("./utils/zero-profile-preferences.js");
47
+ var _timezone = require("./utils/timezone.js");
46
48
  function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
47
49
  const {
48
50
  access,
@@ -54,13 +56,14 @@ const {
54
56
  } = _fs.promises;
55
57
  const SEPARATOR = _path.sep;
56
58
  const OS_PLATFORM = process.platform;
57
- const TIMEZONE_URL = 'https://geo.myip.link';
58
- const PROXY_NONE = 'none';
59
- const debug = (0, _debug.default)('gologin');
59
+ const TIMEZONE_URL = "https://geolocation-db.com/json/";
60
+ // const TIMEZONE_URL = 'https://geo.myip.link';
61
+ const PROXY_NONE = "none";
62
+ const debug = (0, _debug.default)("gologin");
60
63
  const delay = time => new Promise(resolve => setTimeout(resolve, time));
61
64
  class GoLogin {
62
65
  constructor(options = {}) {
63
- this.browserLang = 'en-US';
66
+ this.browserLang = "en-US";
64
67
  this.access_token = options.token;
65
68
  this.profile_id = options.profile_id;
66
69
  this.password = options.password;
@@ -71,11 +74,12 @@ class GoLogin {
71
74
  this.is_active = false;
72
75
  this.is_stopping = false;
73
76
  this.differentOs = false;
74
- this.profileOs = 'lin';
77
+ this.profileOs = "lin";
75
78
  this.waitWebsocket = options.waitWebsocket ?? true;
76
79
  this.isEmptyFonts = false;
77
80
  this.isFirstSession = false;
78
81
  this.isCloudHeadless = options.isCloudHeadless ?? true;
82
+ this.storageGatewayUrl = `${_constants.STORAGE_GATEWAY_BASE_URL}/upload`;
79
83
  this.tmpdir = (0, _os.tmpdir)();
80
84
  this.autoUpdateBrowser = !!options.autoUpdateBrowser;
81
85
  this.checkBrowserUpdate = options.checkBrowserUpdate ?? true;
@@ -92,15 +96,15 @@ class GoLogin {
92
96
  if (options.tmpdir) {
93
97
  this.tmpdir = options.tmpdir;
94
98
  if (!(0, _fs.existsSync)(this.tmpdir)) {
95
- debug('making tmpdir', this.tmpdir);
99
+ debug("making tmpdir", this.tmpdir);
96
100
  (0, _fs.mkdirSync)(this.tmpdir, {
97
101
  recursive: true
98
102
  });
99
103
  }
100
104
  }
101
105
  this.profile_zip_path = (0, _path.join)(this.tmpdir, `gologin_${this.profile_id}.zip`);
102
- this.bookmarksFilePath = (0, _path.join)(this.tmpdir, `gologin_profile_${this.profile_id}`, 'Default', 'Bookmarks');
103
- debug('INIT GOLOGIN', this.profile_id);
106
+ this.bookmarksFilePath = (0, _path.join)(this.tmpdir, `gologin_profile_${this.profile_id}`, "Default", "Bookmarks");
107
+ debug("INIT GOLOGIN", this.profile_id);
104
108
  }
105
109
  async checkBrowser() {
106
110
  return this.browserChecker.checkBrowser(this.autoUpdateBrowser, this.checkBrowserUpdate);
@@ -109,7 +113,7 @@ class GoLogin {
109
113
  this.profile_id = profile_id;
110
114
  this.cookiesFilePath = await (0, _cookiesManager.getCookiesFilePath)(profile_id, this.tmpdir);
111
115
  this.profile_zip_path = (0, _path.join)(this.tmpdir, `gologin_${this.profile_id}.zip`);
112
- this.bookmarksFilePath = (0, _path.join)(this.tmpdir, `gologin_profile_${this.profile_id}`, 'Default', 'Bookmarks');
116
+ this.bookmarksFilePath = (0, _path.join)(this.tmpdir, `gologin_profile_${this.profile_id}`, "Default", "Bookmarks");
113
117
  }
114
118
  async getToken(username, password) {
115
119
  const data = await _requestretry.default.post(`${_common.API_URL}/user/login`, {
@@ -118,17 +122,17 @@ class GoLogin {
118
122
  password
119
123
  }
120
124
  });
121
- if (!Reflect.has(data, 'body.access_token')) {
125
+ if (!Reflect.has(data, "body.access_token")) {
122
126
  throw new Error(`gologin auth failed with status code, ${data.statusCode} DATA ${JSON.stringify(data)}`);
123
127
  }
124
128
  }
125
129
  async getNewFingerPrint(os) {
126
- debug('GETTING FINGERPRINT');
130
+ debug("GETTING FINGERPRINT");
127
131
  const fpResponse = await _requestretry.default.get(`${_common.API_URL}/browser/fingerprint?os=${os}`, {
128
132
  json: true,
129
133
  headers: {
130
- 'Authorization': `Bearer ${this.access_token}`,
131
- 'User-Agent': 'gologin-api'
134
+ Authorization: `Bearer ${this.access_token}`,
135
+ "User-Agent": "gologin-api"
132
136
  }
133
137
  });
134
138
  return fpResponse?.body || {};
@@ -136,31 +140,31 @@ class GoLogin {
136
140
  async profiles() {
137
141
  const profilesResponse = await _requestretry.default.get(`${_common.API_URL}/browser/v2`, {
138
142
  headers: {
139
- 'Authorization': `Bearer ${this.access_token}`,
140
- 'User-Agent': 'gologin-api'
143
+ Authorization: `Bearer ${this.access_token}`,
144
+ "User-Agent": "gologin-api"
141
145
  }
142
146
  });
143
147
  if (profilesResponse.statusCode !== 200) {
144
- throw new Error('Gologin /browser response error');
148
+ throw new Error("Gologin /browser response error");
145
149
  }
146
150
  return JSON.parse(profilesResponse.body);
147
151
  }
148
152
  async getProfile(profile_id) {
149
153
  const id = profile_id || this.profile_id;
150
- debug('getProfile', this.access_token, id);
154
+ debug("getProfile", this.access_token, id);
151
155
  const profileResponse = await _requestretry.default.get(`${_common.API_URL}/browser/features/${id}/info-for-run`, {
152
156
  headers: {
153
- 'Authorization': `Bearer ${this.access_token}`,
154
- 'User-Agent': 'gologin-api'
157
+ Authorization: `Bearer ${this.access_token}`,
158
+ "User-Agent": "gologin-api"
155
159
  }
156
160
  });
157
- debug('profileResponse', profileResponse.statusCode, profileResponse.body);
161
+ debug("profileResponse", profileResponse.statusCode, profileResponse.body);
158
162
  const {
159
- body: errorBody = ''
163
+ body: errorBody = ""
160
164
  } = profileResponse;
161
- const backendErrorHeader = 'backend@error::';
165
+ const backendErrorHeader = "backend@error::";
162
166
  if (errorBody.includes(backendErrorHeader)) {
163
- const errorData = errorBody.replace(backendErrorHeader, '').slice(1, -1);
167
+ const errorData = errorBody.replace(backendErrorHeader, "").slice(1, -1);
164
168
  throw new Error(errorData);
165
169
  }
166
170
  if (profileResponse.statusCode === 404) {
@@ -173,18 +177,18 @@ class GoLogin {
173
177
  throw new Error(`Gologin /browser/${id} response error ${profileResponse.statusCode} INVALID TOKEN OR PROFILE NOT FOUND`);
174
178
  }
175
179
  if (profileResponse.statusCode === 401) {
176
- throw new Error('invalid token');
180
+ throw new Error("invalid token");
177
181
  }
178
182
  return JSON.parse(profileResponse.body);
179
183
  }
180
184
  async emptyProfile() {
181
- return readFile((0, _path.resolve)(__dirname, 'gologin_zeroprofile.b64')).then(res => res.toString());
185
+ return readFile((0, _path.resolve)(__dirname, "gologin_zeroprofile.b64")).then(res => res.toString());
182
186
  }
183
187
  async getProfileS3() {
184
188
  const token = this.access_token;
185
- debug('getProfileS3 token=', token, 'profile=', this.profile_id);
189
+ debug("getProfileS3 token=", token, "profile=", this.profile_id);
186
190
  const downloadURL = `${_constants.STORAGE_GATEWAY_BASE_URL}/download`;
187
- debug('loading profile from public s3 bucket, url=', downloadURL);
191
+ debug("loading profile from public s3 bucket, url=", downloadURL);
188
192
  const profileResponse = await fetch(downloadURL, {
189
193
  headers: {
190
194
  Authorization: `Bearer ${token}`,
@@ -194,22 +198,21 @@ class GoLogin {
194
198
  const profileResponseBody = await profileResponse.arrayBuffer();
195
199
  if (profileResponse.status !== 200) {
196
200
  debug(`Gologin S3 BUCKET ${downloadURL} response error ${profileResponse.statusCode} - use empty`);
197
- return '';
201
+ return "";
198
202
  }
199
203
  return Buffer.from(profileResponseBody);
200
204
  }
201
205
  async postFile(fileName, fileBuff) {
202
- debug('POSTING FILE', fileBuff.length);
203
- debug('Getting signed URL for S3');
204
- const apiUrl = `${_constants.STORAGE_GATEWAY_BASE_URL}/upload`;
206
+ debug("POSTING FILE", fileBuff.length);
207
+ debug("Getting signed URL for S3");
205
208
  const bodyBufferBiteLength = Buffer.byteLength(fileBuff);
206
- console.log('BUFFER SIZE', bodyBufferBiteLength);
207
- await _requestretry.default.put(apiUrl, {
209
+ console.log("BUFFER SIZE", bodyBufferBiteLength);
210
+ await _requestretry.default.put(this.storageGatewayUrl, {
208
211
  headers: {
209
212
  Authorization: `Bearer ${this.access_token}`,
210
213
  browserId: this.profile_id,
211
- 'Content-Type': 'application/zip',
212
- 'Content-Length': bodyBufferBiteLength
214
+ "Content-Type": "application/zip",
215
+ "Content-Length": bodyBufferBiteLength
213
216
  },
214
217
  body: fileBuff,
215
218
  maxBodyLength: Infinity,
@@ -219,41 +222,41 @@ class GoLogin {
219
222
  timeout: 30 * 1000,
220
223
  fullResponse: false
221
224
  });
222
- console.log('Profile has been uploaded to S3 successfully');
225
+ console.log("Profile has been uploaded to S3 successfully");
223
226
  }
224
227
  async emptyProfileFolder() {
225
- debug('get emptyProfileFolder');
226
- const currentDir = (0, _path.dirname)(new URL(require('url').pathToFileURL(__filename).toString()).pathname);
227
- const zeroProfilePath = (0, _path.join)(currentDir, '..', 'zero_profile.zip');
228
+ debug("get emptyProfileFolder");
229
+ const currentDir = (0, _path.dirname)((0, _url.fileURLToPath)(require('url').pathToFileURL(__filename).toString()));
230
+ const zeroProfilePath = (0, _path.join)(currentDir, "..", "zero_profile.zip");
228
231
  const profile = await readFile((0, _path.resolve)(zeroProfilePath));
229
- debug('emptyProfileFolder LENGTH ::', profile.length);
232
+ debug("emptyProfileFolder LENGTH ::", profile.length);
230
233
  return profile;
231
234
  }
232
235
  convertPreferences(preferences) {
233
- if ((0, _utils2.get)(preferences, 'navigator.userAgent')) {
234
- preferences.userAgent = (0, _utils2.get)(preferences, 'navigator.userAgent');
236
+ if ((0, _utils2.get)(preferences, "navigator.userAgent")) {
237
+ preferences.userAgent = (0, _utils2.get)(preferences, "navigator.userAgent");
235
238
  }
236
- if ((0, _utils2.get)(preferences, 'navigator.doNotTrack')) {
237
- preferences.doNotTrack = (0, _utils2.get)(preferences, 'navigator.doNotTrack');
239
+ if ((0, _utils2.get)(preferences, "navigator.doNotTrack")) {
240
+ preferences.doNotTrack = (0, _utils2.get)(preferences, "navigator.doNotTrack");
238
241
  }
239
- if ((0, _utils2.get)(preferences, 'navigator.hardwareConcurrency')) {
240
- preferences.hardwareConcurrency = (0, _utils2.get)(preferences, 'navigator.hardwareConcurrency');
242
+ if ((0, _utils2.get)(preferences, "navigator.hardwareConcurrency")) {
243
+ preferences.hardwareConcurrency = (0, _utils2.get)(preferences, "navigator.hardwareConcurrency");
241
244
  }
242
- if ((0, _utils2.get)(preferences, 'navigator.deviceMemory')) {
243
- preferences.deviceMemory = (0, _utils2.get)(preferences, 'navigator.deviceMemory') * 1024;
245
+ if ((0, _utils2.get)(preferences, "navigator.deviceMemory")) {
246
+ preferences.deviceMemory = (0, _utils2.get)(preferences, "navigator.deviceMemory") * 1024;
244
247
  }
245
- if ((0, _utils2.get)(preferences, 'navigator.language')) {
246
- preferences.langHeader = (0, _utils2.get)(preferences, 'navigator.language');
247
- preferences.languages = (0, _utils2.get)(preferences, 'navigator.language').replace(/;|q=[\d\.]+/img, '');
248
+ if ((0, _utils2.get)(preferences, "navigator.language")) {
249
+ preferences.langHeader = (0, _utils2.get)(preferences, "navigator.language");
250
+ preferences.languages = (0, _utils2.get)(preferences, "navigator.language").replace(/;|q=[\d\.]+/gim, "");
248
251
  }
249
- if ((0, _utils2.get)(preferences, 'navigator.maxTouchPoints')) {
250
- preferences.navigator.max_touch_points = (0, _utils2.get)(preferences, 'navigator.maxTouchPoints');
252
+ if ((0, _utils2.get)(preferences, "navigator.maxTouchPoints")) {
253
+ preferences.navigator.max_touch_points = (0, _utils2.get)(preferences, "navigator.maxTouchPoints");
251
254
  }
252
- if ((0, _utils2.get)(preferences, 'isM1')) {
253
- preferences.is_m1 = (0, _utils2.get)(preferences, 'isM1');
255
+ if ((0, _utils2.get)(preferences, "isM1")) {
256
+ preferences.is_m1 = (0, _utils2.get)(preferences, "isM1");
254
257
  }
255
- if ((0, _utils2.get)(preferences, 'os') == 'android') {
256
- const devicePixelRatio = (0, _utils2.get)(preferences, 'devicePixelRatio');
258
+ if ((0, _utils2.get)(preferences, "os") == "android") {
259
+ const devicePixelRatio = (0, _utils2.get)(preferences, "devicePixelRatio");
257
260
  const deviceScaleFactorCeil = Math.ceil(devicePixelRatio || 3.5);
258
261
  let deviceScaleFactor = devicePixelRatio;
259
262
  if (deviceScaleFactorCeil === devicePixelRatio) {
@@ -274,37 +277,37 @@ class GoLogin {
274
277
  };
275
278
  preferences.webRtc = {
276
279
  ...preferences.webRtc,
277
- fill_based_on_ip: !!(0, _utils2.get)(preferences, 'webRTC.fillBasedOnIp'),
278
- local_ip_masking: !!(0, _utils2.get)(preferences, 'webRTC.local_ip_masking')
280
+ fill_based_on_ip: !!(0, _utils2.get)(preferences, "webRTC.fillBasedOnIp"),
281
+ local_ip_masking: !!(0, _utils2.get)(preferences, "webRTC.local_ip_masking")
279
282
  };
280
283
  return preferences;
281
284
  }
282
285
  async createBrowserExtension() {
283
286
  const that = this;
284
- debug('start createBrowserExtension');
287
+ debug("start createBrowserExtension");
285
288
  await (0, _rimraf.default)(this.orbitaExtensionPath(), () => null);
286
289
  const extPath = this.orbitaExtensionPath();
287
- debug('extension folder sanitized');
288
- const extension_source = (0, _path.resolve)(__dirname, 'gologin-browser-ext.zip');
290
+ debug("extension folder sanitized");
291
+ const extension_source = (0, _path.resolve)(__dirname, "gologin-browser-ext.zip");
289
292
  await (0, _decompress.default)(extension_source, extPath, {
290
293
  plugins: [(0, _decompressUnzip.default)()],
291
- filter: file => !file.path.endsWith('/')
294
+ filter: file => !file.path.endsWith("/")
292
295
  }).then(() => {
293
- debug('extraction done');
294
- debug('create uid.json');
295
- return writeFile((0, _path.join)(extPath, 'uid.json'), JSON.stringify({
296
+ debug("extraction done");
297
+ debug("create uid.json");
298
+ return writeFile((0, _path.join)(extPath, "uid.json"), JSON.stringify({
296
299
  uid: that.profile_id
297
300
  }, null, 2)).then(() => extPath);
298
301
  }).catch(async e => {
299
- debug('orbita extension error', e);
302
+ debug("orbita extension error", e);
300
303
  });
301
- debug('createBrowserExtension done');
304
+ debug("createBrowserExtension done");
302
305
  }
303
306
  extractProfile(path, zipfile) {
304
307
  debug(`extactProfile ${zipfile}, ${path}`);
305
308
  return (0, _decompress.default)(zipfile, path, {
306
309
  plugins: [(0, _decompressUnzip.default)()],
307
- filter: file => !file.path.endsWith('/')
310
+ filter: file => !file.path.endsWith("/")
308
311
  });
309
312
  }
310
313
  async downloadProfileAndExtract(profile, local) {
@@ -315,40 +318,40 @@ class GoLogin {
315
318
  try {
316
319
  profile_folder = await this.getProfileS3();
317
320
  } catch (e) {
318
- debug('Cannot get profile - using empty', e);
321
+ debug("Cannot get profile - using empty", e);
319
322
  }
320
- debug('FILE READY', this.profile_zip_path);
323
+ debug("FILE READY", this.profile_zip_path);
321
324
  await writeFile(this.profile_zip_path, profile_folder);
322
- debug('PROFILE LENGTH', profile_folder.length);
325
+ debug("PROFILE LENGTH", profile_folder.length);
323
326
  } else {
324
- debug('PROFILE LOCAL HAVING', this.profile_zip_path);
327
+ debug("PROFILE LOCAL HAVING", this.profile_zip_path);
325
328
  }
326
- debug('Cleaning up..', profilePath);
329
+ debug("Cleaning up..", profilePath);
327
330
  try {
328
331
  await this.extractProfile(profilePath, this.profile_zip_path);
329
- debug('extraction done');
332
+ debug("extraction done");
330
333
  } catch (e) {
331
334
  console.trace(e);
332
335
  profile_folder = await this.emptyProfileFolder();
333
336
  await writeFile(this.profile_zip_path, profile_folder);
334
337
  await this.extractProfile(profilePath, this.profile_zip_path);
335
338
  }
336
- const singletonLockPath = (0, _path.join)(profilePath, 'SingletonLock');
339
+ const singletonLockPath = (0, _path.join)(profilePath, "SingletonLock");
337
340
  const singletonLockExists = await access(singletonLockPath).then(() => true).catch(() => false);
338
341
  if (singletonLockExists) {
339
- debug('removing SingletonLock');
342
+ debug("removing SingletonLock");
340
343
  await unlink(singletonLockPath);
341
- debug('SingletonLock removed');
344
+ debug("SingletonLock removed");
342
345
  }
343
346
  }
344
347
  async createZeroProfile(createCookiesTableQuery) {
345
348
  const profilePath = (0, _path.join)(this.tmpdir, `gologin_profile_${this.profile_id}`);
346
- const defaultFilePath = (0, _path.resolve)(profilePath, 'Default');
347
- const preferencesFilePath = (0, _path.resolve)(defaultFilePath, 'Preferences');
348
- const bookmarksFilePath = (0, _path.resolve)(defaultFilePath, 'Bookmarks');
349
- const cookiesFilePath = (0, _path.resolve)(defaultFilePath, 'Network', 'Cookies');
350
- const cookiesFileSecondPath = (0, _path.resolve)(defaultFilePath, 'Cookies');
351
- await mkdir((0, _path.resolve)(defaultFilePath, 'Network'), {
349
+ const defaultFilePath = (0, _path.resolve)(profilePath, "Default");
350
+ const preferencesFilePath = (0, _path.resolve)(defaultFilePath, "Preferences");
351
+ const bookmarksFilePath = (0, _path.resolve)(defaultFilePath, "Bookmarks");
352
+ const cookiesFilePath = (0, _path.resolve)(defaultFilePath, "Network", "Cookies");
353
+ const cookiesFileSecondPath = (0, _path.resolve)(defaultFilePath, "Cookies");
354
+ await mkdir((0, _path.resolve)(defaultFilePath, "Network"), {
352
355
  recursive: true
353
356
  }).catch(console.log);
354
357
  await Promise.all([writeFile(preferencesFilePath, JSON.stringify(_zeroProfilePreferences.zeroProfilePreferences), {
@@ -364,7 +367,7 @@ class GoLogin {
364
367
  async createStartup(local = false) {
365
368
  const profilePath = (0, _path.join)(this.tmpdir, `gologin_profile_${this.profile_id}`);
366
369
  await (0, _rimraf.default)(profilePath, () => null);
367
- debug('-', profilePath, 'dropped');
370
+ debug("-", profilePath, "dropped");
368
371
  const profile = await this.getProfile();
369
372
  const {
370
373
  navigator = {},
@@ -373,13 +376,13 @@ class GoLogin {
373
376
  } = profile;
374
377
  this.fontsMasking = fonts?.enableMasking;
375
378
  this.profileOs = profileOs;
376
- this.differentOs = profileOs !== 'android' && (OS_PLATFORM === 'win32' && profileOs !== 'win' || OS_PLATFORM === 'darwin' && profileOs !== 'mac' || OS_PLATFORM === 'linux' && profileOs !== 'lin');
379
+ this.differentOs = profileOs !== "android" && (OS_PLATFORM === "win32" && profileOs !== "win" || OS_PLATFORM === "darwin" && profileOs !== "mac" || OS_PLATFORM === "linux" && profileOs !== "lin");
377
380
  const {
378
- resolution = '1920x1080',
379
- language = 'en-US,en;q=0.9'
381
+ resolution = "1920x1080",
382
+ language = "en-US,en;q=0.9"
380
383
  } = navigator;
381
384
  this.language = language;
382
- const [screenWidth, screenHeight] = resolution.split('x');
385
+ const [screenWidth, screenHeight] = resolution.split("x");
383
386
  this.resolution = {
384
387
  width: parseInt(screenWidth, 10),
385
388
  height: parseInt(screenHeight, 10)
@@ -391,19 +394,19 @@ class GoLogin {
391
394
  this.isFirstSession = false;
392
395
  await this.downloadProfileAndExtract(profile, local);
393
396
  }
394
- const pref_file_name = (0, _path.join)(profilePath, 'Default', 'Preferences');
395
- debug('reading', pref_file_name);
397
+ const pref_file_name = (0, _path.join)(profilePath, "Default", "Preferences");
398
+ debug("reading", pref_file_name);
396
399
  const prefFileExists = await access(pref_file_name).then(() => true).catch(() => false);
397
400
  if (!prefFileExists) {
398
- debug('Preferences file not exists waiting', pref_file_name, '. Using empty profile');
399
- await writeFile(pref_file_name, '{}');
401
+ debug("Preferences file not exists waiting", pref_file_name, ". Using empty profile");
402
+ await writeFile(pref_file_name, "{}");
400
403
  }
401
404
  const preferences_raw = await readFile(pref_file_name);
402
405
  const preferences = JSON.parse(preferences_raw.toString());
403
- let proxy = (0, _utils2.get)(profile, 'proxy');
404
- const name = (0, _utils2.get)(profile, 'name');
405
- const chromeExtensions = (0, _utils2.get)(profile, 'chromeExtensions') || [];
406
- const userChromeExtensions = (0, _utils2.get)(profile, 'userChromeExtensions') || [];
406
+ let proxy = (0, _utils2.get)(profile, "proxy");
407
+ const name = (0, _utils2.get)(profile, "name");
408
+ const chromeExtensions = (0, _utils2.get)(profile, "chromeExtensions") || [];
409
+ const userChromeExtensions = (0, _utils2.get)(profile, "userChromeExtensions") || [];
407
410
  const allExtensions = [...chromeExtensions, ...userChromeExtensions];
408
411
  if (allExtensions.length) {
409
412
  const ExtensionsManagerInst = new _extensionsManager.default();
@@ -416,26 +419,26 @@ class GoLogin {
416
419
  const promises = [ExtensionsManagerInst.checkChromeExtensions(allExtensions).then(res => ({
417
420
  profileExtensionsCheckRes: res
418
421
  })).catch(e => {
419
- console.log('checkChromeExtensions error: ', e);
422
+ console.log("checkChromeExtensions error: ", e);
420
423
  return {
421
424
  profileExtensionsCheckRes: []
422
425
  };
423
426
  }), ExtensionsManagerInst.checkLocalUserChromeExtensions(userChromeExtensions, this.profile_id).then(res => ({
424
427
  profileUserExtensionsCheckRes: res
425
428
  })).catch(error => {
426
- console.log('checkUserChromeExtensions error: ', error);
429
+ console.log("checkUserChromeExtensions error: ", error);
427
430
  return null;
428
431
  })];
429
432
  const extensionsResult = await Promise.all(promises);
430
- const profileExtensionPathRes = extensionsResult.find(el => 'profileExtensionsCheckRes' in el) || {};
431
- const profileUserExtensionPathRes = extensionsResult.find(el => 'profileUserExtensionsCheckRes' in el);
433
+ const profileExtensionPathRes = extensionsResult.find(el => "profileExtensionsCheckRes" in el) || {};
434
+ const profileUserExtensionPathRes = extensionsResult.find(el => "profileUserExtensionsCheckRes" in el);
432
435
  profileExtensionsCheckRes = (profileExtensionPathRes?.profileExtensionsCheckRes || []).concat(profileUserExtensionPathRes?.profileUserExtensionsCheckRes || []);
433
436
  }
434
437
  let extSettings;
435
438
  if (ExtensionsManagerInst.useLocalExtStorage) {
436
439
  extSettings = await (0, _browserUserDataManager.setExtPathsAndRemoveDeleted)(preferences, profileExtensionsCheckRes, this.profile_id);
437
440
  } else {
438
- const originalExtensionsFolder = (0, _path.join)(profilePath, 'Default', 'Extensions');
441
+ const originalExtensionsFolder = (0, _path.join)(profilePath, "Default", "Extensions");
439
442
  extSettings = await (0, _browserUserDataManager.setOriginalExtPaths)(preferences, originalExtensionsFolder);
440
443
  }
441
444
  this.extensionPathsToInstall = ExtensionsManagerInst.getExtensionsToInstall(extSettings, profileExtensionsCheckRes);
@@ -445,30 +448,30 @@ class GoLogin {
445
448
  preferences.extensions = currentExtSettings;
446
449
  }
447
450
  }
448
- if (proxy.mode === 'gologin' || proxy.mode === 'tor') {
449
- const autoProxyServer = (0, _utils2.get)(profile, 'autoProxyServer');
450
- const splittedAutoProxyServer = autoProxyServer.split('://');
451
- const splittedProxyAddress = splittedAutoProxyServer[1].split(':');
451
+ if (proxy.mode === "gologin" || proxy.mode === "tor") {
452
+ const autoProxyServer = (0, _utils2.get)(profile, "autoProxyServer");
453
+ const splittedAutoProxyServer = autoProxyServer.split("://");
454
+ const splittedProxyAddress = splittedAutoProxyServer[1].split(":");
452
455
  const port = splittedProxyAddress[1];
453
456
  proxy = {
454
- 'mode': splittedAutoProxyServer[0],
455
- 'host': splittedProxyAddress[0],
457
+ mode: splittedAutoProxyServer[0],
458
+ host: splittedProxyAddress[0],
456
459
  port,
457
- 'username': (0, _utils2.get)(profile, 'autoProxyUsername'),
458
- 'password': (0, _utils2.get)(profile, 'autoProxyPassword')
460
+ username: (0, _utils2.get)(profile, "autoProxyUsername"),
461
+ password: (0, _utils2.get)(profile, "autoProxyPassword")
459
462
  };
460
- profile.proxy.username = (0, _utils2.get)(profile, 'autoProxyUsername');
461
- profile.proxy.password = (0, _utils2.get)(profile, 'autoProxyPassword');
463
+ profile.proxy.username = (0, _utils2.get)(profile, "autoProxyUsername");
464
+ profile.proxy.password = (0, _utils2.get)(profile, "autoProxyPassword");
462
465
  }
463
- if (proxy.mode === 'geolocation') {
464
- proxy.mode = 'http';
466
+ if (proxy.mode === "geolocation") {
467
+ proxy.mode = "http";
465
468
  }
466
469
  if (proxy.mode === PROXY_NONE) {
467
470
  proxy = null;
468
471
  }
469
472
  this.proxy = proxy;
470
473
  await this.getTimeZone(proxy).catch(e => {
471
- console.error('Proxy Error. Check it and try again.');
474
+ console.error("Proxy Error. Check it and try again.");
472
475
  throw new Error(`Proxy Error. ${e.message}`);
473
476
  });
474
477
  const [latitude, longitude] = this._tz.ll;
@@ -483,19 +486,19 @@ class GoLogin {
483
486
  };
484
487
  profile.geoLocation = this.getGeolocationParams(profileGeolocation, tzGeoLocation);
485
488
  profile.name = name;
486
- profile.name_base64 = Buffer.from(name).toString('base64');
489
+ profile.name_base64 = Buffer.from(name).toString("base64");
487
490
  profile.profile_id = this.profile_id;
488
491
  profile.webRtc = {
489
- mode: (0, _utils2.get)(profile, 'webRTC.mode') === 'alerted' ? 'public' : (0, _utils2.get)(profile, 'webRTC.mode'),
490
- publicIP: (0, _utils2.get)(profile, 'webRTC.fillBasedOnIp') ? this._tz.ip : (0, _utils2.get)(profile, 'webRTC.publicIp'),
491
- localIps: (0, _utils2.get)(profile, 'webRTC.localIps', [])
492
+ mode: (0, _utils2.get)(profile, "webRTC.mode") === "alerted" ? "public" : (0, _utils2.get)(profile, "webRTC.mode"),
493
+ publicIP: (0, _utils2.get)(profile, "webRTC.fillBasedOnIp") ? this._tz.ip : (0, _utils2.get)(profile, "webRTC.publicIp"),
494
+ localIps: (0, _utils2.get)(profile, "webRTC.localIps", [])
492
495
  };
493
- debug('profile.webRtc=', profile.webRtc);
494
- debug('profile.timezone=', profile.timezone);
495
- debug('profile.mediaDevices=', profile.mediaDevices);
496
+ debug("profile.webRtc=", profile.webRtc);
497
+ debug("profile.timezone=", profile.timezone);
498
+ debug("profile.mediaDevices=", profile.mediaDevices);
496
499
  const audioContext = profile.audioContext || {};
497
500
  const {
498
- mode: audioCtxMode = 'off',
501
+ mode: audioCtxMode = "off",
499
502
  noise: audioCtxNoise
500
503
  } = audioContext;
501
504
  if (profile.timezone.fillBasedOnIp === false) {
@@ -512,14 +515,14 @@ class GoLogin {
512
515
  profile.canvasMode = profile.canvas.mode;
513
516
  profile.canvasNoise = profile.canvas.noise;
514
517
  profile.audioContext = {
515
- enable: audioCtxMode !== 'off',
518
+ enable: audioCtxMode !== "off",
516
519
  noiseValue: audioCtxNoise
517
520
  };
518
521
  profile.webgl = {
519
522
  metadata: {
520
- vendor: (0, _utils2.get)(profile, 'webGLMetadata.vendor'),
521
- renderer: (0, _utils2.get)(profile, 'webGLMetadata.renderer'),
522
- mode: (0, _utils2.get)(profile, 'webGLMetadata.mode') === 'mask'
523
+ vendor: (0, _utils2.get)(profile, "webGLMetadata.vendor"),
524
+ renderer: (0, _utils2.get)(profile, "webGLMetadata.renderer"),
525
+ mode: (0, _utils2.get)(profile, "webGLMetadata.mode") === "mask"
523
526
  }
524
527
  };
525
528
  profile.custom_fonts = {
@@ -529,7 +532,7 @@ class GoLogin {
529
532
  debug(`Writing profile for screenWidth ${profilePath}`, JSON.stringify(gologin));
530
533
  gologin.screenWidth = this.resolution.width;
531
534
  gologin.screenHeight = this.resolution.height;
532
- debug('writeCookiesFromServer', this.writeCookiesFromServer);
535
+ debug("writeCookiesFromServer", this.writeCookiesFromServer);
533
536
  this.cookiesFilePath = await (0, _cookiesManager.getCookiesFilePath)(this.profile_id, this.tmpdir);
534
537
  if (this.writeCookiesFromServer) {
535
538
  await this.writeCookiesToFile(profile.cookies?.cookies);
@@ -545,42 +548,42 @@ class GoLogin {
545
548
  console.trace(e);
546
549
  }
547
550
  }
548
- const languages = this.language.replace(/;|q=[\d\.]+/img, '');
551
+ const languages = this.language.replace(/;|q=[\d\.]+/gim, "");
549
552
  if (preferences.gologin == null) {
550
553
  preferences.gologin = {};
551
554
  }
552
555
  preferences.gologin.langHeader = gologin.navigator.language;
553
556
  preferences.gologin.language = languages;
554
- const [splittedLangs] = gologin.navigator.language.split(';');
555
- const [browserLang] = splittedLangs.split(',');
557
+ const [splittedLangs] = gologin.navigator.language.split(";");
558
+ const [browserLang] = splittedLangs.split(",");
556
559
  gologin.browserLang = browserLang;
557
- const isMAC = OS_PLATFORM === 'darwin';
560
+ const isMAC = OS_PLATFORM === "darwin";
558
561
  const checkAutoLangResult = (0, _browser.checkAutoLang)(gologin, this._tz);
559
- this.browserLang = isMAC ? 'en-US' : checkAutoLangResult;
560
- await writeFile((0, _path.join)(profilePath, 'Default', 'Preferences'), JSON.stringify(Object.assign(preferences, {
562
+ this.browserLang = isMAC ? "en-US" : checkAutoLangResult;
563
+ await writeFile((0, _path.join)(profilePath, "Default", "Preferences"), JSON.stringify(Object.assign(preferences, {
561
564
  gologin
562
565
  })));
563
566
  const bookmarksParsedData = await (0, _utils.getCurrentProfileBookmarks)(this.bookmarksFilePath);
564
567
  const bookmarksFromDb = profile.bookmarks?.bookmark_bar;
565
568
  bookmarksParsedData.roots = bookmarksFromDb ? profile.bookmarks : bookmarksParsedData.roots;
566
569
  await writeFile(this.bookmarksFilePath, JSON.stringify(bookmarksParsedData));
567
- debug('Profile ready. Path: ', profilePath, 'PROXY', JSON.stringify((0, _utils2.get)(preferences, 'gologin.proxy')));
570
+ debug("Profile ready. Path: ", profilePath, "PROXY", JSON.stringify((0, _utils2.get)(preferences, "gologin.proxy")));
568
571
  return profilePath;
569
572
  }
570
573
  async commitProfile() {
571
574
  const dataBuff = await this.getProfileDataToUpdate();
572
- debug('begin updating', dataBuff.length);
575
+ debug("begin updating", dataBuff.length);
573
576
  if (!dataBuff.length) {
574
- debug('WARN: profile zip data empty - SKIPPING PROFILE COMMIT');
577
+ debug("WARN: profile zip data empty - SKIPPING PROFILE COMMIT");
575
578
  return;
576
579
  }
577
580
  try {
578
- debug('Patching profile');
579
- await this.postFile('profile', dataBuff);
581
+ debug("Patching profile");
582
+ await this.postFile("profile", dataBuff);
580
583
  } catch (e) {
581
- debug('CANNOT COMMIT PROFILE', e);
584
+ debug("CANNOT COMMIT PROFILE", e);
582
585
  }
583
- debug('COMMIT COMPLETED');
586
+ debug("COMMIT COMPLETED");
584
587
  }
585
588
  profilePath() {
586
589
  return (0, _path.join)(this.tmpdir, `gologin_profile_${this.profile_id}`);
@@ -594,10 +597,10 @@ class GoLogin {
594
597
  return Math.floor(Math.random() * (max - min + 1)) + min;
595
598
  }
596
599
  async checkPortAvailable(port) {
597
- debug('CHECKING PORT AVAILABLE', port);
600
+ debug("CHECKING PORT AVAILABLE", port);
598
601
  try {
599
602
  const portAvailable = await (0, _utils2.isPortReachable)(port, {
600
- host: 'localhost'
603
+ host: "localhost"
601
604
  });
602
605
  if (portAvailable) {
603
606
  debug(`PORT ${port} IS OPEN`);
@@ -619,65 +622,89 @@ class GoLogin {
619
622
  return port;
620
623
  }
621
624
  async getTimeZone(proxy) {
622
- debug('getting timeZone proxy=', proxy);
625
+ debug("getting timeZone proxy=", proxy);
623
626
  if (this.timezone) {
624
- debug('getTimeZone from options', this.timezone);
627
+ debug("getTimeZone from options", this.timezone);
625
628
  this._tz = this.timezone;
626
629
  return this._tz.timezone;
627
630
  }
628
631
  let data = null;
629
632
  if (proxy && proxy.mode !== PROXY_NONE) {
630
- if (proxy.mode.includes('socks')) {
633
+ if (proxy.mode.includes("socks")) {
631
634
  for (let i = 0; i < 5; i++) {
632
635
  try {
633
- debug('getting timeZone socks try', i + 1);
636
+ debug("getting timeZone socks try", i + 1);
634
637
  return this.getTimezoneWithSocks(proxy);
635
638
  } catch (e) {
636
639
  console.log(e.message);
637
640
  }
638
641
  }
639
- throw new Error('Socks proxy connection timed out');
642
+ throw new Error("Socks proxy connection timed out");
640
643
  }
641
644
  const proxyUrl = `${proxy.mode}://${proxy.username}:${proxy.password}@${proxy.host}:${proxy.port}`;
642
645
  debug(`getTimeZone start ${TIMEZONE_URL}`, proxyUrl);
643
- data = await _requestretry.default.get(TIMEZONE_URL, {
646
+ const response = await _requestretry.default.get(TIMEZONE_URL, {
644
647
  proxy: proxyUrl,
645
648
  timeout: 20 * 1000,
646
649
  maxAttempts: 5
647
650
  });
651
+ const result = JSON.parse(response.body);
652
+ data = {
653
+ body: {
654
+ country: result.country_code,
655
+ stateProv: result.city,
656
+ city: result.city,
657
+ timezone: (0, _timezone.tzlookup)(result.latitude, result.longitude),
658
+ ll: [result.latitude, result.longitude],
659
+ languages: "en",
660
+ accuracy: 100
661
+ }
662
+ };
648
663
  } else {
649
- data = await _requestretry.default.get(TIMEZONE_URL, {
664
+ const response = await _requestretry.default.get(TIMEZONE_URL, {
650
665
  timeout: 20 * 1000,
651
666
  maxAttempts: 5
652
667
  });
668
+ const result = JSON.parse(response.body);
669
+ data = {
670
+ body: {
671
+ country: result.country_code,
672
+ stateProv: result.city,
673
+ city: result.city,
674
+ timezone: (0, _timezone.tzlookup)(result.latitude, result.longitude),
675
+ ll: [result.latitude, result.longitude],
676
+ languages: "en",
677
+ accuracy: 100
678
+ }
679
+ };
653
680
  }
654
- debug('getTimeZone finish', data.body);
655
- this._tz = JSON.parse(data.body);
681
+ debug("getTimeZone finish", data.body);
682
+ this._tz = data.body;
656
683
  return this._tz.timezone;
657
684
  }
658
685
  async getTimezoneWithSocks(params) {
659
686
  const {
660
687
  host,
661
688
  port,
662
- username = '',
663
- password = ''
689
+ username = "",
690
+ password = ""
664
691
  } = params;
665
692
  let body;
666
- let proxy = 'socks://';
693
+ let proxy = "socks://";
667
694
  if (username) {
668
- const resultPassword = password ? ':' + password + '@' : '@';
695
+ const resultPassword = password ? ":" + password + "@" : "@";
669
696
  proxy += username + resultPassword;
670
697
  }
671
- proxy += host + ':' + port;
698
+ proxy += host + ":" + port;
672
699
  const agent = new _socksProxyAgent.SocksProxyAgent(proxy);
673
700
  const checkData = await new Promise((resolve, reject) => {
674
701
  (0, _https.get)(TIMEZONE_URL, {
675
702
  agent,
676
703
  timeout: 10000
677
704
  }, res => {
678
- let resultResponse = '';
679
- res.on('data', data => resultResponse += data);
680
- res.on('end', () => {
705
+ let resultResponse = "";
706
+ res.on("data", data => resultResponse += data);
707
+ res.on("end", () => {
681
708
  let parsedData;
682
709
  try {
683
710
  parsedData = JSON.parse(resultResponse);
@@ -689,13 +716,13 @@ class GoLogin {
689
716
  body: parsedData
690
717
  });
691
718
  });
692
- }).on('error', err => reject(err));
719
+ }).on("error", err => reject(err));
693
720
  });
694
721
  body = checkData.body || {};
695
- if (!body.ip && checkData.statusCode.toString().startsWith('4')) {
722
+ if (!body.ip && checkData.statusCode.toString().startsWith("4")) {
696
723
  throw checkData;
697
724
  }
698
- debug('getTimeZone finish', body.body);
725
+ debug("getTimeZone finish", body.body);
699
726
  this._tz = body;
700
727
  return this._tz.timezone;
701
728
  }
@@ -710,11 +737,11 @@ class GoLogin {
710
737
  env[key] = process.env[key];
711
738
  });
712
739
  const tz = await this.getTimeZone(this.proxy).catch(e => {
713
- console.error('Proxy Error. Check it and try again.');
740
+ console.error("Proxy Error. Check it and try again.");
714
741
  throw e;
715
742
  });
716
743
  env.TZ = tz;
717
- let params = [`--proxy-server=${proxy}`, `--user-data-dir=${profile_path}`, '--password-store=basic', `--tz=${tz}`, '--lang=en'];
744
+ let params = [`--proxy-server=${proxy}`, `--user-data-dir=${profile_path}`, "--password-store=basic", `--tz=${tz}`, "--lang=en"];
718
745
  if (Array.isArray(this.extra_params) && this.extra_params.length) {
719
746
  params = params.concat(this.extra_params);
720
747
  }
@@ -735,7 +762,7 @@ class GoLogin {
735
762
  let {
736
763
  proxy
737
764
  } = this;
738
- let proxy_host = '';
765
+ let proxy_host = "";
739
766
  if (proxy) {
740
767
  proxy_host = this.proxy.host;
741
768
  proxy = `${proxy.mode}://${proxy.host}:${proxy.port}`;
@@ -748,39 +775,39 @@ class GoLogin {
748
775
  env[key] = process.env[key];
749
776
  });
750
777
  const tz = await this.getTimeZone(this.proxy).catch(e => {
751
- console.error('Proxy Error. Check it and try again.');
778
+ console.error("Proxy Error. Check it and try again.");
752
779
  throw e;
753
780
  });
754
781
  env.TZ = tz;
755
782
  if (this.vnc_port) {
756
- const script_path = (0, _path.resolve)(__dirname, './run.sh');
757
- debug('RUNNING', script_path, ORBITA_BROWSER, remote_debugging_port, proxy, profile_path, this.vnc_port);
783
+ const script_path = (0, _path.resolve)(__dirname, "./run.sh");
784
+ debug("RUNNING", script_path, ORBITA_BROWSER, remote_debugging_port, proxy, profile_path, this.vnc_port);
758
785
  (0, _child_process.execFile)(script_path, [ORBITA_BROWSER, remote_debugging_port, proxy, profile_path, this.vnc_port, tz], {
759
786
  env
760
787
  });
761
788
  } else {
762
- let params = [`--remote-debugging-port=${remote_debugging_port}`, `--user-data-dir=${profile_path}`, '--password-store=basic', `--tz=${tz}`, `--lang=${this.browserLang}`];
789
+ let params = [`--remote-debugging-port=${remote_debugging_port}`, `--user-data-dir=${profile_path}`, "--password-store=basic", `--tz=${tz}`, `--lang=${this.browserLang}`];
763
790
  if (this.extensionPathsToInstall.length) {
764
791
  if (Array.isArray(this.extra_params) && this.extra_params.length) {
765
792
  this.extra_params.forEach((param, index) => {
766
- if (!param.includes('--load-extension=')) {
793
+ if (!param.includes("--load-extension=")) {
767
794
  return;
768
795
  }
769
- const [_, extPathsString] = param.split('=');
770
- const extPathsArray = extPathsString.split(',');
796
+ const [_, extPathsString] = param.split("=");
797
+ const extPathsArray = extPathsString.split(",");
771
798
  this.extensionPathsToInstall = [...this.extensionPathsToInstall, ...extPathsArray];
772
799
  this.extra_params.splice(index, 1);
773
800
  });
774
801
  }
775
- params.push(`--load-extension=${this.extensionPathsToInstall.join(',')}`);
802
+ params.push(`--load-extension=${this.extensionPathsToInstall.join(",")}`);
776
803
  }
777
804
  if (this.fontsMasking) {
778
- let arg = '--font-masking-mode=2';
805
+ let arg = "--font-masking-mode=2";
779
806
  if (this.differentOs) {
780
- arg = '--font-masking-mode=3';
807
+ arg = "--font-masking-mode=3";
781
808
  }
782
- if (this.profileOs === 'android' || this.isEmptyFonts) {
783
- arg = '--font-masking-mode=1';
809
+ if (this.profileOs === "android" || this.isEmptyFonts) {
810
+ arg = "--font-masking-mode=1";
784
811
  }
785
812
  params.push(arg);
786
813
  }
@@ -793,7 +820,7 @@ class GoLogin {
793
820
  params = params.concat(this.extra_params);
794
821
  }
795
822
  if (!this.isFirstSession && this.restoreLastSession) {
796
- params.push('--restore-last-session');
823
+ params.push("--restore-last-session");
797
824
  }
798
825
  params.push(...new Set(customArgs));
799
826
  console.log(params);
@@ -802,19 +829,19 @@ class GoLogin {
802
829
  });
803
830
  this.processSpawned = child;
804
831
  // const child = spawn(ORBITA_BROWSER, params, { env, shell: true });
805
- child.stdout.on('data', data => debug(data.toString()));
806
- debug('SPAWN CMD', ORBITA_BROWSER, params.join(' '));
832
+ child.stdout.on("data", data => debug(data.toString()));
833
+ debug("SPAWN CMD", ORBITA_BROWSER, params.join(" "));
807
834
  }
808
835
  if (this.waitWebsocket) {
809
- debug('GETTING WS URL FROM BROWSER');
836
+ debug("GETTING WS URL FROM BROWSER");
810
837
  const data = await _requestretry.default.get(`http://127.0.0.1:${remote_debugging_port}/json/version`, {
811
838
  json: true
812
839
  });
813
- debug('WS IS', (0, _utils2.get)(data, 'body.webSocketDebuggerUrl', ''));
840
+ debug("WS IS", (0, _utils2.get)(data, "body.webSocketDebuggerUrl", ""));
814
841
  this.is_active = true;
815
- return (0, _utils2.get)(data, 'body.webSocketDebuggerUrl', '');
842
+ return (0, _utils2.get)(data, "body.webSocketDebuggerUrl", "");
816
843
  }
817
- return '';
844
+ return "";
818
845
  }
819
846
  async createStartupAndSpawnBrowser() {
820
847
  await this.createStartup();
@@ -832,12 +859,12 @@ class GoLogin {
832
859
  // backward compability
833
860
  false;
834
861
  if (this.uploadCookiesToServer) {
835
- await this.uploadProfileCookiesToServer();
862
+ const updateResult = await this.uploadProfileDataToServer();
863
+ this.storageGatewayUrl = updateResult.storageGateway.url;
836
864
  }
837
865
  this.is_stopping = true;
838
866
  await this.sanitizeProfile();
839
867
  if (is_posting) {
840
- await this.saveBookmarksToDb();
841
868
  await this.commitProfile();
842
869
  }
843
870
  this.is_stopping = false;
@@ -850,14 +877,38 @@ class GoLogin {
850
877
  debug(`PROFILE ${this.profile_id} STOPPED AND CLEAR`);
851
878
  return false;
852
879
  }
880
+ async uploadProfileDataToServer() {
881
+ const cookies = await (0, _cookiesManager.loadCookiesFromFile)(this.cookiesFilePath);
882
+ const bookmarks = await (0, _utils.getCurrentProfileBookmarks)(this.bookmarksFilePath);
883
+ const body = {
884
+ cookies,
885
+ bookmarks,
886
+ isCookiesEncrypted: true,
887
+ isStorageGateway: true
888
+ };
889
+ const updateResult = await _requestretry.default.post(`${_common.API_URL}/browser/features/profile/${this.profile_id}/update_after_close`, {
890
+ headers: {
891
+ Authorization: `Bearer ${this.access_token}`,
892
+ "User-Agent": "gologin-api"
893
+ },
894
+ json: body,
895
+ maxAttempts: 3,
896
+ retryDelay: 2000,
897
+ timeout: 20 * 1000
898
+ }).catch(e => {
899
+ console.log(e);
900
+ return e;
901
+ });
902
+ return updateResult.body;
903
+ }
853
904
  async stopBrowser() {
854
905
  if (!this.port) {
855
- throw new Error('Empty GoLogin port');
906
+ throw new Error("Empty GoLogin port");
856
907
  }
857
- const ls = await (0, _child_process.spawn)('fuser', ['-k TERM', `-n tcp ${this.port}`], {
908
+ const ls = await (0, _child_process.spawn)("fuser", ["-k TERM", `-n tcp ${this.port}`], {
858
909
  shell: true
859
910
  });
860
- debug('browser killed');
911
+ debug("browser killed");
861
912
  }
862
913
  killBrowser() {
863
914
  if (!this.processSpawned.pid) {
@@ -865,7 +916,7 @@ class GoLogin {
865
916
  }
866
917
  try {
867
918
  this.processSpawned.kill();
868
- debug('browser killed');
919
+ debug("browser killed");
869
920
  } catch (error) {
870
921
  console.error(error);
871
922
  }
@@ -881,7 +932,7 @@ class GoLogin {
881
932
  await Promise.all(remove_dirs.map(d => {
882
933
  const path_to_remove = `${that.profilePath()}${d}`;
883
934
  return new Promise(resolve => {
884
- debug('DROPPING', path_to_remove);
935
+ debug("DROPPING", path_to_remove);
885
936
  (0, _rimraf.default)(path_to_remove, {
886
937
  maxBusyTries: 100
887
938
  }, e => {
@@ -898,52 +949,52 @@ class GoLogin {
898
949
  await unlink(zipPath);
899
950
  }
900
951
  await this.sanitizeProfile();
901
- debug('profile sanitized');
952
+ debug("profile sanitized");
902
953
  const profilePath = this.profilePath();
903
954
  const fileBuff = await (0, _profileArchiver.archiveProfile)(profilePath);
904
- debug('PROFILE ZIP CREATED', profilePath, zipPath);
955
+ debug("PROFILE ZIP CREATED", profilePath, zipPath);
905
956
  return fileBuff;
906
957
  }
907
958
  async profileExists() {
908
959
  const profileResponse = await _requestretry.default.post(`${_common.API_URL}/browser`, {
909
960
  headers: {
910
- 'Authorization': `Bearer ${this.access_token}`,
911
- 'User-Agent': 'gologin-api'
961
+ Authorization: `Bearer ${this.access_token}`,
962
+ "User-Agent": "gologin-api"
912
963
  },
913
964
  json: {}
914
965
  });
915
966
  if (profileResponse.statusCode !== 200) {
916
967
  return false;
917
968
  }
918
- debug('profile is', profileResponse.body);
969
+ debug("profile is", profileResponse.body);
919
970
  return true;
920
971
  }
921
972
  async getRandomFingerprint(options) {
922
- let os = 'lin';
973
+ let os = "lin";
923
974
  if (options.os) {
924
975
  os = options.os;
925
976
  }
926
977
  let url = `${_common.API_URL}/browser/fingerprint?os=${os}`;
927
978
  if (options.isM1) {
928
- url += '&isM1=true';
979
+ url += "&isM1=true";
929
980
  }
930
981
  const fingerprint = await _requestretry.default.get(url, {
931
982
  headers: {
932
- 'Authorization': `Bearer ${this.access_token}`,
933
- 'User-Agent': 'gologin-api'
983
+ Authorization: `Bearer ${this.access_token}`,
984
+ "User-Agent": "gologin-api"
934
985
  }
935
986
  });
936
987
  return JSON.parse(fingerprint.body);
937
988
  }
938
989
  async create(options) {
939
- debug('createProfile', options);
990
+ debug("createProfile", options);
940
991
  const fingerprint = await this.getRandomFingerprint(options);
941
- debug('fingerprint=', fingerprint);
992
+ debug("fingerprint=", fingerprint);
942
993
  if (fingerprint.statusCode === 500) {
943
- throw new Error('no valid random fingerprint check os param');
994
+ throw new Error("no valid random fingerprint check os param");
944
995
  }
945
996
  if (fingerprint.statusCode === 401) {
946
- throw new Error('invalid token');
997
+ throw new Error("invalid token");
947
998
  }
948
999
  const {
949
1000
  navigator,
@@ -956,26 +1007,26 @@ class GoLogin {
956
1007
  deviceMemory = 1;
957
1008
  }
958
1009
  navigator.deviceMemory = deviceMemory * 1024;
959
- webGLMetadata.mode = webGLMetadata.mode === 'noise' ? 'mask' : 'off';
1010
+ webGLMetadata.mode = webGLMetadata.mode === "noise" ? "mask" : "off";
960
1011
  const json = {
961
1012
  ...fingerprint,
962
1013
  navigator,
963
1014
  webGLMetadata,
964
- browserType: 'chrome',
965
- name: 'default_name',
966
- notes: 'auto generated',
1015
+ browserType: "chrome",
1016
+ name: "default_name",
1017
+ notes: "auto generated",
967
1018
  fonts: {
968
1019
  families: fonts
969
1020
  },
970
1021
  webRTC: {
971
1022
  ...webRTC,
972
- mode: 'alerted'
1023
+ mode: "alerted"
973
1024
  }
974
1025
  };
975
1026
  const user_agent = options.navigator?.userAgent;
976
1027
  const orig_user_agent = json.navigator.userAgent;
977
1028
  Object.keys(options).forEach(key => {
978
- if (typeof json[key] === 'object') {
1029
+ if (typeof json[key] === "object") {
979
1030
  json[key] = {
980
1031
  ...json[key],
981
1032
  ...options[key]
@@ -984,13 +1035,13 @@ class GoLogin {
984
1035
  }
985
1036
  json[key] = options[key];
986
1037
  });
987
- if (user_agent === 'random') {
1038
+ if (user_agent === "random") {
988
1039
  json.navigator.userAgent = orig_user_agent;
989
1040
  }
990
1041
  const response = await _requestretry.default.post(`${_common.API_URL}/browser`, {
991
1042
  headers: {
992
- 'Authorization': `Bearer ${this.access_token}`,
993
- 'User-Agent': 'gologin-api'
1043
+ Authorization: `Bearer ${this.access_token}`,
1044
+ "User-Agent": "gologin-api"
994
1045
  },
995
1046
  json
996
1047
  });
@@ -1004,11 +1055,11 @@ class GoLogin {
1004
1055
  return response.body.id;
1005
1056
  }
1006
1057
  async createCustom(options) {
1007
- debug('createCustomProfile', options);
1058
+ debug("createCustomProfile", options);
1008
1059
  const response = await _requestretry.default.post(`${_common.API_URL}/browser/custom`, {
1009
1060
  headers: {
1010
- 'Authorization': `Bearer ${this.access_token}`,
1011
- 'User-Agent': 'gologin-api'
1061
+ Authorization: `Bearer ${this.access_token}`,
1062
+ "User-Agent": "gologin-api"
1012
1063
  },
1013
1064
  json: options
1014
1065
  });
@@ -1021,17 +1072,17 @@ class GoLogin {
1021
1072
  debug(JSON.stringify(response));
1022
1073
  return response.body.id;
1023
1074
  }
1024
- async quickCreateProfile(name = '') {
1075
+ async quickCreateProfile(name = "") {
1025
1076
  const osInfo = await (0, _common.getOsAdvanced)();
1026
1077
  const {
1027
1078
  os,
1028
1079
  osSpec
1029
1080
  } = osInfo;
1030
- const resultName = name || 'api-generated';
1081
+ const resultName = name || "api-generated";
1031
1082
  return _requestretry.default.post(`${_common.API_URL}/browser/quick`, {
1032
1083
  headers: {
1033
- 'Authorization': `Bearer ${this.access_token}`,
1034
- 'User-Agent': 'gologin-api'
1084
+ Authorization: `Bearer ${this.access_token}`,
1085
+ "User-Agent": "gologin-api"
1035
1086
  },
1036
1087
  json: {
1037
1088
  os,
@@ -1044,8 +1095,8 @@ class GoLogin {
1044
1095
  const profile_id = pid || this.profile_id;
1045
1096
  await _requestretry.default.delete(`${_common.API_URL}/browser/${profile_id}`, {
1046
1097
  headers: {
1047
- 'Authorization': `Bearer ${this.access_token}`,
1048
- 'User-Agent': 'gologin-api'
1098
+ Authorization: `Bearer ${this.access_token}`,
1099
+ "User-Agent": "gologin-api"
1049
1100
  }
1050
1101
  });
1051
1102
  }
@@ -1057,18 +1108,18 @@ class GoLogin {
1057
1108
  profile.navigator[e] = options.navigator[e];
1058
1109
  });
1059
1110
  }
1060
- Object.keys(options).filter(el => el !== 'navigator').forEach(el => {
1111
+ Object.keys(options).filter(el => el !== "navigator").forEach(el => {
1061
1112
  profile[el] = options[el];
1062
1113
  });
1063
- debug('update profile', profile);
1114
+ debug("update profile", profile);
1064
1115
  const response = await _requestretry.default.put(`${_common.API_URL}/browser/${options.id}`, {
1065
1116
  json: profile,
1066
1117
  headers: {
1067
- 'Authorization': `Bearer ${this.access_token}`,
1068
- 'User-Agent': 'gologin-api'
1118
+ Authorization: `Bearer ${this.access_token}`,
1119
+ "User-Agent": "gologin-api"
1069
1120
  }
1070
1121
  });
1071
- debug('response', JSON.stringify(response.body));
1122
+ debug("response", JSON.stringify(response.body));
1072
1123
  return response.body;
1073
1124
  }
1074
1125
  setActive(is_active) {
@@ -1097,8 +1148,8 @@ class GoLogin {
1097
1148
  }
1098
1149
  async postCookies(profileId, cookies) {
1099
1150
  const formattedCookies = cookies.map(cookie => {
1100
- if (!['no_restriction', 'lax', 'strict', 'unspecified'].includes(cookie.sameSite)) {
1101
- cookie.sameSite = 'unspecified';
1151
+ if (!["no_restriction", "lax", "strict", "unspecified"].includes(cookie.sameSite)) {
1152
+ cookie.sameSite = "unspecified";
1102
1153
  }
1103
1154
  return cookie;
1104
1155
  });
@@ -1112,7 +1163,7 @@ class GoLogin {
1112
1163
  return response.body;
1113
1164
  }
1114
1165
  return {
1115
- status: 'failure',
1166
+ status: "failure",
1116
1167
  status_code: response.statusCode,
1117
1168
  body: response.body
1118
1169
  };
@@ -1126,11 +1177,11 @@ class GoLogin {
1126
1177
  return response.body;
1127
1178
  }
1128
1179
  getCookiePath(defaultFilePath) {
1129
- let primary = (0, _path.join)(defaultFilePath, 'Cookies');
1130
- let secondary = (0, _path.join)(defaultFilePath, 'Network', 'Cookies');
1180
+ let primary = (0, _path.join)(defaultFilePath, "Cookies");
1181
+ let secondary = (0, _path.join)(defaultFilePath, "Network", "Cookies");
1131
1182
  if (!(0, _fs.existsSync)(primary)) {
1132
- primary = (0, _path.join)(defaultFilePath, 'Network', 'Cookies');
1133
- secondary = (0, _path.join)(defaultFilePath, 'Cookies');
1183
+ primary = (0, _path.join)(defaultFilePath, "Network", "Cookies");
1184
+ secondary = (0, _path.join)(defaultFilePath, "Cookies");
1134
1185
  }
1135
1186
  return {
1136
1187
  primary,
@@ -1150,7 +1201,7 @@ class GoLogin {
1150
1201
  }));
1151
1202
  let db;
1152
1203
  const profilePath = (0, _path.join)(this.tmpdir, `gologin_profile_${this.profile_id}`);
1153
- const defaultFilePath = (0, _path.resolve)(profilePath, 'Default');
1204
+ const defaultFilePath = (0, _path.resolve)(profilePath, "Default");
1154
1205
  const cookiesPaths = this.getCookiePath(defaultFilePath);
1155
1206
  try {
1156
1207
  db = await (0, _cookiesManager.getDB)(cookiesPaths.primary, false);
@@ -1196,7 +1247,7 @@ class GoLogin {
1196
1247
  const wsUrl = await this.spawnBrowser();
1197
1248
  this.setActive(true);
1198
1249
  return {
1199
- status: 'success',
1250
+ status: "success",
1200
1251
  wsUrl
1201
1252
  };
1202
1253
  }
@@ -1206,7 +1257,7 @@ class GoLogin {
1206
1257
  const wsUrl = await this.spawnBrowser();
1207
1258
  this.setActive(true);
1208
1259
  return {
1209
- status: 'success',
1260
+ status: "success",
1210
1261
  wsUrl
1211
1262
  };
1212
1263
  }
@@ -1225,10 +1276,10 @@ class GoLogin {
1225
1276
  async waitDebuggingUrl(delay_ms, try_count = 0, remoteOrbitaUrl) {
1226
1277
  await delay(delay_ms);
1227
1278
  const url = `${remoteOrbitaUrl}/json/version`;
1228
- console.log('try_count=', try_count, 'url=', url);
1279
+ console.log("try_count=", try_count, "url=", url);
1229
1280
  const response = await _requestretry.default.get(url);
1230
- let wsUrl = '';
1231
- console.log('response', response.body);
1281
+ let wsUrl = "";
1282
+ console.log("response", response.body);
1232
1283
  if (!response.body) {
1233
1284
  return wsUrl;
1234
1285
  }
@@ -1240,22 +1291,22 @@ class GoLogin {
1240
1291
  return this.waitDebuggingUrl(delay_ms, try_count + 1, remoteOrbitaUrl);
1241
1292
  }
1242
1293
  return {
1243
- status: 'failure',
1294
+ status: "failure",
1244
1295
  wsUrl,
1245
- message: 'Check proxy settings',
1246
- 'profile_id': this.profile_id
1296
+ message: "Check proxy settings",
1297
+ profile_id: this.profile_id
1247
1298
  };
1248
1299
  }
1249
- const remoteOrbitaUrlWithoutProtocol = remoteOrbitaUrl.replace('https://', '');
1250
- wsUrl = wsUrl.replace('ws://', 'wss://').replace('127.0.0.1', remoteOrbitaUrlWithoutProtocol);
1300
+ const remoteOrbitaUrlWithoutProtocol = remoteOrbitaUrl.replace("https://", "");
1301
+ wsUrl = wsUrl.replace("ws://", "wss://").replace("127.0.0.1", remoteOrbitaUrlWithoutProtocol);
1251
1302
  return wsUrl;
1252
1303
  }
1253
1304
  async stopRemote() {
1254
1305
  debug(`stopRemote ${this.profile_id}`);
1255
1306
  const profileResponse = await _requestretry.default.delete(`${_common.API_URL}/browser/${this.profile_id}/web`, {
1256
1307
  headers: {
1257
- 'Authorization': `Bearer ${this.access_token}`,
1258
- 'User-Agent': 'gologin-api'
1308
+ Authorization: `Bearer ${this.access_token}`,
1309
+ "User-Agent": "gologin-api"
1259
1310
  }
1260
1311
  });
1261
1312
  console.log(`stopRemote ${profileResponse.body}`);