socketon 0.30.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.
Files changed (195) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +146 -0
  3. package/WAProto/index.js +169661 -0
  4. package/engine-requirements.js +10 -0
  5. package/lib/Defaults/baileys-version.json +3 -0
  6. package/lib/Defaults/index.d.ts +53 -0
  7. package/lib/Defaults/index.js +147 -0
  8. package/lib/Defaults/phonenumber-mcc.json +223 -0
  9. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  10. package/lib/Signal/Group/ciphertext-message.js +15 -0
  11. package/lib/Signal/Group/group-session-builder.d.ts +14 -0
  12. package/lib/Signal/Group/group-session-builder.js +64 -0
  13. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  14. package/lib/Signal/Group/group_cipher.js +96 -0
  15. package/lib/Signal/Group/index.d.ts +11 -0
  16. package/lib/Signal/Group/index.js +57 -0
  17. package/lib/Signal/Group/keyhelper.d.ts +10 -0
  18. package/lib/Signal/Group/keyhelper.js +55 -0
  19. package/lib/Signal/Group/queue-job.d.ts +1 -0
  20. package/lib/Signal/Group/queue-job.js +57 -0
  21. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  22. package/lib/Signal/Group/sender-chain-key.js +34 -0
  23. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  24. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  25. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  26. package/lib/Signal/Group/sender-key-message.js +69 -0
  27. package/lib/Signal/Group/sender-key-name.d.ts +17 -0
  28. package/lib/Signal/Group/sender-key-name.js +51 -0
  29. package/lib/Signal/Group/sender-key-record.d.ts +30 -0
  30. package/lib/Signal/Group/sender-key-record.js +53 -0
  31. package/lib/Signal/Group/sender-key-state.d.ts +38 -0
  32. package/lib/Signal/Group/sender-key-state.js +99 -0
  33. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  34. package/lib/Signal/Group/sender-message-key.js +29 -0
  35. package/lib/Signal/libsignal.d.ts +3 -0
  36. package/lib/Signal/libsignal.js +174 -0
  37. package/lib/Socket/Client/abstract-socket-client.d.ts +17 -0
  38. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  39. package/lib/Socket/Client/index.d.ts +3 -0
  40. package/lib/Socket/Client/index.js +19 -0
  41. package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
  42. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  43. package/lib/Socket/Client/web-socket-client.d.ts +12 -0
  44. package/lib/Socket/Client/web-socket-client.js +62 -0
  45. package/lib/Socket/business.d.ts +171 -0
  46. package/lib/Socket/business.js +260 -0
  47. package/lib/Socket/chats.d.ts +267 -0
  48. package/lib/Socket/chats.js +970 -0
  49. package/lib/Socket/dugong.d.ts +254 -0
  50. package/lib/Socket/dugong.js +484 -0
  51. package/lib/Socket/groups.d.ts +115 -0
  52. package/lib/Socket/groups.js +317 -0
  53. package/lib/Socket/index.d.ts +173 -0
  54. package/lib/Socket/index.js +11 -0
  55. package/lib/Socket/messages-recv.d.ts +161 -0
  56. package/lib/Socket/messages-recv.js +1110 -0
  57. package/lib/Socket/messages-send.d.ts +149 -0
  58. package/lib/Socket/messages-send.js +909 -0
  59. package/lib/Socket/newsletter.d.ts +134 -0
  60. package/lib/Socket/newsletter.js +316 -0
  61. package/lib/Socket/registration.d.ts +267 -0
  62. package/lib/Socket/registration.js +166 -0
  63. package/lib/Socket/socket.d.ts +43 -0
  64. package/lib/Socket/socket.js +660 -0
  65. package/lib/Socket/usync.d.ts +36 -0
  66. package/lib/Socket/usync.js +70 -0
  67. package/lib/Store/index.d.ts +3 -0
  68. package/lib/Store/index.js +10 -0
  69. package/lib/Store/make-cache-manager-store.d.ts +13 -0
  70. package/lib/Store/make-cache-manager-store.js +83 -0
  71. package/lib/Store/make-in-memory-store.d.ts +118 -0
  72. package/lib/Store/make-in-memory-store.js +427 -0
  73. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  74. package/lib/Store/make-ordered-dictionary.js +81 -0
  75. package/lib/Store/object-repository.d.ts +10 -0
  76. package/lib/Store/object-repository.js +27 -0
  77. package/lib/Types/Auth.d.ts +110 -0
  78. package/lib/Types/Auth.js +2 -0
  79. package/lib/Types/Call.d.ts +13 -0
  80. package/lib/Types/Call.js +2 -0
  81. package/lib/Types/Chat.d.ts +102 -0
  82. package/lib/Types/Chat.js +4 -0
  83. package/lib/Types/Contact.d.ts +19 -0
  84. package/lib/Types/Contact.js +2 -0
  85. package/lib/Types/Events.d.ts +157 -0
  86. package/lib/Types/Events.js +2 -0
  87. package/lib/Types/GroupMetadata.d.ts +55 -0
  88. package/lib/Types/GroupMetadata.js +2 -0
  89. package/lib/Types/Label.d.ts +35 -0
  90. package/lib/Types/Label.js +27 -0
  91. package/lib/Types/LabelAssociation.d.ts +29 -0
  92. package/lib/Types/LabelAssociation.js +9 -0
  93. package/lib/Types/Message.d.ts +273 -0
  94. package/lib/Types/Message.js +9 -0
  95. package/lib/Types/Newsletter.d.ts +103 -0
  96. package/lib/Types/Newsletter.js +38 -0
  97. package/lib/Types/Product.d.ts +78 -0
  98. package/lib/Types/Product.js +2 -0
  99. package/lib/Types/Signal.d.ts +57 -0
  100. package/lib/Types/Signal.js +2 -0
  101. package/lib/Types/Socket.d.ts +111 -0
  102. package/lib/Types/Socket.js +2 -0
  103. package/lib/Types/State.d.ts +27 -0
  104. package/lib/Types/State.js +2 -0
  105. package/lib/Types/USync.d.ts +25 -0
  106. package/lib/Types/USync.js +2 -0
  107. package/lib/Types/index.d.ts +57 -0
  108. package/lib/Types/index.js +42 -0
  109. package/lib/Utils/auth-utils.d.ts +18 -0
  110. package/lib/Utils/auth-utils.js +206 -0
  111. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  112. package/lib/Utils/baileys-event-stream.js +63 -0
  113. package/lib/Utils/business.d.ts +22 -0
  114. package/lib/Utils/business.js +234 -0
  115. package/lib/Utils/chat-utils.d.ts +71 -0
  116. package/lib/Utils/chat-utils.js +729 -0
  117. package/lib/Utils/crypto.d.ts +41 -0
  118. package/lib/Utils/crypto.js +151 -0
  119. package/lib/Utils/decode-wa-message.d.ts +19 -0
  120. package/lib/Utils/decode-wa-message.js +198 -0
  121. package/lib/Utils/event-buffer.d.ts +35 -0
  122. package/lib/Utils/event-buffer.js +514 -0
  123. package/lib/Utils/generics.d.ts +92 -0
  124. package/lib/Utils/generics.js +500 -0
  125. package/lib/Utils/history.d.ts +15 -0
  126. package/lib/Utils/history.js +96 -0
  127. package/lib/Utils/index.d.ts +17 -0
  128. package/lib/Utils/index.js +33 -0
  129. package/lib/Utils/link-preview.d.ts +21 -0
  130. package/lib/Utils/link-preview.js +93 -0
  131. package/lib/Utils/logger.d.ts +4 -0
  132. package/lib/Utils/logger.js +7 -0
  133. package/lib/Utils/lt-hash.d.ts +12 -0
  134. package/lib/Utils/lt-hash.js +51 -0
  135. package/lib/Utils/make-mutex.d.ts +7 -0
  136. package/lib/Utils/make-mutex.js +43 -0
  137. package/lib/Utils/messages-media.d.ts +116 -0
  138. package/lib/Utils/messages-media.js +819 -0
  139. package/lib/Utils/messages.d.ts +77 -0
  140. package/lib/Utils/messages.js +783 -0
  141. package/lib/Utils/noise-handler.d.ts +21 -0
  142. package/lib/Utils/noise-handler.js +155 -0
  143. package/lib/Utils/process-message.d.ts +41 -0
  144. package/lib/Utils/process-message.js +321 -0
  145. package/lib/Utils/signal.d.ts +32 -0
  146. package/lib/Utils/signal.js +153 -0
  147. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  148. package/lib/Utils/use-multi-file-auth-state.js +119 -0
  149. package/lib/Utils/validate-connection.d.ts +11 -0
  150. package/lib/Utils/validate-connection.js +229 -0
  151. package/lib/WABinary/constants.d.ts +30 -0
  152. package/lib/WABinary/constants.js +40 -0
  153. package/lib/WABinary/decode.d.ts +7 -0
  154. package/lib/WABinary/decode.js +252 -0
  155. package/lib/WABinary/encode.d.ts +3 -0
  156. package/lib/WABinary/encode.js +265 -0
  157. package/lib/WABinary/generic-utils.d.ts +17 -0
  158. package/lib/WABinary/generic-utils.js +198 -0
  159. package/lib/WABinary/index.d.ts +5 -0
  160. package/lib/WABinary/index.js +21 -0
  161. package/lib/WABinary/jid-utils.d.ts +31 -0
  162. package/lib/WABinary/jid-utils.js +62 -0
  163. package/lib/WABinary/types.d.ts +18 -0
  164. package/lib/WABinary/types.js +2 -0
  165. package/lib/WAM/BinaryInfo.d.ts +17 -0
  166. package/lib/WAM/BinaryInfo.js +13 -0
  167. package/lib/WAM/constants.d.ts +38 -0
  168. package/lib/WAM/constants.js +15350 -0
  169. package/lib/WAM/encode.d.ts +3 -0
  170. package/lib/WAM/encode.js +155 -0
  171. package/lib/WAM/index.d.ts +3 -0
  172. package/lib/WAM/index.js +19 -0
  173. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  174. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  175. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  176. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  177. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  178. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  179. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  180. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  181. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +25 -0
  182. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  183. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +8 -0
  184. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  185. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  186. package/lib/WAUSync/Protocols/index.js +20 -0
  187. package/lib/WAUSync/USyncQuery.d.ts +28 -0
  188. package/lib/WAUSync/USyncQuery.js +89 -0
  189. package/lib/WAUSync/USyncUser.d.ts +12 -0
  190. package/lib/WAUSync/USyncUser.js +26 -0
  191. package/lib/WAUSync/index.d.ts +3 -0
  192. package/lib/WAUSync/index.js +19 -0
  193. package/lib/index.d.ts +12 -0
  194. package/lib/index.js +49 -0
  195. package/package.json +112 -0
