@cdteam/cdwa 0.0.0-stage → 0.1.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.
Files changed (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +112 -2
  3. package/dist/auth/index.cjs +191 -0
  4. package/dist/auth/index.cjs.map +1 -0
  5. package/dist/auth/index.d.cts +25 -0
  6. package/dist/auth/index.d.ts +25 -0
  7. package/dist/auth/index.js +183 -0
  8. package/dist/auth/index.js.map +1 -0
  9. package/dist/binary/index.cjs +414 -0
  10. package/dist/binary/index.cjs.map +1 -0
  11. package/dist/binary/index.d.cts +92 -0
  12. package/dist/binary/index.d.ts +92 -0
  13. package/dist/binary/index.js +407 -0
  14. package/dist/binary/index.js.map +1 -0
  15. package/dist/crypto/index.cjs +207 -0
  16. package/dist/crypto/index.cjs.map +1 -0
  17. package/dist/crypto/index.d.cts +91 -0
  18. package/dist/crypto/index.d.ts +91 -0
  19. package/dist/crypto/index.js +201 -0
  20. package/dist/crypto/index.js.map +1 -0
  21. package/dist/index-CcMoHfPz.d.cts +70 -0
  22. package/dist/index-CcMoHfPz.d.ts +70 -0
  23. package/dist/index.cjs +1254 -0
  24. package/dist/index.cjs.map +1 -0
  25. package/dist/index.d.cts +97 -0
  26. package/dist/index.d.ts +97 -0
  27. package/dist/index.js +1224 -0
  28. package/dist/index.js.map +1 -0
  29. package/dist/messages/index.cjs +662 -0
  30. package/dist/messages/index.cjs.map +1 -0
  31. package/dist/messages/index.d.cts +122 -0
  32. package/dist/messages/index.d.ts +122 -0
  33. package/dist/messages/index.js +659 -0
  34. package/dist/messages/index.js.map +1 -0
  35. package/dist/signal/index.cjs +38 -0
  36. package/dist/signal/index.cjs.map +1 -0
  37. package/dist/signal/index.d.cts +30 -0
  38. package/dist/signal/index.d.ts +30 -0
  39. package/dist/signal/index.js +36 -0
  40. package/dist/signal/index.js.map +1 -0
  41. package/package.json +91 -4
package/dist/index.js ADDED
@@ -0,0 +1,1224 @@
1
+ import { x25519 } from '@noble/curves/ed25519';
2
+ import { hkdf } from '@noble/hashes/hkdf';
3
+ import { sha256 } from '@noble/hashes/sha256';
4
+ import { gcm } from '@noble/ciphers/aes';
5
+ import { randomBytes, createCipheriv, createHmac } from 'crypto';
6
+ import { promises } from 'fs';
7
+ import path from 'path';
8
+ import WebSocket from 'ws';
9
+ import { EventEmitter } from 'events';
10
+
11
+ // src/crypto/index.ts
12
+ var NOISE_PROTOCOL_NAME = "Noise_XX_25519_AESGCM_SHA256";
13
+ var WA_NOISE_HEADER = new Uint8Array([87, 65, 6, 2]);
14
+ var NoiseCipherState = class {
15
+ key = null;
16
+ nonce = 0;
17
+ constructor(key) {
18
+ if (key) {
19
+ this.key = key;
20
+ }
21
+ }
22
+ hasKey() {
23
+ return this.key !== null;
24
+ }
25
+ setKey(key) {
26
+ this.key = key;
27
+ this.nonce = 0;
28
+ }
29
+ encryptWithAd(ad, plaintext) {
30
+ if (!this.key) {
31
+ return plaintext;
32
+ }
33
+ const iv = this.generateNonceBuffer(this.nonce);
34
+ this.nonce += 1;
35
+ return CryptoEngine.aesGcmEncrypt(this.key, plaintext, iv, ad);
36
+ }
37
+ decryptWithAd(ad, ciphertext) {
38
+ if (!this.key) {
39
+ return ciphertext;
40
+ }
41
+ const iv = this.generateNonceBuffer(this.nonce);
42
+ this.nonce += 1;
43
+ return CryptoEngine.aesGcmDecrypt(this.key, ciphertext, iv, ad);
44
+ }
45
+ generateNonceBuffer(nonce) {
46
+ const buffer = new Uint8Array(12);
47
+ const view = new DataView(buffer.buffer);
48
+ view.setUint32(8, nonce, false);
49
+ return buffer;
50
+ }
51
+ };
52
+ var NoiseHandshake = class {
53
+ symmetricState;
54
+ localEphemeral;
55
+ localStatic;
56
+ remoteEphemeral = null;
57
+ remoteStatic = null;
58
+ constructor(localStaticKey) {
59
+ this.localStatic = localStaticKey;
60
+ this.localEphemeral = CryptoEngine.generateKeyPair();
61
+ const protocolHash = sha256(new TextEncoder().encode(NOISE_PROTOCOL_NAME));
62
+ this.symmetricState = {
63
+ h: new Uint8Array(protocolHash),
64
+ ck: new Uint8Array(protocolHash),
65
+ cipher: new NoiseCipherState()
66
+ };
67
+ this.mixHash(WA_NOISE_HEADER);
68
+ }
69
+ mixHash(data) {
70
+ const merged = new Uint8Array(this.symmetricState.h.length + data.length);
71
+ merged.set(this.symmetricState.h, 0);
72
+ merged.set(data, this.symmetricState.h.length);
73
+ this.symmetricState.h = sha256(merged);
74
+ }
75
+ mixKey(data) {
76
+ const derived = CryptoEngine.deriveKey(data, "", this.symmetricState.ck, 64);
77
+ this.symmetricState.ck = derived.slice(0, 32);
78
+ const tempK = derived.slice(32, 64);
79
+ this.symmetricState.cipher.setKey(tempK);
80
+ }
81
+ /**
82
+ * Passo 1: Início do Handshake -> Envia chave efêmera local (e)
83
+ */
84
+ startHandshake() {
85
+ this.mixHash(this.localEphemeral.public);
86
+ const message = new Uint8Array(WA_NOISE_HEADER.length + this.localEphemeral.public.length);
87
+ message.set(WA_NOISE_HEADER, 0);
88
+ message.set(this.localEphemeral.public, WA_NOISE_HEADER.length);
89
+ return message;
90
+ }
91
+ /**
92
+ * Passo 2: Recebe resposta do servidor WhatsApp <- (e, ee, s, es)
93
+ */
94
+ processServerHello(serverBuffer) {
95
+ this.remoteEphemeral = serverBuffer.slice(0, 32);
96
+ this.mixHash(this.remoteEphemeral);
97
+ const ee = CryptoEngine.sharedKey(this.localEphemeral.private, this.remoteEphemeral);
98
+ this.mixKey(ee);
99
+ const encryptedStatic = serverBuffer.slice(32, 80);
100
+ this.remoteStatic = this.symmetricState.cipher.decryptWithAd(this.symmetricState.h, encryptedStatic);
101
+ this.mixHash(encryptedStatic);
102
+ const es = CryptoEngine.sharedKey(this.localEphemeral.private, this.remoteStatic);
103
+ this.mixKey(es);
104
+ const encryptedPayload = serverBuffer.slice(80);
105
+ const decryptedPayload = this.symmetricState.cipher.decryptWithAd(this.symmetricState.h, encryptedPayload);
106
+ this.mixHash(encryptedPayload);
107
+ return decryptedPayload;
108
+ }
109
+ /**
110
+ * Passo 3: Envia resposta final de autenticação do cliente -> (s, se) + payload
111
+ * Retorna os CipherStates de leitura e escrita para uso no WebSocket
112
+ */
113
+ finishHandshake(payload) {
114
+ const encryptedStatic = this.symmetricState.cipher.encryptWithAd(this.symmetricState.h, this.localStatic.public);
115
+ this.mixHash(encryptedStatic);
116
+ if (!this.remoteEphemeral) {
117
+ throw new Error("Remote ephemeral key is missing in Noise Handshake");
118
+ }
119
+ const se = CryptoEngine.sharedKey(this.localStatic.private, this.remoteEphemeral);
120
+ this.mixKey(se);
121
+ const encryptedPayload = this.symmetricState.cipher.encryptWithAd(this.symmetricState.h, payload);
122
+ this.mixHash(encryptedPayload);
123
+ const handshakeMessage = new Uint8Array(encryptedStatic.length + encryptedPayload.length);
124
+ handshakeMessage.set(encryptedStatic, 0);
125
+ handshakeMessage.set(encryptedPayload, encryptedStatic.length);
126
+ const transportKeys = CryptoEngine.deriveKey(new Uint8Array(0), "", this.symmetricState.ck, 64);
127
+ const writeKey = transportKeys.slice(0, 32);
128
+ const readKey = transportKeys.slice(32, 64);
129
+ return {
130
+ handshakeMessage,
131
+ writeCipher: new NoiseCipherState(writeKey),
132
+ readCipher: new NoiseCipherState(readKey)
133
+ };
134
+ }
135
+ };
136
+
137
+ // src/crypto/index.ts
138
+ var CryptoEngine = class {
139
+ /**
140
+ * Gera um novo par de chaves Curve25519 (Diffie-Hellman)
141
+ */
142
+ static generateKeyPair() {
143
+ const priv = randomBytes(32);
144
+ const pub = x25519.getPublicKey(priv);
145
+ return {
146
+ private: new Uint8Array(priv),
147
+ public: new Uint8Array(pub)
148
+ };
149
+ }
150
+ /**
151
+ * Executa Diffie-Hellman compartilhado (Shared Secret) usando Curve25519
152
+ */
153
+ static sharedKey(privateKey, publicKey) {
154
+ return x25519.getSharedSecret(privateKey, publicKey);
155
+ }
156
+ /**
157
+ * HKDF baseado em SHA-256 para derivação segura de chaves (RFC 5869)
158
+ */
159
+ static deriveKey(secret, info, salt, length = 32) {
160
+ const infoBytes = typeof info === "string" ? new TextEncoder().encode(info) : info;
161
+ return hkdf(sha256, secret, salt, infoBytes, length);
162
+ }
163
+ /**
164
+ * Encriptação autenticada com AES-256-GCM
165
+ */
166
+ static aesGcmEncrypt(key, plaintext, iv, additionalData) {
167
+ const cipher = gcm(key, iv, additionalData);
168
+ return cipher.encrypt(plaintext);
169
+ }
170
+ /**
171
+ * Decriptação autenticada com AES-256-GCM
172
+ */
173
+ static aesGcmDecrypt(key, ciphertext, iv, additionalData) {
174
+ const cipher = gcm(key, iv, additionalData);
175
+ return cipher.decrypt(ciphertext);
176
+ }
177
+ /**
178
+ * Encripta um payload com uma senha mestra (para proteger credenciais at-rest)
179
+ */
180
+ static encryptAtRest(payload, masterPassphrase) {
181
+ const salt = randomBytes(16);
182
+ const iv = randomBytes(12);
183
+ const key = hkdf(sha256, new TextEncoder().encode(masterPassphrase), salt, new TextEncoder().encode("cdwa-at-rest"), 32);
184
+ const encrypted = this.aesGcmEncrypt(key, payload, iv);
185
+ return {
186
+ salt: Buffer.from(salt).toString("hex"),
187
+ iv: Buffer.from(iv).toString("hex"),
188
+ data: Buffer.from(encrypted).toString("base64")
189
+ };
190
+ }
191
+ /**
192
+ * Decripta um payload protegido com a senha mestra
193
+ */
194
+ static decryptAtRest(encryptedBundle, masterPassphrase) {
195
+ const salt = Buffer.from(encryptedBundle.salt, "hex");
196
+ const iv = Buffer.from(encryptedBundle.iv, "hex");
197
+ const data = Buffer.from(encryptedBundle.data, "base64");
198
+ const key = hkdf(sha256, new TextEncoder().encode(masterPassphrase), salt, new TextEncoder().encode("cdwa-at-rest"), 32);
199
+ return this.aesGcmDecrypt(key, data, iv);
200
+ }
201
+ };
202
+ function initAuthCreds() {
203
+ const identityKeyPair = CryptoEngine.generateKeyPair();
204
+ const noiseKey = CryptoEngine.generateKeyPair();
205
+ const pairingEphemeral = CryptoEngine.generateKeyPair();
206
+ const signedPreKey = CryptoEngine.generateKeyPair();
207
+ const signedSignature = CryptoEngine.sharedKey(identityKeyPair.private, signedPreKey.public);
208
+ return {
209
+ noiseKey,
210
+ pairingEphemeralKeyPair: pairingEphemeral,
211
+ signedIdentityKey: identityKeyPair,
212
+ signedPreKey: {
213
+ ...signedPreKey,
214
+ keyId: 1,
215
+ signature: signedSignature
216
+ },
217
+ registrationId: Math.floor(Math.random() * 16384),
218
+ advSecretKey: Buffer.from(randomBytes(32)).toString("base64"),
219
+ firstUnuploadedPreKeyId: 1,
220
+ nextPreKeyId: 1
221
+ };
222
+ }
223
+ var EncryptedFileAuthState = class {
224
+ folderPath;
225
+ passphrase;
226
+ constructor(folderPath, passphrase) {
227
+ this.folderPath = folderPath;
228
+ this.passphrase = passphrase;
229
+ }
230
+ async ensureDir() {
231
+ await promises.mkdir(this.folderPath, { recursive: true });
232
+ }
233
+ getFilePath(filename) {
234
+ return path.join(this.folderPath, `${filename}.json`);
235
+ }
236
+ async save(key, data) {
237
+ await this.ensureDir();
238
+ const filePath = this.getFilePath(key);
239
+ const jsonString = JSON.stringify(data, (_, value) => {
240
+ if (value instanceof Uint8Array) {
241
+ return { __type: "Buffer", data: Buffer.from(value).toString("base64") };
242
+ }
243
+ return value;
244
+ });
245
+ if (this.passphrase) {
246
+ const encrypted = CryptoEngine.encryptAtRest(new TextEncoder().encode(jsonString), this.passphrase);
247
+ await promises.writeFile(filePath, JSON.stringify(encrypted), "utf-8");
248
+ } else {
249
+ await promises.writeFile(filePath, jsonString, "utf-8");
250
+ }
251
+ }
252
+ async load(key) {
253
+ const filePath = this.getFilePath(key);
254
+ try {
255
+ const content = await promises.readFile(filePath, "utf-8");
256
+ let jsonString = content;
257
+ if (this.passphrase) {
258
+ const bundle = JSON.parse(content);
259
+ const decryptedBytes = CryptoEngine.decryptAtRest(bundle, this.passphrase);
260
+ jsonString = new TextDecoder().decode(decryptedBytes);
261
+ }
262
+ return JSON.parse(jsonString, (_, value) => {
263
+ if (value && value.__type === "Buffer") {
264
+ return new Uint8Array(Buffer.from(value.data, "base64"));
265
+ }
266
+ return value;
267
+ });
268
+ } catch {
269
+ return null;
270
+ }
271
+ }
272
+ createKeyStore() {
273
+ return {
274
+ get: async (type, ids) => {
275
+ const result = {};
276
+ for (const id of ids) {
277
+ const item = await this.load(`${type}-${id}`);
278
+ if (item) {
279
+ result[id] = item;
280
+ }
281
+ }
282
+ return result;
283
+ },
284
+ set: async (data) => {
285
+ for (const [type, entries] of Object.entries(data)) {
286
+ for (const [id, value] of Object.entries(entries)) {
287
+ await this.save(`${type}-${id}`, value);
288
+ }
289
+ }
290
+ }
291
+ };
292
+ }
293
+ };
294
+ async function useSecureAuthState(folderPath, passphrase) {
295
+ const storage = new EncryptedFileAuthState(folderPath, passphrase);
296
+ let creds = await storage.load("creds");
297
+ if (!creds) {
298
+ creds = initAuthCreds();
299
+ await storage.save("creds", creds);
300
+ }
301
+ return {
302
+ creds,
303
+ keys: storage.createKeyStore()
304
+ };
305
+ }
306
+
307
+ // src/signal/index.ts
308
+ var SignalEngine = class {
309
+ keyStore;
310
+ constructor(keyStore) {
311
+ this.keyStore = keyStore;
312
+ }
313
+ /**
314
+ * Inicializa ou recupera uma sessão de Double Ratchet com um contato/dispositivo
315
+ */
316
+ async getSession(address) {
317
+ const sessions = await this.keyStore.get("session", [address]);
318
+ return sessions[address] || null;
319
+ }
320
+ /**
321
+ * Salva uma sessão atualizada após troca de chaves
322
+ */
323
+ async saveSession(address, sessionData) {
324
+ await this.keyStore.set({
325
+ session: {
326
+ [address]: sessionData
327
+ }
328
+ });
329
+ }
330
+ /**
331
+ * Gerenciamento de chaves de remetente (Sender Keys) para envio otimizado em grupos
332
+ */
333
+ async getGroupSenderKey(groupId, senderId) {
334
+ const keyKey = `${groupId}::${senderId}`;
335
+ const keys = await this.keyStore.get("sender-key", [keyKey]);
336
+ return keys[keyKey] || null;
337
+ }
338
+ };
339
+
340
+ // src/binary/constants.ts
341
+ var WABinaryConstants = {
342
+ LIST_EMPTY: 0,
343
+ STREAM_END: 2,
344
+ DICTIONARY_0: 236,
345
+ DICTIONARY_1: 237,
346
+ DICTIONARY_2: 238,
347
+ DICTIONARY_3: 239,
348
+ LIST_8: 248,
349
+ LIST_16: 249,
350
+ JID_PAIR: 250,
351
+ HEX_8: 251,
352
+ BINARY_8: 252,
353
+ BINARY_20: 253,
354
+ BINARY_32: 254,
355
+ NIBBLE_8: 255,
356
+ SINGLE_BYTE_MAX: 256
357
+ };
358
+ var SINGLE_BYTE_TOKENS = [
359
+ "",
360
+ "",
361
+ "",
362
+ "200",
363
+ "400",
364
+ "404",
365
+ "500",
366
+ "501",
367
+ "502",
368
+ "action",
369
+ "add",
370
+ "after",
371
+ "archive",
372
+ "author",
373
+ "available",
374
+ "battery",
375
+ "before",
376
+ "body",
377
+ "broadcast",
378
+ "chat",
379
+ "clear",
380
+ "code",
381
+ "composing",
382
+ "config",
383
+ "contacts",
384
+ "count",
385
+ "create",
386
+ "debug",
387
+ "delete",
388
+ "demote",
389
+ "duplicate",
390
+ "encoding",
391
+ "error",
392
+ "false",
393
+ "filehash",
394
+ "from",
395
+ "g.us",
396
+ "group",
397
+ "groups_v2",
398
+ "height",
399
+ "ib",
400
+ "id",
401
+ "image",
402
+ "in",
403
+ "index",
404
+ "invis",
405
+ "item",
406
+ "jid",
407
+ "kind",
408
+ "last",
409
+ "leave",
410
+ "live",
411
+ "log",
412
+ "media",
413
+ "message",
414
+ "mimetype",
415
+ "missing",
416
+ "modify",
417
+ "name",
418
+ "notification",
419
+ "notify",
420
+ "out",
421
+ "owner",
422
+ "participant",
423
+ "paused",
424
+ "picture",
425
+ "played",
426
+ "presence",
427
+ "preview",
428
+ "promote",
429
+ "query",
430
+ "raw",
431
+ "read",
432
+ "receipt",
433
+ "received",
434
+ "recipient",
435
+ "recording",
436
+ "relay",
437
+ "remove",
438
+ "response",
439
+ "resume",
440
+ "retry",
441
+ "s.whatsapp.net",
442
+ "seconds",
443
+ "set",
444
+ "size",
445
+ "status",
446
+ "subject",
447
+ "subscribe",
448
+ "t",
449
+ "text",
450
+ "to",
451
+ "true",
452
+ "type",
453
+ "unarchive",
454
+ "unavailable",
455
+ "url",
456
+ "user",
457
+ "value",
458
+ "web",
459
+ "width",
460
+ "mute",
461
+ "read_only",
462
+ "admin",
463
+ "creator",
464
+ "short",
465
+ "update",
466
+ "powersave",
467
+ "rich",
468
+ "modify_tag",
469
+ "message_info",
470
+ "opaque",
471
+ "contact",
472
+ "unlink",
473
+ "iq",
474
+ "ping",
475
+ "version",
476
+ "client",
477
+ "pair-device",
478
+ "pair-success",
479
+ "success",
480
+ "failure"
481
+ ];
482
+ var TOKEN_MAP = /* @__PURE__ */ new Map();
483
+ SINGLE_BYTE_TOKENS.forEach((token, index) => {
484
+ if (token) {
485
+ TOKEN_MAP.set(token, index);
486
+ }
487
+ });
488
+
489
+ // src/binary/encoder.ts
490
+ var BinaryEncoder = class {
491
+ buffer = [];
492
+ encode(node) {
493
+ this.buffer = [];
494
+ this.writeNode(node);
495
+ return new Uint8Array(this.buffer);
496
+ }
497
+ writeByte(byte) {
498
+ this.buffer.push(byte & 255);
499
+ }
500
+ writeBytes(bytes) {
501
+ for (let i = 0; i < bytes.length; i++) {
502
+ this.writeByte(bytes[i]);
503
+ }
504
+ }
505
+ writeInt16(value) {
506
+ this.writeByte(value >> 8 & 255);
507
+ this.writeByte(value & 255);
508
+ }
509
+ writeInt32(value) {
510
+ this.writeByte(value >> 24 & 255);
511
+ this.writeByte(value >> 16 & 255);
512
+ this.writeByte(value >> 8 & 255);
513
+ this.writeByte(value & 255);
514
+ }
515
+ writeListStart(size) {
516
+ if (size === 0) {
517
+ this.writeByte(WABinaryConstants.LIST_EMPTY);
518
+ } else if (size < 256) {
519
+ this.writeByte(WABinaryConstants.LIST_8);
520
+ this.writeByte(size);
521
+ } else {
522
+ this.writeByte(WABinaryConstants.LIST_16);
523
+ this.writeInt16(size);
524
+ }
525
+ }
526
+ writeString(str) {
527
+ const tokenIndex = TOKEN_MAP.get(str);
528
+ if (tokenIndex !== void 0) {
529
+ this.writeByte(tokenIndex);
530
+ return;
531
+ }
532
+ const encoded = new TextEncoder().encode(str);
533
+ if (encoded.length < 256) {
534
+ this.writeByte(WABinaryConstants.BINARY_8);
535
+ this.writeByte(encoded.length);
536
+ } else {
537
+ this.writeByte(WABinaryConstants.BINARY_32);
538
+ this.writeInt32(encoded.length);
539
+ }
540
+ this.writeBytes(encoded);
541
+ }
542
+ writeNode(node) {
543
+ const numAttrs = Object.keys(node.attrs).length;
544
+ const hasContent = node.content !== void 0;
545
+ const listSize = 1 + numAttrs * 2 + (hasContent ? 1 : 0);
546
+ this.writeListStart(listSize);
547
+ this.writeString(node.tag);
548
+ for (const [key, value] of Object.entries(node.attrs)) {
549
+ if (value !== void 0) {
550
+ this.writeString(key);
551
+ this.writeString(String(value));
552
+ }
553
+ }
554
+ if (hasContent) {
555
+ if (Array.isArray(node.content)) {
556
+ this.writeListStart(node.content.length);
557
+ for (const child of node.content) {
558
+ this.writeNode(child);
559
+ }
560
+ } else if (typeof node.content === "string") {
561
+ this.writeString(node.content);
562
+ } else if (node.content instanceof Uint8Array) {
563
+ if (node.content.length < 256) {
564
+ this.writeByte(WABinaryConstants.BINARY_8);
565
+ this.writeByte(node.content.length);
566
+ } else {
567
+ this.writeByte(WABinaryConstants.BINARY_32);
568
+ this.writeInt32(node.content.length);
569
+ }
570
+ this.writeBytes(node.content);
571
+ }
572
+ }
573
+ }
574
+ };
575
+
576
+ // src/binary/decoder.ts
577
+ var BinaryDecoder = class {
578
+ buffer = new Uint8Array(0);
579
+ offset = 0;
580
+ decode(buffer) {
581
+ this.buffer = buffer;
582
+ this.offset = 0;
583
+ return this.readNode();
584
+ }
585
+ readByte() {
586
+ if (this.offset >= this.buffer.length) {
587
+ throw new Error(`Unexpected EOF in WABinary stream at offset ${this.offset}`);
588
+ }
589
+ const b = this.buffer[this.offset];
590
+ this.offset += 1;
591
+ return b;
592
+ }
593
+ readBytes(length) {
594
+ if (this.offset + length > this.buffer.length) {
595
+ throw new Error(`Buffer underrun: requested ${length} bytes, have ${this.buffer.length - this.offset}`);
596
+ }
597
+ const slice = this.buffer.slice(this.offset, this.offset + length);
598
+ this.offset += length;
599
+ return slice;
600
+ }
601
+ readInt16() {
602
+ const b0 = this.readByte();
603
+ const b1 = this.readByte();
604
+ return b0 << 8 | b1;
605
+ }
606
+ readInt32() {
607
+ const b0 = this.readByte();
608
+ const b1 = this.readByte();
609
+ const b2 = this.readByte();
610
+ const b3 = this.readByte();
611
+ return b0 << 24 | b1 << 16 | b2 << 8 | b3;
612
+ }
613
+ readListSize() {
614
+ const tag = this.readByte();
615
+ if (tag === WABinaryConstants.LIST_EMPTY) {
616
+ return 0;
617
+ }
618
+ if (tag === WABinaryConstants.LIST_8) {
619
+ return this.readByte();
620
+ }
621
+ if (tag === WABinaryConstants.LIST_16) {
622
+ return this.readInt16();
623
+ }
624
+ throw new Error(`Invalid list tag byte: ${tag}`);
625
+ }
626
+ readString() {
627
+ const tag = this.readByte();
628
+ if (tag < SINGLE_BYTE_TOKENS.length && SINGLE_BYTE_TOKENS[tag]) {
629
+ return SINGLE_BYTE_TOKENS[tag];
630
+ }
631
+ if (tag === WABinaryConstants.BINARY_8) {
632
+ const length = this.readByte();
633
+ const bytes = this.readBytes(length);
634
+ return new TextDecoder().decode(bytes);
635
+ }
636
+ if (tag === WABinaryConstants.BINARY_32) {
637
+ const length = this.readInt32();
638
+ const bytes = this.readBytes(length);
639
+ return new TextDecoder().decode(bytes);
640
+ }
641
+ throw new Error(`Unsupported string tag: ${tag} at offset ${this.offset - 1}`);
642
+ }
643
+ readNode() {
644
+ const listSize = this.readListSize();
645
+ if (listSize === 0) {
646
+ throw new Error("Invalid empty node");
647
+ }
648
+ const tag = this.readString();
649
+ const attrs = {};
650
+ let remaining = listSize - 1;
651
+ while (remaining > 1) {
652
+ const key = this.readString();
653
+ const val = this.readString();
654
+ attrs[key] = val;
655
+ remaining -= 2;
656
+ }
657
+ let content;
658
+ if (remaining === 1) {
659
+ const peekByte = this.buffer[this.offset];
660
+ if (peekByte === WABinaryConstants.LIST_EMPTY || peekByte === WABinaryConstants.LIST_8 || peekByte === WABinaryConstants.LIST_16) {
661
+ const childCount = this.readListSize();
662
+ const children = [];
663
+ for (let i = 0; i < childCount; i++) {
664
+ children.push(this.readNode());
665
+ }
666
+ content = children;
667
+ } else if (peekByte === WABinaryConstants.BINARY_8 || peekByte === WABinaryConstants.BINARY_32) {
668
+ const nextTag = this.readByte();
669
+ const length = nextTag === WABinaryConstants.BINARY_8 ? this.readByte() : this.readInt32();
670
+ content = this.readBytes(length);
671
+ } else {
672
+ content = this.readString();
673
+ }
674
+ }
675
+ return { tag, attrs, content };
676
+ }
677
+ };
678
+
679
+ // src/binary/index.ts
680
+ var BinaryProtocol = class {
681
+ static encoder = new BinaryEncoder();
682
+ static decoder = new BinaryDecoder();
683
+ /**
684
+ * Converte um BinaryNode para bytes WABinary
685
+ */
686
+ static encode(node) {
687
+ return this.encoder.encode(node);
688
+ }
689
+ /**
690
+ * Converte bytes WABinary de volta para um BinaryNode estruturado
691
+ */
692
+ static decode(buffer) {
693
+ return this.decoder.decode(buffer);
694
+ }
695
+ /**
696
+ * Constrói um nó binário com validação de formato
697
+ */
698
+ static createNode(tag, attrs = {}, content) {
699
+ return {
700
+ tag,
701
+ attrs,
702
+ content
703
+ };
704
+ }
705
+ /**
706
+ * Localiza o primeiro filho correspondente à tag fornecida
707
+ */
708
+ static getChildNode(node, childTag) {
709
+ if (Array.isArray(node.content)) {
710
+ return node.content.find((child) => child.tag === childTag);
711
+ }
712
+ return void 0;
713
+ }
714
+ /**
715
+ * Extrai todos os nós filhos que batem com uma determinada tag
716
+ */
717
+ static getChildrenNodes(node, childTag) {
718
+ if (Array.isArray(node.content)) {
719
+ return node.content.filter((child) => child.tag === childTag);
720
+ }
721
+ return [];
722
+ }
723
+ /**
724
+ * Converte o nó para representação em string legível para debug
725
+ */
726
+ static stringify(node, indent = 0) {
727
+ const spaces = " ".repeat(indent);
728
+ const attrsStr = Object.entries(node.attrs).map(([k, v]) => `${k}="${v}"`).join(" ");
729
+ const openTag = attrsStr ? `<${node.tag} ${attrsStr}>` : `<${node.tag}>`;
730
+ if (!node.content) {
731
+ return `${spaces}<${node.tag} ${attrsStr} />`;
732
+ }
733
+ if (Array.isArray(node.content)) {
734
+ const children = node.content.map((c) => this.stringify(c, indent + 1)).join("\n");
735
+ return `${spaces}${openTag}
736
+ ${children}
737
+ ${spaces}</${node.tag}>`;
738
+ }
739
+ const contentStr = node.content instanceof Uint8Array ? `[Buffer ${node.content.length}b]` : String(node.content);
740
+ return `${spaces}${openTag}${contentStr}</${node.tag}>`;
741
+ }
742
+ };
743
+ var MEDIA_HKDF_INFO = {
744
+ image: "WhatsApp Image Keys",
745
+ video: "WhatsApp Video Keys",
746
+ audio: "WhatsApp Audio Keys",
747
+ document: "WhatsApp Document Keys"
748
+ };
749
+ var MediaCrypto = class {
750
+ /**
751
+ * Criptografa o arquivo de mídia de acordo com o padrão RFC do WhatsApp
752
+ */
753
+ static encryptMedia(mediaBuffer, type) {
754
+ const mediaKey = randomBytes(32);
755
+ const info = MEDIA_HKDF_INFO[type];
756
+ const expandedKeys = CryptoEngine.deriveKey(new Uint8Array(mediaKey), info, void 0, 112);
757
+ const iv = expandedKeys.slice(0, 16);
758
+ const cipherKey = expandedKeys.slice(16, 48);
759
+ const macKey = expandedKeys.slice(48, 80);
760
+ const fileSha256 = sha256(mediaBuffer);
761
+ const cipher = createCipheriv("aes-256-cbc", Buffer.from(cipherKey), Buffer.from(iv));
762
+ const encryptedBody = Buffer.concat([cipher.update(Buffer.from(mediaBuffer)), cipher.final()]);
763
+ const hmac = createHmac("sha256", Buffer.from(macKey));
764
+ hmac.update(Buffer.from(iv));
765
+ hmac.update(encryptedBody);
766
+ const fullMac = hmac.digest();
767
+ const mac = fullMac.subarray(0, 10);
768
+ const finalCiphertext = new Uint8Array(encryptedBody.length + mac.length);
769
+ finalCiphertext.set(encryptedBody, 0);
770
+ finalCiphertext.set(mac, encryptedBody.length);
771
+ const fileEncSha256 = sha256(finalCiphertext);
772
+ return {
773
+ mediaKey: new Uint8Array(mediaKey),
774
+ ciphertext: finalCiphertext,
775
+ fileSha256: new Uint8Array(fileSha256),
776
+ fileEncSha256: new Uint8Array(fileEncSha256),
777
+ mac: new Uint8Array(mac)
778
+ };
779
+ }
780
+ };
781
+
782
+ // src/messages/builder.ts
783
+ var MessageBuilder = class {
784
+ /**
785
+ * Converte qualquer conteúdo de mensagem em uma stanza <message> pronta para transmissão
786
+ */
787
+ static async buildMessageNode(jid, content, options = {}) {
788
+ const messageId = `3EB0${Date.now().toString(16).toUpperCase()}${Math.floor(Math.random() * 1e4)}`;
789
+ const timestamp = options.timestamp || Math.floor(Date.now() / 1e3);
790
+ const messageAttrs = {
791
+ id: messageId,
792
+ to: jid,
793
+ type: "text",
794
+ t: timestamp
795
+ };
796
+ let payloadContent = new Uint8Array(0);
797
+ if ("text" in content) {
798
+ payloadContent = new TextEncoder().encode(content.text);
799
+ } else if ("image" in content) {
800
+ messageAttrs.type = "media";
801
+ messageAttrs.mediatype = "image";
802
+ const buffer = await this.resolveMediaBuffer(content.image);
803
+ const encrypted = MediaCrypto.encryptMedia(buffer, "image");
804
+ payloadContent = [
805
+ BinaryProtocol.createNode("image", {
806
+ mimetype: content.mimetype || "image/jpeg",
807
+ caption: content.caption,
808
+ fileLength: buffer.length,
809
+ fileSha256: Buffer.from(encrypted.fileSha256).toString("base64"),
810
+ fileEncSha256: Buffer.from(encrypted.fileEncSha256).toString("base64"),
811
+ mediaKey: Buffer.from(encrypted.mediaKey).toString("base64")
812
+ })
813
+ ];
814
+ } else if ("video" in content) {
815
+ messageAttrs.type = "media";
816
+ messageAttrs.mediatype = "video";
817
+ const buffer = await this.resolveMediaBuffer(content.video);
818
+ const encrypted = MediaCrypto.encryptMedia(buffer, "video");
819
+ payloadContent = [
820
+ BinaryProtocol.createNode("video", {
821
+ mimetype: content.mimetype || "video/mp4",
822
+ caption: content.caption,
823
+ gifPlayback: content.gifPlayback ? "true" : void 0,
824
+ ptv: content.ptv ? "true" : void 0,
825
+ fileLength: buffer.length,
826
+ fileSha256: Buffer.from(encrypted.fileSha256).toString("base64"),
827
+ fileEncSha256: Buffer.from(encrypted.fileEncSha256).toString("base64"),
828
+ mediaKey: Buffer.from(encrypted.mediaKey).toString("base64")
829
+ })
830
+ ];
831
+ } else if ("audio" in content) {
832
+ messageAttrs.type = "media";
833
+ messageAttrs.mediatype = "audio";
834
+ const buffer = await this.resolveMediaBuffer(content.audio);
835
+ const encrypted = MediaCrypto.encryptMedia(buffer, "audio");
836
+ payloadContent = [
837
+ BinaryProtocol.createNode("audio", {
838
+ mimetype: content.mimetype || (content.ptt ? "audio/ogg; codecs=opus" : "audio/mp4"),
839
+ ptt: content.ptt ? "true" : "false",
840
+ fileLength: buffer.length,
841
+ fileSha256: Buffer.from(encrypted.fileSha256).toString("base64"),
842
+ fileEncSha256: Buffer.from(encrypted.fileEncSha256).toString("base64"),
843
+ mediaKey: Buffer.from(encrypted.mediaKey).toString("base64")
844
+ })
845
+ ];
846
+ } else if ("document" in content) {
847
+ messageAttrs.type = "media";
848
+ messageAttrs.mediatype = "document";
849
+ const buffer = await this.resolveMediaBuffer(content.document);
850
+ const encrypted = MediaCrypto.encryptMedia(buffer, "document");
851
+ payloadContent = [
852
+ BinaryProtocol.createNode("document", {
853
+ mimetype: content.mimetype,
854
+ fileName: content.fileName || "file",
855
+ caption: content.caption,
856
+ fileLength: buffer.length,
857
+ fileSha256: Buffer.from(encrypted.fileSha256).toString("base64"),
858
+ fileEncSha256: Buffer.from(encrypted.fileEncSha256).toString("base64"),
859
+ mediaKey: Buffer.from(encrypted.mediaKey).toString("base64")
860
+ })
861
+ ];
862
+ } else if ("location" in content) {
863
+ messageAttrs.type = "location";
864
+ payloadContent = [
865
+ BinaryProtocol.createNode("location", {
866
+ degreesLatitude: content.location.degreesLatitude,
867
+ degreesLongitude: content.location.degreesLongitude,
868
+ name: content.location.name,
869
+ address: content.location.address,
870
+ url: content.location.url
871
+ })
872
+ ];
873
+ } else if ("contact" in content) {
874
+ messageAttrs.type = "contact";
875
+ payloadContent = [
876
+ BinaryProtocol.createNode("contact", {
877
+ displayName: content.contact.displayName,
878
+ vcard: content.contact.vcard
879
+ })
880
+ ];
881
+ } else if ("contacts" in content) {
882
+ messageAttrs.type = "contacts";
883
+ const contactNodes = content.contacts.contacts.map(
884
+ (c) => BinaryProtocol.createNode("contact", {
885
+ displayName: c.displayName,
886
+ vcard: c.vcard
887
+ })
888
+ );
889
+ payloadContent = [
890
+ BinaryProtocol.createNode(
891
+ "contacts",
892
+ { displayName: content.contacts.displayName },
893
+ contactNodes
894
+ )
895
+ ];
896
+ } else if ("react" in content) {
897
+ messageAttrs.type = "reaction";
898
+ payloadContent = [
899
+ BinaryProtocol.createNode("reaction", {
900
+ text: content.react.text,
901
+ targetId: content.react.key.id,
902
+ targetJid: content.react.key.remoteJid
903
+ })
904
+ ];
905
+ }
906
+ const node = BinaryProtocol.createNode("message", messageAttrs, payloadContent);
907
+ return {
908
+ node,
909
+ messageId
910
+ };
911
+ }
912
+ /**
913
+ * Resolve diferentes fontes de mídia (Buffer, Uint8Array ou URL) para um Uint8Array em memória
914
+ */
915
+ static async resolveMediaBuffer(source) {
916
+ if (source instanceof Uint8Array) {
917
+ return source;
918
+ }
919
+ if (Buffer.isBuffer(source)) {
920
+ return new Uint8Array(source);
921
+ }
922
+ if (typeof source === "object" && source !== null && "url" in source) {
923
+ const res = await fetch(source.url);
924
+ const arrayBuf = await res.arrayBuffer();
925
+ return new Uint8Array(arrayBuf);
926
+ }
927
+ throw new Error("Unsupported media source format");
928
+ }
929
+ };
930
+ var DEFAULT_WA_WS_URL = "wss://web.whatsapp.com/ws/chat";
931
+ var WhatsAppSocket = class extends EventEmitter {
932
+ ws = null;
933
+ config;
934
+ pingInterval = null;
935
+ state = "close";
936
+ // Noise Handshake & Ciphers
937
+ noise = null;
938
+ writeCipher = null;
939
+ readCipher = null;
940
+ isHandshakeComplete = false;
941
+ constructor(config = {}) {
942
+ super();
943
+ this.config = {
944
+ waWebSocketUrl: DEFAULT_WA_WS_URL,
945
+ connectTimeoutMs: 2e4,
946
+ keepAliveIntervalMs: 3e4,
947
+ ...config
948
+ };
949
+ }
950
+ get connectionState() {
951
+ return this.state;
952
+ }
953
+ updateConnection(update) {
954
+ if (update.connection) {
955
+ this.state = update.connection;
956
+ }
957
+ this.emit("connection.update", update);
958
+ }
959
+ async connect(staticKey) {
960
+ if (this.ws && (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING)) {
961
+ return;
962
+ }
963
+ this.isHandshakeComplete = false;
964
+ this.writeCipher = null;
965
+ this.readCipher = null;
966
+ this.noise = new NoiseHandshake(staticKey);
967
+ this.updateConnection({ connection: "connecting" });
968
+ const wsUrl = this.config.waWebSocketUrl || DEFAULT_WA_WS_URL;
969
+ this.ws = new WebSocket(wsUrl, {
970
+ origin: "https://web.whatsapp.com",
971
+ headers: {
972
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
973
+ }
974
+ });
975
+ this.ws.on("open", () => {
976
+ this.startKeepAlive();
977
+ this.emit("open");
978
+ this.initiateNoiseHandshake();
979
+ });
980
+ this.ws.on("message", (data) => {
981
+ const buffer = Buffer.isBuffer(data) ? data : Buffer.from(data);
982
+ this.handleIncomingFrame(new Uint8Array(buffer));
983
+ });
984
+ this.ws.on("close", (code, reason) => {
985
+ this.cleanup();
986
+ this.updateConnection({
987
+ connection: "close",
988
+ lastDisconnect: {
989
+ error: new Error(`WebSocket closed with code ${code}: ${reason.toString()}`),
990
+ date: /* @__PURE__ */ new Date()
991
+ }
992
+ });
993
+ });
994
+ this.ws.on("error", (err) => {
995
+ this.emit("error", err);
996
+ });
997
+ }
998
+ /**
999
+ * Envia a mensagem inicial do Noise Handshake
1000
+ */
1001
+ initiateNoiseHandshake() {
1002
+ if (!this.noise) return;
1003
+ const initialPayload = this.noise.startHandshake();
1004
+ this.sendRaw(initialPayload);
1005
+ }
1006
+ /**
1007
+ * Trata frames recebidos pelo WebSocket
1008
+ */
1009
+ handleIncomingFrame(frame) {
1010
+ if (!this.isHandshakeComplete) {
1011
+ this.handleHandshakeFrame(frame);
1012
+ return;
1013
+ }
1014
+ if (this.readCipher && frame.length > 3) {
1015
+ const ciphertext = frame.slice(3);
1016
+ const decrypted = this.readCipher.decryptWithAd(new Uint8Array(0), ciphertext);
1017
+ try {
1018
+ const node = BinaryProtocol.decode(decrypted);
1019
+ this.emit("node", node);
1020
+ } catch (err) {
1021
+ this.emit("error", new Error(`Failed to decode WABinary stanza: ${err.message}`));
1022
+ }
1023
+ }
1024
+ }
1025
+ /**
1026
+ * Conclui as etapas do Noise Handshake
1027
+ */
1028
+ handleHandshakeFrame(frame) {
1029
+ if (!this.noise) return;
1030
+ try {
1031
+ this.noise.processServerHello(frame);
1032
+ const clientPayload = new Uint8Array([0]);
1033
+ const finish = this.noise.finishHandshake(clientPayload);
1034
+ this.writeCipher = finish.writeCipher;
1035
+ this.readCipher = finish.readCipher;
1036
+ this.isHandshakeComplete = true;
1037
+ this.sendRaw(finish.handshakeMessage);
1038
+ this.updateConnection({ connection: "open" });
1039
+ this.emit("handshake.complete");
1040
+ } catch (err) {
1041
+ this.emit("error", new Error(`Noise Handshake failed: ${err.message}`));
1042
+ this.disconnect();
1043
+ }
1044
+ }
1045
+ /**
1046
+ * Envia uma stanza estruturada, codificando em WABinary e criptografando com o Noise Write Cipher
1047
+ */
1048
+ sendNode(node) {
1049
+ if (!this.isHandshakeComplete || !this.writeCipher) {
1050
+ throw new Error("Cannot send stanza: Noise Handshake is not complete");
1051
+ }
1052
+ const encodedNode = BinaryProtocol.encode(node);
1053
+ const encrypted = this.writeCipher.encryptWithAd(new Uint8Array(0), encodedNode);
1054
+ const length = encrypted.length;
1055
+ const frame = new Uint8Array(3 + length);
1056
+ frame[0] = length >> 16 & 255;
1057
+ frame[1] = length >> 8 & 255;
1058
+ frame[2] = length & 255;
1059
+ frame.set(encrypted, 3);
1060
+ this.sendRaw(frame);
1061
+ }
1062
+ sendRaw(data) {
1063
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
1064
+ throw new Error("Cannot send raw data: WebSocket is not open");
1065
+ }
1066
+ this.ws.send(data);
1067
+ }
1068
+ startKeepAlive() {
1069
+ this.stopKeepAlive();
1070
+ this.pingInterval = setInterval(() => {
1071
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) {
1072
+ this.ws.ping();
1073
+ }
1074
+ }, this.config.keepAliveIntervalMs);
1075
+ }
1076
+ stopKeepAlive() {
1077
+ if (this.pingInterval) {
1078
+ clearInterval(this.pingInterval);
1079
+ this.pingInterval = null;
1080
+ }
1081
+ }
1082
+ cleanup() {
1083
+ this.stopKeepAlive();
1084
+ this.isHandshakeComplete = false;
1085
+ this.writeCipher = null;
1086
+ this.readCipher = null;
1087
+ this.noise = null;
1088
+ if (this.ws) {
1089
+ this.ws.removeAllListeners();
1090
+ this.ws = null;
1091
+ }
1092
+ }
1093
+ disconnect() {
1094
+ this.cleanup();
1095
+ this.updateConnection({ connection: "close" });
1096
+ }
1097
+ };
1098
+ var WhatsAppClient = class extends EventEmitter {
1099
+ socket;
1100
+ auth = null;
1101
+ signal = null;
1102
+ config;
1103
+ constructor(config = {}) {
1104
+ super();
1105
+ this.config = config;
1106
+ this.socket = new WhatsAppSocket(config);
1107
+ if (config.auth) {
1108
+ this.setAuthState(config.auth);
1109
+ }
1110
+ this.setupListeners();
1111
+ }
1112
+ setAuthState(auth) {
1113
+ this.auth = auth;
1114
+ this.signal = new SignalEngine(auth.keys);
1115
+ }
1116
+ setupListeners() {
1117
+ this.socket.on("connection.update", (update) => {
1118
+ this.emit("connection.update", update);
1119
+ });
1120
+ this.socket.on("handshake.complete", () => {
1121
+ this.onHandshakeComplete();
1122
+ });
1123
+ this.socket.on("node", (node) => {
1124
+ this.handleIncomingNode(node);
1125
+ });
1126
+ this.socket.on("error", (err) => {
1127
+ this.emit("error", err);
1128
+ });
1129
+ }
1130
+ /**
1131
+ * Disparado após a conexão criptografada (Noise) estar pronta
1132
+ */
1133
+ async onHandshakeComplete() {
1134
+ if (!this.auth) {
1135
+ return;
1136
+ }
1137
+ if (!this.auth.creds.me) {
1138
+ await this.requestPairingCode();
1139
+ } else {
1140
+ this.emit("connection.update", { connection: "open", isNewLogin: false });
1141
+ }
1142
+ }
1143
+ /**
1144
+ * Envia stanza solicitando o QR Code de pareamento
1145
+ */
1146
+ async requestPairingCode() {
1147
+ if (!this.auth) return;
1148
+ const pairNode = BinaryProtocol.createNode(
1149
+ "iq",
1150
+ {
1151
+ to: "s.whatsapp.net",
1152
+ type: "set",
1153
+ xmlns: "pair-device",
1154
+ id: `pair-${Date.now()}`
1155
+ },
1156
+ [
1157
+ BinaryProtocol.createNode("pair-device", {}, [
1158
+ BinaryProtocol.createNode("ref", {}, void 0)
1159
+ ])
1160
+ ]
1161
+ );
1162
+ this.socket.sendNode(pairNode);
1163
+ }
1164
+ /**
1165
+ * Processa stanzas recebidas do WhatsApp
1166
+ */
1167
+ handleIncomingNode(node) {
1168
+ this.emit("raw.node", node);
1169
+ if (node.tag === "iq" && node.attrs.type === "result") {
1170
+ const pairDevice = BinaryProtocol.getChildNode(node, "pair-device");
1171
+ if (pairDevice) {
1172
+ const refNode = BinaryProtocol.getChildNode(pairDevice, "ref");
1173
+ if (refNode && typeof refNode.content === "string" && this.auth) {
1174
+ const ref = refNode.content;
1175
+ const pubKey = Buffer.from(this.auth.creds.signedIdentityKey.public).toString("base64");
1176
+ const noisePub = Buffer.from(this.auth.creds.noiseKey.public).toString("base64");
1177
+ const qrString = `${ref},${noisePub},${pubKey},${this.auth.creds.advSecretKey}`;
1178
+ this.emit("connection.update", { qr: qrString });
1179
+ }
1180
+ }
1181
+ }
1182
+ if (node.tag === "iq" && node.attrs.xmlns === "pair-success") {
1183
+ this.emit("connection.update", { connection: "open", isNewLogin: true });
1184
+ }
1185
+ if (node.tag === "message") {
1186
+ this.emit("messages.upsert", { node });
1187
+ }
1188
+ }
1189
+ /**
1190
+ * Inicia o fluxo de conexão com o WhatsApp Web
1191
+ */
1192
+ async connect() {
1193
+ if (!this.auth) {
1194
+ throw new Error("AuthenticationState must be provided before calling connect()");
1195
+ }
1196
+ await this.socket.connect(this.auth.creds.noiseKey);
1197
+ }
1198
+ /**
1199
+ * Envia qualquer tipo de mensagem (Texto, Imagem, Vídeo, Áudio, Localização, Contato, Reação)
1200
+ */
1201
+ async sendMessage(jid, content, options = {}) {
1202
+ const normalizedContent = typeof content === "string" ? { text: content } : content;
1203
+ const { node, messageId } = await MessageBuilder.buildMessageNode(
1204
+ jid,
1205
+ normalizedContent,
1206
+ options
1207
+ );
1208
+ this.socket.sendNode(node);
1209
+ return { messageId };
1210
+ }
1211
+ /**
1212
+ * Encerra a conexão
1213
+ */
1214
+ disconnect() {
1215
+ this.socket.disconnect();
1216
+ }
1217
+ };
1218
+ function makeWASocket(config = {}) {
1219
+ return new WhatsAppClient(config);
1220
+ }
1221
+
1222
+ export { BinaryDecoder, BinaryEncoder, BinaryProtocol, CryptoEngine, DEFAULT_WA_WS_URL, EncryptedFileAuthState, MediaCrypto, MessageBuilder, NOISE_PROTOCOL_NAME, NoiseCipherState, NoiseHandshake, SINGLE_BYTE_TOKENS, SignalEngine, TOKEN_MAP, WABinaryConstants, WA_NOISE_HEADER, WhatsAppClient, WhatsAppSocket, makeWASocket as default, initAuthCreds, makeWASocket, useSecureAuthState };
1223
+ //# sourceMappingURL=index.js.map
1224
+ //# sourceMappingURL=index.js.map