@sgintokic/baileys 0.0.2

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.

Potentially problematic release.


This version of @sgintokic/baileys might be problematic. Click here for more details.

Files changed (106) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +1097 -0
  3. package/WAProto/index.js +2 -0
  4. package/engine-requirements.js +1 -0
  5. package/lib/Defaults/index.js +155 -0
  6. package/lib/Signal/Group/ciphertext-message.js +11 -0
  7. package/lib/Signal/Group/group-session-builder.js +41 -0
  8. package/lib/Signal/Group/group_cipher.js +108 -0
  9. package/lib/Signal/Group/index.js +11 -0
  10. package/lib/Signal/Group/keyhelper.js +14 -0
  11. package/lib/Signal/Group/sender-chain-key.js +31 -0
  12. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  13. package/lib/Signal/Group/sender-key-message.js +79 -0
  14. package/lib/Signal/Group/sender-key-name.js +49 -0
  15. package/lib/Signal/Group/sender-key-record.js +46 -0
  16. package/lib/Signal/Group/sender-key-state.js +104 -0
  17. package/lib/Signal/Group/sender-message-key.js +29 -0
  18. package/lib/Signal/libsignal.js +485 -0
  19. package/lib/Signal/lid-mapping.js +291 -0
  20. package/lib/Socket/Client/index.js +2 -0
  21. package/lib/Socket/Client/types.js +10 -0
  22. package/lib/Socket/Client/websocket.js +64 -0
  23. package/lib/Socket/business.js +293 -0
  24. package/lib/Socket/chats.js +1068 -0
  25. package/lib/Socket/communities.js +476 -0
  26. package/lib/Socket/groups.js +383 -0
  27. package/lib/Socket/index.js +8 -0
  28. package/lib/Socket/messages-recv.js +1830 -0
  29. package/lib/Socket/messages-send.js +1462 -0
  30. package/lib/Socket/mex.js +55 -0
  31. package/lib/Socket/newsletter.js +277 -0
  32. package/lib/Socket/socket.js +1087 -0
  33. package/lib/Store/index.js +3 -0
  34. package/lib/Store/make-in-memory-store.js +517 -0
  35. package/lib/Store/make-ordered-dictionary.js +75 -0
  36. package/lib/Store/object-repository.js +23 -0
  37. package/lib/Types/Auth.js +1 -0
  38. package/lib/Types/Bussines.js +1 -0
  39. package/lib/Types/Call.js +1 -0
  40. package/lib/Types/Chat.js +7 -0
  41. package/lib/Types/Contact.js +1 -0
  42. package/lib/Types/Events.js +1 -0
  43. package/lib/Types/GroupMetadata.js +1 -0
  44. package/lib/Types/Label.js +24 -0
  45. package/lib/Types/LabelAssociation.js +6 -0
  46. package/lib/Types/Message.js +18 -0
  47. package/lib/Types/Newsletter.js +33 -0
  48. package/lib/Types/Product.js +1 -0
  49. package/lib/Types/Signal.js +1 -0
  50. package/lib/Types/Socket.js +2 -0
  51. package/lib/Types/State.js +15 -0
  52. package/lib/Types/USync.js +1 -0
  53. package/lib/Types/index.js +31 -0
  54. package/lib/Utils/auth-utils.js +293 -0
  55. package/lib/Utils/browser-utils.js +32 -0
  56. package/lib/Utils/business.js +245 -0
  57. package/lib/Utils/chat-utils.js +959 -0
  58. package/lib/Utils/crypto.js +133 -0
  59. package/lib/Utils/decode-wa-message.js +376 -0
  60. package/lib/Utils/event-buffer.js +620 -0
  61. package/lib/Utils/generics.js +417 -0
  62. package/lib/Utils/history.js +150 -0
  63. package/lib/Utils/identity-change-handler.js +63 -0
  64. package/lib/Utils/index.js +21 -0
  65. package/lib/Utils/link-preview.js +91 -0
  66. package/lib/Utils/logger.js +2 -0
  67. package/lib/Utils/lt-hash.js +6 -0
  68. package/lib/Utils/make-mutex.js +31 -0
  69. package/lib/Utils/message-retry-manager.js +240 -0
  70. package/lib/Utils/messages-media.js +901 -0
  71. package/lib/Utils/messages.js +2052 -0
  72. package/lib/Utils/noise-handler.js +229 -0
  73. package/lib/Utils/offline-node-processor.js +50 -0
  74. package/lib/Utils/pre-key-manager.js +119 -0
  75. package/lib/Utils/process-message.js +641 -0
  76. package/lib/Utils/reporting-utils.js +346 -0
  77. package/lib/Utils/signal.js +188 -0
  78. package/lib/Utils/stanza-ack.js +33 -0
  79. package/lib/Utils/sync-action-utils.js +53 -0
  80. package/lib/Utils/tc-token-utils.js +15 -0
  81. package/lib/Utils/use-multi-file-auth-state.js +116 -0
  82. package/lib/Utils/use-single-file-auth-state.js +94 -0
  83. package/lib/Utils/validate-connection.js +235 -0
  84. package/lib/WABinary/constants.js +1300 -0
  85. package/lib/WABinary/decode.js +258 -0
  86. package/lib/WABinary/encode.js +219 -0
  87. package/lib/WABinary/generic-utils.js +203 -0
  88. package/lib/WABinary/index.js +5 -0
  89. package/lib/WABinary/jid-utils.js +93 -0
  90. package/lib/WABinary/types.js +1 -0
  91. package/lib/WAM/BinaryInfo.js +9 -0
  92. package/lib/WAM/constants.js +20669 -0
  93. package/lib/WAM/encode.js +151 -0
  94. package/lib/WAM/index.js +3 -0
  95. package/lib/WAUSync/Protocols/USyncContactProtocol.js +21 -0
  96. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +50 -0
  97. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +20 -0
  98. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +29 -0
  99. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +59 -0
  100. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +21 -0
  101. package/lib/WAUSync/Protocols/index.js +4 -0
  102. package/lib/WAUSync/USyncQuery.js +103 -0
  103. package/lib/WAUSync/USyncUser.js +22 -0
  104. package/lib/WAUSync/index.js +3 -0
  105. package/lib/index.js +11 -0
  106. package/package.json +58 -0
