@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/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,60 @@
|
|
|
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
|
+
|
|
35
|
+
## <small>2.3.5 (2026-10-15)</small>
|
|
36
|
+
|
|
37
|
+
### Bug Fixes
|
|
38
|
+
|
|
39
|
+
- **auth:** cancel pending QR attempts on close (#2915) ([1ada250](https://github.com/wppconnect-team/wppconnect/commit/1ada250)), closes [#2915](https://github.com/wppconnect-team/wppconnect/issues/2915)
|
|
40
|
+
- **browser:** tolerate slow WPP.isReady during injection (#2909) ([9ab531c](https://github.com/wppconnect-team/wppconnect/commit/9ab531c)), closes [#2909](https://github.com/wppconnect-team/wppconnect/issues/2909) [#2873](https://github.com/wppconnect-team/wppconnect/issues/2873)
|
|
41
|
+
- bump wa-js version to 4.7.1 (#2917) ([f988414](https://github.com/wppconnect-team/wppconnect/commit/f988414)), closes [#2917](https://github.com/wppconnect-team/wppconnect/issues/2917)
|
|
42
|
+
|
|
43
|
+
### Build System
|
|
44
|
+
|
|
45
|
+
- **deps-dev:** bump handlebars from 4.7.9 to 4.7.10 (#2911) ([22184d9](https://github.com/wppconnect-team/wppconnect/commit/22184d9)), closes [#2911](https://github.com/wppconnect-team/wppconnect/issues/2911)
|
|
46
|
+
- **deps-dev:** bump markdown-it from 14.3.0 to 14.3.2 (#2901) ([820ef4e](https://github.com/wppconnect-team/wppconnect/commit/820ef4e)), closes [#2901](https://github.com/wppconnect-team/wppconnect/issues/2901)
|
|
47
|
+
- **deps-dev:** update commitlint monorepo to ^21.2.3 (#2903) ([6ab0ccc](https://github.com/wppconnect-team/wppconnect/commit/6ab0ccc)), closes [#2903](https://github.com/wppconnect-team/wppconnect/issues/2903)
|
|
48
|
+
- **deps-dev:** update dependency @babel/eslint-parser to ^7.29.9 (#2904) ([a1c771b](https://github.com/wppconnect-team/wppconnect/commit/a1c771b)), closes [#2904](https://github.com/wppconnect-team/wppconnect/issues/2904)
|
|
49
|
+
- **deps-dev:** update dependency concurrently to ^10.0.6 (#2913) ([2c44b8e](https://github.com/wppconnect-team/wppconnect/commit/2c44b8e)), closes [#2913](https://github.com/wppconnect-team/wppconnect/issues/2913)
|
|
50
|
+
- **deps-dev:** update dependency eslint to v10.12.0 (#2908) ([f115c57](https://github.com/wppconnect-team/wppconnect/commit/f115c57)), closes [#2908](https://github.com/wppconnect-team/wppconnect/issues/2908)
|
|
51
|
+
- **deps-dev:** update dependency globals to ^17.13.0 (#2910) ([c2b3f7b](https://github.com/wppconnect-team/wppconnect/commit/c2b3f7b)), closes [#2910](https://github.com/wppconnect-team/wppconnect/issues/2910)
|
|
52
|
+
- **deps-dev:** update dependency mocha to v12 (#2889) ([0d922dd](https://github.com/wppconnect-team/wppconnect/commit/0d922dd)), closes [#2889](https://github.com/wppconnect-team/wppconnect/issues/2889)
|
|
53
|
+
- **deps-dev:** update dependency release-it to ^21.1.1 (#2914) ([05b2463](https://github.com/wppconnect-team/wppconnect/commit/05b2463)), closes [#2914](https://github.com/wppconnect-team/wppconnect/issues/2914)
|
|
54
|
+
- **deps-dev:** update dependency typescript-eslint to ^8.71.2 (#2916) ([e1a8767](https://github.com/wppconnect-team/wppconnect/commit/e1a8767)), closes [#2916](https://github.com/wppconnect-team/wppconnect/issues/2916)
|
|
55
|
+
- **deps:** update dependency @img/sharp-win32-x64 to ^0.35.5 (#2905) ([3a313d7](https://github.com/wppconnect-team/wppconnect/commit/3a313d7)), closes [#2905](https://github.com/wppconnect-team/wppconnect/issues/2905)
|
|
56
|
+
- **deps:** update dependency sharp to v0.35.5 [security] (#2907) ([79fa1aa](https://github.com/wppconnect-team/wppconnect/commit/79fa1aa)), closes [#2907](https://github.com/wppconnect-team/wppconnect/issues/2907)
|
|
57
|
+
|
|
1
58
|
## <small>2.3.4 (2026-10-02)</small>
|
|
2
59
|
|
|
3
60
|
### 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
|
|
@@ -15,10 +15,14 @@ export declare class HostLayer {
|
|
|
15
15
|
protected isInitialized: boolean;
|
|
16
16
|
protected isInjected: boolean;
|
|
17
17
|
protected pageLoadPromise?: Promise<void>;
|
|
18
|
+
protected pageLoadAbort?: AbortController;
|
|
19
|
+
protected injectionStartedAt?: number;
|
|
20
|
+
protected documentWatch?: Promise<void>;
|
|
21
|
+
protected isNavigating: boolean;
|
|
18
22
|
protected isStarted: boolean;
|
|
23
|
+
protected qrLoopCancelled: boolean;
|
|
19
24
|
protected isLogged: boolean;
|
|
20
25
|
protected isInChat: boolean;
|
|
21
|
-
protected checkStartInterval?: NodeJS.Timer;
|
|
22
26
|
protected urlCode: string;
|
|
23
27
|
protected attempt: number;
|
|
24
28
|
catchQR?: CatchQRCallback;
|
|
@@ -28,11 +32,27 @@ export declare class HostLayer {
|
|
|
28
32
|
constructor(page: Page, session?: string, options?: CreateConfig);
|
|
29
33
|
protected log(level: LogLevel, message: string, meta?: object): void;
|
|
30
34
|
protected initialize(): Promise<void>;
|
|
31
|
-
protected
|
|
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>;
|
|
44
|
+
protected afterPageLoad(signal?: AbortSignal): Promise<void>;
|
|
45
|
+
protected waitForNavigationCommit(signal?: AbortSignal): Promise<void>;
|
|
46
|
+
protected isInjectionExpired(): boolean;
|
|
32
47
|
protected afterPageScriptInjected(): Promise<void>;
|
|
33
48
|
start(): Promise<void>;
|
|
34
|
-
protected checkStart(): Promise<void>;
|
|
35
49
|
protected checkQrCode(): Promise<void>;
|
|
50
|
+
/**
|
|
51
|
+
* Stop QR attempts and suppress pending QR callbacks for this client.
|
|
52
|
+
* Create a new client to start pairing again.
|
|
53
|
+
* @category Host
|
|
54
|
+
*/
|
|
55
|
+
cancelQrLoop(): void;
|
|
36
56
|
protected loginByCode(phone: string): Promise<void>;
|
|
37
57
|
protected onLinkCode(code: string): void;
|
|
38
58
|
/**
|
|
@@ -33,10 +33,14 @@ class HostLayer {
|
|
|
33
33
|
isInitialized = false;
|
|
34
34
|
isInjected = false;
|
|
35
35
|
pageLoadPromise;
|
|
36
|
+
pageLoadAbort;
|
|
37
|
+
injectionStartedAt;
|
|
38
|
+
documentWatch;
|
|
39
|
+
isNavigating = false;
|
|
36
40
|
isStarted = false;
|
|
41
|
+
qrLoopCancelled = false;
|
|
37
42
|
isLogged = false;
|
|
38
43
|
isInChat = false;
|
|
39
|
-
checkStartInterval = null;
|
|
40
44
|
urlCode = '';
|
|
41
45
|
attempt = 0;
|
|
42
46
|
catchQR = null;
|
|
@@ -68,37 +72,126 @@ class HostLayer {
|
|
|
68
72
|
this.page.on('load', () => {
|
|
69
73
|
this.log('verbose', 'Page loaded', { type: 'page' });
|
|
70
74
|
this.isInjected = false;
|
|
75
|
+
// One budget per injection cycle, so a reload loop cannot extend it
|
|
76
|
+
this.injectionStartedAt ??= Date.now();
|
|
77
|
+
// Also aborted on document change; this covers pages without a CDP session
|
|
78
|
+
this.pageLoadAbort?.abort();
|
|
79
|
+
const abort = new AbortController();
|
|
80
|
+
this.pageLoadAbort = abort;
|
|
71
81
|
const previousPageLoad = this.pageLoadPromise?.catch(() => undefined);
|
|
72
|
-
const pageLoad = (previousPageLoad || Promise.resolve()).then(() => this.afterPageLoad());
|
|
82
|
+
const pageLoad = (previousPageLoad || Promise.resolve()).then(() => this.afterPageLoad(abort.signal));
|
|
73
83
|
this.pageLoadPromise = pageLoad;
|
|
74
84
|
void pageLoad.catch(() => undefined);
|
|
75
85
|
});
|
|
86
|
+
this.documentWatch = this.watchDocumentChanges();
|
|
76
87
|
this.isInitialized = true;
|
|
77
88
|
}
|
|
78
|
-
async
|
|
89
|
+
async watchDocumentChanges() {
|
|
90
|
+
try {
|
|
91
|
+
// Page 'framenavigated' also fires on pushState; these CDP events only for a new document
|
|
92
|
+
const session = await this.page.createCDPSession();
|
|
93
|
+
await session.send('Page.enable');
|
|
94
|
+
const { frameTree } = await session.send('Page.getFrameTree');
|
|
95
|
+
let mainFrameId = frameTree.frame.id;
|
|
96
|
+
// Steps in flight fail from here on, before the new document exists
|
|
97
|
+
session.on('Page.frameStartedNavigating', (event) => {
|
|
98
|
+
if (event.frameId === mainFrameId &&
|
|
99
|
+
!/samedocument/i.test(event.navigationType)) {
|
|
100
|
+
this.isNavigating = true;
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
session.on('Page.frameNavigated', ({ frame }) => {
|
|
104
|
+
if (frame.parentId)
|
|
105
|
+
return;
|
|
106
|
+
mainFrameId = frame.id;
|
|
107
|
+
this.isNavigating = false;
|
|
108
|
+
this.isInjected = false;
|
|
109
|
+
this.pageLoadAbort?.abort();
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
catch (error) {
|
|
113
|
+
this.log('warn', 'Could not watch document changes', { error });
|
|
114
|
+
}
|
|
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
|
+
}
|
|
135
|
+
async afterPageLoad(signal) {
|
|
136
|
+
if (signal?.aborted) {
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
79
139
|
this.log('verbose', 'Injecting wapi.js');
|
|
80
|
-
const options = {
|
|
81
|
-
deviceName: this.options.deviceName,
|
|
82
|
-
disableGoogleAnalytics: this.options.disableGoogleAnalytics,
|
|
83
|
-
googleAnalyticsId: this.options.googleAnalyticsId,
|
|
84
|
-
linkPreviewApiServers: this.options.linkPreviewApiServers,
|
|
85
|
-
poweredBy: this.options.poweredBy,
|
|
86
|
-
};
|
|
87
|
-
await (0, helpers_1.evaluateAndReturn)(this.page, (options) => {
|
|
88
|
-
window.WPPConfig = options;
|
|
89
|
-
}, options);
|
|
90
140
|
try {
|
|
91
|
-
await (0, browser_1.injectApi)(this.page, this.onLoadingScreen
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
141
|
+
await (0, browser_1.injectApi)(this.page, this.onLoadingScreen, {
|
|
142
|
+
timeout: this.options.injectionTimeout,
|
|
143
|
+
startedAt: this.injectionStartedAt,
|
|
144
|
+
signal,
|
|
145
|
+
config: {
|
|
146
|
+
deviceName: this.options.deviceName,
|
|
147
|
+
disableGoogleAnalytics: this.options.disableGoogleAnalytics,
|
|
148
|
+
googleAnalyticsId: this.options.googleAnalyticsId,
|
|
149
|
+
linkPreviewApiServers: this.options.linkPreviewApiServers,
|
|
150
|
+
poweredBy: this.options.poweredBy,
|
|
151
|
+
},
|
|
152
|
+
});
|
|
95
153
|
}
|
|
96
154
|
catch (error) {
|
|
155
|
+
if (this.isNavigating) {
|
|
156
|
+
await this.waitForNavigationCommit(signal);
|
|
157
|
+
}
|
|
158
|
+
// A newer document owns the page now; its injection decides the outcome
|
|
159
|
+
if (signal?.aborted) {
|
|
160
|
+
this.log('verbose', 'wapi.js injection superseded by page reload');
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
const failure = this.isInjectionExpired() && !(error instanceof browser_1.InjectionTimeoutError)
|
|
164
|
+
? new browser_1.InjectionTimeoutError(this.options.injectionTimeout, {
|
|
165
|
+
cause: error,
|
|
166
|
+
})
|
|
167
|
+
: error;
|
|
168
|
+
this.injectionStartedAt = undefined;
|
|
97
169
|
this.log('verbose', 'wapi.js failed');
|
|
98
|
-
this.log('error',
|
|
99
|
-
throw
|
|
170
|
+
this.log('error', failure);
|
|
171
|
+
throw failure;
|
|
172
|
+
}
|
|
173
|
+
if (signal?.aborted) {
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
this.injectionStartedAt = undefined;
|
|
177
|
+
this.isInjected = true;
|
|
178
|
+
this.log('verbose', 'wapi.js injected');
|
|
179
|
+
this.afterPageScriptInjected().catch((error) => this.log('error', error));
|
|
180
|
+
}
|
|
181
|
+
async waitForNavigationCommit(signal) {
|
|
182
|
+
while (this.isNavigating &&
|
|
183
|
+
!signal?.aborted &&
|
|
184
|
+
!this.page.isClosed() &&
|
|
185
|
+
!this.isInjectionExpired()) {
|
|
186
|
+
await (0, sleep_1.sleep)(50);
|
|
100
187
|
}
|
|
101
188
|
}
|
|
189
|
+
isInjectionExpired() {
|
|
190
|
+
const timeout = this.options.injectionTimeout;
|
|
191
|
+
return (timeout > 0 &&
|
|
192
|
+
this.injectionStartedAt !== undefined &&
|
|
193
|
+
Date.now() >= this.injectionStartedAt + timeout);
|
|
194
|
+
}
|
|
102
195
|
async afterPageScriptInjected() {
|
|
103
196
|
this.getWAVersion()
|
|
104
197
|
.then((version) => {
|
|
@@ -125,33 +218,32 @@ class HostLayer {
|
|
|
125
218
|
await (0, helpers_1.evaluateAndReturn)(this.page, () => {
|
|
126
219
|
WPP.on('conn.auth_code_change', window.checkQrCode);
|
|
127
220
|
}).catch(() => null);
|
|
128
|
-
this.checkQrCode();
|
|
221
|
+
this.checkQrCode().catch((error) => this.log('error', error));
|
|
129
222
|
}
|
|
130
|
-
this.checkInChat();
|
|
223
|
+
this.checkInChat().catch((error) => this.log('error', error));
|
|
131
224
|
}
|
|
132
225
|
async start() {
|
|
133
226
|
if (this.isStarted) {
|
|
134
227
|
return;
|
|
135
228
|
}
|
|
136
229
|
this.isStarted = true;
|
|
230
|
+
await this.documentWatch;
|
|
137
231
|
await (0, browser_1.initWhatsapp)(this.page, null, false, this.options.whatsappVersion, this.options.proxy, this.log.bind(this));
|
|
138
|
-
await this.
|
|
139
|
-
await this.
|
|
140
|
-
await this.
|
|
141
|
-
await this.
|
|
142
|
-
await this.
|
|
143
|
-
this.checkStartInterval = setInterval(() => this.checkStart(), 5000);
|
|
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());
|
|
144
237
|
this.page.on('close', () => {
|
|
145
|
-
|
|
238
|
+
this.cancelQrLoop();
|
|
146
239
|
});
|
|
147
240
|
}
|
|
148
|
-
async checkStart() {
|
|
149
|
-
(0, auth_1.needsToScan)(this.page)
|
|
150
|
-
.then((need) => { })
|
|
151
|
-
.catch(() => null);
|
|
152
|
-
}
|
|
153
241
|
async checkQrCode() {
|
|
242
|
+
if (this.qrLoopCancelled || this.page.isClosed())
|
|
243
|
+
return;
|
|
154
244
|
const needScan = await (0, auth_1.needsToScan)(this.page).catch(() => null);
|
|
245
|
+
if (this.qrLoopCancelled || this.page.isClosed())
|
|
246
|
+
return;
|
|
155
247
|
// A navigation can invalidate the execution context while waiting for QR.
|
|
156
248
|
// An unknown result is not proof that the session has registered.
|
|
157
249
|
if (needScan === null)
|
|
@@ -162,6 +254,8 @@ class HostLayer {
|
|
|
162
254
|
return;
|
|
163
255
|
}
|
|
164
256
|
const result = await this.getQrCode();
|
|
257
|
+
if (this.qrLoopCancelled || this.page.isClosed())
|
|
258
|
+
return;
|
|
165
259
|
if (!result?.urlCode || this.urlCode === result.urlCode) {
|
|
166
260
|
return;
|
|
167
261
|
}
|
|
@@ -171,6 +265,8 @@ class HostLayer {
|
|
|
171
265
|
if (this.options.logQR || this.catchQR) {
|
|
172
266
|
qr = await (0, auth_1.asciiQr)(this.urlCode);
|
|
173
267
|
}
|
|
268
|
+
if (this.qrLoopCancelled || this.page.isClosed())
|
|
269
|
+
return;
|
|
174
270
|
if (this.options.logQR) {
|
|
175
271
|
this.log('info', `Waiting for QRCode Scan (Attempt ${this.attempt})...:\n${qr}`, { code: this.urlCode });
|
|
176
272
|
}
|
|
@@ -179,6 +275,14 @@ class HostLayer {
|
|
|
179
275
|
}
|
|
180
276
|
this.catchQR?.(result.base64Image, qr, this.attempt, result.urlCode);
|
|
181
277
|
}
|
|
278
|
+
/**
|
|
279
|
+
* Stop QR attempts and suppress pending QR callbacks for this client.
|
|
280
|
+
* Create a new client to start pairing again.
|
|
281
|
+
* @category Host
|
|
282
|
+
*/
|
|
283
|
+
cancelQrLoop() {
|
|
284
|
+
this.qrLoopCancelled = true;
|
|
285
|
+
}
|
|
182
286
|
async loginByCode(phone) {
|
|
183
287
|
await (0, helpers_1.evaluateAndReturn)(this.page, async ({ phone }) => {
|
|
184
288
|
await WPP.conn.startLinkDeviceCodeForPhoneNumber(phone);
|
|
@@ -202,12 +306,18 @@ class HostLayer {
|
|
|
202
306
|
}
|
|
203
307
|
async checkInChat() {
|
|
204
308
|
const inChat = await (0, auth_1.isInsideChat)(this.page).catch(() => null);
|
|
309
|
+
const wasInChat = this.isInChat;
|
|
205
310
|
this.isInChat = !!inChat;
|
|
206
|
-
if (!inChat) {
|
|
311
|
+
if (!inChat || wasInChat) {
|
|
207
312
|
return;
|
|
208
313
|
}
|
|
209
314
|
this.log('http', 'Connected');
|
|
210
|
-
|
|
315
|
+
try {
|
|
316
|
+
this.statusFind?.('inChat', this.session);
|
|
317
|
+
}
|
|
318
|
+
catch (error) {
|
|
319
|
+
this.log('error', error);
|
|
320
|
+
}
|
|
211
321
|
}
|
|
212
322
|
tryAutoClose() {
|
|
213
323
|
if (this.autoCloseInterval) {
|
|
@@ -283,8 +393,9 @@ class HostLayer {
|
|
|
283
393
|
return false;
|
|
284
394
|
}
|
|
285
395
|
await (0, sleep_1.sleep)(1000);
|
|
286
|
-
|
|
287
|
-
|
|
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();
|
|
288
399
|
}
|
|
289
400
|
return this.isInChat;
|
|
290
401
|
}
|
|
@@ -295,11 +406,22 @@ class HostLayer {
|
|
|
295
406
|
await (0, sleep_1.sleep)(50);
|
|
296
407
|
continue;
|
|
297
408
|
}
|
|
298
|
-
await pageLoad;
|
|
299
|
-
|
|
300
|
-
|
|
409
|
+
const failure = await pageLoad.then(() => null, (error) => ({ error }));
|
|
410
|
+
// Superseded by a newer load: wait for that injection instead
|
|
411
|
+
if (pageLoad !== this.pageLoadPromise) {
|
|
412
|
+
continue;
|
|
413
|
+
}
|
|
414
|
+
if (failure) {
|
|
415
|
+
throw failure.error;
|
|
416
|
+
}
|
|
417
|
+
if (this.isInjected) {
|
|
301
418
|
return;
|
|
302
419
|
}
|
|
420
|
+
// Superseded by a navigation whose 'load' has not fired yet
|
|
421
|
+
if (this.isInjectionExpired()) {
|
|
422
|
+
throw new browser_1.InjectionTimeoutError(this.options.injectionTimeout);
|
|
423
|
+
}
|
|
424
|
+
await (0, sleep_1.sleep)(50);
|
|
303
425
|
}
|
|
304
426
|
throw new Error('Page closed before WAPI injection completed');
|
|
305
427
|
}
|
|
@@ -341,6 +463,10 @@ class HostLayer {
|
|
|
341
463
|
this.statusFind?.('isLogged', this.session);
|
|
342
464
|
}
|
|
343
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;
|
|
344
470
|
// Reinicia o contador do autoclose
|
|
345
471
|
this.cancelAutoClose();
|
|
346
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
|