jagproject 26.3.22 → 26.3.25

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 (206) hide show
  1. package/WAProto/GenerateStatics.sh +3 -4
  2. package/WAProto/WAProto.proto +1215 -511
  3. package/WAProto/fix-imports.js +73 -0
  4. package/WAProto/index.d.ts +14017 -0
  5. package/WAProto/index.js +64857 -145167
  6. package/engine-requirements.js +4 -7
  7. package/lib/Defaults/index.d.ts +74 -0
  8. package/lib/Defaults/index.js +51 -33
  9. package/lib/Defaults/phonenumber-mcc.json +223 -0
  10. package/lib/Defaults/wileys-version.json +2 -2
  11. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  12. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  13. package/lib/Signal/Group/group-session-builder.js +5 -3
  14. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  15. package/lib/Signal/Group/group_cipher.js +35 -46
  16. package/lib/Signal/Group/index.d.ts +12 -0
  17. package/lib/Signal/Group/index.js +21 -21
  18. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  19. package/lib/Signal/Group/keyhelper.js +2 -2
  20. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  21. package/lib/Signal/Group/sender-chain-key.js +5 -10
  22. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  23. package/lib/Signal/Group/sender-key-distribution-message.js +7 -7
  24. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  25. package/lib/Signal/Group/sender-key-message.js +8 -8
  26. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  27. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  28. package/lib/Signal/Group/sender-key-record.js +7 -16
  29. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  30. package/lib/Signal/Group/sender-key-state.js +25 -37
  31. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  32. package/lib/Signal/Group/sender-message-key.js +2 -2
  33. package/lib/Signal/libsignal.d.ts +5 -0
  34. package/lib/Signal/libsignal.js +358 -54
  35. package/lib/Signal/lid-mapping.d.ts +19 -0
  36. package/lib/Signal/lid-mapping.js +274 -0
  37. package/lib/Socket/Client/index.d.ts +3 -0
  38. package/lib/Socket/Client/index.js +2 -2
  39. package/lib/Socket/Client/types.d.ts +16 -0
  40. package/lib/Socket/Client/types.js +1 -0
  41. package/lib/Socket/Client/websocket.d.ts +13 -0
  42. package/lib/Socket/Client/websocket.js +18 -30
  43. package/lib/Socket/business.d.ts +202 -0
  44. package/lib/Socket/business.js +160 -38
  45. package/lib/Socket/chats.d.ts +111 -0
  46. package/lib/Socket/chats.js +497 -314
  47. package/lib/Socket/communities.d.ts +258 -0
  48. package/lib/Socket/communities.js +438 -0
  49. package/lib/Socket/community.js +333 -0
  50. package/lib/Socket/groups.d.ts +150 -0
  51. package/lib/Socket/groups.js +229 -91
  52. package/lib/Socket/index.d.ts +245 -0
  53. package/lib/Socket/index.js +9 -6
  54. package/lib/Socket/messages-recv.d.ts +187 -0
  55. package/lib/Socket/messages-recv.js +1105 -501
  56. package/lib/Socket/messages-send.d.ts +183 -0
  57. package/lib/Socket/messages-send.js +1184 -501
  58. package/lib/Socket/mex.d.ts +3 -0
  59. package/lib/Socket/mex.js +45 -0
  60. package/lib/Socket/newsletter.d.ts +160 -0
  61. package/lib/Socket/newsletter.js +227 -200
  62. package/lib/Socket/socket.d.ts +55 -0
  63. package/lib/Socket/socket.js +507 -206
  64. package/lib/Socket/usync.js +6 -6
  65. package/lib/Store/index.js +17 -5
  66. package/lib/Store/make-cache-manager-store.js +83 -0
  67. package/lib/Store/make-in-memory-store.js +48 -89
  68. package/lib/Store/make-ordered-dictionary.js +1 -1
  69. package/lib/Types/Auth.d.ts +116 -0
  70. package/lib/Types/Bussines.d.ts +25 -0
  71. package/lib/Types/Bussines.js +2 -0
  72. package/lib/Types/Call.d.ts +15 -0
  73. package/lib/Types/Chat.d.ts +123 -0
  74. package/lib/Types/Chat.js +7 -1
  75. package/lib/Types/Contact.d.ts +24 -0
  76. package/lib/Types/Events.d.ts +237 -0
  77. package/lib/Types/Events.js +1 -0
  78. package/lib/Types/GroupMetadata.d.ts +67 -0
  79. package/lib/Types/Label.d.ts +47 -0
  80. package/lib/Types/Label.js +1 -3
  81. package/lib/Types/LabelAssociation.d.ts +30 -0
  82. package/lib/Types/LabelAssociation.js +1 -3
  83. package/lib/Types/Message.d.ts +305 -0
  84. package/lib/Types/Message.js +9 -5
  85. package/lib/Types/MexUpdates.js +11 -0
  86. package/lib/Types/Newsletter.d.ts +135 -0
  87. package/lib/Types/Newsletter.js +36 -11
  88. package/lib/Types/Product.d.ts +79 -0
  89. package/lib/Types/Signal.d.ts +76 -0
  90. package/lib/Types/Signal.js +1 -0
  91. package/lib/Types/Socket.d.ts +133 -0
  92. package/lib/Types/Socket.js +1 -0
  93. package/lib/Types/State.d.ts +39 -0
  94. package/lib/Types/State.js +12 -0
  95. package/lib/Types/USync.d.ts +26 -0
  96. package/lib/Types/USync.js +1 -0
  97. package/lib/Types/index.d.ts +65 -0
  98. package/lib/Types/index.js +14 -14
  99. package/lib/Utils/audioToBuffer.js +31 -0
  100. package/lib/Utils/auth-utils.d.ts +19 -0
  101. package/lib/Utils/auth-utils.js +222 -123
  102. package/lib/Utils/baileys-event-stream.js +60 -0
  103. package/lib/Utils/browser-utils.d.ts +4 -0
  104. package/lib/Utils/browser-utils.js +38 -29
  105. package/lib/Utils/business.d.ts +23 -0
  106. package/lib/Utils/business.js +54 -48
  107. package/lib/Utils/chat-utils.d.ts +70 -0
  108. package/lib/Utils/chat-utils.js +284 -189
  109. package/lib/Utils/crypto.d.ts +37 -0
  110. package/lib/Utils/crypto.js +16 -41
  111. package/lib/Utils/decode-wa-message.d.ts +48 -0
  112. package/lib/Utils/decode-wa-message.js +128 -48
  113. package/lib/Utils/event-buffer.d.ts +34 -0
  114. package/lib/Utils/event-buffer.js +124 -62
  115. package/lib/Utils/generics.d.ts +91 -0
  116. package/lib/Utils/generics.js +154 -138
  117. package/lib/Utils/history.d.ts +22 -0
  118. package/lib/Utils/history.js +77 -34
  119. package/lib/Utils/identity-change-handler.d.ts +37 -0
  120. package/lib/Utils/identity-change-handler.js +54 -0
  121. package/lib/Utils/index.d.ts +22 -0
  122. package/lib/Utils/index.js +32 -19
  123. package/lib/Utils/link-preview.d.ts +21 -0
  124. package/lib/Utils/link-preview.js +12 -17
  125. package/lib/Utils/logger.d.ts +13 -0
  126. package/lib/Utils/lt-hash.d.ts +8 -0
  127. package/lib/Utils/lt-hash.js +2 -43
  128. package/lib/Utils/make-mutex.d.ts +9 -0
  129. package/lib/Utils/make-mutex.js +21 -27
  130. package/lib/Utils/message-retry-manager.d.ts +110 -0
  131. package/lib/Utils/message-retry-manager.js +143 -45
  132. package/lib/Utils/messages-media.d.ts +130 -0
  133. package/lib/Utils/messages-media.js +429 -502
  134. package/lib/Utils/messages-newsletter.d.ts +84 -0
  135. package/lib/Utils/messages-newsletter.js +295 -0
  136. package/lib/Utils/messages.d.ts +92 -0
  137. package/lib/Utils/messages.js +1099 -400
  138. package/lib/Utils/noise-handler.d.ts +20 -0
  139. package/lib/Utils/noise-handler.js +145 -91
  140. package/lib/Utils/pre-key-manager.d.ts +28 -0
  141. package/lib/Utils/pre-key-manager.js +112 -0
  142. package/lib/Utils/process-message.d.ts +60 -0
  143. package/lib/Utils/process-message.js +316 -184
  144. package/lib/Utils/reporting-utils.d.ts +11 -0
  145. package/lib/Utils/reporting-utils.js +262 -0
  146. package/lib/Utils/resolve-jid.d.ts +43 -0
  147. package/lib/Utils/resolve-jid.js +95 -0
  148. package/lib/Utils/serial-task-queue.js +29 -0
  149. package/lib/Utils/signal.d.ts +34 -0
  150. package/lib/Utils/signal.js +56 -39
  151. package/lib/Utils/streamToBuffer.js +17 -0
  152. package/lib/Utils/sync-action-utils.d.ts +19 -0
  153. package/lib/Utils/sync-action-utils.js +52 -0
  154. package/lib/Utils/tc-token-utils.d.ts +12 -0
  155. package/lib/Utils/tc-token-utils.js +20 -0
  156. package/lib/Utils/use-mongo-file-auth-state.js +71 -0
  157. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  158. package/lib/Utils/use-multi-file-auth-state.js +11 -12
  159. package/lib/Utils/use-single-file-auth-state.js +73 -0
  160. package/lib/Utils/validate-connection.d.ts +11 -0
  161. package/lib/Utils/validate-connection.js +59 -82
  162. package/lib/Utils/wileys-event-stream.js +1 -61
  163. package/lib/WABinary/constants.d.ts +28 -0
  164. package/lib/WABinary/decode.d.ts +7 -0
  165. package/lib/WABinary/decode.js +39 -4
  166. package/lib/WABinary/encode.d.ts +3 -0
  167. package/lib/WABinary/encode.js +17 -11
  168. package/lib/WABinary/generic-utils.d.ts +15 -0
  169. package/lib/WABinary/generic-utils.js +46 -18
  170. package/lib/WABinary/index.d.ts +6 -0
  171. package/lib/WABinary/index.js +9 -5
  172. package/lib/WABinary/jid-utils.d.ts +48 -0
  173. package/lib/WABinary/jid-utils.js +67 -37
  174. package/lib/WABinary/types.d.ts +19 -0
  175. package/lib/WABinary/types.js +34 -0
  176. package/lib/WAM/BinaryInfo.d.ts +9 -0
  177. package/lib/WAM/constants.d.ts +40 -0
  178. package/lib/WAM/constants.js +19183 -11678
  179. package/lib/WAM/encode.d.ts +3 -0
  180. package/lib/WAM/encode.js +15 -17
  181. package/lib/WAM/index.d.ts +4 -0
  182. package/lib/WAM/index.js +3 -3
  183. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  184. package/lib/WAUSync/Protocols/USyncContactProtocol.js +6 -6
  185. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  186. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +9 -9
  187. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  188. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +6 -6
  189. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  190. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +7 -8
  191. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  192. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +18 -17
  193. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  194. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +11 -3
  195. package/lib/WAUSync/Protocols/index.d.ts +5 -0
  196. package/lib/WAUSync/Protocols/index.js +6 -4
  197. package/lib/WAUSync/USyncQuery.d.ts +29 -0
  198. package/lib/WAUSync/USyncQuery.js +38 -30
  199. package/lib/WAUSync/USyncUser.d.ts +13 -0
  200. package/lib/WAUSync/index.d.ts +4 -0
  201. package/lib/WAUSync/index.js +3 -3
  202. package/lib/index.d.ts +12 -0
  203. package/lib/index.js +3 -5
  204. package/package.json +10 -6
  205. package/readme.md +97 -0
  206. package/LICENSE +0 -21