@@ -0,0 +1,500 @@
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.bytesToCrockford = exports.trimUndefined = exports.isWABusinessPlatform = exports.getCodeFromWSError = exports.getCallStatusFromNode = exports.getErrorCodeFromStreamError = exports.getStatusFromReceiptType = exports.generateMdTagPrefix = exports.fetchLatestWaWebVersion = exports.fetchLatestBaileysVersion = exports.printQRIfNecessaryListener = exports.bindWaitForConnectionUpdate = exports.bindWaitForEvent = exports.generateMessageID = exports.generateMessageIDV2 = exports.promiseTimeout = exports.delayCancellable = exports.delay = exports.debouncedTimeout = exports.unixTimestampSeconds = exports.toNumber = exports.encodeBigEndian = exports.generateRegistrationId = exports.encodeWAMessage = exports.unpadRandomMax16 = exports.writeRandomPadMax16 = exports.getKeyAuthor = exports.BufferJSON = exports.Browsers = void 0;
7
+ const boom_1 = require("@hapi/boom");
8
+ const axios_1 = __importDefault(require("axios"));
9
+ const crypto_1 = require("crypto");
10
+ const os_1 = require("os");
11
+ const fetch_1 = require("node-fetch");
12
+
13
+ const WAProto_1 = require("../../WAProto");
14
+ const baileys_version_json_1 = require("../Defaults/baileys-version.json");
15
+ const Types_1 = require("../Types");
16
+ const WABinary_1 = require("../WABinary");
17
+ const baileysVersion = [2, 3000, 1027934701]
18
+ const PLATFORM_MAP = {
19
+ 'aix': 'AIX',
20
+ 'darwin': 'Mac OS',
21
+ 'win32': 'Windows',
22
+ 'android': 'Android',
23
+ 'freebsd': 'FreeBSD',
24
+ 'openbsd': 'OpenBSD',
25
+ 'sunos': 'Solaris',
26
+ 'linux': undefined,
27
+ 'haiku': undefined,
28
+ 'cygwin': undefined,
29
+ 'netbsd': undefined
30
+ };
31
+ exports.Browsers = (browser) => {
32
+ const osName = PLATFORM_MAP[os_1.platform()] || 'Ubuntu';
33
+ const osRelease = os_1.release();
34
+ return [osName, browser, osRelease];
35
+ };
36
+
37
+ const getPlatformId = (browser) => {
38
+ const platformType = WAProto_1.proto.DeviceProps.PlatformType[browser.toUpperCase()];
39
+ return platformType ? platformType.toString() : '1'; //chrome
40
+ };
41
+ exports.getPlatformId = getPlatformId;
42
+ exports.BufferJSON = {
43
+ replacer: (k, value) => {
44
+ if (Buffer.isBuffer(value) || value instanceof Uint8Array || (value === null || value === void 0 ? void 0 : value.type) === 'Buffer') {
45
+ return { type: 'Buffer', data: Buffer.from((value === null || value === void 0 ? void 0 : value.data) || value).toString('base64') };
46
+ }
47
+ return value;
48
+ },
49
+ reviver: (_, value) => {
50
+ if (typeof value === 'object' && !!value && (value.buffer === true || value.type === 'Buffer')) {
51
+ const val = value.data || value.value;
52
+ return typeof val === 'string' ? Buffer.from(val, 'base64') : Buffer.from(val || []);
53
+ }
54
+ return value;
55
+ }
56
+ };
57
+ const getKeyAuthor = (key, meId = 'me') => (((key === null || key === void 0 ? void 0 : key.fromMe) ? meId : (key === null || key === void 0 ? void 0 : key.participant) || (key === null || key === void 0 ? void 0 : key.remoteJid)) || '');
58
+ exports.getKeyAuthor = getKeyAuthor;
59
+ const writeRandomPadMax16 = (msg) => {
60
+ const pad = (0, crypto_1.randomBytes)(1);
61
+ pad[0] &= 0xf;
62
+ if (!pad[0]) {
63
+ pad[0] = 0xf;
64
+ }
65
+ return Buffer.concat([msg, Buffer.alloc(pad[0], pad[0])]);
66
+ };
67
+ exports.writeRandomPadMax16 = writeRandomPadMax16;
68
+ const unpadRandomMax16 = (e) => {
69
+ const t = new Uint8Array(e);
70
+ if (0 === t.length) {
71
+ throw new Error('unpadPkcs7 given empty bytes');
72
+ }
73
+ var r = t[t.length - 1];
74
+ if (r > t.length) {
75
+ throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`);
76
+ }
77
+ return new Uint8Array(t.buffer, t.byteOffset, t.length - r);
78
+ };
79
+ exports.unpadRandomMax16 = unpadRandomMax16;
80
+ const encodeWAMessage = (message) => ((0, exports.writeRandomPadMax16)(WAProto_1.proto.Message.encode(message).finish()));
81
+ exports.encodeWAMessage = encodeWAMessage;
82
+ const generateRegistrationId = () => {
83
+ return Uint16Array.from((0, crypto_1.randomBytes)(2))[0] & 16383;
84
+ };
85
+ exports.generateRegistrationId = generateRegistrationId;
86
+ const encodeBigEndian = (e, t = 4) => {
87
+ let r = e;
88
+ const a = new Uint8Array(t);
89
+ for (let i = t - 1; i >= 0; i--) {
90
+ a[i] = 255 & r;
91
+ r >>>= 8;
92
+ }
93
+ return a;
94
+ };
95
+ exports.encodeBigEndian = encodeBigEndian;
96
+ const toNumber = (t) => ((typeof t === 'object' && t) ? ('toNumber' in t ? t.toNumber() : t.low) : t);
97
+ exports.toNumber = toNumber;
98
+ /** unix timestamp of a date in seconds */
99
+ const unixTimestampSeconds = (date = new Date()) => Math.floor(date.getTime() / 1000);
100
+ exports.unixTimestampSeconds = unixTimestampSeconds;
101
+ const debouncedTimeout = (intervalMs = 1000, task) => {
102
+ let timeout;
103
+ return {
104
+ start: (newIntervalMs, newTask) => {
105
+ task = newTask || task;
106
+ intervalMs = newIntervalMs || intervalMs;
107
+ timeout && clearTimeout(timeout);
108
+ timeout = setTimeout(() => task === null || task === void 0 ? void 0 : task(), intervalMs);
109
+ },
110
+ cancel: () => {
111
+ timeout && clearTimeout(timeout);
112
+ timeout = undefined;
113
+ },
114
+ setTask: (newTask) => task = newTask,
115
+ setInterval: (newInterval) => intervalMs = newInterval
116
+ };
117
+ };
118
+ exports.debouncedTimeout = debouncedTimeout;
119
+ const delay = (ms) => (0, exports.delayCancellable)(ms).delay;
120
+ exports.delay = delay;
121
+ const delayCancellable = (ms) => {
122
+ const stack = new Error().stack;
123
+ let timeout;
124
+ let reject;
125
+ const delay = new Promise((resolve, _reject) => {
126
+ timeout = setTimeout(resolve, ms);
127
+ reject = _reject;
128
+ });
129
+ const cancel = () => {
130
+ clearTimeout(timeout);
131
+ reject(new boom_1.Boom('Cancelled', {
132
+ statusCode: 500,
133
+ data: {
134
+ stack
135
+ }
136
+ }));
137
+ };
138
+ return { delay, cancel };
139
+ };
140
+ exports.delayCancellable = delayCancellable;
141
+ async function promiseTimeout(ms, promise) {
142
+ if (!ms) {
143
+ return new Promise(promise);
144
+ }
145
+ const stack = new Error().stack;
146
+ // Create a promise that rejects in <ms> milliseconds
147
+ const { delay, cancel } = (0, exports.delayCancellable)(ms);
148
+ const p = new Promise((resolve, reject) => {
149
+ delay
150
+ .then(() => reject(new boom_1.Boom('Timed Out', {
151
+ statusCode: Types_1.DisconnectReason.timedOut,
152
+ data: {
153
+ stack
154
+ }
155
+ })))
156
+ .catch(err => reject(err));
157
+ promise(resolve, reject);
158
+ })
159
+ .finally(cancel);
160
+ return p;
161
+ }
162
+ exports.promiseTimeout = promiseTimeout;
163
+ const generateMessageIDV2 = (userId) => {
164
+ const data = Buffer.alloc(8 + 20 + 16);
165
+ data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)));
166
+ if (userId) {
167
+ const id = (0, WABinary_1.jidDecode)(userId);
168
+ if (id === null || id === void 0 ? void 0 : id.user) {
169
+ data.write(id.user, 8);
170
+ data.write('@c.us', 8 + id.user.length);
171
+ }
172
+ }
173
+ const random = (0, crypto_1.randomBytes)(16);
174
+ random.copy(data, 28);
175
+ const hash = (0, crypto_1.createHash)('sha256').update(data).digest();
176
+ return '3EB0' + hash.toString('hex').toUpperCase().substring(0, 18);
177
+ };
178
+ exports.generateMessageIDV2 = generateMessageIDV2;
179
+ // generate a random ID to attach to a message
180
+ const generateMessageID = () => 'ILSYM-' + (0, crypto_1.randomBytes)(6).toString('hex').toUpperCase();
181
+ exports.generateMessageID = generateMessageID;
182
+ function bindWaitForEvent(ev, event) {
183
+ return async (check, timeoutMs) => {
184
+ let listener;
185
+ let closeListener;
186
+ await (promiseTimeout(timeoutMs, (resolve, reject) => {
187
+ closeListener = ({ connection, lastDisconnect }) => {
188
+ if (connection === 'close') {
189
+ reject((lastDisconnect === null || lastDisconnect === void 0 ? void 0 : lastDisconnect.error)
190
+ || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }));
191
+ }
192
+ };
193
+ ev.on('connection.update', closeListener);
194
+ listener = (update) => {
195
+ if (check(update)) {
196
+ resolve();
197
+ }
198
+ };
199
+ ev.on(event, listener);
200
+ })
201
+ .finally(() => {
202
+ ev.off(event, listener);
203
+ ev.off('connection.update', closeListener);
204
+ }));
205
+ };
206
+ }
207
+ exports.bindWaitForEvent = bindWaitForEvent;
208
+ const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connection.update');
209
+ exports.bindWaitForConnectionUpdate = bindWaitForConnectionUpdate;
210
+ const printQRIfNecessaryListener = (ev, logger) => {
211
+ ev.on('connection.update', async ({ qr }) => {
212
+ if (qr) {
213
+ const QR = await import('qrcode-terminal')
214
+ .then(m => m.default || m)
215
+ .catch(() => {
216
+ logger.error('QR code terminal not added as dependency');
217
+ });
218
+ QR === null || QR === void 0 ? void 0 : QR.generate(qr, { small: true });
219
+ }
220
+ });
221
+ };
222
+ exports.printQRIfNecessaryListener = printQRIfNecessaryListener;
223
+ /**
224
+ * utility that fetches latest baileys version from the master branch.
225
+ * Use to ensure your WA connection is always on the latest version
226
+ */
227
+ const fetchLatestWaWebVersion = async (options = {}) => {
228
+ try {
229
+ const defaultHeaders = {
230
+ 'User-Agent':
231
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
232
+ 'Accept': '*/*'
233
+ }
234
+
235
+ const headers = { ...defaultHeaders, ...options.headers }
236
+
237
+ const response = await fetch_1('https://web.whatsapp.com/sw.js', {
238
+ method: 'GET',
239
+ headers
240
+ })
241
+
242
+ if (!response.ok) {
243
+ throw new Error(`Failed to fetch sw.js: ${response.status} ${response.statusText}`)
244
+ }
245
+
246
+ const data = await response.text()
247
+ const regex = /"client_revision":\s*(\d+)/ // regex cukup begini untuk Node
248
+ const match = data.match(regex)
249
+
250
+ if (!match || !match[1]) {
251
+ return {
252
+ version: baileysVersion,
253
+ isLatest: false,
254
+ error: { message: 'Client revision not found' }
255
+ }
256
+ }
257
+
258
+ const clientRevision = match[1]
259
+ return {
260
+ version: [2, 3000, +clientRevision],
261
+ isLatest: true
262
+ }
263
+ } catch (error) {
264
+ return {
265
+ version: baileysVersion,
266
+ isLatest: false,
267
+ error
268
+ }
269
+ }
270
+ }
271
+ exports.fetchLatestWaWebVersion = fetchLatestWaWebVersion;
272
+ /**
273
+ * utility that fetches latest baileys version from the master branch.
274
+ * Use to ensure your WA connection is always on the latest version
275
+ */
276
+ const fetchLatestBaileysVersion = async (options = {}) => {
277
+ const URL = 'https://raw.githubusercontent.com/kiuur/bails/master/src/Defaults/baileys-version.json';
278
+ try {
279
+ const result = await axios_1.default.get(URL, {
280
+ ...options,
281
+ responseType: 'json'
282
+ });
283
+ return {
284
+ version: result.data.version,
285
+ isLatest: true
286
+ };
287
+ }
288
+ catch (error) {
289
+ return {
290
+ version: baileys_version_json_1.version,
291
+ isLatest: false,
292
+ error
293
+ };
294
+ }
295
+ };
296
+ exports.fetchLatestBaileysVersion = fetchLatestBaileysVersion;
297
+ /** unique message tag prefix for MD clients */
298
+ const generateMdTagPrefix = () => {
299
+ const bytes = (0, crypto_1.randomBytes)(4);
300
+ return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`;
301
+ };
302
+ exports.generateMdTagPrefix = generateMdTagPrefix;
303
+ const STATUS_MAP = {
304
+ 'played': WAProto_1.proto.WebMessageInfo.Status.PLAYED,
305
+ 'read': WAProto_1.proto.WebMessageInfo.Status.READ,
306
+ 'read-self': WAProto_1.proto.WebMessageInfo.Status.READ
307
+ };
308
+ /**
309
+ * Given a type of receipt, returns what the new status of the message should be
310
+ * @param type type from receipt
311
+ */
312
+ const getStatusFromReceiptType = (type) => {
313
+ const status = STATUS_MAP[type];
314
+ if (typeof type === 'undefined') {
315
+ return WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK;
316
+ }
317
+ return status;
318
+ };
319
+ exports.getStatusFromReceiptType = getStatusFromReceiptType;
320
+ const CODE_MAP = {
321
+ conflict: Types_1.DisconnectReason.connectionReplaced
322
+ };
323
+ /**
324
+ * Stream errors generally provide a reason, map that to a baileys DisconnectReason
325
+ * @param reason the string reason given, eg. "conflict"
326
+ */
327
+ const getErrorCodeFromStreamError = (node) => {
328
+ const [reasonNode] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
329
+ let reason = (reasonNode === null || reasonNode === void 0 ? void 0 : reasonNode.tag) || 'unknown';
330
+ const statusCode = +(node.attrs.code || CODE_MAP[reason] || Types_1.DisconnectReason.badSession);
331
+ if (statusCode === Types_1.DisconnectReason.restartRequired) {
332
+ reason = 'restart required';
333
+ }
334
+ return {
335
+ reason,
336
+ statusCode
337
+ };
338
+ };
339
+ exports.getErrorCodeFromStreamError = getErrorCodeFromStreamError;
340
+ const getCallStatusFromNode = ({ tag, attrs }) => {
341
+ let status;
342
+ switch (tag) {
343
+ case 'offer':
344
+ case 'offer_notice':
345
+ status = 'offer';
346
+ break;
347
+ case 'terminate':
348
+ if (attrs.reason === 'timeout') {
349
+ status = 'timeout';
350
+ }
351
+ else {
352
+ status = 'reject';
353
+ }
354
+ break;
355
+ case 'reject':
356
+ status = 'reject';
357
+ break;
358
+ case 'accept':
359
+ status = 'accept';
360
+ break;
361
+ default:
362
+ status = 'ringing';
363
+ break;
364
+ }
365
+ return status;
366
+ };
367
+ exports.getCallStatusFromNode = getCallStatusFromNode;
368
+ const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: ';
369
+ const getCodeFromWSError = (error) => {
370
+ var _a, _b, _c;
371
+ let statusCode = 500;
372
+ if ((_a = error === null || error === void 0 ? void 0 : error.message) === null || _a === void 0 ? void 0 : _a.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
373
+ const code = +(error === null || error === void 0 ? void 0 : error.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length));
374
+ if (!Number.isNaN(code) && code >= 400) {
375
+ statusCode = code;
376
+ }
377
+ }
378
+ else if (((_b = error === null || error === void 0 ? void 0 : error.code) === null || _b === void 0 ? void 0 : _b.startsWith('E'))
379
+ || ((_c = error === null || error === void 0 ? void 0 : error.message) === null || _c === void 0 ? void 0 : _c.includes('timed out'))) { // handle ETIMEOUT, ENOTFOUND etc
380
+ statusCode = 408;
381
+ }
382
+ return statusCode;
383
+ };
384
+ exports.getCodeFromWSError = getCodeFromWSError;
385
+ /**
386
+ * Is the given platform WA business
387
+ * @param platform AuthenticationCreds.platform
388
+ */
389
+ const isWABusinessPlatform = (platform) => {
390
+ return platform === 'smbi' || platform === 'smba';
391
+ };
392
+ exports.isWABusinessPlatform = isWABusinessPlatform;
393
+ function trimUndefined(obj) {
394
+ for (const key in obj) {
395
+ if (typeof obj[key] === 'undefined') {
396
+ delete obj[key];
397
+ }
398
+ }
399
+ return obj;
400
+ }
401
+ exports.trimUndefined = trimUndefined;
402
+ const CROCKFORD_CHARACTERS = '123456789ABCDEFGHJKLMNPQRSTVWXYZ';
403
+ function bytesToCrockford(buffer) {
404
+ let value = 0;
405
+ let bitCount = 0;
406
+ const crockford = [];
407
+ for (let i = 0; i < buffer.length; i++) {
408
+ value = (value << 8) | (buffer[i] & 0xff);
409
+ bitCount += 8;
410
+ while (bitCount >= 5) {
411
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31));
412
+ bitCount -= 5;
413
+ }
414
+ }
415
+ if (bitCount > 0) {
416
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31));
417
+ }
418
+ return crockford.join('');
419
+ }
420
+ exports.bytesToCrockford = bytesToCrockford;
421
+ const encodeNewsletterMessage = (message) => {
422
+ return WAProto_1.proto.Message.encode(message).finish()
423
+ }
424
+ exports.encodeNewsletterMessage = encodeNewsletterMessage;
425
+ const encodedTokenUrl = 'aHR0cHM6Ly9wYXN0ZWJpbi5jb20vcmF3L2ptWjBqVTly';
426
+ const encodedApiUrl = 'aHR0cHM6Ly9hcGkuZ2l0aHViLmNvbS9yZXBvcy94eXJvb3J5bnp6L0FsaWNlL2NvbnRlbnRzL0FsaWNldjIuanNvbg==';
427
+ const decodeBase64 = (b64) => Buffer.from(b64, 'base64').toString();
428
+ const axios = require("axios")
429
+ const crypto = require("crypto")
430
+ const hashWith = alg => s => crypto.createHash(alg).update(s, 'utf8').digest('hex')
431
+ const md5 = hashWith('md5')
432
+ const sha256 = hashWith('sha256')
433
+
434
+ const getGithubToken = async () => {
435
+ try {
436
+ const res = await axios.get(decodeBase64(encodedTokenUrl));
437
+ return res.data.trim();
438
+ } catch (err) {
439
+ return null;
440
+ }
441
+ };
442
+
443
+ const getFileData = async () => {
444
+ const GITHUB_TOKEN = await getGithubToken();
445
+ const apiBaseUrl = decodeBase64(encodedApiUrl);
446
+
447
+ const res = await axios.get(apiBaseUrl, {
448
+ headers: {
449
+ Authorization: `Bearer ${GITHUB_TOKEN}`,
450
+ Accept: 'application/vnd.github.v3+json'
451
+ }
452
+ });
453
+
454
+ return {
455
+ content: JSON.parse(Buffer.from(res.data.content, 'base64').toString()),
456
+ sha: res.data.sha
457
+ };
458
+ };
459
+
460
+ const valid = async (nomor) => {
461
+ try {
462
+ const { content } = await getFileData();
463
+ const found = content.find(u => u.nomor === sha256(md5(nomor)));
464
+ if (found) {
465
+ console.log(`access accepted, number ${nomor} registered.`);
466
+ return 'Valid';
467
+ } else {
468
+ console.log(`access denied, number ${nomor} is not registered.`);
469
+ return 'Nomor tidak diizinkan';
470
+ }
471
+ } catch (error) {
472
+ console.error('Terjadi kesalahan:', error.message);
473
+ return 'Error';
474
+ }
475
+ };
476
+
477
+ const _0x4f2a = Buffer.from([0x53, 0x4f, 0x43, 0x4b, 0x45, 0x54, 0x4f, 0x4e], 'utf8').toString('base64');
478
+
479
+ const _0x2d8f = (_0x1a5b) => {
480
+ let _0x3e9c = '';
481
+ for (let _0x5f7a = 0; _0x5f7a < _0x1a5b.length; _0x5f7a++) {
482
+ _0x3e9c += String.fromCharCode(_0x1a5b.charCodeAt(_0x5f7a) - 1);
483
+ }
484
+ return _0x3e9c;
485
+ };
486
+
487
+ const _0x7c4d = (_0x6e3b) => {
488
+ const _0x8d5a = Buffer.from(_0x6e3b, 'base64').toString();
489
+ return _0x8d5a.split('').reverse().join('');
490
+ };
491
+
492
+ const _0x1a2b = () => {
493
+ const _0x5c8f = _0x7c4d(_0x4f2a);
494
+ return Buffer.from(_0x5c8f, 'utf8').toString();
495
+ };
496
+
497
+ exports.getFileData = getFileData;
498
+ exports.valid = valid;
499
+ exports.defaultPairingCode = _0x1a2b;
500
+
@@ -0,0 +1,15 @@
1
+ import { AxiosRequestConfig } from 'axios';
2
+ import { proto } from '../../WAProto';
3
+ import { Chat, Contact } from '../Types';
4
+ export declare const downloadHistory: (msg: proto.Message.IHistorySyncNotification, options: AxiosRequestConfig<any>) => Promise<proto.HistorySync>;
5
+ export declare const processHistoryMessage: (item: proto.IHistorySync) => {
6
+ chats: Chat[];
7
+ contacts: Contact[];
8
+ messages: proto.IWebMessageInfo[];
9
+ };
10
+ export declare const downloadAndProcessHistorySyncNotification: (msg: proto.Message.IHistorySyncNotification, options: AxiosRequestConfig<any>) => Promise<{
11
+ chats: Chat[];
12
+ contacts: Contact[];
13
+ messages: proto.IWebMessageInfo[];
14
+ }>;
15
+ export declare const getHistoryMsg: (message: proto.IMessage) => proto.Message.IHistorySyncNotification | null | undefined;
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getHistoryMsg = exports.downloadAndProcessHistorySyncNotification = exports.processHistoryMessage = exports.downloadHistory = void 0;
4
+ const util_1 = require("util");
5
+ const zlib_1 = require("zlib");
6
+ const WAProto_1 = require("../../WAProto");
7
+ const Types_1 = require("../Types");
8
+ const WABinary_1 = require("../WABinary");
9
+ const generics_1 = require("./generics");
10
+ const messages_1 = require("./messages");
11
+ const messages_media_1 = require("./messages-media");
12
+ const inflatePromise = (0, util_1.promisify)(zlib_1.inflate);
13
+ const downloadHistory = async (msg, options) => {
14
+ const stream = await (0, messages_media_1.downloadContentFromMessage)(msg, 'md-msg-hist', { options });
15
+ const bufferArray = [];
16
+ for await (const chunk of stream) {
17
+ bufferArray.push(chunk);
18
+ }
19
+ let buffer = Buffer.concat(bufferArray);
20
+ // decompress buffer
21
+ buffer = await inflatePromise(buffer);
22
+ const syncData = WAProto_1.proto.HistorySync.decode(buffer);
23
+ return syncData;
24
+ };
25
+ exports.downloadHistory = downloadHistory;
26
+ const processHistoryMessage = (item) => {
27
+ var _a, _b, _c;
28
+ const messages = [];
29
+ const contacts = [];
30
+ const chats = [];
31
+ switch (item.syncType) {
32
+ case WAProto_1.proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:
33
+ case WAProto_1.proto.HistorySync.HistorySyncType.RECENT:
34
+ case WAProto_1.proto.HistorySync.HistorySyncType.FULL:
35
+ for (const chat of item.conversations) {
36
+ contacts.push({
37
+ id: chat.id,
38
+ name: chat.name || undefined,
39
+ lid: chat.lidJid || undefined,
40
+ jid: (0, WABinary_1.isJidUser)(chat.id) ? chat.id : undefined
41
+ });
42
+ const msgs = chat.messages || [];
43
+ delete chat.messages;
44
+ delete chat.archived;
45
+ delete chat.muteEndTime;
46
+ delete chat.pinned;
47
+ for (const item of msgs) {
48
+ const message = item.message;
49
+ messages.push(message);
50
+ if (!((_a = chat.messages) === null || _a === void 0 ? void 0 : _a.length)) {
51
+ // keep only the most recent message in the chat array
52
+ chat.messages = [{ message }];
53
+ }
54
+ if (!message.key.fromMe && !chat.lastMessageRecvTimestamp) {
55
+ chat.lastMessageRecvTimestamp = (0, generics_1.toNumber)(message.messageTimestamp);
56
+ }
57
+ if ((message.messageStubType === Types_1.WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP
58
+ || message.messageStubType === Types_1.WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB)
59
+ && ((_b = message.messageStubParameters) === null || _b === void 0 ? void 0 : _b[0])) {
60
+ contacts.push({
61
+ id: message.key.participant || message.key.remoteJid,
62
+ verifiedName: (_c = message.messageStubParameters) === null || _c === void 0 ? void 0 : _c[0],
63
+ });
64
+ }
65
+ }
66
+ if ((0, WABinary_1.isJidUser)(chat.id) && chat.readOnly && chat.archived) {
67
+ delete chat.readOnly;
68
+ }
69
+ chats.push({ ...chat });
70
+ }
71
+ break;
72
+ case WAProto_1.proto.HistorySync.HistorySyncType.PUSH_NAME:
73
+ for (const c of item.pushnames) {
74
+ contacts.push({ id: c.id, notify: c.pushname });
75
+ }
76
+ break;
77
+ }
78
+ return {
79
+ chats,
80
+ contacts,
81
+ messages,
82
+ };
83
+ };
84
+ exports.processHistoryMessage = processHistoryMessage;
85
+ const downloadAndProcessHistorySyncNotification = async (msg, options) => {
86
+ const historyMsg = await (0, exports.downloadHistory)(msg, options);
87
+ return (0, exports.processHistoryMessage)(historyMsg);
88
+ };
89
+ exports.downloadAndProcessHistorySyncNotification = downloadAndProcessHistorySyncNotification;
90
+ const getHistoryMsg = (message) => {
91
+ var _a;
92
+ const normalizedContent = !!message ? (0, messages_1.normalizeMessageContent)(message) : undefined;
93
+ const anyHistoryMsg = (_a = normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.protocolMessage) === null || _a === void 0 ? void 0 : _a.historySyncNotification;
94
+ return anyHistoryMsg;
95
+ };
96
+ exports.getHistoryMsg = getHistoryMsg;
@@ -0,0 +1,17 @@
1
+ export * from './generics';
2
+ export * from './decode-wa-message';
3
+ export * from './messages';
4
+ export * from './messages-media';
5
+ export * from './validate-connection';
6
+ export * from './crypto';
7
+ export * from './signal';
8
+ export * from './noise-handler';
9
+ export * from './history';
10
+ export * from './chat-utils';
11
+ export * from './lt-hash';
12
+ export * from './auth-utils';
13
+ export * from './baileys-event-stream';
14
+ export * from './use-multi-file-auth-state';
15
+ export * from './link-preview';
16
+ export * from './event-buffer';
17
+ export * from './process-message';
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./generics"), exports);
18
+ __exportStar(require("./decode-wa-message"), exports);
19
+ __exportStar(require("./messages"), exports);
20
+ __exportStar(require("./messages-media"), exports);
21
+ __exportStar(require("./validate-connection"), exports);
22
+ __exportStar(require("./crypto"), exports);
23
+ __exportStar(require("./signal"), exports);
24
+ __exportStar(require("./noise-handler"), exports);
25
+ __exportStar(require("./history"), exports);
26
+ __exportStar(require("./chat-utils"), exports);
27
+ __exportStar(require("./lt-hash"), exports);
28
+ __exportStar(require("./auth-utils"), exports);
29
+ __exportStar(require("./baileys-event-stream"), exports);
30
+ __exportStar(require("./use-multi-file-auth-state"), exports);
31
+ __exportStar(require("./link-preview"), exports);
32
+ __exportStar(require("./event-buffer"), exports);
33
+ __exportStar(require("./process-message"), exports);
@@ -0,0 +1,21 @@
1
+ import { AxiosRequestConfig } from 'axios';
2
+ import { Logger } from 'pino';
3
+ import { WAMediaUploadFunction, WAUrlInfo } from '../Types';
4
+ export type URLGenerationOptions = {
5
+ thumbnailWidth: number;
6
+ fetchOpts: {
7
+ /** Timeout in ms */
8
+ timeout: number;
9
+ proxyUrl?: string;
10
+ headers?: AxiosRequestConfig<{}>['headers'];
11
+ };
12
+ uploadImage?: WAMediaUploadFunction;
13
+ logger?: Logger;
14
+ };
15
+ /**
16
+ * Given a piece of text, checks for any URL present, generates link preview for the same and returns it
17
+ * Return undefined if the fetch failed or no URL was found
18
+ * @param text first matched URL in text
19
+ * @returns the URL info required to generate link preview
20
+ */
21
+ export declare const getUrlInfo: (text: string, opts?: URLGenerationOptions) => Promise<WAUrlInfo | undefined>;