@wppconnect-team/wppconnect 2.3.4 → 2.3.6
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.
- package/CHANGELOG.md +57 -0
- package/dist/api/helpers/decrypt.js +8 -19
- package/dist/api/helpers/download-file.d.ts +4 -0
- package/dist/api/helpers/download-file.js +12 -0
- package/dist/api/helpers/file-to-base64.d.ts +6 -0
- package/dist/api/helpers/file-to-base64.js +27 -10
- package/dist/api/layers/group.layer.js +2 -4
- package/dist/api/layers/host.layer.d.ts +23 -3
- package/dist/api/layers/host.layer.js +166 -40
- package/dist/api/whatsapp.d.ts +24 -0
- package/dist/api/whatsapp.js +102 -52
- package/dist/config/create-config.d.ts +17 -1
- package/dist/config/create-config.js +3 -2
- package/dist/config/puppeteer.config.d.ts +12 -0
- package/dist/config/puppeteer.config.js +17 -7
- package/dist/controllers/auth.js +3 -1
- package/dist/controllers/browser.d.ts +47 -1
- package/dist/controllers/browser.js +187 -28
- package/dist/controllers/initializer.js +62 -40
- package/dist/index.d.ts +1 -0
- package/dist/index.js +3 -1
- package/package.json +15 -15
package/dist/api/whatsapp.js
CHANGED
|
@@ -52,57 +52,125 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
52
52
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
53
53
|
};
|
|
54
54
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
55
|
-
exports.Whatsapp = void 0;
|
|
55
|
+
exports.Whatsapp = exports.DECRYPT_TIMEOUT_MS = void 0;
|
|
56
|
+
exports.getUntilOk = getUntilOk;
|
|
56
57
|
const axios_1 = __importDefault(require("axios"));
|
|
57
58
|
const fs = __importStar(require("fs"));
|
|
58
59
|
const promises_1 = require("stream/promises");
|
|
60
|
+
const browser_1 = require("../controllers/browser");
|
|
59
61
|
const WAuserAgente_1 = require("../config/WAuserAgente");
|
|
60
62
|
const sleep_1 = require("../utils/sleep");
|
|
61
63
|
const helpers_1 = require("./helpers");
|
|
62
64
|
const decrypt_1 = require("./helpers/decrypt");
|
|
63
65
|
const business_layer_1 = require("./layers/business.layer");
|
|
66
|
+
/** Per-request timeout so a single fetch cannot hang a send indefinitely. */
|
|
67
|
+
exports.DECRYPT_TIMEOUT_MS = 30000;
|
|
68
|
+
/**
|
|
69
|
+
* GETs a URL until HTTP 200, retrying transient failures (including a rejected
|
|
70
|
+
* status) with linear backoff. Replaces an unbounded `while` loop that wedged
|
|
71
|
+
* `decryptFile` forever on a persistently failing download. Each attempt is
|
|
72
|
+
* bounded by `timeout` (defaults to {@link DECRYPT_TIMEOUT_MS}) so a stalled
|
|
73
|
+
* response cannot hang either.
|
|
74
|
+
*/
|
|
75
|
+
async function getUntilOk(url, options, maxAttempts = 3) {
|
|
76
|
+
const requestOptions = { timeout: exports.DECRYPT_TIMEOUT_MS, ...options };
|
|
77
|
+
let lastError;
|
|
78
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
79
|
+
try {
|
|
80
|
+
const res = await axios_1.default.get(url, requestOptions);
|
|
81
|
+
if (res.status == 200) {
|
|
82
|
+
return res;
|
|
83
|
+
}
|
|
84
|
+
lastError = new Error(`unexpected status ${res.status}`);
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
lastError = error;
|
|
88
|
+
}
|
|
89
|
+
if (attempt < maxAttempts) {
|
|
90
|
+
await (0, decrypt_1.timeout)(2000 * attempt);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
throw new Error(`Error trying to download the file (${(lastError && lastError.message) || lastError}).`);
|
|
94
|
+
}
|
|
64
95
|
class Whatsapp extends business_layer_1.BusinessLayer {
|
|
65
96
|
page;
|
|
97
|
+
/**
|
|
98
|
+
* The page binding exposed by `wireConnectionEvents` can only be registered
|
|
99
|
+
* once per page, but a page may be reused by a later client. This maps each
|
|
100
|
+
* page to the callback of the client that most recently wired it, so the
|
|
101
|
+
* existing binding can be redirected to the current client.
|
|
102
|
+
*/
|
|
103
|
+
static connectionDispatchers = new WeakMap();
|
|
66
104
|
connected = null;
|
|
67
105
|
constructor(page, session, options) {
|
|
68
106
|
super(page, session, options);
|
|
69
107
|
this.page = page;
|
|
70
|
-
let interval = null;
|
|
71
|
-
if (this.page) {
|
|
72
|
-
this.page.on('close', async () => {
|
|
73
|
-
clearInterval(interval);
|
|
74
|
-
});
|
|
75
|
-
}
|
|
76
|
-
interval = setInterval(async () => {
|
|
77
|
-
const newConnected = await page
|
|
78
|
-
.evaluate(() => WPP.conn.isRegistered())
|
|
79
|
-
.catch(() => null);
|
|
80
|
-
if (newConnected === null || newConnected === this.connected) {
|
|
81
|
-
return;
|
|
82
|
-
}
|
|
83
|
-
this.connected = newConnected;
|
|
84
|
-
if (!newConnected) {
|
|
85
|
-
this.log('info', 'Session Unpaired', { type: 'session' });
|
|
86
|
-
setTimeout(async () => {
|
|
87
|
-
if (this.statusFind) {
|
|
88
|
-
try {
|
|
89
|
-
this.statusFind('disconnectedMobile', session || '');
|
|
90
|
-
}
|
|
91
|
-
catch (error) { }
|
|
92
|
-
}
|
|
93
|
-
}, 1000);
|
|
94
|
-
}
|
|
95
|
-
}, 1000);
|
|
96
108
|
}
|
|
97
109
|
async afterPageScriptInjected() {
|
|
98
110
|
await super.afterPageScriptInjected();
|
|
111
|
+
await this.wireConnectionEvents();
|
|
99
112
|
this.page
|
|
100
113
|
.evaluate(() => WPP.conn.isRegistered())
|
|
101
114
|
.then((isAuthenticated) => {
|
|
102
|
-
|
|
115
|
+
// Do not overwrite a connection event that arrived while the initial
|
|
116
|
+
// state was being read.
|
|
117
|
+
if (this.connected === null) {
|
|
118
|
+
this.connected = isAuthenticated;
|
|
119
|
+
}
|
|
103
120
|
})
|
|
104
121
|
.catch(() => null);
|
|
105
122
|
}
|
|
123
|
+
/**
|
|
124
|
+
* Forwards wa-js connection events to the Node side instead of polling
|
|
125
|
+
* `WPP.conn.isRegistered()` every second. Re-registered after every page
|
|
126
|
+
* load, since the in-page listeners do not survive navigation.
|
|
127
|
+
*/
|
|
128
|
+
async wireConnectionEvents() {
|
|
129
|
+
const page = this.page;
|
|
130
|
+
// `exposeFunction` can only bind a given name once and a page can be
|
|
131
|
+
// reused by a later client, so route the page binding through a per-page
|
|
132
|
+
// dispatcher. A second client re-points the existing binding at itself
|
|
133
|
+
// instead of leaving the previous client's callback installed.
|
|
134
|
+
await page
|
|
135
|
+
.exposeFunction('onConnectionChange', (isRegistered) => {
|
|
136
|
+
Whatsapp.connectionDispatchers.get(page)?.(isRegistered);
|
|
137
|
+
})
|
|
138
|
+
.catch(() => null);
|
|
139
|
+
Whatsapp.connectionDispatchers.set(page, (isRegistered) => this.onConnectionChange(isRegistered));
|
|
140
|
+
await (0, helpers_1.evaluateAndReturn)(page, () => {
|
|
141
|
+
const handler = window.onConnectionChange;
|
|
142
|
+
if (typeof handler !== 'function' || handler.__wppWired) {
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
handler.__wppWired = true;
|
|
146
|
+
WPP.on('conn.authenticated', () => handler(true));
|
|
147
|
+
WPP.on('conn.main_ready', () => handler(true));
|
|
148
|
+
WPP.on('conn.logout', () => handler(false));
|
|
149
|
+
WPP.on('conn.require_auth', () => handler(false));
|
|
150
|
+
}).catch(() => null);
|
|
151
|
+
}
|
|
152
|
+
onConnectionChange(isRegistered) {
|
|
153
|
+
if (isRegistered === this.connected) {
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
const wasConnected = this.connected;
|
|
157
|
+
this.connected = isRegistered;
|
|
158
|
+
// Only a registered -> unregistered transition is a disconnection. The
|
|
159
|
+
// first event on a fresh page can arrive before afterPageScriptInjected()
|
|
160
|
+
// records the initial state, and a page that was never paired is not a
|
|
161
|
+
// phone that disconnected.
|
|
162
|
+
if (!isRegistered && wasConnected === true) {
|
|
163
|
+
this.log('info', 'Session Unpaired', { type: 'session' });
|
|
164
|
+
setTimeout(() => {
|
|
165
|
+
if (this.statusFind) {
|
|
166
|
+
try {
|
|
167
|
+
this.statusFind('disconnectedMobile', this.session || '');
|
|
168
|
+
}
|
|
169
|
+
catch (error) { }
|
|
170
|
+
}
|
|
171
|
+
}, 1000);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
106
174
|
/**
|
|
107
175
|
* Decrypts message file
|
|
108
176
|
* @param data Message object
|
|
@@ -169,20 +237,11 @@ class Whatsapp extends business_layer_1.BusinessLayer {
|
|
|
169
237
|
* @internal
|
|
170
238
|
*/
|
|
171
239
|
async close() {
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
Code was removed as it is not necessary.
|
|
178
|
-
try {
|
|
179
|
-
const process = browser.process();
|
|
180
|
-
if (process) {
|
|
181
|
-
treekill(process.pid, 'SIGKILL');
|
|
182
|
-
}
|
|
183
|
-
} catch (error) {}
|
|
184
|
-
*/
|
|
185
|
-
}
|
|
240
|
+
this.cancelQrLoop();
|
|
241
|
+
// The page may already be closed (autoClose, crash or logout), but the
|
|
242
|
+
// browser and its OS process tree must still be released
|
|
243
|
+
await this.page.close().catch(() => null);
|
|
244
|
+
await (0, browser_1.closeBrowser)(this.page.browser());
|
|
186
245
|
return true;
|
|
187
246
|
}
|
|
188
247
|
/**
|
|
@@ -221,18 +280,9 @@ class Whatsapp extends business_layer_1.BusinessLayer {
|
|
|
221
280
|
const options = (0, decrypt_1.makeOptions)(WAuserAgente_1.useragentOverride);
|
|
222
281
|
if (!mediaUrl)
|
|
223
282
|
throw new Error('message is missing critical data (`mediaUrl`) needed to download the file.');
|
|
224
|
-
let haventGottenImageYet = true;
|
|
225
283
|
let res;
|
|
226
284
|
try {
|
|
227
|
-
|
|
228
|
-
res = await axios_1.default.get(mediaUrl.trim(), options);
|
|
229
|
-
if (res.status == 200) {
|
|
230
|
-
haventGottenImageYet = false;
|
|
231
|
-
}
|
|
232
|
-
else {
|
|
233
|
-
await (0, decrypt_1.timeout)(2000);
|
|
234
|
-
}
|
|
235
|
-
}
|
|
285
|
+
res = await getUntilOk(mediaUrl.trim(), options);
|
|
236
286
|
}
|
|
237
287
|
catch (error) {
|
|
238
288
|
throw new Error('Error trying to download the file.');
|
|
@@ -30,6 +30,16 @@ export interface CreateConfig {
|
|
|
30
30
|
* Parameters to be added into the chrome browser instance
|
|
31
31
|
*/
|
|
32
32
|
browserArgs?: string[];
|
|
33
|
+
/**
|
|
34
|
+
* Adds the protection-disabling launch flags (`--no-sandbox`,
|
|
35
|
+
* `--disable-setuid-sandbox`, `--ignore-certificate-errors` and
|
|
36
|
+
* `--disable-site-isolation-trials`) to the resolved launch arguments.
|
|
37
|
+
* Disabling these protections weakens the browser sandbox and certificate
|
|
38
|
+
* validation, so it is opt-in and should only be used where the environment
|
|
39
|
+
* requires it.
|
|
40
|
+
* @default false
|
|
41
|
+
*/
|
|
42
|
+
useInsecureChromiumArgs?: boolean;
|
|
33
43
|
/**
|
|
34
44
|
* Will be passed to puppeteer.launch
|
|
35
45
|
*/
|
|
@@ -67,6 +77,12 @@ export interface CreateConfig {
|
|
|
67
77
|
* @default 180000 (3 minutes)
|
|
68
78
|
*/
|
|
69
79
|
deviceSyncTimeout?: number;
|
|
80
|
+
/**
|
|
81
|
+
* Time in ms for wa-js to be injected and `WPP.isReady`, from the first page load (reloads share it).
|
|
82
|
+
* Exceeding it fails the page load with `InjectionTimeoutError`; 0 waits until ready or closed.
|
|
83
|
+
* @default 120000 (2 minutes)
|
|
84
|
+
*/
|
|
85
|
+
injectionTimeout?: number;
|
|
70
86
|
/**
|
|
71
87
|
* Wait for in chat to return a instance of {@link Whatsapp}
|
|
72
88
|
* @default false
|
|
@@ -109,7 +125,7 @@ export interface CreateConfig {
|
|
|
109
125
|
* Normalmente, versões mais antigas continuam funcionando por mais um tempo,
|
|
110
126
|
* assim, com essa opção, é possível ter uma janela de tempo maior para se preparar para atualizações.
|
|
111
127
|
* Caso seja definido vazio ou null, será usado a versão atual, ou seja, sem forçar versão específica.
|
|
112
|
-
* @default
|
|
128
|
+
* @default ''
|
|
113
129
|
*/
|
|
114
130
|
whatsappVersion?: string;
|
|
115
131
|
/**
|
|
@@ -10,17 +10,18 @@ exports.defaultOptions = {
|
|
|
10
10
|
debug: false,
|
|
11
11
|
logQR: true,
|
|
12
12
|
browserWS: '',
|
|
13
|
-
|
|
13
|
+
useInsecureChromiumArgs: false,
|
|
14
14
|
puppeteerOptions: {},
|
|
15
15
|
disableWelcome: false,
|
|
16
16
|
updatesLog: true,
|
|
17
17
|
autoClose: 60000,
|
|
18
18
|
deviceSyncTimeout: 180000,
|
|
19
|
+
injectionTimeout: 120000,
|
|
19
20
|
createPathFileToken: true,
|
|
20
21
|
waitForLogin: true,
|
|
21
22
|
logger: logger_1.defaultLogger,
|
|
22
23
|
tokenStore: 'file',
|
|
23
|
-
whatsappVersion: '
|
|
24
|
+
whatsappVersion: '',
|
|
24
25
|
deviceName: false,
|
|
25
26
|
linkPreviewApiServers: null,
|
|
26
27
|
disableGoogleAnalytics: true,
|
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
declare const puppeteerConfig: {
|
|
2
2
|
whatsappUrl: string;
|
|
3
|
+
/**
|
|
4
|
+
* Default launch and performance flags for headless/container environments.
|
|
5
|
+
* They do not disable browser protection; callers that need the flags in
|
|
6
|
+
* `protectionDisablingChromiumArgs` must opt in explicitly.
|
|
7
|
+
*/
|
|
3
8
|
chromiumArgs: string[];
|
|
9
|
+
/**
|
|
10
|
+
* Flags that disable browser protections. They are never applied by default:
|
|
11
|
+
* use `useInsecureChromiumArgs: true` or add them to `browserArgs` when an
|
|
12
|
+
* environment explicitly requires them (for example a container that cannot
|
|
13
|
+
* use the Chromium sandbox).
|
|
14
|
+
*/
|
|
15
|
+
protectionDisablingChromiumArgs: string[];
|
|
4
16
|
};
|
|
5
17
|
export { puppeteerConfig };
|
|
@@ -19,28 +19,26 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
19
19
|
exports.puppeteerConfig = void 0;
|
|
20
20
|
const puppeteerConfig = {
|
|
21
21
|
whatsappUrl: 'https://web.whatsapp.com',
|
|
22
|
+
/**
|
|
23
|
+
* Default launch and performance flags for headless/container environments.
|
|
24
|
+
* They do not disable browser protection; callers that need the flags in
|
|
25
|
+
* `protectionDisablingChromiumArgs` must opt in explicitly.
|
|
26
|
+
*/
|
|
22
27
|
chromiumArgs: [
|
|
23
28
|
// `--app=${WAUrl}`,
|
|
24
29
|
'--log-level=3', // fatal only
|
|
25
30
|
//'--start-maximized',
|
|
26
31
|
'--no-default-browser-check',
|
|
27
|
-
'--disable-site-isolation-trials',
|
|
28
32
|
'--no-experiments',
|
|
29
33
|
'--ignore-gpu-blacklist',
|
|
30
|
-
'--ignore-certificate-errors',
|
|
31
|
-
'--ignore-certificate-errors-spki-list',
|
|
32
34
|
'--disable-gpu',
|
|
33
35
|
'--disable-extensions',
|
|
34
36
|
'--disable-default-apps',
|
|
35
37
|
'--enable-features=NetworkService',
|
|
36
|
-
'--disable-setuid-sandbox',
|
|
37
|
-
'--no-sandbox',
|
|
38
38
|
// Extras
|
|
39
39
|
'--disable-webgl',
|
|
40
40
|
'--disable-infobars',
|
|
41
41
|
'--window-position=0,0',
|
|
42
|
-
'--ignore-certifcate-errors',
|
|
43
|
-
'--ignore-certifcate-errors-spki-list',
|
|
44
42
|
'--disable-threaded-animation',
|
|
45
43
|
'--disable-threaded-scrolling',
|
|
46
44
|
'--disable-in-process-stack-traces',
|
|
@@ -58,5 +56,17 @@ const puppeteerConfig = {
|
|
|
58
56
|
'--autoplay-policy=no-user-gesture-required',
|
|
59
57
|
'--disable-blink-features=AutomationControlled',
|
|
60
58
|
],
|
|
59
|
+
/**
|
|
60
|
+
* Flags that disable browser protections. They are never applied by default:
|
|
61
|
+
* use `useInsecureChromiumArgs: true` or add them to `browserArgs` when an
|
|
62
|
+
* environment explicitly requires them (for example a container that cannot
|
|
63
|
+
* use the Chromium sandbox).
|
|
64
|
+
*/
|
|
65
|
+
protectionDisablingChromiumArgs: [
|
|
66
|
+
'--no-sandbox',
|
|
67
|
+
'--disable-setuid-sandbox',
|
|
68
|
+
'--ignore-certificate-errors',
|
|
69
|
+
'--disable-site-isolation-trials',
|
|
70
|
+
],
|
|
61
71
|
};
|
|
62
72
|
exports.puppeteerConfig = puppeteerConfig;
|
package/dist/controllers/auth.js
CHANGED
|
@@ -94,7 +94,9 @@ const needsToScan = async (waPage) => {
|
|
|
94
94
|
};
|
|
95
95
|
exports.needsToScan = needsToScan;
|
|
96
96
|
const isInsideChat = async (waPage) => {
|
|
97
|
-
|
|
97
|
+
// Some WhatsApp versions report main_ready while still showing the QR screen.
|
|
98
|
+
// Read both conditions in the same document before treating it as a chat.
|
|
99
|
+
return await waPage.evaluate(() => WPP.conn.isRegistered() && WPP.conn.isMainReady());
|
|
98
100
|
};
|
|
99
101
|
exports.isInsideChat = isInsideChat;
|
|
100
102
|
const isConnectingToPhone = async (waPage) => {
|
|
@@ -17,10 +17,56 @@ export declare function initWhatsapp(page: Page, token?: SessionToken, clear?: b
|
|
|
17
17
|
password: string;
|
|
18
18
|
}, log?: (level: LogLevel, message: string, meta?: object) => any): Promise<Page>;
|
|
19
19
|
export declare function onLoadingScreen(page: Page, onLoadingScreenCallBack?: LoadingScreenCallback): Promise<void>;
|
|
20
|
-
export
|
|
20
|
+
export interface WaitForReadyOptions {
|
|
21
|
+
/** Milliseconds; 0 waits until ready, aborted or closed */
|
|
22
|
+
timeout?: number;
|
|
23
|
+
/** Epoch ms the timeout counts from; defaults to the call time */
|
|
24
|
+
startedAt?: number;
|
|
25
|
+
signal?: AbortSignal;
|
|
26
|
+
}
|
|
27
|
+
export interface InjectApiOptions extends WaitForReadyOptions {
|
|
28
|
+
/** Assigned to window.WPPConfig before wa-js loads */
|
|
29
|
+
config?: object;
|
|
30
|
+
}
|
|
31
|
+
export declare class InjectionTimeoutError extends Error {
|
|
32
|
+
readonly timeout: number;
|
|
33
|
+
name: string;
|
|
34
|
+
constructor(timeout: number, options?: ErrorOptions);
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Waits for WAPI, Store and WPP.isReady on the current document
|
|
38
|
+
*/
|
|
39
|
+
export declare function waitForWppReady(page: Page, options?: WaitForReadyOptions): Promise<void>;
|
|
40
|
+
export declare function injectApi(page: Page, onLoadingScreenCallBack?: LoadingScreenCallback, options?: InjectApiOptions): Promise<void>;
|
|
41
|
+
/**
|
|
42
|
+
* Resolves the Chromium launch arguments.
|
|
43
|
+
*
|
|
44
|
+
* When the caller passes no arguments (or an empty list) the default
|
|
45
|
+
* `puppeteerConfig.chromiumArgs` are used. A non-empty list replaces the
|
|
46
|
+
* defaults, matching the existing `browserArgs` contract. The default list only
|
|
47
|
+
* contains launch and performance flags; the flags that disable browser
|
|
48
|
+
* protections live in `puppeteerConfig.protectionDisablingChromiumArgs` and are
|
|
49
|
+
* only merged in when `useInsecureChromiumArgs` is explicitly enabled.
|
|
50
|
+
*/
|
|
51
|
+
export declare function resolveBrowserArgs(requested?: string[], useInsecure?: boolean): string[];
|
|
21
52
|
/**
|
|
22
53
|
* Initializes browser, will try to use chrome as default
|
|
23
54
|
* @param session
|
|
24
55
|
*/
|
|
25
56
|
export declare function initBrowser(session: string, options: CreateConfig, logger: Logger): Promise<Browser>;
|
|
57
|
+
/**
|
|
58
|
+
* Closes a browser and, when it was launched by this process, guarantees its
|
|
59
|
+
* OS process tree is terminated even if the graceful close fails or hangs.
|
|
60
|
+
* Remote browsers (`browserWS`) expose no process handle and are only
|
|
61
|
+
* disconnected. Safe to call when the page/browser was already closed.
|
|
62
|
+
*/
|
|
63
|
+
export declare function closeBrowser(browser: Browser): Promise<void>;
|
|
26
64
|
export declare function getOrCreatePage(browser: Browser | BrowserContext): Promise<Page>;
|
|
65
|
+
/**
|
|
66
|
+
* Returns whether at least one open, non-blank page remains.
|
|
67
|
+
*
|
|
68
|
+
* Puppeteer commonly leaves an `about:blank` tab behind after the session page
|
|
69
|
+
* is closed, so a non-empty `browser.pages()` does not prove a real page is
|
|
70
|
+
* still alive. This drives the auto-close guard in `create()`.
|
|
71
|
+
*/
|
|
72
|
+
export declare function hasAlivePage(pages: Page[]): boolean;
|
|
@@ -52,13 +52,18 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
52
52
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
53
53
|
};
|
|
54
54
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
55
|
+
exports.InjectionTimeoutError = void 0;
|
|
55
56
|
exports.unregisterServiceWorker = unregisterServiceWorker;
|
|
56
57
|
exports.setWhatsappVersion = setWhatsappVersion;
|
|
57
58
|
exports.initWhatsapp = initWhatsapp;
|
|
58
59
|
exports.onLoadingScreen = onLoadingScreen;
|
|
60
|
+
exports.waitForWppReady = waitForWppReady;
|
|
59
61
|
exports.injectApi = injectApi;
|
|
62
|
+
exports.resolveBrowserArgs = resolveBrowserArgs;
|
|
60
63
|
exports.initBrowser = initBrowser;
|
|
64
|
+
exports.closeBrowser = closeBrowser;
|
|
61
65
|
exports.getOrCreatePage = getOrCreatePage;
|
|
66
|
+
exports.hasAlivePage = hasAlivePage;
|
|
62
67
|
const ChromeLauncher = __importStar(require("chrome-launcher"));
|
|
63
68
|
const os = __importStar(require("os"));
|
|
64
69
|
const path = __importStar(require("path"));
|
|
@@ -70,6 +75,7 @@ const puppeteer_config_1 = require("../config/puppeteer.config");
|
|
|
70
75
|
const puppeteer_extra_plugin_stealth_1 = __importDefault(require("puppeteer-extra-plugin-stealth"));
|
|
71
76
|
const WAuserAgente_1 = require("../config/WAuserAgente");
|
|
72
77
|
const websocket_1 = require("./websocket");
|
|
78
|
+
const treeKill = require('tree-kill');
|
|
73
79
|
async function unregisterServiceWorker(page) {
|
|
74
80
|
await page.evaluateOnNewDocument(() => {
|
|
75
81
|
// Remove existent service worker
|
|
@@ -84,10 +90,10 @@ async function unregisterServiceWorker(page) {
|
|
|
84
90
|
// Disable service worker registration
|
|
85
91
|
// @ts-ignore
|
|
86
92
|
navigator.serviceWorker.register = new Promise(() => { });
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
93
|
+
// Assign once per document; re-running this on an interval only wakes the
|
|
94
|
+
// renderer every 500ms for no benefit
|
|
95
|
+
window.onerror = console.error;
|
|
96
|
+
window.onunhandledrejection = console.error;
|
|
91
97
|
});
|
|
92
98
|
}
|
|
93
99
|
/**
|
|
@@ -213,34 +219,140 @@ async function onLoadingScreen(page, onLoadingScreenCallBack) {
|
|
|
213
219
|
PROGRESS_MESSAGE_NEW_THEME: "//*[@id='app']/div/div/div[2]",
|
|
214
220
|
});
|
|
215
221
|
}
|
|
216
|
-
|
|
222
|
+
class InjectionTimeoutError extends Error {
|
|
223
|
+
timeout;
|
|
224
|
+
name = 'InjectionTimeoutError';
|
|
225
|
+
constructor(timeout, options) {
|
|
226
|
+
super(`WPP.isReady not reached after ${timeout}ms`, options);
|
|
227
|
+
this.timeout = timeout;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
exports.InjectionTimeoutError = InjectionTimeoutError;
|
|
231
|
+
const isTimeoutError = (error) => error instanceof Error && error.name === 'TimeoutError';
|
|
232
|
+
/**
|
|
233
|
+
* Waits for WAPI, Store and WPP.isReady on the current document
|
|
234
|
+
*/
|
|
235
|
+
async function waitForWppReady(page, options = {}) {
|
|
236
|
+
// Explicit timeout so puppeteer's 30s default never applies
|
|
237
|
+
const timeout = options.timeout ?? 0;
|
|
238
|
+
const startedAt = options.startedAt ?? Date.now();
|
|
239
|
+
const deadline = timeout > 0 ? startedAt + timeout : Infinity;
|
|
240
|
+
// puppeteer ignores a signal that is already aborted
|
|
241
|
+
options.signal?.throwIfAborted();
|
|
242
|
+
try {
|
|
243
|
+
await page.waitForFunction(() => {
|
|
244
|
+
return (typeof window.WAPI !== 'undefined' &&
|
|
245
|
+
typeof window.Store !== 'undefined' &&
|
|
246
|
+
!!window.WPP?.isReady);
|
|
247
|
+
}, {
|
|
248
|
+
// 0 would mean no limit to puppeteer
|
|
249
|
+
timeout: deadline === Infinity ? 0 : Math.max(deadline - Date.now(), 1),
|
|
250
|
+
signal: options.signal,
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
catch (error) {
|
|
254
|
+
if (isTimeoutError(error)) {
|
|
255
|
+
throw new InjectionTimeoutError(timeout, { cause: error });
|
|
256
|
+
}
|
|
257
|
+
// puppeteer's own 30s wait for an execution context: still loading
|
|
258
|
+
if (isTimeoutError(error?.cause) && !page.isClosed()) {
|
|
259
|
+
return waitForWppReady(page, { ...options, startedAt });
|
|
260
|
+
}
|
|
261
|
+
throw error;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
async function injectApi(page, onLoadingScreenCallBack, options = {}) {
|
|
265
|
+
const timeout = options.timeout ?? 0;
|
|
266
|
+
const startedAt = options.startedAt ?? Date.now();
|
|
267
|
+
// Stops the remaining steps once superseded or out of time
|
|
268
|
+
const controller = new AbortController();
|
|
269
|
+
const abort = () => controller.abort();
|
|
270
|
+
if (options.signal?.aborted)
|
|
271
|
+
abort();
|
|
272
|
+
options.signal?.addEventListener('abort', abort);
|
|
273
|
+
let timer;
|
|
274
|
+
const expired = new Promise((_, reject) => {
|
|
275
|
+
if (timeout > 0) {
|
|
276
|
+
timer = setTimeout(() => {
|
|
277
|
+
reject(new InjectionTimeoutError(timeout));
|
|
278
|
+
abort();
|
|
279
|
+
}, startedAt + timeout - Date.now());
|
|
280
|
+
}
|
|
281
|
+
});
|
|
282
|
+
try {
|
|
283
|
+
// A step stuck in a starved renderer must not stretch the deadline
|
|
284
|
+
await Promise.race([
|
|
285
|
+
runInjection(page, onLoadingScreenCallBack, {
|
|
286
|
+
...options,
|
|
287
|
+
startedAt,
|
|
288
|
+
signal: controller.signal,
|
|
289
|
+
}),
|
|
290
|
+
expired,
|
|
291
|
+
]);
|
|
292
|
+
}
|
|
293
|
+
finally {
|
|
294
|
+
clearTimeout(timer);
|
|
295
|
+
options.signal?.removeEventListener('abort', abort);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
async function runInjection(page, onLoadingScreenCallBack, options) {
|
|
299
|
+
const { signal } = options;
|
|
300
|
+
if (options.config) {
|
|
301
|
+
await page.evaluate((config) => {
|
|
302
|
+
window.WPPConfig = config;
|
|
303
|
+
}, options.config);
|
|
304
|
+
}
|
|
217
305
|
const injected = await page
|
|
218
306
|
.evaluate(() => {
|
|
219
|
-
//
|
|
220
|
-
return (typeof window.
|
|
307
|
+
// wapi.js defines WAPI and Store even when wa-js is missing
|
|
308
|
+
return (typeof window.WPP !== 'undefined' &&
|
|
309
|
+
typeof window.WAPI !== 'undefined' &&
|
|
221
310
|
typeof window.Store !== 'undefined');
|
|
222
311
|
})
|
|
223
312
|
.catch(() => false);
|
|
224
|
-
|
|
225
|
-
|
|
313
|
+
// Stop between steps so a superseded injection does not keep writing
|
|
314
|
+
if (!injected) {
|
|
315
|
+
signal?.throwIfAborted();
|
|
316
|
+
await page.addScriptTag({
|
|
317
|
+
path: require.resolve('@wppconnect/wa-js'),
|
|
318
|
+
});
|
|
319
|
+
signal?.throwIfAborted();
|
|
320
|
+
await page.evaluate(() => {
|
|
321
|
+
WPP.chat.defaultSendMessageOptions.createChat = true;
|
|
322
|
+
WPP.conn.setKeepAlive(true);
|
|
323
|
+
});
|
|
324
|
+
signal?.throwIfAborted();
|
|
325
|
+
await page.addScriptTag({
|
|
326
|
+
path: require.resolve(path.join(__dirname, '../../dist/lib/wapi', 'wapi.js')),
|
|
327
|
+
});
|
|
328
|
+
signal?.throwIfAborted();
|
|
329
|
+
await onLoadingScreen(page, onLoadingScreenCallBack);
|
|
226
330
|
}
|
|
227
|
-
await page.addScriptTag({
|
|
228
|
-
path: require.resolve('@wppconnect/wa-js'),
|
|
229
|
-
});
|
|
230
|
-
await page.evaluate(() => {
|
|
231
|
-
WPP.chat.defaultSendMessageOptions.createChat = true;
|
|
232
|
-
WPP.conn.setKeepAlive(true);
|
|
233
|
-
});
|
|
234
|
-
await page.addScriptTag({
|
|
235
|
-
path: require.resolve(path.join(__dirname, '../../dist/lib/wapi', 'wapi.js')),
|
|
236
|
-
});
|
|
237
|
-
await onLoadingScreen(page, onLoadingScreenCallBack);
|
|
238
331
|
// Make sure WAPI is initialized
|
|
239
|
-
await page
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
332
|
+
await waitForWppReady(page, options);
|
|
333
|
+
}
|
|
334
|
+
/**
|
|
335
|
+
* Resolves the Chromium launch arguments.
|
|
336
|
+
*
|
|
337
|
+
* When the caller passes no arguments (or an empty list) the default
|
|
338
|
+
* `puppeteerConfig.chromiumArgs` are used. A non-empty list replaces the
|
|
339
|
+
* defaults, matching the existing `browserArgs` contract. The default list only
|
|
340
|
+
* contains launch and performance flags; the flags that disable browser
|
|
341
|
+
* protections live in `puppeteerConfig.protectionDisablingChromiumArgs` and are
|
|
342
|
+
* only merged in when `useInsecureChromiumArgs` is explicitly enabled.
|
|
343
|
+
*/
|
|
344
|
+
function resolveBrowserArgs(requested, useInsecure = false) {
|
|
345
|
+
const args = [
|
|
346
|
+
...(requested?.length ? requested : puppeteer_config_1.puppeteerConfig.chromiumArgs),
|
|
347
|
+
];
|
|
348
|
+
if (useInsecure) {
|
|
349
|
+
for (const arg of puppeteer_config_1.puppeteerConfig.protectionDisablingChromiumArgs) {
|
|
350
|
+
if (!args.includes(arg)) {
|
|
351
|
+
args.push(arg);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
return args;
|
|
244
356
|
}
|
|
245
357
|
/**
|
|
246
358
|
* Initializes browser, will try to use chrome as default
|
|
@@ -277,9 +389,7 @@ async function initBrowser(session, options, logger) {
|
|
|
277
389
|
* If proxy settings are provided, they are applied to the browser launch arguments.
|
|
278
390
|
* This allows the browser to use the specified proxy server for all network requests.
|
|
279
391
|
*/
|
|
280
|
-
const args = options.browserArgs
|
|
281
|
-
? options.browserArgs
|
|
282
|
-
: [...puppeteer_config_1.puppeteerConfig.chromiumArgs];
|
|
392
|
+
const args = resolveBrowserArgs(options.browserArgs, options.useInsecureChromiumArgs);
|
|
283
393
|
if (options.proxy && options.proxy.url) {
|
|
284
394
|
args.push(`--proxy-server=${options.proxy.url}`);
|
|
285
395
|
}
|
|
@@ -312,6 +422,45 @@ async function initBrowser(session, options, logger) {
|
|
|
312
422
|
}
|
|
313
423
|
return browser;
|
|
314
424
|
}
|
|
425
|
+
/**
|
|
426
|
+
* Closes a browser and, when it was launched by this process, guarantees its
|
|
427
|
+
* OS process tree is terminated even if the graceful close fails or hangs.
|
|
428
|
+
* Remote browsers (`browserWS`) expose no process handle and are only
|
|
429
|
+
* disconnected. Safe to call when the page/browser was already closed.
|
|
430
|
+
*/
|
|
431
|
+
async function closeBrowser(browser) {
|
|
432
|
+
// Only browsers launched by this process expose a process handle
|
|
433
|
+
const pid = browser.process?.()?.pid;
|
|
434
|
+
if (!pid) {
|
|
435
|
+
// Caller-supplied remote connection: detach this client only. Closing it
|
|
436
|
+
// would terminate the browser shared with every other connected client.
|
|
437
|
+
// Connections that expose neither a process handle nor a disconnect method
|
|
438
|
+
// (e.g. test doubles) fall back to close().
|
|
439
|
+
if (typeof browser.disconnect === 'function') {
|
|
440
|
+
await browser.disconnect().catch(() => null);
|
|
441
|
+
}
|
|
442
|
+
else {
|
|
443
|
+
await browser.close().catch(() => null);
|
|
444
|
+
}
|
|
445
|
+
return;
|
|
446
|
+
}
|
|
447
|
+
const gracefulClose = browser.close().catch(() => null);
|
|
448
|
+
// Bound the graceful close so an unresponsive browser cannot hang teardown
|
|
449
|
+
let timer;
|
|
450
|
+
const timedOut = new Promise((resolve) => {
|
|
451
|
+
timer = setTimeout(resolve, 5000);
|
|
452
|
+
});
|
|
453
|
+
try {
|
|
454
|
+
await Promise.race([gracefulClose, timedOut]);
|
|
455
|
+
}
|
|
456
|
+
finally {
|
|
457
|
+
clearTimeout(timer);
|
|
458
|
+
}
|
|
459
|
+
// Force kill the process tree if the graceful close did not take it down
|
|
460
|
+
await new Promise((resolve) => {
|
|
461
|
+
treeKill(pid, 'SIGKILL', () => resolve());
|
|
462
|
+
});
|
|
463
|
+
}
|
|
315
464
|
async function getOrCreatePage(browser) {
|
|
316
465
|
const pages = await browser.pages();
|
|
317
466
|
if (pages.length) {
|
|
@@ -319,6 +468,16 @@ async function getOrCreatePage(browser) {
|
|
|
319
468
|
}
|
|
320
469
|
return await browser.newPage();
|
|
321
470
|
}
|
|
471
|
+
/**
|
|
472
|
+
* Returns whether at least one open, non-blank page remains.
|
|
473
|
+
*
|
|
474
|
+
* Puppeteer commonly leaves an `about:blank` tab behind after the session page
|
|
475
|
+
* is closed, so a non-empty `browser.pages()` does not prove a real page is
|
|
476
|
+
* still alive. This drives the auto-close guard in `create()`.
|
|
477
|
+
*/
|
|
478
|
+
function hasAlivePage(pages) {
|
|
479
|
+
return pages.some((page) => !page.isClosed() && page.url() !== 'about:blank');
|
|
480
|
+
}
|
|
322
481
|
/**
|
|
323
482
|
* Retrieves chrome instance path
|
|
324
483
|
*/
|