@wppconnect-team/wppconnect 2.3.5 → 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 +34 -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 +8 -2
- package/dist/api/layers/host.layer.js +39 -20
- package/dist/api/whatsapp.d.ts +24 -0
- package/dist/api/whatsapp.js +101 -52
- package/dist/config/create-config.d.ts +11 -1
- package/dist/config/create-config.js +2 -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 +26 -0
- package/dist/controllers/browser.js +81 -7
- package/dist/controllers/initializer.js +62 -40
- package/package.json +8 -8
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,37 @@
|
|
|
1
|
+
## <small>2.3.6 (2026-10-23)</small>
|
|
2
|
+
|
|
3
|
+
### Bug Fixes
|
|
4
|
+
|
|
5
|
+
- **auth:** keep unpaired QR sessions out of chat readiness ([8f46042](https://github.com/wppconnect-team/wppconnect/commit/8f46042))
|
|
6
|
+
- **auth:** mark restored sessions as logged before waiting for chat ([366e3c0](https://github.com/wppconnect-team/wppconnect/commit/366e3c0))
|
|
7
|
+
- **auth:** only report disconnectedMobile after a real unpair ([111633b](https://github.com/wppconnect-team/wppconnect/commit/111633b))
|
|
8
|
+
- **browser:** apply default launch args and opt-in protection bypasses ([c2e0c06](https://github.com/wppconnect-team/wppconnect/commit/c2e0c06))
|
|
9
|
+
- **browser:** auto-close when only blank or closed tabs remain ([c165218](https://github.com/wppconnect-team/wppconnect/commit/c165218))
|
|
10
|
+
- **browser:** release the browser process tree on close and failed create ([b1407bf](https://github.com/wppconnect-team/wppconnect/commit/b1407bf))
|
|
11
|
+
- **deps:** require wa-js 4.7.2 for unread actions ([6b2a41b](https://github.com/wppconnect-team/wppconnect/commit/6b2a41b))
|
|
12
|
+
- **host:** guard exposeFunction against reused pages ([a778f5a](https://github.com/wppconnect-team/wppconnect/commit/a778f5a))
|
|
13
|
+
- **media:** bound resource use in file and download helpers ([5f5d9de](https://github.com/wppconnect-team/wppconnect/commit/5f5d9de))
|
|
14
|
+
|
|
15
|
+
### Performance Improvements
|
|
16
|
+
|
|
17
|
+
- **decrypt:** decode media buffers directly instead of per-byte loops ([b03a29d](https://github.com/wppconnect-team/wppconnect/commit/b03a29d))
|
|
18
|
+
- **group:** fetch group member contacts in a single page call ([a41709e](https://github.com/wppconnect-team/wppconnect/commit/a41709e))
|
|
19
|
+
- **polling:** remove idle polling from live sessions ([de07dab](https://github.com/wppconnect-team/wppconnect/commit/de07dab))
|
|
20
|
+
|
|
21
|
+
### Build System
|
|
22
|
+
|
|
23
|
+
- **deps-dev:** bump markdown-it from 14.3.2 to 14.3.3 ([7698abf](https://github.com/wppconnect-team/wppconnect/commit/7698abf))
|
|
24
|
+
- **deps-dev:** update commitlint monorepo to ^21.2.4 (#2932) ([b03defc](https://github.com/wppconnect-team/wppconnect/commit/b03defc)), closes [#2932](https://github.com/wppconnect-team/wppconnect/issues/2932)
|
|
25
|
+
- **deps-dev:** update dependency eslint to v10.13.0 (#2928) ([fd42ca9](https://github.com/wppconnect-team/wppconnect/commit/fd42ca9)), closes [#2928](https://github.com/wppconnect-team/wppconnect/issues/2928)
|
|
26
|
+
- **deps-dev:** update dependency eslint-plugin-prettier to ^5.5.7 (#2927) ([cdb3572](https://github.com/wppconnect-team/wppconnect/commit/cdb3572)), closes [#2927](https://github.com/wppconnect-team/wppconnect/issues/2927)
|
|
27
|
+
- **deps-dev:** update dependency typescript-eslint to ^8.72.0 (#2935) ([bb16ae6](https://github.com/wppconnect-team/wppconnect/commit/bb16ae6)), closes [#2935](https://github.com/wppconnect-team/wppconnect/issues/2935)
|
|
28
|
+
- **deps:** bump follow-redirects from 1.16.0 to 1.16.1 ([385ed97](https://github.com/wppconnect-team/wppconnect/commit/385ed97))
|
|
29
|
+
- **deps:** bump ip-address from 10.7.2 to 10.7.4 ([8a54f25](https://github.com/wppconnect-team/wppconnect/commit/8a54f25))
|
|
30
|
+
|
|
31
|
+
### Chores
|
|
32
|
+
|
|
33
|
+
- **ci:** associate schedule with joaosouz4dev ([488d952](https://github.com/wppconnect-team/wppconnect/commit/488d952))
|
|
34
|
+
|
|
1
35
|
## <small>2.3.5 (2026-10-15)</small>
|
|
2
36
|
|
|
3
37
|
### Bug Fixes
|
|
@@ -55,7 +55,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
55
55
|
exports.newMagix = exports.magix = exports.mediaTypes = exports.timeout = exports.makeOptions = void 0;
|
|
56
56
|
const crypto = __importStar(require("crypto"));
|
|
57
57
|
const futoin_hkdf_1 = __importDefault(require("futoin-hkdf"));
|
|
58
|
-
const atob_1 = __importDefault(require("atob"));
|
|
59
58
|
const stream_1 = require("stream");
|
|
60
59
|
const makeOptions = (useragentOverride, responseType = 'arraybuffer') => ({
|
|
61
60
|
responseType: responseType,
|
|
@@ -86,9 +85,14 @@ const processUA = (userAgent) => {
|
|
|
86
85
|
return ua;
|
|
87
86
|
};
|
|
88
87
|
const magix = (fileData, mediaKeyBase64, mediaType, expectedSize) => {
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
88
|
+
// fileData is already raw bytes. Converting it to hex and back per byte
|
|
89
|
+
// (substr + parseInt per byte, multi-MB intermediate strings) is pure
|
|
90
|
+
// overhead on every decrypt.
|
|
91
|
+
const encodedBytes = Buffer.isBuffer(fileData)
|
|
92
|
+
? fileData
|
|
93
|
+
: Buffer.from(fileData);
|
|
94
|
+
// atob + charCodeAt per byte === base64 decode
|
|
95
|
+
const mediaKeyBytes = Buffer.from(mediaKeyBase64, 'base64');
|
|
92
96
|
const info = `WhatsApp ${exports.mediaTypes[mediaType.toUpperCase()]} Keys`;
|
|
93
97
|
const hash = 'sha256';
|
|
94
98
|
const salt = new Uint8Array(32);
|
|
@@ -124,21 +128,6 @@ const fixPadding = (data, expectedSize) => {
|
|
|
124
128
|
//@ts-ignore
|
|
125
129
|
return Buffer.from(data, 'utf-8');
|
|
126
130
|
};
|
|
127
|
-
const hexToBytes = (hexStr) => {
|
|
128
|
-
const intArray = [];
|
|
129
|
-
for (let i = 0; i < hexStr.length; i += 2) {
|
|
130
|
-
intArray.push(parseInt(hexStr.substr(i, 2), 16));
|
|
131
|
-
}
|
|
132
|
-
return new Uint8Array(intArray);
|
|
133
|
-
};
|
|
134
|
-
const base64ToBytes = (base64Str) => {
|
|
135
|
-
const binaryStr = (0, atob_1.default)(base64Str);
|
|
136
|
-
const byteArray = new Uint8Array(binaryStr.length);
|
|
137
|
-
for (let i = 0; i < binaryStr.length; i++) {
|
|
138
|
-
byteArray[i] = binaryStr.charCodeAt(i);
|
|
139
|
-
}
|
|
140
|
-
return byteArray;
|
|
141
|
-
};
|
|
142
131
|
const newMagix = (mediaKeyBase64, mediaType, expectedSize) => {
|
|
143
132
|
const mediaKeyBytes = newBase64ToBytes(mediaKeyBase64);
|
|
144
133
|
const info = `WhatsApp ${exports.mediaTypes[mediaType.toUpperCase()]} Keys`;
|
|
@@ -1 +1,5 @@
|
|
|
1
|
+
/** Upper bound so one remote file cannot exhaust a small host (100 MB). */
|
|
2
|
+
export declare const MAX_DOWNLOAD_BYTES: number;
|
|
3
|
+
/** Remote fetches must not wedge a send forever. */
|
|
4
|
+
export declare const DOWNLOAD_TIMEOUT_MS = 30000;
|
|
1
5
|
export declare function downloadFileToBase64(_path: string, _mines?: (string | RegExp)[]): Promise<string | false>;
|
|
@@ -19,8 +19,13 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
19
19
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
20
20
|
};
|
|
21
21
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
22
|
+
exports.DOWNLOAD_TIMEOUT_MS = exports.MAX_DOWNLOAD_BYTES = void 0;
|
|
22
23
|
exports.downloadFileToBase64 = downloadFileToBase64;
|
|
23
24
|
const axios_1 = __importDefault(require("axios"));
|
|
25
|
+
/** Upper bound so one remote file cannot exhaust a small host (100 MB). */
|
|
26
|
+
exports.MAX_DOWNLOAD_BYTES = 100 * 1024 * 1024;
|
|
27
|
+
/** Remote fetches must not wedge a send forever. */
|
|
28
|
+
exports.DOWNLOAD_TIMEOUT_MS = 30000;
|
|
24
29
|
async function downloadFileToBase64(_path, _mines = []) {
|
|
25
30
|
if (!Array.isArray(_mines)) {
|
|
26
31
|
console.error(`set mines string array, not "${typeof _mines}" `);
|
|
@@ -33,7 +38,14 @@ async function downloadFileToBase64(_path, _mines = []) {
|
|
|
33
38
|
try {
|
|
34
39
|
const response = await axios_1.default.get(_path, {
|
|
35
40
|
responseType: 'arraybuffer',
|
|
41
|
+
timeout: exports.DOWNLOAD_TIMEOUT_MS,
|
|
42
|
+
maxContentLength: exports.MAX_DOWNLOAD_BYTES,
|
|
36
43
|
});
|
|
44
|
+
// Refuse to materialize a huge body (headers arrive before the bytes)
|
|
45
|
+
const contentLength = Number(response.headers['content-length']);
|
|
46
|
+
if (Number.isFinite(contentLength) && contentLength > exports.MAX_DOWNLOAD_BYTES) {
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
37
49
|
const mimeType = String(response.headers['content-type'] ?? '');
|
|
38
50
|
if (_mines.length) {
|
|
39
51
|
const isValidMime = _mines.some((m) => {
|
|
@@ -1,3 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Upper bound for a single file read. A base64 data URI is ~1.37x the file
|
|
3
|
+
* size in one contiguous string, so an unbounded read can exhaust a small
|
|
4
|
+
* host on a single send.
|
|
5
|
+
*/
|
|
6
|
+
export declare const MAX_FILE_BYTES: number;
|
|
1
7
|
/**
|
|
2
8
|
* Converts given file into base64 string
|
|
3
9
|
* @param path file path
|
|
@@ -49,30 +49,47 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
49
49
|
};
|
|
50
50
|
})();
|
|
51
51
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
52
|
+
exports.MAX_FILE_BYTES = void 0;
|
|
52
53
|
exports.fileToBase64 = fileToBase64;
|
|
53
54
|
exports.Mine = Mine;
|
|
54
55
|
const mimeTypes = __importStar(require("mime-types"));
|
|
55
56
|
const fs = __importStar(require("fs"));
|
|
57
|
+
/**
|
|
58
|
+
* Upper bound for a single file read. A base64 data URI is ~1.37x the file
|
|
59
|
+
* size in one contiguous string, so an unbounded read can exhaust a small
|
|
60
|
+
* host on a single send.
|
|
61
|
+
*/
|
|
62
|
+
exports.MAX_FILE_BYTES = 100 * 1024 * 1024;
|
|
56
63
|
/**
|
|
57
64
|
* Converts given file into base64 string
|
|
58
65
|
* @param path file path
|
|
59
66
|
* @param mime Optional, will retrieve file mime automatically if not defined (Example: 'image/png')
|
|
60
67
|
*/
|
|
61
68
|
async function fileToBase64(path, mime) {
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
69
|
+
let size;
|
|
70
|
+
try {
|
|
71
|
+
const stat = await fs.promises.stat(path);
|
|
72
|
+
if (!stat.isFile()) {
|
|
73
|
+
return false;
|
|
66
74
|
}
|
|
67
|
-
|
|
68
|
-
mime = 'application/octet-stream';
|
|
69
|
-
}
|
|
70
|
-
const data = `data:${mime};base64,${base64}`;
|
|
71
|
-
return data;
|
|
75
|
+
size = stat.size;
|
|
72
76
|
}
|
|
73
|
-
|
|
77
|
+
catch {
|
|
74
78
|
return false;
|
|
75
79
|
}
|
|
80
|
+
if (size > exports.MAX_FILE_BYTES) {
|
|
81
|
+
console.error(`fileToBase64: "${path}" is ${size} bytes, exceeding the ${exports.MAX_FILE_BYTES} byte limit.`);
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
const base64 = (await fs.promises.readFile(path)).toString('base64');
|
|
85
|
+
if (mime === undefined) {
|
|
86
|
+
mime = mimeTypes.lookup(path);
|
|
87
|
+
}
|
|
88
|
+
if (!mime) {
|
|
89
|
+
mime = 'application/octet-stream';
|
|
90
|
+
}
|
|
91
|
+
const data = `data:${mime};base64,${base64}`;
|
|
92
|
+
return data;
|
|
76
93
|
}
|
|
77
94
|
async function Mine(path) {
|
|
78
95
|
if (fs.existsSync(path)) {
|
|
@@ -49,10 +49,8 @@ class GroupLayer extends retriever_layer_1.RetrieverLayer {
|
|
|
49
49
|
*/
|
|
50
50
|
async getGroupMembers(groupId) {
|
|
51
51
|
const membersIds = await this.getGroupMembersIds(groupId);
|
|
52
|
-
const
|
|
53
|
-
|
|
54
|
-
});
|
|
55
|
-
return Promise.all(actions);
|
|
52
|
+
const membersIdValues = membersIds.map((memberId) => memberId._serialized);
|
|
53
|
+
return (0, helpers_1.evaluateAndReturn)(this.page, (membersIdValues) => membersIdValues.map((memberId) => WAPI.getContact(memberId)), membersIdValues);
|
|
56
54
|
}
|
|
57
55
|
/**
|
|
58
56
|
* Generates group-invite link
|
|
@@ -23,7 +23,6 @@ export declare class HostLayer {
|
|
|
23
23
|
protected qrLoopCancelled: boolean;
|
|
24
24
|
protected isLogged: boolean;
|
|
25
25
|
protected isInChat: boolean;
|
|
26
|
-
protected checkStartInterval?: NodeJS.Timer;
|
|
27
26
|
protected urlCode: string;
|
|
28
27
|
protected attempt: number;
|
|
29
28
|
catchQR?: CatchQRCallback;
|
|
@@ -34,12 +33,19 @@ export declare class HostLayer {
|
|
|
34
33
|
protected log(level: LogLevel, message: string, meta?: object): void;
|
|
35
34
|
protected initialize(): Promise<void>;
|
|
36
35
|
protected watchDocumentChanges(): Promise<void>;
|
|
36
|
+
/**
|
|
37
|
+
* Exposes a Node callback on the page. A page reused across clients
|
|
38
|
+
* (`browserWS` or an injected `page`) still carries the binding from the
|
|
39
|
+
* previous client, and puppeteer refuses to overwrite it (`... already
|
|
40
|
+
* exists!`). Drop the stale binding first so the newest client's callback
|
|
41
|
+
* wins; any other error propagates unchanged.
|
|
42
|
+
*/
|
|
43
|
+
protected exposePageFunction(name: string, fn: (...args: any[]) => any): Promise<void>;
|
|
37
44
|
protected afterPageLoad(signal?: AbortSignal): Promise<void>;
|
|
38
45
|
protected waitForNavigationCommit(signal?: AbortSignal): Promise<void>;
|
|
39
46
|
protected isInjectionExpired(): boolean;
|
|
40
47
|
protected afterPageScriptInjected(): Promise<void>;
|
|
41
48
|
start(): Promise<void>;
|
|
42
|
-
protected checkStart(): Promise<void>;
|
|
43
49
|
protected checkQrCode(): Promise<void>;
|
|
44
50
|
/**
|
|
45
51
|
* Stop QR attempts and suppress pending QR callbacks for this client.
|
|
@@ -41,7 +41,6 @@ class HostLayer {
|
|
|
41
41
|
qrLoopCancelled = false;
|
|
42
42
|
isLogged = false;
|
|
43
43
|
isInChat = false;
|
|
44
|
-
checkStartInterval = null;
|
|
45
44
|
urlCode = '';
|
|
46
45
|
attempt = 0;
|
|
47
46
|
catchQR = null;
|
|
@@ -114,6 +113,25 @@ class HostLayer {
|
|
|
114
113
|
this.log('warn', 'Could not watch document changes', { error });
|
|
115
114
|
}
|
|
116
115
|
}
|
|
116
|
+
/**
|
|
117
|
+
* Exposes a Node callback on the page. A page reused across clients
|
|
118
|
+
* (`browserWS` or an injected `page`) still carries the binding from the
|
|
119
|
+
* previous client, and puppeteer refuses to overwrite it (`... already
|
|
120
|
+
* exists!`). Drop the stale binding first so the newest client's callback
|
|
121
|
+
* wins; any other error propagates unchanged.
|
|
122
|
+
*/
|
|
123
|
+
async exposePageFunction(name, fn) {
|
|
124
|
+
try {
|
|
125
|
+
await this.page.exposeFunction(name, fn);
|
|
126
|
+
}
|
|
127
|
+
catch (error) {
|
|
128
|
+
if (!/already exists/i.test(error?.message ?? '')) {
|
|
129
|
+
throw error;
|
|
130
|
+
}
|
|
131
|
+
await this.page.removeExposedFunction(name).catch(() => null);
|
|
132
|
+
await this.page.exposeFunction(name, fn);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
117
135
|
async afterPageLoad(signal) {
|
|
118
136
|
if (signal?.aborted) {
|
|
119
137
|
return;
|
|
@@ -211,24 +229,15 @@ class HostLayer {
|
|
|
211
229
|
this.isStarted = true;
|
|
212
230
|
await this.documentWatch;
|
|
213
231
|
await (0, browser_1.initWhatsapp)(this.page, null, false, this.options.whatsappVersion, this.options.proxy, this.log.bind(this));
|
|
214
|
-
await this.
|
|
215
|
-
await this.
|
|
216
|
-
await this.
|
|
217
|
-
await this.
|
|
218
|
-
await this.
|
|
219
|
-
if (!this.qrLoopCancelled) {
|
|
220
|
-
this.checkStartInterval = setInterval(() => this.checkStart(), 5000);
|
|
221
|
-
}
|
|
232
|
+
await this.exposePageFunction('checkQrCode', () => this.checkQrCode());
|
|
233
|
+
await this.exposePageFunction('onLinkCode', (code) => this.onLinkCode(code));
|
|
234
|
+
await this.exposePageFunction('onLinkCodeExpired', () => this.log('warn', 'Login by code expired; call refreshLinkCode() to retry'));
|
|
235
|
+
await this.exposePageFunction('onLinkCodeError', (message) => this.log('error', `Login by code failed: ${message}`));
|
|
236
|
+
await this.exposePageFunction('checkInChat', () => this.checkInChat());
|
|
222
237
|
this.page.on('close', () => {
|
|
223
238
|
this.cancelQrLoop();
|
|
224
|
-
clearInterval(this.checkStartInterval);
|
|
225
239
|
});
|
|
226
240
|
}
|
|
227
|
-
async checkStart() {
|
|
228
|
-
(0, auth_1.needsToScan)(this.page)
|
|
229
|
-
.then((need) => { })
|
|
230
|
-
.catch(() => null);
|
|
231
|
-
}
|
|
232
241
|
async checkQrCode() {
|
|
233
242
|
if (this.qrLoopCancelled || this.page.isClosed())
|
|
234
243
|
return;
|
|
@@ -273,7 +282,6 @@ class HostLayer {
|
|
|
273
282
|
*/
|
|
274
283
|
cancelQrLoop() {
|
|
275
284
|
this.qrLoopCancelled = true;
|
|
276
|
-
clearInterval(this.checkStartInterval);
|
|
277
285
|
}
|
|
278
286
|
async loginByCode(phone) {
|
|
279
287
|
await (0, helpers_1.evaluateAndReturn)(this.page, async ({ phone }) => {
|
|
@@ -298,12 +306,18 @@ class HostLayer {
|
|
|
298
306
|
}
|
|
299
307
|
async checkInChat() {
|
|
300
308
|
const inChat = await (0, auth_1.isInsideChat)(this.page).catch(() => null);
|
|
309
|
+
const wasInChat = this.isInChat;
|
|
301
310
|
this.isInChat = !!inChat;
|
|
302
|
-
if (!inChat) {
|
|
311
|
+
if (!inChat || wasInChat) {
|
|
303
312
|
return;
|
|
304
313
|
}
|
|
305
314
|
this.log('http', 'Connected');
|
|
306
|
-
|
|
315
|
+
try {
|
|
316
|
+
this.statusFind?.('inChat', this.session);
|
|
317
|
+
}
|
|
318
|
+
catch (error) {
|
|
319
|
+
this.log('error', error);
|
|
320
|
+
}
|
|
307
321
|
}
|
|
308
322
|
tryAutoClose() {
|
|
309
323
|
if (this.autoCloseInterval) {
|
|
@@ -379,8 +393,9 @@ class HostLayer {
|
|
|
379
393
|
return false;
|
|
380
394
|
}
|
|
381
395
|
await (0, sleep_1.sleep)(1000);
|
|
382
|
-
|
|
383
|
-
|
|
396
|
+
// main_ready may already have fired on the QR screen, so pairing can
|
|
397
|
+
// finish without another event. Publish only the verified transition.
|
|
398
|
+
await this.checkInChat();
|
|
384
399
|
}
|
|
385
400
|
return this.isInChat;
|
|
386
401
|
}
|
|
@@ -448,6 +463,10 @@ class HostLayer {
|
|
|
448
463
|
this.statusFind?.('isLogged', this.session);
|
|
449
464
|
}
|
|
450
465
|
if (authenticated === true) {
|
|
466
|
+
// A stored session takes the "Authenticated" branch above without going
|
|
467
|
+
// through waitForQrCodeScan(), so nothing else may have recorded the
|
|
468
|
+
// login yet. waitForInChat() bails out early when isLogged is false.
|
|
469
|
+
this.isLogged = true;
|
|
451
470
|
// Reinicia o contador do autoclose
|
|
452
471
|
this.cancelAutoClose();
|
|
453
472
|
// Wait for interface update
|
package/dist/api/whatsapp.d.ts
CHANGED
|
@@ -2,11 +2,35 @@ import { Page } from 'puppeteer';
|
|
|
2
2
|
import { CreateConfig } from '../config/create-config';
|
|
3
3
|
import { BusinessLayer } from './layers/business.layer';
|
|
4
4
|
import { GetMessagesParam, Message } from './model';
|
|
5
|
+
/** Per-request timeout so a single fetch cannot hang a send indefinitely. */
|
|
6
|
+
export declare const DECRYPT_TIMEOUT_MS = 30000;
|
|
7
|
+
/**
|
|
8
|
+
* GETs a URL until HTTP 200, retrying transient failures (including a rejected
|
|
9
|
+
* status) with linear backoff. Replaces an unbounded `while` loop that wedged
|
|
10
|
+
* `decryptFile` forever on a persistently failing download. Each attempt is
|
|
11
|
+
* bounded by `timeout` (defaults to {@link DECRYPT_TIMEOUT_MS}) so a stalled
|
|
12
|
+
* response cannot hang either.
|
|
13
|
+
*/
|
|
14
|
+
export declare function getUntilOk(url: string, options?: any, maxAttempts?: number): Promise<any>;
|
|
5
15
|
export declare class Whatsapp extends BusinessLayer {
|
|
6
16
|
page: Page;
|
|
17
|
+
/**
|
|
18
|
+
* The page binding exposed by `wireConnectionEvents` can only be registered
|
|
19
|
+
* once per page, but a page may be reused by a later client. This maps each
|
|
20
|
+
* page to the callback of the client that most recently wired it, so the
|
|
21
|
+
* existing binding can be redirected to the current client.
|
|
22
|
+
*/
|
|
23
|
+
private static readonly connectionDispatchers;
|
|
7
24
|
private connected;
|
|
8
25
|
constructor(page: Page, session?: string, options?: CreateConfig);
|
|
9
26
|
protected afterPageScriptInjected(): Promise<void>;
|
|
27
|
+
/**
|
|
28
|
+
* Forwards wa-js connection events to the Node side instead of polling
|
|
29
|
+
* `WPP.conn.isRegistered()` every second. Re-registered after every page
|
|
30
|
+
* load, since the in-page listeners do not survive navigation.
|
|
31
|
+
*/
|
|
32
|
+
protected wireConnectionEvents(): Promise<void>;
|
|
33
|
+
protected onConnectionChange(isRegistered: boolean): void;
|
|
10
34
|
/**
|
|
11
35
|
* Decrypts message file
|
|
12
36
|
* @param data Message object
|
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
|
|
@@ -170,20 +238,10 @@ class Whatsapp extends business_layer_1.BusinessLayer {
|
|
|
170
238
|
*/
|
|
171
239
|
async close() {
|
|
172
240
|
this.cancelQrLoop();
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
/*
|
|
178
|
-
Code was removed as it is not necessary.
|
|
179
|
-
try {
|
|
180
|
-
const process = browser.process();
|
|
181
|
-
if (process) {
|
|
182
|
-
treekill(process.pid, 'SIGKILL');
|
|
183
|
-
}
|
|
184
|
-
} catch (error) {}
|
|
185
|
-
*/
|
|
186
|
-
}
|
|
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());
|
|
187
245
|
return true;
|
|
188
246
|
}
|
|
189
247
|
/**
|
|
@@ -222,18 +280,9 @@ class Whatsapp extends business_layer_1.BusinessLayer {
|
|
|
222
280
|
const options = (0, decrypt_1.makeOptions)(WAuserAgente_1.useragentOverride);
|
|
223
281
|
if (!mediaUrl)
|
|
224
282
|
throw new Error('message is missing critical data (`mediaUrl`) needed to download the file.');
|
|
225
|
-
let haventGottenImageYet = true;
|
|
226
283
|
let res;
|
|
227
284
|
try {
|
|
228
|
-
|
|
229
|
-
res = await axios_1.default.get(mediaUrl.trim(), options);
|
|
230
|
-
if (res.status == 200) {
|
|
231
|
-
haventGottenImageYet = false;
|
|
232
|
-
}
|
|
233
|
-
else {
|
|
234
|
-
await (0, decrypt_1.timeout)(2000);
|
|
235
|
-
}
|
|
236
|
-
}
|
|
285
|
+
res = await getUntilOk(mediaUrl.trim(), options);
|
|
237
286
|
}
|
|
238
287
|
catch (error) {
|
|
239
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
|
*/
|
|
@@ -115,7 +125,7 @@ export interface CreateConfig {
|
|
|
115
125
|
* Normalmente, versões mais antigas continuam funcionando por mais um tempo,
|
|
116
126
|
* assim, com essa opção, é possível ter uma janela de tempo maior para se preparar para atualizações.
|
|
117
127
|
* Caso seja definido vazio ou null, será usado a versão atual, ou seja, sem forçar versão específica.
|
|
118
|
-
* @default
|
|
128
|
+
* @default ''
|
|
119
129
|
*/
|
|
120
130
|
whatsappVersion?: string;
|
|
121
131
|
/**
|
|
@@ -10,7 +10,7 @@ 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,
|
|
@@ -21,7 +21,7 @@ exports.defaultOptions = {
|
|
|
21
21
|
waitForLogin: true,
|
|
22
22
|
logger: logger_1.defaultLogger,
|
|
23
23
|
tokenStore: 'file',
|
|
24
|
-
whatsappVersion: '
|
|
24
|
+
whatsappVersion: '',
|
|
25
25
|
deviceName: false,
|
|
26
26
|
linkPreviewApiServers: null,
|
|
27
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) => {
|
|
@@ -38,9 +38,35 @@ export declare class InjectionTimeoutError extends Error {
|
|
|
38
38
|
*/
|
|
39
39
|
export declare function waitForWppReady(page: Page, options?: WaitForReadyOptions): Promise<void>;
|
|
40
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[];
|
|
41
52
|
/**
|
|
42
53
|
* Initializes browser, will try to use chrome as default
|
|
43
54
|
* @param session
|
|
44
55
|
*/
|
|
45
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>;
|
|
46
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;
|
|
@@ -59,8 +59,11 @@ exports.initWhatsapp = initWhatsapp;
|
|
|
59
59
|
exports.onLoadingScreen = onLoadingScreen;
|
|
60
60
|
exports.waitForWppReady = waitForWppReady;
|
|
61
61
|
exports.injectApi = injectApi;
|
|
62
|
+
exports.resolveBrowserArgs = resolveBrowserArgs;
|
|
62
63
|
exports.initBrowser = initBrowser;
|
|
64
|
+
exports.closeBrowser = closeBrowser;
|
|
63
65
|
exports.getOrCreatePage = getOrCreatePage;
|
|
66
|
+
exports.hasAlivePage = hasAlivePage;
|
|
64
67
|
const ChromeLauncher = __importStar(require("chrome-launcher"));
|
|
65
68
|
const os = __importStar(require("os"));
|
|
66
69
|
const path = __importStar(require("path"));
|
|
@@ -72,6 +75,7 @@ const puppeteer_config_1 = require("../config/puppeteer.config");
|
|
|
72
75
|
const puppeteer_extra_plugin_stealth_1 = __importDefault(require("puppeteer-extra-plugin-stealth"));
|
|
73
76
|
const WAuserAgente_1 = require("../config/WAuserAgente");
|
|
74
77
|
const websocket_1 = require("./websocket");
|
|
78
|
+
const treeKill = require('tree-kill');
|
|
75
79
|
async function unregisterServiceWorker(page) {
|
|
76
80
|
await page.evaluateOnNewDocument(() => {
|
|
77
81
|
// Remove existent service worker
|
|
@@ -86,10 +90,10 @@ async function unregisterServiceWorker(page) {
|
|
|
86
90
|
// Disable service worker registration
|
|
87
91
|
// @ts-ignore
|
|
88
92
|
navigator.serviceWorker.register = new Promise(() => { });
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
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;
|
|
93
97
|
});
|
|
94
98
|
}
|
|
95
99
|
/**
|
|
@@ -327,6 +331,29 @@ async function runInjection(page, onLoadingScreenCallBack, options) {
|
|
|
327
331
|
// Make sure WAPI is initialized
|
|
328
332
|
await waitForWppReady(page, options);
|
|
329
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;
|
|
356
|
+
}
|
|
330
357
|
/**
|
|
331
358
|
* Initializes browser, will try to use chrome as default
|
|
332
359
|
* @param session
|
|
@@ -362,9 +389,7 @@ async function initBrowser(session, options, logger) {
|
|
|
362
389
|
* If proxy settings are provided, they are applied to the browser launch arguments.
|
|
363
390
|
* This allows the browser to use the specified proxy server for all network requests.
|
|
364
391
|
*/
|
|
365
|
-
const args = options.browserArgs
|
|
366
|
-
? options.browserArgs
|
|
367
|
-
: [...puppeteer_config_1.puppeteerConfig.chromiumArgs];
|
|
392
|
+
const args = resolveBrowserArgs(options.browserArgs, options.useInsecureChromiumArgs);
|
|
368
393
|
if (options.proxy && options.proxy.url) {
|
|
369
394
|
args.push(`--proxy-server=${options.proxy.url}`);
|
|
370
395
|
}
|
|
@@ -397,6 +422,45 @@ async function initBrowser(session, options, logger) {
|
|
|
397
422
|
}
|
|
398
423
|
return browser;
|
|
399
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
|
+
}
|
|
400
464
|
async function getOrCreatePage(browser) {
|
|
401
465
|
const pages = await browser.pages();
|
|
402
466
|
if (pages.length) {
|
|
@@ -404,6 +468,16 @@ async function getOrCreatePage(browser) {
|
|
|
404
468
|
}
|
|
405
469
|
return await browser.newPage();
|
|
406
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
|
+
}
|
|
407
481
|
/**
|
|
408
482
|
* Retrieves chrome instance path
|
|
409
483
|
*/
|
|
@@ -60,8 +60,9 @@ const whatsapp_1 = require("../api/whatsapp");
|
|
|
60
60
|
const create_config_1 = require("../config/create-config");
|
|
61
61
|
const logger_1 = require("../utils/logger");
|
|
62
62
|
const sleep_1 = require("../utils/sleep");
|
|
63
|
-
const
|
|
63
|
+
const browserModule = __importStar(require("./browser"));
|
|
64
64
|
const welcome_1 = require("./welcome");
|
|
65
|
+
const browser_1 = require("./browser");
|
|
65
66
|
process.on('unhandledRejection', (reason, promise) => {
|
|
66
67
|
let message = 'Unhandled Rejection: ';
|
|
67
68
|
if (reason instanceof Error) {
|
|
@@ -117,6 +118,7 @@ async function create(sessionOrOption, catchQR, statusFind, onLoadingScreen, cat
|
|
|
117
118
|
}
|
|
118
119
|
let browser = mergedOptions.browser;
|
|
119
120
|
let page = mergedOptions.page;
|
|
121
|
+
let browserCreated = false;
|
|
120
122
|
if (!browser && page) {
|
|
121
123
|
// Get browser from page
|
|
122
124
|
browser = page.browser();
|
|
@@ -139,7 +141,9 @@ async function create(sessionOrOption, catchQR, statusFind, onLoadingScreen, cat
|
|
|
139
141
|
}
|
|
140
142
|
// Initialize new browser
|
|
141
143
|
logger.info('Initializing browser...', { session, type: 'browser' });
|
|
142
|
-
browser = await
|
|
144
|
+
browser = await browserModule
|
|
145
|
+
.initBrowser(session, mergedOptions, logger)
|
|
146
|
+
.catch((e) => {
|
|
143
147
|
if (mergedOptions.browserWS && mergedOptions.browserWS != '') {
|
|
144
148
|
logger.error(`Error when try to connect ${mergedOptions.browserWS}`, {
|
|
145
149
|
session,
|
|
@@ -174,6 +178,7 @@ async function create(sessionOrOption, catchQR, statusFind, onLoadingScreen, cat
|
|
|
174
178
|
type: 'browser',
|
|
175
179
|
});
|
|
176
180
|
}
|
|
181
|
+
browserCreated = !mergedOptions.browserWS;
|
|
177
182
|
}
|
|
178
183
|
if (!mergedOptions.browserWS && browser['_process']) {
|
|
179
184
|
browser['_process'].once('close', () => {
|
|
@@ -181,12 +186,20 @@ async function create(sessionOrOption, catchQR, statusFind, onLoadingScreen, cat
|
|
|
181
186
|
});
|
|
182
187
|
}
|
|
183
188
|
browser.on('targetdestroyed', async (target) => {
|
|
189
|
+
// The handler is registered before the session page is acquired, so ignore
|
|
190
|
+
// targets destroyed during startup: there is nothing to auto-close yet.
|
|
191
|
+
if (!page) {
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
184
194
|
if (typeof browser.isConnected === 'function' &&
|
|
185
195
|
!browser.isConnected()) {
|
|
186
196
|
return;
|
|
187
197
|
}
|
|
188
198
|
const pages = await browser.pages();
|
|
189
|
-
|
|
199
|
+
// An `about:blank` tab often remains after the session page is closed, so
|
|
200
|
+
// close only once the session page itself is gone and no real page is left
|
|
201
|
+
// (#2896). A temporarily blank session page must not be mistaken for it.
|
|
202
|
+
if (page.isClosed() && !(0, browser_1.hasAlivePage)(pages)) {
|
|
190
203
|
browser.close().catch(() => null);
|
|
191
204
|
}
|
|
192
205
|
});
|
|
@@ -198,46 +211,55 @@ async function create(sessionOrOption, catchQR, statusFind, onLoadingScreen, cat
|
|
|
198
211
|
statusFind && statusFind('browserClose', session);
|
|
199
212
|
}
|
|
200
213
|
});
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
if (page) {
|
|
206
|
-
await page.setBypassCSP(true);
|
|
207
|
-
const client = new whatsapp_1.Whatsapp(page, session, mergedOptions);
|
|
208
|
-
client.catchQR = catchQR;
|
|
209
|
-
client.statusFind = statusFind;
|
|
210
|
-
client.onLoadingScreen = onLoadingScreen;
|
|
211
|
-
client.catchLinkCode = catchLinkCode;
|
|
212
|
-
if (onStreamModeChanged) {
|
|
213
|
-
client.onStreamModeChanged(onStreamModeChanged);
|
|
214
|
-
}
|
|
215
|
-
if (onStreamInfoChanged) {
|
|
216
|
-
client.onStreamInfoChanged(onStreamInfoChanged);
|
|
214
|
+
try {
|
|
215
|
+
if (!page) {
|
|
216
|
+
// Initialize a page
|
|
217
|
+
page = await browserModule.getOrCreatePage(browser);
|
|
217
218
|
}
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
const
|
|
221
|
-
|
|
222
|
-
|
|
219
|
+
if (page) {
|
|
220
|
+
await page.setBypassCSP(true);
|
|
221
|
+
const client = new whatsapp_1.Whatsapp(page, session, mergedOptions);
|
|
222
|
+
client.catchQR = catchQR;
|
|
223
|
+
client.statusFind = statusFind;
|
|
224
|
+
client.onLoadingScreen = onLoadingScreen;
|
|
225
|
+
client.catchLinkCode = catchLinkCode;
|
|
226
|
+
if (onStreamModeChanged) {
|
|
227
|
+
client.onStreamModeChanged(onStreamModeChanged);
|
|
223
228
|
}
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
.catch(() => { })
|
|
233
|
-
.finally(() => {
|
|
234
|
-
waitLoginPromise = null;
|
|
235
|
-
});
|
|
236
|
-
}
|
|
237
|
-
await waitLoginPromise;
|
|
229
|
+
if (onStreamInfoChanged) {
|
|
230
|
+
client.onStreamInfoChanged(onStreamInfoChanged);
|
|
231
|
+
}
|
|
232
|
+
await client.start();
|
|
233
|
+
if (mergedOptions.waitForLogin) {
|
|
234
|
+
const isLogged = await client.waitForLogin();
|
|
235
|
+
if (!isLogged) {
|
|
236
|
+
throw new Error('Not Logged');
|
|
238
237
|
}
|
|
239
|
-
|
|
238
|
+
let waitLoginPromise = null;
|
|
239
|
+
client.onStateChange(async (state) => {
|
|
240
|
+
const connected = await page.evaluate(() => WPP.conn.isRegistered());
|
|
241
|
+
if (!connected) {
|
|
242
|
+
await (0, sleep_1.sleep)(2000);
|
|
243
|
+
if (!waitLoginPromise) {
|
|
244
|
+
waitLoginPromise = client
|
|
245
|
+
.waitForLogin()
|
|
246
|
+
.catch(() => { })
|
|
247
|
+
.finally(() => {
|
|
248
|
+
waitLoginPromise = null;
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
await waitLoginPromise;
|
|
252
|
+
}
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
return client;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
catch (error) {
|
|
259
|
+
// Release a browser launched here; the caller never got a reference
|
|
260
|
+
if (browserCreated) {
|
|
261
|
+
await browserModule.closeBrowser(browser);
|
|
240
262
|
}
|
|
241
|
-
|
|
263
|
+
throw error;
|
|
242
264
|
}
|
|
243
265
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wppconnect-team/wppconnect",
|
|
3
|
-
"version": "2.3.
|
|
3
|
+
"version": "2.3.6",
|
|
4
4
|
"description": "WPPConnect is an open source project developed by the JavaScript community with the aim of exporting functions from WhatsApp Web to the node, which can be used to support the creation of any interaction, such as customer service, media sending, intelligence recognition based on phrases artificial and many other things, use your imagination... 😀🤔💭",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -59,9 +59,9 @@
|
|
|
59
59
|
"@babel/eslint-parser": "^7.29.9",
|
|
60
60
|
"@babel/eslint-plugin": "^7.29.7",
|
|
61
61
|
"@babel/preset-env": "^7.29.7",
|
|
62
|
-
"@commitlint/cli": "^21.2.
|
|
63
|
-
"@commitlint/config-conventional": "^21.2.
|
|
64
|
-
"@commitlint/cz-commitlint": "^21.2.
|
|
62
|
+
"@commitlint/cli": "^21.2.4",
|
|
63
|
+
"@commitlint/config-conventional": "^21.2.4",
|
|
64
|
+
"@commitlint/cz-commitlint": "^21.2.4",
|
|
65
65
|
"@eslint/js": "^10.0.1",
|
|
66
66
|
"@tony.ganchev/eslint-plugin-header": "^3.4.4",
|
|
67
67
|
"@types/atob": "^2.1.4",
|
|
@@ -75,9 +75,9 @@
|
|
|
75
75
|
"commitizen": "^4.3.2",
|
|
76
76
|
"concurrently": "^10.0.6",
|
|
77
77
|
"conventional-changelog-cli": "^5.0.0",
|
|
78
|
-
"eslint": "10.
|
|
78
|
+
"eslint": "10.13.0",
|
|
79
79
|
"eslint-config-prettier": "^10.1.8",
|
|
80
|
-
"eslint-plugin-prettier": "^5.5.
|
|
80
|
+
"eslint-plugin-prettier": "^5.5.7",
|
|
81
81
|
"globals": "^17.13.0",
|
|
82
82
|
"husky": "^9.1.7",
|
|
83
83
|
"mocha": "^12.0.3",
|
|
@@ -89,12 +89,12 @@
|
|
|
89
89
|
"ts-node": "^10.9.2",
|
|
90
90
|
"typedoc": "^0.28.20",
|
|
91
91
|
"typescript": "^5.9.3",
|
|
92
|
-
"typescript-eslint": "^8.
|
|
92
|
+
"typescript-eslint": "^8.72.0",
|
|
93
93
|
"webpack": "^5.110.3",
|
|
94
94
|
"webpack-cli": "^6.0.1"
|
|
95
95
|
},
|
|
96
96
|
"dependencies": {
|
|
97
|
-
"@wppconnect/wa-js": "^4.7.
|
|
97
|
+
"@wppconnect/wa-js": "^4.7.2",
|
|
98
98
|
"@wppconnect/wa-version": "^1.5.4472",
|
|
99
99
|
"atob": "^2.1.2",
|
|
100
100
|
"axios": "^1.20.0",
|