@@ -0,0 +1,20 @@
1
+ import { proto } from '../../WAProto/index.js';
2
+ import type { KeyPair } from '../Types/index.js';
3
+ import type { BinaryNode } from '../WABinary/index.js';
4
+ import type { ILogger } from './logger.js';
5
+ export declare const makeNoiseHandler: ({ keyPair: { private: privateKey, public: publicKey }, NOISE_HEADER, logger, routingInfo }: {
6
+ keyPair: KeyPair;
7
+ NOISE_HEADER: Uint8Array;
8
+ logger: ILogger;
9
+ routingInfo?: Buffer | undefined;
10
+ }) => {
11
+ encrypt: (plaintext: Uint8Array) => Uint8Array;
12
+ decrypt: (ciphertext: Uint8Array) => Uint8Array;
13
+ authenticate: (data: Uint8Array) => void;
14
+ mixIntoKey: (data: Uint8Array) => void;
15
+ finishInit: () => Promise<void>;
16
+ processHandshake: ({ serverHello }: proto.HandshakeMessage, noiseKey: KeyPair) => Uint8Array<ArrayBufferLike>;
17
+ encodeFrame: (data: Buffer | Uint8Array) => Buffer<ArrayBuffer>;
18
+ decodeFrame: (newData: Buffer | Uint8Array, onFrame: (buff: Uint8Array | BinaryNode) => void) => Promise<void>;
19
+ };
20
+ //# sourceMappingURL=noise-handler.d.ts.map
@@ -2,73 +2,133 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.makeNoiseHandler = void 0;
4
4
  const boom_1 = require("@hapi/boom");
