@genuxofficial/baileys 3.0.0 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/WAProto/WAProto.proto +24 -206
- package/WAProto/index.d.ts +219 -2233
- package/WAProto/index.js +525 -6773
- package/WAProto/shizo.x +1 -0
- package/lib/Defaults/baileys-version.json +1 -1
- package/lib/Defaults/index.d.ts +231 -0
- package/lib/Defaults/index.js +17 -1
- package/lib/Defaults/phonenumber-mcc.json +223 -0
- package/lib/Socket/Client/index.d.ts +3 -2
- package/lib/Socket/Client/index.js +3 -2
- package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
- package/lib/Socket/Client/mobile-socket-client.js +65 -0
- package/lib/Socket/Client/{websocket.d.ts → web-socket-client.d.ts} +1 -1
- package/lib/Socket/Client/{websocket.js → web-socket-client.js} +2 -2
- package/lib/Socket/business.d.ts +7 -9
- package/lib/Socket/chats.d.ts +5 -8
- package/lib/Socket/chats.js +8 -38
- package/lib/Socket/groups.d.ts +5 -7
- package/lib/Socket/groups.js +2 -14
- package/lib/Socket/index.d.ts +9 -9
- package/lib/Socket/index.js +2 -2
- package/lib/Socket/messages-recv.d.ts +8 -10
- package/lib/Socket/messages-recv.js +11 -18
- package/lib/Socket/messages-send.d.ts +7 -14
- package/lib/Socket/messages-send.js +13 -36
- package/lib/Socket/newsletter.d.ts +7 -9
- package/lib/Socket/newsletter.js +3 -11
- package/lib/Socket/registration.d.ts +271 -0
- package/lib/Socket/registration.js +166 -0
- package/lib/Socket/socket.d.ts +4 -5
- package/lib/Socket/socket.js +18 -15
- package/lib/Socket/usync.d.ts +4 -4
- package/lib/Store/index.d.ts +2 -1
- package/lib/Store/index.js +3 -1
- package/lib/Store/make-cache-manager-store.d.ts +14 -0
- package/lib/Store/make-cache-manager-store.js +83 -0
- package/lib/Store/make-in-memory-store.js +10 -8
- package/lib/Store/make-ordered-dictionary.js +2 -2
- package/lib/Types/Auth.d.ts +6 -0
- package/lib/Types/Chat.d.ts +0 -4
- package/lib/Types/Contact.d.ts +1 -1
- package/lib/Types/GroupMetadata.d.ts +0 -6
- package/lib/Types/Message.d.ts +5 -29
- package/lib/Types/Message.js +2 -0
- package/lib/Types/Socket.d.ts +4 -7
- package/lib/Utils/auth-utils.d.ts +1 -1
- package/lib/Utils/auth-utils.js +9 -2
- package/lib/Utils/business.js +3 -15
- package/lib/Utils/chat-utils.d.ts +4 -4
- package/lib/Utils/chat-utils.js +2 -1
- package/lib/Utils/decode-wa-message.d.ts +2 -4
- package/lib/Utils/decode-wa-message.js +24 -145
- package/lib/Utils/event-buffer.js +6 -4
- package/lib/Utils/generics.d.ts +4 -7
- package/lib/Utils/generics.js +17 -9
- package/lib/Utils/lt-hash.d.ts +3 -3
- package/lib/Utils/lt-hash.js +45 -11
- package/lib/Utils/messages-media.d.ts +4 -4
- package/lib/Utils/messages-media.js +57 -69
- package/lib/Utils/messages.js +39 -33
- package/lib/Utils/noise-handler.d.ts +2 -1
- package/lib/Utils/noise-handler.js +10 -5
- package/lib/Utils/use-multi-file-auth-state.js +11 -48
- package/lib/Utils/validate-connection.d.ts +1 -0
- package/lib/Utils/validate-connection.js +44 -10
- package/lib/WABinary/constants.js +5 -5
- package/lib/WABinary/encode.js +10 -23
- package/lib/WABinary/generic-utils.d.ts +5 -3
- package/lib/WABinary/generic-utils.js +19 -34
- package/lib/WABinary/jid-utils.d.ts +2 -11
- package/lib/WABinary/jid-utils.js +2 -27
- package/lib/WAM/BinaryInfo.d.ts +2 -2
- package/lib/WAM/constants.d.ts +2 -3
- package/lib/WAM/encode.js +2 -2
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +12 -21
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +3 -3
- package/lib/WAUSync/USyncQuery.d.ts +0 -2
- package/lib/WAUSync/USyncQuery.js +0 -10
- package/lib/WAUSync/USyncUser.d.ts +0 -2
- package/lib/WAUSync/USyncUser.js +0 -4
- package/package.json +5 -6
- package/LICENSE +0 -21
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +0 -25
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +0 -53
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +0 -8
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +0 -24
- /package/lib/Socket/Client/{types.d.ts → abstract-socket-client.d.ts} +0 -0
- /package/lib/Socket/Client/{types.js → abstract-socket-client.js} +0 -0
@@ -0,0 +1,166 @@
|
|
1
|
+
"use strict";
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
4
|
+
};
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
6
|
+
exports.mobileRegisterFetch = exports.mobileRegisterEncrypt = exports.mobileRegister = exports.mobileRegisterExists = exports.mobileRegisterCode = exports.registrationParams = exports.makeRegistrationSocket = void 0;
|
7
|
+
/* eslint-disable camelcase */
|
8
|
+
const axios_1 = __importDefault(require("axios"));
|
9
|
+
const Defaults_1 = require("../Defaults");
|
10
|
+
const crypto_1 = require("../Utils/crypto");
|
11
|
+
const WABinary_1 = require("../WABinary");
|
12
|
+
const business_1 = require("./business");
|
13
|
+
function urlencode(str) {
|
14
|
+
return str.replace(/-/g, '%2d').replace(/_/g, '%5f').replace(/~/g, '%7e');
|
15
|
+
}
|
16
|
+
const validRegistrationOptions = (config) => (config === null || config === void 0 ? void 0 : config.phoneNumberCountryCode) &&
|
17
|
+
config.phoneNumberNationalNumber &&
|
18
|
+
config.phoneNumberMobileCountryCode;
|
19
|
+
const makeRegistrationSocket = (config) => {
|
20
|
+
const sock = (0, business_1.makeBusinessSocket)(config);
|
21
|
+
const register = async (code) => {
|
22
|
+
if (!validRegistrationOptions(config.auth.creds.registration)) {
|
23
|
+
throw new Error('please specify the registration options');
|
24
|
+
}
|
25
|
+
const result = await mobileRegister({ ...sock.authState.creds, ...sock.authState.creds.registration, code }, config.options);
|
26
|
+
sock.authState.creds.me = {
|
27
|
+
id: (0, WABinary_1.jidEncode)(result.login, 's.whatsapp.net'),
|
28
|
+
name: '~'
|
29
|
+
};
|
30
|
+
sock.authState.creds.registered = true;
|
31
|
+
sock.ev.emit('creds.update', sock.authState.creds);
|
32
|
+
return result;
|
33
|
+
};
|
34
|
+
const requestRegistrationCode = async (registrationOptions) => {
|
35
|
+
registrationOptions = registrationOptions || config.auth.creds.registration;
|
36
|
+
if (!validRegistrationOptions(registrationOptions)) {
|
37
|
+
throw new Error('Invalid registration options');
|
38
|
+
}
|
39
|
+
sock.authState.creds.registration = registrationOptions;
|
40
|
+
sock.ev.emit('creds.update', sock.authState.creds);
|
41
|
+
return mobileRegisterCode({ ...config.auth.creds, ...registrationOptions }, config.options);
|
42
|
+
};
|
43
|
+
return {
|
44
|
+
...sock,
|
45
|
+
register,
|
46
|
+
requestRegistrationCode,
|
47
|
+
};
|
48
|
+
};
|
49
|
+
exports.makeRegistrationSocket = makeRegistrationSocket;
|
50
|
+
function convertBufferToUrlHex(buffer) {
|
51
|
+
var id = '';
|
52
|
+
buffer.forEach((x) => {
|
53
|
+
// encode random identity_id buffer as percentage url encoding
|
54
|
+
id += `%${x.toString(16).padStart(2, '0').toLowerCase()}`;
|
55
|
+
});
|
56
|
+
return id;
|
57
|
+
}
|
58
|
+
function registrationParams(params) {
|
59
|
+
const e_regid = Buffer.alloc(4);
|
60
|
+
e_regid.writeInt32BE(params.registrationId);
|
61
|
+
const e_skey_id = Buffer.alloc(3);
|
62
|
+
e_skey_id.writeInt16BE(params.signedPreKey.keyId);
|
63
|
+
params.phoneNumberCountryCode = params.phoneNumberCountryCode.replace('+', '').trim();
|
64
|
+
params.phoneNumberNationalNumber = params.phoneNumberNationalNumber.replace(/[/-\s)(]/g, '').trim();
|
65
|
+
return {
|
66
|
+
cc: params.phoneNumberCountryCode,
|
67
|
+
in: params.phoneNumberNationalNumber,
|
68
|
+
Rc: '0',
|
69
|
+
lg: 'en',
|
70
|
+
lc: 'GB',
|
71
|
+
mistyped: '6',
|
72
|
+
authkey: Buffer.from(params.noiseKey.public).toString('base64url'),
|
73
|
+
e_regid: e_regid.toString('base64url'),
|
74
|
+
e_keytype: 'BQ',
|
75
|
+
e_ident: Buffer.from(params.signedIdentityKey.public).toString('base64url'),
|
76
|
+
// e_skey_id: e_skey_id.toString('base64url'),
|
77
|
+
e_skey_id: 'AAAA',
|
78
|
+
e_skey_val: Buffer.from(params.signedPreKey.keyPair.public).toString('base64url'),
|
79
|
+
e_skey_sig: Buffer.from(params.signedPreKey.signature).toString('base64url'),
|
80
|
+
fdid: params.phoneId,
|
81
|
+
network_ratio_type: '1',
|
82
|
+
expid: params.deviceId,
|
83
|
+
simnum: '1',
|
84
|
+
hasinrc: '1',
|
85
|
+
pid: Math.floor(Math.random() * 1000).toString(),
|
86
|
+
id: convertBufferToUrlHex(params.identityId),
|
87
|
+
backup_token: convertBufferToUrlHex(params.backupToken),
|
88
|
+
token: (0, crypto_1.md5)(Buffer.concat([Defaults_1.MOBILE_TOKEN, Buffer.from(params.phoneNumberNationalNumber)])).toString('hex'),
|
89
|
+
fraud_checkpoint_code: params.captcha,
|
90
|
+
};
|
91
|
+
}
|
92
|
+
exports.registrationParams = registrationParams;
|
93
|
+
/**
|
94
|
+
* Requests a registration code for the given phone number.
|
95
|
+
*/
|
96
|
+
function mobileRegisterCode(params, fetchOptions) {
|
97
|
+
return mobileRegisterFetch('/code', {
|
98
|
+
params: {
|
99
|
+
...registrationParams(params),
|
100
|
+
mcc: `${params.phoneNumberMobileCountryCode}`.padStart(3, '0'),
|
101
|
+
mnc: `${params.phoneNumberMobileNetworkCode || '001'}`.padStart(3, '0'),
|
102
|
+
sim_mcc: '000',
|
103
|
+
sim_mnc: '000',
|
104
|
+
method: (params === null || params === void 0 ? void 0 : params.method) || 'sms',
|
105
|
+
reason: '',
|
106
|
+
hasav: '1'
|
107
|
+
},
|
108
|
+
...fetchOptions,
|
109
|
+
});
|
110
|
+
}
|
111
|
+
exports.mobileRegisterCode = mobileRegisterCode;
|
112
|
+
function mobileRegisterExists(params, fetchOptions) {
|
113
|
+
return mobileRegisterFetch('/exist', {
|
114
|
+
params: registrationParams(params),
|
115
|
+
...fetchOptions
|
116
|
+
});
|
117
|
+
}
|
118
|
+
exports.mobileRegisterExists = mobileRegisterExists;
|
119
|
+
/**
|
120
|
+
* Registers the phone number on whatsapp with the received OTP code.
|
121
|
+
*/
|
122
|
+
async function mobileRegister(params, fetchOptions) {
|
123
|
+
//const result = await mobileRegisterFetch(`/reg_onboard_abprop?cc=${params.phoneNumberCountryCode}&in=${params.phoneNumberNationalNumber}&rc=0`)
|
124
|
+
return mobileRegisterFetch('/register', {
|
125
|
+
params: { ...registrationParams(params), code: params.code.replace('-', '') },
|
126
|
+
...fetchOptions,
|
127
|
+
});
|
128
|
+
}
|
129
|
+
exports.mobileRegister = mobileRegister;
|
130
|
+
/**
|
131
|
+
* Encrypts the given string as AEAD aes-256-gcm with the public whatsapp key and a random keypair.
|
132
|
+
*/
|
133
|
+
function mobileRegisterEncrypt(data) {
|
134
|
+
const keypair = crypto_1.Curve.generateKeyPair();
|
135
|
+
const key = crypto_1.Curve.sharedKey(keypair.private, Defaults_1.REGISTRATION_PUBLIC_KEY);
|
136
|
+
const buffer = (0, crypto_1.aesEncryptGCM)(Buffer.from(data), new Uint8Array(key), Buffer.alloc(12), Buffer.alloc(0));
|
137
|
+
return Buffer.concat([Buffer.from(keypair.public), buffer]).toString('base64url');
|
138
|
+
}
|
139
|
+
exports.mobileRegisterEncrypt = mobileRegisterEncrypt;
|
140
|
+
async function mobileRegisterFetch(path, opts = {}) {
|
141
|
+
let url = `${Defaults_1.MOBILE_REGISTRATION_ENDPOINT}${path}`;
|
142
|
+
if (opts.params) {
|
143
|
+
const parameter = [];
|
144
|
+
for (const param in opts.params) {
|
145
|
+
if (opts.params[param] !== null && opts.params[param] !== undefined) {
|
146
|
+
parameter.push(param + '=' + urlencode(opts.params[param]));
|
147
|
+
}
|
148
|
+
}
|
149
|
+
url += `?${parameter.join('&')}`;
|
150
|
+
delete opts.params;
|
151
|
+
}
|
152
|
+
if (!opts.headers) {
|
153
|
+
opts.headers = {};
|
154
|
+
}
|
155
|
+
opts.headers['User-Agent'] = Defaults_1.MOBILE_USERAGENT;
|
156
|
+
const response = await (0, axios_1.default)(url, opts);
|
157
|
+
var json = response.data;
|
158
|
+
if (response.status > 300 || json.reason) {
|
159
|
+
throw json;
|
160
|
+
}
|
161
|
+
if (json.status && !['ok', 'sent'].includes(json.status)) {
|
162
|
+
throw json;
|
163
|
+
}
|
164
|
+
return json;
|
165
|
+
}
|
166
|
+
exports.mobileRegisterFetch = mobileRegisterFetch;
|
package/lib/Socket/socket.d.ts
CHANGED
@@ -3,7 +3,6 @@
|
|
3
3
|
import { Boom } from '@hapi/boom';
|
4
4
|
import { SocketConfig } from '../Types';
|
5
5
|
import { BinaryNode } from '../WABinary';
|
6
|
-
import { WebSocketClient } from './Client';
|
7
6
|
/**
|
8
7
|
* Connects to WA servers and performs:
|
9
8
|
* - simple queries (no retry mechanism, wait for connection establishment)
|
@@ -12,7 +11,7 @@ import { WebSocketClient } from './Client';
|
|
12
11
|
*/
|
13
12
|
export declare const makeSocket: (config: SocketConfig) => {
|
14
13
|
type: "md";
|
15
|
-
ws:
|
14
|
+
ws: any;
|
16
15
|
ev: import("../Types").BaileysEventEmitter & {
|
17
16
|
process(handler: (events: Partial<import("../Types").BaileysEventMap>) => void | Promise<void>): () => void;
|
18
17
|
buffer(): void;
|
@@ -27,8 +26,8 @@ export declare const makeSocket: (config: SocketConfig) => {
|
|
27
26
|
signalRepository: import("../Types").SignalRepository;
|
28
27
|
readonly user: import("../Types").Contact | undefined;
|
29
28
|
generateMessageTag: () => string;
|
30
|
-
query: (node: BinaryNode, timeoutMs?: number) => Promise<
|
31
|
-
waitForMessage: <T_1>(msgId: string, timeoutMs?: number | undefined) => Promise<
|
29
|
+
query: (node: BinaryNode, timeoutMs?: number) => Promise<BinaryNode>;
|
30
|
+
waitForMessage: <T_1>(msgId: string, timeoutMs?: number | undefined) => Promise<T_1>;
|
32
31
|
waitForSocketOpen: () => Promise<void>;
|
33
32
|
sendRawMessage: (data: Uint8Array | Buffer) => Promise<void>;
|
34
33
|
sendNode: (frame: BinaryNode) => Promise<void>;
|
@@ -40,6 +39,6 @@ export declare const makeSocket: (config: SocketConfig) => {
|
|
40
39
|
requestPairingCode: (phoneNumber: string, pairCode: string) => Promise<string>;
|
41
40
|
/** Waits for the connection to WA to reach a state */
|
42
41
|
waitForConnectionUpdate: (check: (u: Partial<import("../Types").ConnectionState>) => Promise<boolean | undefined>, timeoutMs?: number | undefined) => Promise<void>;
|
43
|
-
sendWAMBuffer: (wamBuffer: Buffer) => Promise<
|
42
|
+
sendWAMBuffer: (wamBuffer: Buffer) => Promise<BinaryNode>;
|
44
43
|
};
|
45
44
|
export type Socket = ReturnType<typeof makeSocket>;
|
package/lib/Socket/socket.js
CHANGED
@@ -20,14 +20,15 @@ const Client_1 = require("./Client");
|
|
20
20
|
const makeSocket = (config) => {
|
21
21
|
var _a, _b;
|
22
22
|
const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, browser, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository, } = config;
|
23
|
-
|
24
|
-
|
25
|
-
|
23
|
+
let url = typeof waWebSocketUrl === 'string' ? new url_1.URL(waWebSocketUrl) : waWebSocketUrl;
|
24
|
+
config.mobile = config.mobile || url.protocol === 'tcp:';
|
25
|
+
if (config.mobile && url.protocol !== 'tcp:') {
|
26
|
+
url = new url_1.URL(`tcp://${Defaults_1.MOBILE_ENDPOINT}:${Defaults_1.MOBILE_PORT}`);
|
26
27
|
}
|
27
|
-
if (url.protocol === 'wss' && ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.routingInfo)) {
|
28
|
+
if (!config.mobile && url.protocol === 'wss' && ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.routingInfo)) {
|
28
29
|
url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'));
|
29
30
|
}
|
30
|
-
const ws = new Client_1.WebSocketClient(url, config);
|
31
|
+
const ws = config.socket ? config.socket : config.mobile ? new Client_1.MobileSocketClient(url, config) : new Client_1.WebSocketClient(url, config);
|
31
32
|
ws.connect();
|
32
33
|
const ev = (0, Utils_1.makeEventBuffer)(logger);
|
33
34
|
/** ephemeral key pair used to encrypt/decrypt communication. Unique for each connection */
|
@@ -35,7 +36,8 @@ const makeSocket = (config) => {
|
|
35
36
|
/** WA noise protocol wrapper */
|
36
37
|
const noise = (0, Utils_1.makeNoiseHandler)({
|
37
38
|
keyPair: ephemeralKeyPair,
|
38
|
-
NOISE_HEADER: Defaults_1.NOISE_WA_HEADER,
|
39
|
+
NOISE_HEADER: config.mobile ? Defaults_1.MOBILE_NOISE_HEADER : Defaults_1.NOISE_WA_HEADER,
|
40
|
+
mobile: config.mobile,
|
39
41
|
logger,
|
40
42
|
routingInfo: (_b = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _b === void 0 ? void 0 : _b.routingInfo
|
41
43
|
});
|
@@ -114,7 +116,7 @@ const makeSocket = (config) => {
|
|
114
116
|
let onRecv;
|
115
117
|
let onErr;
|
116
118
|
try {
|
117
|
-
|
119
|
+
return await (0, Utils_1.promiseTimeout)(timeoutMs, (resolve, reject) => {
|
118
120
|
onRecv = resolve;
|
119
121
|
onErr = err => {
|
120
122
|
reject(err || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }));
|
@@ -123,7 +125,6 @@ const makeSocket = (config) => {
|
|
123
125
|
ws.on('close', onErr); // if the socket closes, you'll never receive the message
|
124
126
|
ws.off('error', onErr);
|
125
127
|
});
|
126
|
-
return result;
|
127
128
|
}
|
128
129
|
finally {
|
129
130
|
ws.off(`TAG:${msgId}`, onRecv);
|
@@ -137,10 +138,9 @@ const makeSocket = (config) => {
|
|
137
138
|
node.attrs.id = generateMessageTag();
|
138
139
|
}
|
139
140
|
const msgId = node.attrs.id;
|
140
|
-
const
|
141
|
-
|
142
|
-
|
143
|
-
]);
|
141
|
+
const wait = waitForMessage(msgId, timeoutMs);
|
142
|
+
await sendNode(node);
|
143
|
+
const result = await wait;
|
144
144
|
if ('tag' in result) {
|
145
145
|
(0, WABinary_1.assertNodeErrorFree)(result);
|
146
146
|
}
|
@@ -159,7 +159,10 @@ const makeSocket = (config) => {
|
|
159
159
|
logger.trace({ handshake }, 'handshake recv from WA');
|
160
160
|
const keyEnc = await noise.processHandshake(handshake, creds.noiseKey);
|
161
161
|
let node;
|
162
|
-
if (
|
162
|
+
if (config.mobile) {
|
163
|
+
node = (0, Utils_1.generateMobileNode)(config);
|
164
|
+
}
|
165
|
+
else if (!creds.me) {
|
163
166
|
node = (0, Utils_1.generateRegistrationNode)(creds, config);
|
164
167
|
logger.info({ node }, 'not logged in, attempting registration...');
|
165
168
|
}
|
@@ -229,11 +232,11 @@ const makeSocket = (config) => {
|
|
229
232
|
const l0 = frame.tag;
|
230
233
|
const l1 = frame.attrs || {};
|
231
234
|
const l2 = Array.isArray(frame.content) ? (_a = frame.content[0]) === null || _a === void 0 ? void 0 : _a.tag : '';
|
232
|
-
|
235
|
+
Object.keys(l1).forEach(key => {
|
233
236
|
anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered;
|
234
237
|
anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered;
|
235
238
|
anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered;
|
236
|
-
}
|
239
|
+
});
|
237
240
|
anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered;
|
238
241
|
anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered;
|
239
242
|
if (!anyTriggered && logger.level === 'debug') {
|
package/lib/Socket/usync.d.ts
CHANGED
@@ -7,7 +7,7 @@ import { USyncQuery } from '../WAUSync';
|
|
7
7
|
export declare const makeUSyncSocket: (config: SocketConfig) => {
|
8
8
|
executeUSyncQuery: (usyncQuery: USyncQuery) => Promise<import("../WAUSync").USyncQueryResult | undefined>;
|
9
9
|
type: "md";
|
10
|
-
ws:
|
10
|
+
ws: any;
|
11
11
|
ev: import("../Types").BaileysEventEmitter & {
|
12
12
|
process(handler: (events: Partial<import("../Types").BaileysEventMap>) => void | Promise<void>): () => void;
|
13
13
|
buffer(): void;
|
@@ -22,8 +22,8 @@ export declare const makeUSyncSocket: (config: SocketConfig) => {
|
|
22
22
|
signalRepository: import("../Types").SignalRepository;
|
23
23
|
user: import("../Types").Contact | undefined;
|
24
24
|
generateMessageTag: () => string;
|
25
|
-
query: (node: BinaryNode, timeoutMs?: number | undefined) => Promise<
|
26
|
-
waitForMessage: <T_1>(msgId: string, timeoutMs?: number | undefined) => Promise<
|
25
|
+
query: (node: BinaryNode, timeoutMs?: number | undefined) => Promise<BinaryNode>;
|
26
|
+
waitForMessage: <T_1>(msgId: string, timeoutMs?: number | undefined) => Promise<T_1>;
|
27
27
|
waitForSocketOpen: () => Promise<void>;
|
28
28
|
sendRawMessage: (data: Uint8Array | Buffer) => Promise<void>;
|
29
29
|
sendNode: (frame: BinaryNode) => Promise<void>;
|
@@ -34,5 +34,5 @@ export declare const makeUSyncSocket: (config: SocketConfig) => {
|
|
34
34
|
uploadPreKeysToServerIfRequired: () => Promise<void>;
|
35
35
|
requestPairingCode: (phoneNumber: string, pairCode: string) => Promise<string>;
|
36
36
|
waitForConnectionUpdate: (check: (u: Partial<import("../Types").ConnectionState>) => Promise<boolean | undefined>, timeoutMs?: number | undefined) => Promise<void>;
|
37
|
-
sendWAMBuffer: (wamBuffer: Buffer) => Promise<
|
37
|
+
sendWAMBuffer: (wamBuffer: Buffer) => Promise<BinaryNode>;
|
38
38
|
};
|
package/lib/Store/index.d.ts
CHANGED
package/lib/Store/index.js
CHANGED
@@ -3,6 +3,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
4
4
|
};
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
6
|
-
exports.makeInMemoryStore = void 0;
|
6
|
+
exports.makeCacheManagerAuthState = exports.makeInMemoryStore = void 0;
|
7
|
+
const make_cache_manager_store_1 = __importDefault(require("./make-cache-manager-store"));
|
8
|
+
exports.makeCacheManagerAuthState = make_cache_manager_store_1.default;
|
7
9
|
const make_in_memory_store_1 = __importDefault(require("./make-in-memory-store"));
|
8
10
|
exports.makeInMemoryStore = make_in_memory_store_1.default;
|
@@ -0,0 +1,14 @@
|
|
1
|
+
import { Store } from 'cache-manager';
|
2
|
+
import { AuthenticationCreds } from '../Types';
|
3
|
+
declare const makeCacheManagerAuthState: (store: Store, sessionKey: string) => Promise<{
|
4
|
+
clearState: () => Promise<void>;
|
5
|
+
saveCreds: () => Promise<void>;
|
6
|
+
state: {
|
7
|
+
creds: AuthenticationCreds;
|
8
|
+
keys: {
|
9
|
+
get: (type: string, ids: string[]) => Promise<{}>;
|
10
|
+
set: (data: any) => Promise<void>;
|
11
|
+
};
|
12
|
+
};
|
13
|
+
}>;
|
14
|
+
export default makeCacheManagerAuthState;
|
@@ -0,0 +1,83 @@
|
|
1
|
+
"use strict";
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
4
|
+
};
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
6
|
+
const cache_manager_1 = require("cache-manager");
|
7
|
+
const WAProto_1 = require("../../WAProto");
|
8
|
+
const Utils_1 = require("../Utils");
|
9
|
+
const logger_1 = __importDefault(require("../Utils/logger"));
|
10
|
+
const makeCacheManagerAuthState = async (store, sessionKey) => {
|
11
|
+
const defaultKey = (file) => `${sessionKey}:${file}`;
|
12
|
+
const databaseConn = await (0, cache_manager_1.caching)(store);
|
13
|
+
const writeData = async (file, data) => {
|
14
|
+
let ttl = undefined;
|
15
|
+
if (file === 'creds') {
|
16
|
+
ttl = 63115200; // 2 years
|
17
|
+
}
|
18
|
+
await databaseConn.set(defaultKey(file), JSON.stringify(data, Utils_1.BufferJSON.replacer), ttl);
|
19
|
+
};
|
20
|
+
const readData = async (file) => {
|
21
|
+
try {
|
22
|
+
const data = await databaseConn.get(defaultKey(file));
|
23
|
+
if (data) {
|
24
|
+
return JSON.parse(data, Utils_1.BufferJSON.reviver);
|
25
|
+
}
|
26
|
+
return null;
|
27
|
+
}
|
28
|
+
catch (error) {
|
29
|
+
logger_1.default.error(error);
|
30
|
+
return null;
|
31
|
+
}
|
32
|
+
};
|
33
|
+
const removeData = async (file) => {
|
34
|
+
try {
|
35
|
+
return await databaseConn.del(defaultKey(file));
|
36
|
+
}
|
37
|
+
catch (_a) {
|
38
|
+
logger_1.default.error(`Error removing ${file} from session ${sessionKey}`);
|
39
|
+
}
|
40
|
+
};
|
41
|
+
const clearState = async () => {
|
42
|
+
try {
|
43
|
+
const result = await databaseConn.store.keys(`${sessionKey}*`);
|
44
|
+
await Promise.all(result.map(async (key) => await databaseConn.del(key)));
|
45
|
+
}
|
46
|
+
catch (err) {
|
47
|
+
}
|
48
|
+
};
|
49
|
+
const creds = (await readData('creds')) || (0, Utils_1.initAuthCreds)();
|
50
|
+
return {
|
51
|
+
clearState,
|
52
|
+
saveCreds: () => writeData('creds', creds),
|
53
|
+
state: {
|
54
|
+
creds,
|
55
|
+
keys: {
|
56
|
+
get: async (type, ids) => {
|
57
|
+
const data = {};
|
58
|
+
await Promise.all(ids.map(async (id) => {
|
59
|
+
let value = await readData(`${type}-${id}`);
|
60
|
+
if (type === 'app-state-sync-key' && value) {
|
61
|
+
value = WAProto_1.proto.Message.AppStateSyncKeyData.fromObject(value);
|
62
|
+
}
|
63
|
+
data[id] = value;
|
64
|
+
}));
|
65
|
+
return data;
|
66
|
+
},
|
67
|
+
set: async (data) => {
|
68
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
69
|
+
const tasks = [];
|
70
|
+
for (const category in data) {
|
71
|
+
for (const id in data[category]) {
|
72
|
+
const value = data[category][id];
|
73
|
+
const key = `${category}-${id}`;
|
74
|
+
tasks.push(value ? writeData(key, value) : removeData(key));
|
75
|
+
}
|
76
|
+
}
|
77
|
+
await Promise.all(tasks);
|
78
|
+
},
|
79
|
+
}
|
80
|
+
}
|
81
|
+
};
|
82
|
+
};
|
83
|
+
exports.default = makeCacheManagerAuthState;
|
@@ -191,14 +191,16 @@ exports.default = (config) => {
|
|
191
191
|
const jid = (0, WABinary_1.jidNormalizedUser)(msg.key.remoteJid);
|
192
192
|
const list = assertMessageList(jid);
|
193
193
|
list.upsert(msg, 'append');
|
194
|
-
if (type === 'notify'
|
195
|
-
|
196
|
-
|
197
|
-
|
198
|
-
|
199
|
-
|
200
|
-
|
201
|
-
|
194
|
+
if (type === 'notify') {
|
195
|
+
if (!chats.get(jid)) {
|
196
|
+
ev.emit('chats.upsert', [
|
197
|
+
{
|
198
|
+
id: jid,
|
199
|
+
conversationTimestamp: (0, Utils_1.toNumber)(msg.messageTimestamp),
|
200
|
+
unreadCount: 1
|
201
|
+
}
|
202
|
+
]);
|
203
|
+
}
|
202
204
|
}
|
203
205
|
}
|
204
206
|
break;
|
@@ -56,9 +56,9 @@ function makeOrderedDictionary(idGetter) {
|
|
56
56
|
},
|
57
57
|
clear: () => {
|
58
58
|
array.splice(0, array.length);
|
59
|
-
|
59
|
+
Object.keys(dict).forEach(key => {
|
60
60
|
delete dict[key];
|
61
|
-
}
|
61
|
+
});
|
62
62
|
},
|
63
63
|
filter: (contain) => {
|
64
64
|
let i = 0;
|
package/lib/Types/Auth.d.ts
CHANGED
@@ -1,6 +1,7 @@
|
|
1
1
|
/// <reference types="node" />
|
2
2
|
/// <reference types="node" />
|
3
3
|
import type { proto } from '../../WAProto';
|
4
|
+
import { RegistrationOptions } from '../Socket/registration';
|
4
5
|
import type { Contact } from './Contact';
|
5
6
|
import type { MinimalMessage } from './Message';
|
6
7
|
export type KeyPair = {
|
@@ -57,7 +58,12 @@ export type AuthenticationCreds = SignalCreds & {
|
|
57
58
|
/** number of times history & app state has been synced */
|
58
59
|
accountSyncCounter: number;
|
59
60
|
accountSettings: AccountSettings;
|
61
|
+
deviceId: string;
|
62
|
+
phoneId: string;
|
63
|
+
identityId: Buffer;
|
60
64
|
registered: boolean;
|
65
|
+
backupToken: Buffer;
|
66
|
+
registration: RegistrationOptions;
|
61
67
|
pairingCode: string | undefined;
|
62
68
|
lastPropHash: string | undefined;
|
63
69
|
routingInfo: Buffer | undefined;
|
package/lib/Types/Chat.d.ts
CHANGED
@@ -19,10 +19,6 @@ export interface PresenceData {
|
|
19
19
|
lastKnownPresence: WAPresence;
|
20
20
|
lastSeen?: number;
|
21
21
|
}
|
22
|
-
export type BotListInfo = {
|
23
|
-
jid: string;
|
24
|
-
personaId: string;
|
25
|
-
};
|
26
22
|
export type ChatMutation = {
|
27
23
|
syncAction: proto.ISyncActionData;
|
28
24
|
index: string[];
|
package/lib/Types/Contact.d.ts
CHANGED
@@ -3,28 +3,22 @@ export type GroupParticipant = (Contact & {
|
|
3
3
|
isAdmin?: boolean;
|
4
4
|
isSuperAdmin?: boolean;
|
5
5
|
admin?: 'admin' | 'superadmin' | null;
|
6
|
-
phoneNumber?: string | undefined;
|
7
6
|
});
|
8
7
|
export type ParticipantAction = 'add' | 'remove' | 'promote' | 'demote' | 'modify';
|
9
8
|
export type RequestJoinAction = 'created' | 'revoked' | 'rejected';
|
10
9
|
export type RequestJoinMethod = 'invite_link' | 'linked_group_join' | 'non_admin_add' | undefined;
|
11
10
|
export interface GroupMetadata {
|
12
11
|
id: string;
|
13
|
-
/** group uses 'lid' or 'pn' to send messages */
|
14
|
-
addressingMode: "pn" | "lid";
|
15
12
|
owner: string | undefined;
|
16
13
|
subject: string;
|
17
14
|
/** group subject owner */
|
18
15
|
subjectOwner?: string;
|
19
|
-
subjectOwnerPhoneNumber?: string;
|
20
16
|
/** group subject modification date */
|
21
17
|
subjectTime?: number;
|
22
18
|
creation?: number;
|
23
19
|
desc?: string;
|
24
20
|
descOwner?: string;
|
25
|
-
descOwnerPhoneNumber?: string;
|
26
21
|
descId?: string;
|
27
|
-
descTime?: number;
|
28
22
|
/** if this group is part of a community, it returns the jid of the community to which it belongs */
|
29
23
|
linkedParent?: string;
|
30
24
|
/** is set when the group only allows admins to change group settings */
|
package/lib/Types/Message.d.ts
CHANGED
@@ -23,15 +23,13 @@ export type WATextMessage = proto.Message.IExtendedTextMessage;
|
|
23
23
|
export type WAContextInfo = proto.IContextInfo;
|
24
24
|
export type WALocationMessage = proto.Message.ILocationMessage;
|
25
25
|
export type WAGenericMediaMessage = proto.Message.IVideoMessage | proto.Message.IImageMessage | proto.Message.IAudioMessage | proto.Message.IDocumentMessage | proto.Message.IStickerMessage;
|
26
|
-
export
|
27
|
-
export
|
28
|
-
export type
|
26
|
+
export import WAMessageStubType = proto.WebMessageInfo.StubType;
|
27
|
+
export import WAMessageStatus = proto.WebMessageInfo.Status;
|
28
|
+
export type WAMediaUpload = Buffer | {
|
29
29
|
url: URL | string;
|
30
|
-
}
|
31
|
-
export type WAMediaPayloadStream = {
|
30
|
+
} | {
|
32
31
|
stream: Readable;
|
33
32
|
};
|
34
|
-
export type WAMediaUpload = Buffer | WAMediaPayloadStream | WAMediaPayloadURL;
|
35
33
|
/** Set of message types that are supported by the library */
|
36
34
|
export type MessageType = keyof proto.Message;
|
37
35
|
export type DownloadableMessage = {
|
@@ -330,35 +328,13 @@ export type MiscMessageGenerationOptions = MinimalRelayOptions & {
|
|
330
328
|
export type MessageGenerationOptionsFromContent = MiscMessageGenerationOptions & {
|
331
329
|
userJid: string;
|
332
330
|
};
|
333
|
-
export type PrepareStreamResult = {
|
334
|
-
type: 'prepare';
|
335
|
-
mediaKey: undefined;
|
336
|
-
encWriteStream: Buffer;
|
337
|
-
fileLength: number;
|
338
|
-
fileSha256: Buffer;
|
339
|
-
fileEncSha256: undefined;
|
340
|
-
bodyPath: string | undefined;
|
341
|
-
didSaveToTmpPath: boolean;
|
342
|
-
};
|
343
|
-
export type EncryptedStreamResult = {
|
344
|
-
type: 'encrypted';
|
345
|
-
mediaKey: Buffer;
|
346
|
-
originalFilePath: string | undefined;
|
347
|
-
encFilePath: string;
|
348
|
-
mac: Buffer;
|
349
|
-
fileEncSha256: Buffer;
|
350
|
-
fileSha256: Buffer;
|
351
|
-
fileLength: number;
|
352
|
-
didSaveToTmpPath: boolean;
|
353
|
-
};
|
354
|
-
export type StreamResult = PrepareStreamResult | EncryptedStreamResult;
|
355
331
|
export type WAMediaUploadFunctionOpts = {
|
356
332
|
fileEncSha256B64: string;
|
357
333
|
mediaType: MediaType;
|
358
334
|
newsletter?: boolean;
|
359
335
|
timeoutMs?: number;
|
360
336
|
};
|
361
|
-
export type WAMediaUploadFunction = (
|
337
|
+
export type WAMediaUploadFunction = (readStream: Readable | Buffer, opts: WAMediaUploadFunctionOpts) => Promise<{
|
362
338
|
mediaUrl: string;
|
363
339
|
directPath: string;
|
364
340
|
handle?: string;
|
package/lib/Types/Message.js
CHANGED
@@ -3,5 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.WAMessageStatus = exports.WAMessageStubType = exports.WAProto = void 0;
|
4
4
|
const WAProto_1 = require("../../WAProto");
|
5
5
|
Object.defineProperty(exports, "WAProto", { enumerable: true, get: function () { return WAProto_1.proto; } });
|
6
|
+
// eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars
|
6
7
|
exports.WAMessageStubType = WAProto_1.proto.WebMessageInfo.StubType;
|
8
|
+
// eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars
|
7
9
|
exports.WAMessageStatus = WAProto_1.proto.WebMessageInfo.Status;
|
package/lib/Types/Socket.d.ts
CHANGED
@@ -21,9 +21,6 @@ export type CacheStore = {
|
|
21
21
|
/** flush all data */
|
22
22
|
flushAll(): void;
|
23
23
|
};
|
24
|
-
export type PatchedMessageWithRecipientJID = proto.IMessage & {
|
25
|
-
recipientJid?: string;
|
26
|
-
};
|
27
24
|
export type SocketConfig = {
|
28
25
|
/** the WS url to connect to WA */
|
29
26
|
waWebSocketUrl: string | URL;
|
@@ -33,9 +30,7 @@ export type SocketConfig = {
|
|
33
30
|
defaultQueryTimeoutMs: number | undefined;
|
34
31
|
/** ping-pong interval for WS connection */
|
35
32
|
keepAliveIntervalMs: number;
|
36
|
-
/** should baileys use the mobile api instead of the multi device api
|
37
|
-
* @deprecated This feature has been removed
|
38
|
-
*/
|
33
|
+
/** should baileys use the mobile api instead of the multi device api */
|
39
34
|
mobile?: boolean;
|
40
35
|
/** proxy agent */
|
41
36
|
agent?: Agent;
|
@@ -103,7 +98,7 @@ export type SocketConfig = {
|
|
103
98
|
/**
|
104
99
|
* Optionally patch the message before sending out
|
105
100
|
* */
|
106
|
-
patchMessageBeforeSending: (msg: proto.IMessage, recipientJids
|
101
|
+
patchMessageBeforeSending: (msg: proto.IMessage, recipientJids: string[]) => Promise<proto.IMessage> | proto.IMessage;
|
107
102
|
/** verify app state MACs */
|
108
103
|
appStateMacVerification: {
|
109
104
|
patch: boolean;
|
@@ -120,4 +115,6 @@ export type SocketConfig = {
|
|
120
115
|
/** cached group metadata, use to prevent redundant requests to WA & speed up msg sending */
|
121
116
|
cachedGroupMetadata: (jid: string) => Promise<GroupMetadata | undefined>;
|
122
117
|
makeSignalRepository: (auth: SignalAuthState) => SignalRepository;
|
118
|
+
/** Socket passthrough */
|
119
|
+
socket?: any;
|
123
120
|
};
|
@@ -6,7 +6,7 @@ import { ILogger } from './logger';
|
|
6
6
|
* @param logger to log trace events
|
7
7
|
* @param _cache cache store to use
|
8
8
|
*/
|
9
|
-
export declare function makeCacheableSignalKeyStore(store: SignalKeyStore, logger
|
9
|
+
export declare function makeCacheableSignalKeyStore(store: SignalKeyStore, logger: ILogger, _cache?: CacheStore): SignalKeyStore;
|
10
10
|
/**
|
11
11
|
* Adds DB like transaction capability (https://en.wikipedia.org/wiki/Database_transaction) to the SignalKeyStore,
|
12
12
|
* this allows batch read & write operations & improves the performance of the lib
|