@@ -0,0 +1,229 @@
1
+ import { Boom } from "@hapi/boom";
2
+ import { proto } from "../../WAProto/index.js";
3
+ import { NOISE_MODE, WA_CERT_DETAILS } from "../Defaults/index.js";
4
+ import { decodeBinaryNode } from "../WABinary/index.js";
5
+ import { aesDecryptGCM, aesEncryptGCM, Curve, hkdf, sha256 } from "./crypto.js";
6
+ const IV_LENGTH = 12;
7
+ const EMPTY_BUFFER = Buffer.alloc(0);
8
+ const generateIV = (counter) => {
9
+ const iv = new ArrayBuffer(IV_LENGTH);
10
+ new DataView(iv).setUint32(8, counter);
11
+ return new Uint8Array(iv);
12
+ };
13
+ class TransportState {
14
+ constructor(encKey, decKey) {
15
+ this.encKey = encKey;
16
+ this.decKey = decKey;
17
+ this.readCounter = 0;
18
+ this.writeCounter = 0;
19
+ this.iv = new Uint8Array(IV_LENGTH);
20
+ }
21
+ encrypt(plaintext) {
22
+ const c = this.writeCounter++;
23
+ this.iv[8] = (c >>> 24) & 255;
24
+ this.iv[9] = (c >>> 16) & 255;
25
+ this.iv[10] = (c >>> 8) & 255;
26
+ this.iv[11] = c & 255;
27
+ return aesEncryptGCM(plaintext, this.encKey, this.iv, EMPTY_BUFFER);
28
+ }
29
+ decrypt(ciphertext) {
30
+ const c = this.readCounter++;
31
+ this.iv[8] = (c >>> 24) & 255;
32
+ this.iv[9] = (c >>> 16) & 255;
33
+ this.iv[10] = (c >>> 8) & 255;
34
+ this.iv[11] = c & 255;
35
+ return aesDecryptGCM(ciphertext, this.decKey, this.iv, EMPTY_BUFFER);
36
+ }
37
+ }
38
+ export const makeNoiseHandler = ({
39
+ keyPair: { private: privateKey, public: publicKey },
40
+ NOISE_HEADER,
41
+ logger,
42
+ routingInfo,
43
+ }) => {
44
+ logger = logger.child({ class: "ns" });
45
+ const data = Buffer.from(NOISE_MODE);
46
+ let hash = data.byteLength === 32 ? data : sha256(data);
47
+ let salt = hash;
48
+ let encKey = hash;
49
+ let decKey = hash;
50
+ let counter = 0;
51
+ let sentIntro = false;
52
+ let inBytes = Buffer.alloc(0);
53
+ let transport = null;
54
+ let isWaitingForTransport = false;
55
+ let pendingOnFrame = null;
56
+ let introHeader;
57
+ if (routingInfo) {
58
+ introHeader = Buffer.alloc(
59
+ 7 + routingInfo.byteLength + NOISE_HEADER.length,
60
+ );
61
+ introHeader.write("ED", 0, "utf8");
62
+ introHeader.writeUint8(0, 2);
63
+ introHeader.writeUint8(1, 3);
64
+ introHeader.writeUint8(routingInfo.byteLength >> 16, 4);
65
+ introHeader.writeUint16BE(routingInfo.byteLength & 65535, 5);
66
+ introHeader.set(routingInfo, 7);
67
+ introHeader.set(NOISE_HEADER, 7 + routingInfo.byteLength);
68
+ } else {
69
+ introHeader = Buffer.from(NOISE_HEADER);
70
+ }
71
+ const authenticate = (data) => {
72
+ if (!transport) {
73
+ hash = sha256(Buffer.concat([hash, data]));
74
+ }
75
+ };
76
+ const encrypt = (plaintext) => {
77
+ if (transport) {
78
+ return transport.encrypt(plaintext);
79
+ }
80
+ const result = aesEncryptGCM(
81
+ plaintext,
82
+ encKey,
83
+ generateIV(counter++),
84
+ hash,
85
+ );
86
+ authenticate(result);
87
+ return result;
88
+ };
89
+ const decrypt = (ciphertext) => {
90
+ if (transport) {
91
+ return transport.decrypt(ciphertext);
92
+ }
93
+ const result = aesDecryptGCM(
94
+ ciphertext,
95
+ decKey,
96
+ generateIV(counter++),
97
+ hash,
98
+ );
99
+ authenticate(ciphertext);
100
+ return result;
101
+ };
102
+ const localHKDF = (data) => {
103
+ const key = hkdf(Buffer.from(data), 64, { salt: salt, info: "" });
104
+ return [key.subarray(0, 32), key.subarray(32)];
105
+ };
106
+ const mixIntoKey = (data) => {
107
+ const [write, read] = localHKDF(data);
108
+ salt = write;
109
+ encKey = read;
110
+ decKey = read;
111
+ counter = 0;
112
+ };
113
+ const finishInit = async () => {
114
+ isWaitingForTransport = true;
115
+ const [write, read] = localHKDF(new Uint8Array(0));
116
+ transport = new TransportState(write, read);
117
+ isWaitingForTransport = false;
118
+ logger.trace("Noise handler transitioned to Transport state");
119
+ if (pendingOnFrame) {
120
+ logger.trace(
121
+ { length: inBytes.length },
122
+ "Flushing buffered frames after transport ready",
123
+ );
124
+ await processData(pendingOnFrame);
125
+ pendingOnFrame = null;
126
+ }
127
+ };
128
+ const processData = async (onFrame) => {
129
+ let size;
130
+ while (true) {
131
+ if (inBytes.length < 3) return;
132
+ size = (inBytes[0] << 16) | (inBytes[1] << 8) | inBytes[2];
133
+ if (inBytes.length < size + 3) return;
134
+ let frame = inBytes.subarray(3, size + 3);
135
+ inBytes = inBytes.subarray(size + 3);
136
+ if (transport) {
137
+ const result = transport.decrypt(frame);
138
+ frame = await decodeBinaryNode(result);
139
+ }
140
+ if (logger.level === "trace") {
141
+ logger.trace({ msg: frame?.attrs?.id }, "recv frame");
142
+ }
143
+ onFrame(frame);
144
+ }
145
+ };
146
+ authenticate(NOISE_HEADER);
147
+ authenticate(publicKey);
148
+ return {
149
+ encrypt: encrypt,
150
+ decrypt: decrypt,
151
+ authenticate: authenticate,
152
+ mixIntoKey: mixIntoKey,
153
+ finishInit: finishInit,
154
+ processHandshake: ({ serverHello }, noiseKey) => {
155
+ authenticate(serverHello.ephemeral);
156
+ mixIntoKey(Curve.sharedKey(privateKey, serverHello.ephemeral));
157
+ const decStaticContent = decrypt(serverHello.static);
158
+ mixIntoKey(Curve.sharedKey(privateKey, decStaticContent));
159
+ const certDecoded = decrypt(serverHello.payload);
160
+ const { intermediate: certIntermediate, leaf } =
161
+ proto.CertChain.decode(certDecoded);
162
+ // leaf
163
+ if (!leaf?.details || !leaf?.signature) {
164
+ throw new Boom("invalid noise leaf certificate", { statusCode: 400 });
165
+ }
166
+ if (!certIntermediate?.details || !certIntermediate?.signature) {
167
+ throw new Boom("invalid noise intermediate certificate", {
168
+ statusCode: 400,
169
+ });
170
+ }
171
+ const details = proto.CertChain.NoiseCertificate.Details.decode(
172
+ certIntermediate.details,
173
+ );
174
+ const { issuerSerial } = details;
175
+ const verify = Curve.verify(details.key, leaf.details, leaf.signature);
176
+ const verifyIntermediate = Curve.verify(
177
+ WA_CERT_DETAILS.PUBLIC_KEY,
178
+ certIntermediate.details,
179
+ certIntermediate.signature,
180
+ );
181
+ if (!verify) {
182
+ throw new Boom("noise certificate signature invalid", {
183
+ statusCode: 400,
184
+ });
185
+ }
186
+ if (!verifyIntermediate) {
187
+ throw new Boom("noise intermediate certificate signature invalid", {
188
+ statusCode: 400,
189
+ });
190
+ }
191
+ if (issuerSerial !== WA_CERT_DETAILS.SERIAL) {
192
+ throw new Boom("certification match failed", { statusCode: 400 });
193
+ }
194
+ const keyEnc = encrypt(noiseKey.public);
195
+ mixIntoKey(Curve.sharedKey(noiseKey.private, serverHello.ephemeral));
196
+ return keyEnc;
197
+ },
198
+ encodeFrame: (data) => {
199
+ if (transport) {
200
+ data = transport.encrypt(data);
201
+ }
202
+ const dataLen = data.byteLength;
203
+ const introSize = sentIntro ? 0 : introHeader.length;
204
+ const frame = Buffer.allocUnsafe(introSize + 3 + dataLen);
205
+ if (!sentIntro) {
206
+ frame.set(introHeader);
207
+ sentIntro = true;
208
+ }
209
+ frame[introSize] = (dataLen >>> 16) & 255;
210
+ frame[introSize + 1] = (dataLen >>> 8) & 255;
211
+ frame[introSize + 2] = dataLen & 255;
212
+ frame.set(data, introSize + 3);
213
+ return frame;
214
+ },
215
+ decodeFrame: async (newData, onFrame) => {
216
+ if (isWaitingForTransport) {
217
+ inBytes = Buffer.concat([inBytes, newData]);
218
+ pendingOnFrame = onFrame;
219
+ return;
220
+ }
221
+ if (inBytes.length === 0) {
222
+ inBytes = Buffer.from(newData);
223
+ } else {
224
+ inBytes = Buffer.concat([inBytes, newData]);
225
+ }
226
+ await processData(onFrame);
227
+ },
228
+ };
229
+ };
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Creates a processor for offline stanza nodes that:
3
+ * - Queues nodes for sequential processing
4
+ * - Yields to the event loop periodically to avoid blocking
5
+ * - Catches handler errors to prevent the processing loop from crashing
6
+ */
7
+ export function makeOfflineNodeProcessor(
8
+ nodeProcessorMap,
9
+ deps,
10
+ batchSize = 10,
11
+ ) {
12
+ const nodes = [];
13
+ let isProcessing = false;
14
+ const enqueue = (type, node) => {
15
+ nodes.push({ type: type, node: node });
16
+ if (isProcessing) {
17
+ return;
18
+ }
19
+ isProcessing = true;
20
+ const promise = async () => {
21
+ let processedInBatch = 0;
22
+ while (nodes.length && deps.isWsOpen()) {
23
+ const { type, node } = nodes.shift();
24
+ const nodeProcessor = nodeProcessorMap.get(type);
25
+ if (!nodeProcessor) {
26
+ deps.onUnexpectedError(
27
+ new Error(`unknown offline node type: ${type}`),
28
+ "processing offline node",
29
+ );
30
+ continue;
31
+ }
32
+ await nodeProcessor(node).catch((err) =>
33
+ deps.onUnexpectedError(err, `processing offline ${type}`),
34
+ );
35
+ processedInBatch++;
36
+ // Yield to event loop after processing a batch
37
+ // This prevents blocking the event loop for too long when there are many offline nodes
38
+ if (processedInBatch >= batchSize) {
39
+ processedInBatch = 0;
40
+ await deps.yieldToEventLoop();
41
+ }
42
+ }
43
+ isProcessing = false;
44
+ };
45
+ promise().catch((error) =>
46
+ deps.onUnexpectedError(error, "processing offline nodes"),
47
+ );
48
+ };
49
+ return { enqueue: enqueue };
50
+ }
@@ -0,0 +1,119 @@
1
+ import PQueue from "p-queue";
2
+ /**
3
+ * Manages pre-key operations with proper concurrency control
4
+ */ export class PreKeyManager {
5
+ constructor(store, logger) {
6
+ this.store = store;
7
+ this.logger = logger;
8
+ this.queues = new Map();
9
+ }
10
+ /**
11
+ * Get or create a queue for a specific key type
12
+ */ getQueue(keyType) {
13
+ if (!this.queues.has(keyType)) {
14
+ this.queues.set(keyType, new PQueue({ concurrency: 1 }));
15
+ }
16
+ return this.queues.get(keyType);
17
+ }
18
+ /**
19
+ * Process pre-key operations (updates and deletions)
20
+ */ async processOperations(
21
+ data,
22
+ keyType,
23
+ transactionCache,
24
+ mutations,
25
+ isInTransaction,
26
+ ) {
27
+ const keyData = data[keyType];
28
+ if (!keyData) return;
29
+ return this.getQueue(keyType).add(async () => {
30
+ // Ensure structures exist
31
+ transactionCache[keyType] = transactionCache[keyType] || {};
32
+ mutations[keyType] = mutations[keyType] || {};
33
+ // Separate deletions from updates
34
+ const deletions = [];
35
+ const updates = {};
36
+ for (const keyId in keyData) {
37
+ if (keyData[keyId] === null) {
38
+ deletions.push(keyId);
39
+ } else {
40
+ updates[keyId] = keyData[keyId];
41
+ }
42
+ }
43
+ // Process updates (no validation needed)
44
+ if (Object.keys(updates).length > 0) {
45
+ Object.assign(transactionCache[keyType], updates);
46
+ Object.assign(mutations[keyType], updates);
47
+ }
48
+ // Process deletions with validation
49
+ if (deletions.length > 0) {
50
+ await this.processDeletions(
51
+ keyType,
52
+ deletions,
53
+ transactionCache,
54
+ mutations,
55
+ isInTransaction,
56
+ );
57
+ }
58
+ });
59
+ }
60
+ /**
61
+ * Process deletions with validation
62
+ */ async processDeletions(
63
+ keyType,
64
+ ids,
65
+ transactionCache,
66
+ mutations,
67
+ isInTransaction,
68
+ ) {
69
+ if (isInTransaction) {
70
+ // In transaction, only allow deletion if key exists in cache
71
+ for (const keyId of ids) {
72
+ if (transactionCache[keyType]?.[keyId]) {
73
+ transactionCache[keyType][keyId] = null;
74
+ mutations[keyType][keyId] = null;
75
+ } else {
76
+ this.logger.warn(
77
+ `Skipping deletion of non-existent ${keyType} in transaction: ${keyId}`,
78
+ );
79
+ }
80
+ }
81
+ } else {
82
+ // Outside transaction, validate against store
83
+ const existingKeys = await this.store.get(keyType, ids);
84
+ for (const keyId of ids) {
85
+ if (existingKeys[keyId]) {
86
+ transactionCache[keyType][keyId] = null;
87
+ mutations[keyType][keyId] = null;
88
+ } else {
89
+ this.logger.warn(
90
+ `Skipping deletion of non-existent ${keyType}: ${keyId}`,
91
+ );
92
+ }
93
+ }
94
+ }
95
+ }
96
+ /**
97
+ * Validate and process pre-key deletions outside transactions
98
+ */ async validateDeletions(data, keyType) {
99
+ const keyData = data[keyType];
100
+ if (!keyData) return;
101
+ return this.getQueue(keyType).add(async () => {
102
+ // Find all deletion requests
103
+ const deletionIds = Object.keys(keyData).filter(
104
+ (id) => keyData[id] === null,
105
+ );
106
+ if (deletionIds.length === 0) return;
107
+ // Validate deletions
108
+ const existingKeys = await this.store.get(keyType, deletionIds);
109
+ for (const keyId of deletionIds) {
110
+ if (!existingKeys[keyId]) {
111
+ this.logger.warn(
112
+ `Skipping deletion of non-existent ${keyType}: ${keyId}`,
113
+ );
114
+ delete data[keyType][keyId];
115
+ }
116
+ }
117
+ });
118
+ }
119
+ }