5
- const WAProto_1 = require("../../WAProto");
6
- const Defaults_1 = require("../Defaults");
7
- const WABinary_1 = require("../WABinary");
8
- const crypto_1 = require("./crypto");
5
+ const index_js_1 = require("../../WAProto/index.js");
6
+ const index_js_2 = require("../Defaults/index.js");
7
+ const index_js_3 = require("../WABinary/index.js");
8
+ const crypto_js_1 = require("./crypto.js");
9
+ const IV_LENGTH = 12;
10
+ const EMPTY_BUFFER = Buffer.alloc(0);
9
11
  const generateIV = (counter) => {
10
- const iv = new ArrayBuffer(12);
12
+ const iv = new ArrayBuffer(IV_LENGTH);
11
13
  new DataView(iv).setUint32(8, counter);
12
14
  return new Uint8Array(iv);
13
15
  };
16
+ class TransportState {
17
+ constructor(encKey, decKey) {
18
+ this.encKey = encKey;
19
+ this.decKey = decKey;
20
+ this.readCounter = 0;
21
+ this.writeCounter = 0;
22
+ this.iv = new Uint8Array(IV_LENGTH);
23
+ }
24
+ encrypt(plaintext) {
25
+ const c = this.writeCounter++;
26
+ this.iv[8] = (c >>> 24) & 0xff;
27
+ this.iv[9] = (c >>> 16) & 0xff;
28
+ this.iv[10] = (c >>> 8) & 0xff;
29
+ this.iv[11] = c & 0xff;
30
+ return (0, crypto_js_1.aesEncryptGCM)(plaintext, this.encKey, this.iv, EMPTY_BUFFER);
31
+ }
32
+ decrypt(ciphertext) {
33
+ const c = this.readCounter++;
34
+ this.iv[8] = (c >>> 24) & 0xff;
35
+ this.iv[9] = (c >>> 16) & 0xff;
36
+ this.iv[10] = (c >>> 8) & 0xff;
37
+ this.iv[11] = c & 0xff;
38
+ return (0, crypto_js_1.aesDecryptGCM)(ciphertext, this.decKey, this.iv, EMPTY_BUFFER);
39
+ }
40
+ }
14
41
  const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publicKey }, NOISE_HEADER, logger, routingInfo }) => {
15
42
  logger = logger.child({ class: 'ns' });
43
+ const data = Buffer.from(index_js_2.NOISE_MODE);
44
+ let hash = data.byteLength === 32 ? data : (0, crypto_js_1.sha256)(data);
45
+ let salt = hash;
46
+ let encKey = hash;
47
+ let decKey = hash;
48
+ let counter = 0;
49
+ let sentIntro = false;
50
+ let inBytes = Buffer.alloc(0);
51
+ let transport = null;
52
+ let isWaitingForTransport = false;
53
+ let pendingOnFrame = null;
54
+ let introHeader;
55
+ if (routingInfo) {
56
+ introHeader = Buffer.alloc(7 + routingInfo.byteLength + NOISE_HEADER.length);
57
+ introHeader.write('ED', 0, 'utf8');
58
+ introHeader.writeUint8(0, 2);
59
+ introHeader.writeUint8(1, 3);
60
+ introHeader.writeUint8(routingInfo.byteLength >> 16, 4);
61
+ introHeader.writeUint16BE(routingInfo.byteLength & 65535, 5);
62
+ introHeader.set(routingInfo, 7);
63
+ introHeader.set(NOISE_HEADER, 7 + routingInfo.byteLength);
64
+ }
65
+ else {
66
+ introHeader = Buffer.from(NOISE_HEADER);
67
+ }
16
68
  const authenticate = (data) => {
17
- if (!isFinished) {
18
- hash = (0, crypto_1.sha256)(Buffer.concat([hash, data]));
69
+ if (!transport) {
70
+ hash = (0, crypto_js_1.sha256)(Buffer.concat([hash, data]));
19
71
  }
20
72
  };
21
73
  const encrypt = (plaintext) => {
22
- const result = (0, crypto_1.aesEncryptGCM)(plaintext, encKey, generateIV(writeCounter), hash);
23
- writeCounter += 1;
74
+ if (transport) {
75
+ return transport.encrypt(plaintext);
76
+ }
77
+ const result = (0, crypto_js_1.aesEncryptGCM)(plaintext, encKey, generateIV(counter++), hash);
24
78
  authenticate(result);
25
79
  return result;
26
80
  };
27
81
  const decrypt = (ciphertext) => {
28
- // before the handshake is finished, we use the same counter
29
- // after handshake, the counters are different
30
- const iv = generateIV(isFinished ? readCounter : writeCounter);
31
- const result = (0, crypto_1.aesDecryptGCM)(ciphertext, decKey, iv, hash);
32
- if (isFinished) {
33
- readCounter += 1;
34
- }
35
- else {
36
- writeCounter += 1;
82
+ if (transport) {
83
+ return transport.decrypt(ciphertext);
37
84
  }
85
+ const result = (0, crypto_js_1.aesDecryptGCM)(ciphertext, decKey, generateIV(counter++), hash);
38
86
  authenticate(ciphertext);
39
87
  return result;
40
88
  };
41
- const localHKDF = async (data) => {
42
- const key = await (0, crypto_1.hkdf)(Buffer.from(data), 64, { salt, info: '' });
43
- return [key.slice(0, 32), key.slice(32)];
89
+ const localHKDF = (data) => {
90
+ const key = (0, crypto_js_1.hkdf)(Buffer.from(data), 64, { salt, info: '' });
91
+ return [key.subarray(0, 32), key.subarray(32)];
44
92
  };
45
- const mixIntoKey = async (data) => {
46
- const [write, read] = await localHKDF(data);
93
+ const mixIntoKey = (data) => {
94
+ const [write, read] = localHKDF(data);
47
95
  salt = write;
48
96
  encKey = read;
49
97
  decKey = read;
50
- readCounter = 0;
51
- writeCounter = 0;
98
+ counter = 0;
52
99
  };
53
100
  const finishInit = async () => {
54
- const [write, read] = await localHKDF(new Uint8Array(0));
55
- encKey = write;
56
- decKey = read;
57
- hash = Buffer.from([]);
58
- readCounter = 0;
59
- writeCounter = 0;
60
- isFinished = true;
101
+ isWaitingForTransport = true;
102
+ const [write, read] = localHKDF(new Uint8Array(0));
103
+ transport = new TransportState(write, read);
104
+ isWaitingForTransport = false;
105
+ logger.trace('Noise handler transitioned to Transport state');
106
+ if (pendingOnFrame) {
107
+ logger.trace({ length: inBytes.length }, 'Flushing buffered frames after transport ready');
108
+ await processData(pendingOnFrame);
109
+ pendingOnFrame = null;
110
+ }
111
+ };
112
+ const processData = async (onFrame) => {
113
+ let size;
114
+ while (true) {
115
+ if (inBytes.length < 3)
116
+ return;
117
+ size = (inBytes[0] << 16) | (inBytes[1] << 8) | inBytes[2];
118
+ if (inBytes.length < size + 3)
119
+ return;
120
+ let frame = inBytes.subarray(3, size + 3);
121
+ inBytes = inBytes.subarray(size + 3);
122
+ if (transport) {
123
+ const result = transport.decrypt(frame);
124
+ frame = await (0, index_js_3.decodeBinaryNode)(result);
125
+ }
126
+ if (logger.level === 'trace') {
127
+ logger.trace({ msg: frame?.attrs?.id }, 'recv frame');
128
+ }
129
+ onFrame(frame);
130
+ }
61
131
  };
62
- const data = Buffer.from(Defaults_1.NOISE_MODE);
63
- let hash = data.byteLength === 32 ? data : (0, crypto_1.sha256)(data);
64
- let salt = hash;
65
- let encKey = hash;
66
- let decKey = hash;
67
- let readCounter = 0;
68
- let writeCounter = 0;
69
- let isFinished = false;
70
- let sentIntro = false;
71
- let inBytes = Buffer.alloc(0);
72
132
  authenticate(NOISE_HEADER);
73
133
  authenticate(publicKey);
74
134
  return {
@@ -77,73 +137,67 @@ const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publicKey },
77
137
  authenticate,
78
138
  mixIntoKey,
79
139
  finishInit,
80
- processHandshake: async ({ serverHello }, noiseKey) => {
140
+ processHandshake: ({ serverHello }, noiseKey) => {
81
141
  authenticate(serverHello.ephemeral);
82
- await mixIntoKey(crypto_1.Curve.sharedKey(privateKey, serverHello.ephemeral));
142
+ mixIntoKey(crypto_js_1.Curve.sharedKey(privateKey, serverHello.ephemeral));
83
143
  const decStaticContent = decrypt(serverHello.static);
84
- await mixIntoKey(crypto_1.Curve.sharedKey(privateKey, decStaticContent));
144
+ mixIntoKey(crypto_js_1.Curve.sharedKey(privateKey, decStaticContent));
85
145
  const certDecoded = decrypt(serverHello.payload);
86
- const { intermediate: certIntermediate } = WAProto_1.proto.CertChain.decode(certDecoded);
87
- const { issuerSerial } = WAProto_1.proto.CertChain.NoiseCertificate.Details.decode(certIntermediate.details);
88
- if (issuerSerial !== Defaults_1.WA_CERT_DETAILS.SERIAL) {
146
+ const { intermediate: certIntermediate, leaf } = index_js_1.proto.CertChain.decode(certDecoded);
147
+ // leaf
148
+ if (!leaf?.details || !leaf?.signature) {
149
+ throw new boom_1.Boom('invalid noise leaf certificate', { statusCode: 400 });
150
+ }
151
+ if (!certIntermediate?.details || !certIntermediate?.signature) {
152
+ throw new boom_1.Boom('invalid noise intermediate certificate', { statusCode: 400 });
153
+ }
154
+ const details = index_js_1.proto.CertChain.NoiseCertificate.Details.decode(certIntermediate.details);
155
+ const { issuerSerial } = details;
156
+ const verify = crypto_js_1.Curve.verify(details.key, leaf.details, leaf.signature);
157
+ const verifyIntermediate = crypto_js_1.Curve.verify(index_js_2.WA_CERT_DETAILS.PUBLIC_KEY, certIntermediate.details, certIntermediate.signature);
158
+ if (!verify) {
159
+ throw new boom_1.Boom('noise certificate signature invalid', { statusCode: 400 });
160
+ }
161
+ if (!verifyIntermediate) {
162
+ throw new boom_1.Boom('noise intermediate certificate signature invalid', { statusCode: 400 });
163
+ }
164
+ if (issuerSerial !== index_js_2.WA_CERT_DETAILS.SERIAL) {
89
165
  throw new boom_1.Boom('certification match failed', { statusCode: 400 });
90
166
  }
91
167
  const keyEnc = encrypt(noiseKey.public);
92
- await mixIntoKey(crypto_1.Curve.sharedKey(noiseKey.private, serverHello.ephemeral));
168
+ mixIntoKey(crypto_js_1.Curve.sharedKey(noiseKey.private, serverHello.ephemeral));
93
169
  return keyEnc;
94
170
  },
95
171
  encodeFrame: (data) => {
96
- if (isFinished) {
97
- data = encrypt(data);
98
- }
99
- let header;
100
- if (routingInfo) {
101
- header = Buffer.alloc(7);
102
- header.write('ED', 0, 'utf8');
103
- header.writeUint8(0, 2);
104
- header.writeUint8(1, 3);
105
- header.writeUint8(routingInfo.byteLength >> 16, 4);
106
- header.writeUint16BE(routingInfo.byteLength & 65535, 5);
107
- header = Buffer.concat([header, routingInfo, NOISE_HEADER]);
108
- }
109
- else {
110
- header = Buffer.from(NOISE_HEADER);
172
+ if (transport) {
173
+ data = transport.encrypt(data);
111
174
  }
112
- const introSize = sentIntro ? 0 : header.length;
113
- const frame = Buffer.alloc(introSize + 3 + data.byteLength);
175
+ const dataLen = data.byteLength;
176
+ const introSize = sentIntro ? 0 : introHeader.length;
177
+ const frame = Buffer.allocUnsafe(introSize + 3 + dataLen);
114
178
  if (!sentIntro) {
115
- frame.set(header);
179
+ frame.set(introHeader);
116
180
  sentIntro = true;
117
181
  }
118
- frame.writeUInt8(data.byteLength >> 16, introSize);
119
- frame.writeUInt16BE(65535 & data.byteLength, introSize + 1);
182
+ frame[introSize] = (dataLen >>> 16) & 0xff;
183
+ frame[introSize + 1] = (dataLen >>> 8) & 0xff;
184
+ frame[introSize + 2] = dataLen & 0xff;
120
185
  frame.set(data, introSize + 3);
121
186
  return frame;
122
187
  },
123
188
  decodeFrame: async (newData, onFrame) => {
124
- var _a;
125
- // the binary protocol uses its own framing mechanism
126
- // on top of the WS frames
127
- // so we get this data and separate out the frames
128
- const getBytesSize = () => {
129
- if (inBytes.length >= 3) {
130
- return (inBytes.readUInt8() << 16) | inBytes.readUInt16BE(1);
131
- }
132
- };
133
- inBytes = Buffer.concat([inBytes, newData]);
134
- logger.trace(`recv ${newData.length} bytes, total recv ${inBytes.length} bytes`);
135
- let size = getBytesSize();
136
- while (size && inBytes.length >= size + 3) {
137
- let frame = inBytes.slice(3, size + 3);
138
- inBytes = inBytes.slice(size + 3);
139
- if (isFinished) {
140
- const result = decrypt(frame);
141
- frame = await (0, WABinary_1.decodeBinaryNode)(result);
142
- }
143
- logger.trace({ msg: (_a = frame === null || frame === void 0 ? void 0 : frame.attrs) === null || _a === void 0 ? void 0 : _a.id }, 'recv frame');
144
- onFrame(frame);
145
- size = getBytesSize();
189
+ if (isWaitingForTransport) {
190
+ inBytes = Buffer.concat([inBytes, newData]);
191
+ pendingOnFrame = onFrame;
192
+ return;
193
+ }
194
+ if (inBytes.length === 0) {
195
+ inBytes = Buffer.from(newData);
196
+ }
197
+ else {
198
+ inBytes = Buffer.concat([inBytes, newData]);
146
199
  }
200
+ await processData(onFrame);
147
201
  }
148
202
  };
149
203
  };
@@ -0,0 +1,28 @@
1
+ import type { SignalDataSet, SignalDataTypeMap, SignalKeyStore } from '../Types/index.js';
2
+ import type { ILogger } from './logger.js';
3
+ /**
4
+ * Manages pre-key operations with proper concurrency control
5
+ */
6
+ export declare class PreKeyManager {
7
+ private readonly store;
8
+ private readonly logger;
9
+ private readonly queues;
10
+ constructor(store: SignalKeyStore, logger: ILogger);
11
+ /**
12
+ * Get or create a queue for a specific key type
13
+ */
14
+ private getQueue;
15
+ /**
16
+ * Process pre-key operations (updates and deletions)
17
+ */
18
+ processOperations(data: SignalDataSet, keyType: keyof SignalDataTypeMap, transactionCache: SignalDataSet, mutations: SignalDataSet, isInTransaction: boolean): Promise<void>;
19
+ /**
20
+ * Process deletions with validation
21
+ */
22
+ private processDeletions;
23
+ /**
24
+ * Validate and process pre-key deletions outside transactions
25
+ */
26
+ validateDeletions(data: SignalDataSet, keyType: keyof SignalDataTypeMap): Promise<void>;
27
+ }
28
+ //# sourceMappingURL=pre-key-manager.d.ts.map
@@ -0,0 +1,112 @@
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.PreKeyManager = void 0;
7
+ const serial_task_queue_js_1 = __importDefault(require("./serial-task-queue.js"));
8
+ /**
9
+ * Manages pre-key operations with proper concurrency control
10
+ */
11
+ class PreKeyManager {
12
+ constructor(store, logger) {
13
+ this.store = store;
14
+ this.logger = logger;
15
+ this.queues = new Map();
16
+ }
17
+ /**
18
+ * Get or create a queue for a specific key type
19
+ */
20
+ getQueue(keyType) {
21
+ if (!this.queues.has(keyType)) {
22
+ this.queues.set(keyType, new serial_task_queue_js_1.default({ concurrency: 1 }));
23
+ }
24
+ return this.queues.get(keyType);
25
+ }
26
+ /**
27
+ * Process pre-key operations (updates and deletions)
28
+ */
29
+ async processOperations(data, keyType, transactionCache, mutations, isInTransaction) {
30
+ const keyData = data[keyType];
31
+ if (!keyData)
32
+ return;
33
+ return this.getQueue(keyType).add(async () => {
34
+ // Ensure structures exist
35
+ transactionCache[keyType] = transactionCache[keyType] || {};
36
+ mutations[keyType] = mutations[keyType] || {};
37
+ // Separate deletions from updates
38
+ const deletions = [];
39
+ const updates = {};
40
+ for (const keyId in keyData) {
41
+ if (keyData[keyId] === null) {
42
+ deletions.push(keyId);
43
+ }
44
+ else {
45
+ updates[keyId] = keyData[keyId];
46
+ }
47
+ }
48
+ // Process updates (no validation needed)
49
+ if (Object.keys(updates).length > 0) {
50
+ Object.assign(transactionCache[keyType], updates);
51
+ Object.assign(mutations[keyType], updates);
52
+ }
53
+ // Process deletions with validation
54
+ if (deletions.length > 0) {
55
+ await this.processDeletions(keyType, deletions, transactionCache, mutations, isInTransaction);
56
+ }
57
+ });
58
+ }
59
+ /**
60
+ * Process deletions with validation
61
+ */
62
+ async processDeletions(keyType, ids, transactionCache, mutations, isInTransaction) {
63
+ if (isInTransaction) {
64
+ // In transaction, only allow deletion if key exists in cache
65
+ for (const keyId of ids) {
66
+ if (transactionCache[keyType]?.[keyId]) {
67
+ transactionCache[keyType][keyId] = null;
68
+ mutations[keyType][keyId] = null;
69
+ }
70
+ else {
71
+ this.logger.warn(`Skipping deletion of non-existent ${keyType} in transaction: ${keyId}`);
72
+ }
73
+ }
74
+ }
75
+ else {
76
+ // Outside transaction, validate against store
77
+ const existingKeys = await this.store.get(keyType, ids);
78
+ for (const keyId of ids) {
79
+ if (existingKeys[keyId]) {
80
+ transactionCache[keyType][keyId] = null;
81
+ mutations[keyType][keyId] = null;
82
+ }
83
+ else {
84
+ this.logger.warn(`Skipping deletion of non-existent ${keyType}: ${keyId}`);
85
+ }
86
+ }
87
+ }
88
+ }
89
+ /**
90
+ * Validate and process pre-key deletions outside transactions
91
+ */
92
+ async validateDeletions(data, keyType) {
93
+ const keyData = data[keyType];
94
+ if (!keyData)
95
+ return;
96
+ return this.getQueue(keyType).add(async () => {
97
+ // Find all deletion requests
98
+ const deletionIds = Object.keys(keyData).filter(id => keyData[id] === null);
99
+ if (deletionIds.length === 0)
100
+ return;
101
+ // Validate deletions
102
+ const existingKeys = await this.store.get(keyType, deletionIds);
103
+ for (const keyId of deletionIds) {
104
+ if (!existingKeys[keyId]) {
105
+ this.logger.warn(`Skipping deletion of non-existent ${keyType}: ${keyId}`);
106
+ delete data[keyType][keyId];
107
+ }
108
+ }
109
+ });
110
+ }
111
+ }
112
+ exports.PreKeyManager = PreKeyManager;
@@ -0,0 +1,60 @@
1
+ import { proto } from '../../WAProto/index.js';
2
+ import type { AuthenticationCreds, BaileysEventEmitter, CacheStore, SignalKeyStoreWithTransaction, SignalRepositoryWithLIDStore, SocketConfig, WAMessage, WAMessageKey } from '../Types/index.js';
3
+ import type { ILogger } from './logger.js';
4
+ type ProcessMessageContext = {
5
+ shouldProcessHistoryMsg: boolean;
6
+ placeholderResendCache?: CacheStore;
7
+ creds: AuthenticationCreds;
8
+ keyStore: SignalKeyStoreWithTransaction;
9
+ ev: BaileysEventEmitter;
10
+ logger?: ILogger;
11
+ options: RequestInit;
12
+ signalRepository: SignalRepositoryWithLIDStore;
13
+ getMessage: SocketConfig['getMessage'];
14
+ };
15
+ /** Cleans a received message to further processing */
16
+ export declare const cleanMessage: (message: WAMessage, meId: string, meLid: string) => void;
17
+ export declare const isRealMessage: (message: WAMessage) => boolean;
18
+ export declare const shouldIncrementChatUnread: (message: WAMessage) => boolean;
19
+ /**
20
+ * Get the ID of the chat from the given key.
21
+ * Typically -- that'll be the remoteJid, but for broadcasts, it'll be the participant
22
+ */
23
+ export declare const getChatId: ({ remoteJid, participant, fromMe }: WAMessageKey) => string;
24
+ type PollContext = {
25
+ /** normalised jid of the person that created the poll */
26
+ pollCreatorJid: string;
27
+ /** ID of the poll creation message */
28
+ pollMsgId: string;
29
+ /** poll creation message enc key */
30
+ pollEncKey: Uint8Array;
31
+ /** jid of the person that voted */
32
+ voterJid: string;
33
+ };
34
+ type EventContext = {
35
+ /** normalised jid of the person that created the event */
36
+ eventCreatorJid: string;
37
+ /** ID of the event creation message */
38
+ eventMsgId: string;
39
+ /** event creation message enc key */
40
+ eventEncKey: Uint8Array;
41
+ /** jid of the person that responded */
42
+ responderJid: string;
43
+ };
44
+ /**
45
+ * Decrypt a poll vote
46
+ * @param vote encrypted vote
47
+ * @param ctx additional info about the poll required for decryption
48
+ * @returns list of SHA256 options
49
+ */
50
+ export declare function decryptPollVote({ encPayload, encIv }: proto.Message.IPollEncValue, { pollCreatorJid, pollMsgId, pollEncKey, voterJid }: PollContext): proto.Message.PollVoteMessage;
51
+ /**
52
+ * Decrypt an event response
53
+ * @param response encrypted event response
54
+ * @param ctx additional info about the event required for decryption
55
+ * @returns event response message
56
+ */
57
+ export declare function decryptEventResponse({ encPayload, encIv }: proto.Message.IPollEncValue, { eventCreatorJid, eventMsgId, eventEncKey, responderJid }: EventContext): proto.Message.EventResponseMessage;
58
+ declare const processMessage: (message: WAMessage, { shouldProcessHistoryMsg, placeholderResendCache, ev, creds, signalRepository, keyStore, logger, options, getMessage }: ProcessMessageContext) => Promise<void>;
59
+ export default processMessage;
60
+ //# sourceMappingURL=process-message.d.ts.map