ishumdz-bail 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/README.md +772 -0
  2. package/WAProto/fix-imports.js +85 -0
  3. package/WAProto/index.d.ts +79257 -0
  4. package/WAProto/index.js +242946 -0
  5. package/engine-requirements.js +10 -0
  6. package/lib/Defaults/index.js +142 -0
  7. package/lib/Games/index.js +497 -0
  8. package/lib/Signal/Group/ciphertext-message.js +12 -0
  9. package/lib/Signal/Group/group-session-builder.js +30 -0
  10. package/lib/Signal/Group/group_cipher.js +93 -0
  11. package/lib/Signal/Group/index.js +12 -0
  12. package/lib/Signal/Group/keyhelper.js +18 -0
  13. package/lib/Signal/Group/queue-job.js +53 -0
  14. package/lib/Signal/Group/sender-chain-key.js +26 -0
  15. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  16. package/lib/Signal/Group/sender-key-message.js +66 -0
  17. package/lib/Signal/Group/sender-key-name.js +48 -0
  18. package/lib/Signal/Group/sender-key-record.js +41 -0
  19. package/lib/Signal/Group/sender-key-state.js +84 -0
  20. package/lib/Signal/Group/sender-message-key.js +26 -0
  21. package/lib/Signal/libsignal.js +431 -0
  22. package/lib/Signal/lid-mapping.js +277 -0
  23. package/lib/Socket/Client/index.js +3 -0
  24. package/lib/Socket/Client/types.js +11 -0
  25. package/lib/Socket/Client/websocket.js +84 -0
  26. package/lib/Socket/ban-checker.js +265 -0
  27. package/lib/Socket/business.js +379 -0
  28. package/lib/Socket/chats.js +1193 -0
  29. package/lib/Socket/communities.js +431 -0
  30. package/lib/Socket/groups.js +374 -0
  31. package/lib/Socket/index.js +13 -0
  32. package/lib/Socket/luxu.js +460 -0
  33. package/lib/Socket/messages-recv.js +1916 -0
  34. package/lib/Socket/messages-send.js +1469 -0
  35. package/lib/Socket/mex.js +41 -0
  36. package/lib/Socket/newsletter.js +261 -0
  37. package/lib/Socket/socket.js +988 -0
  38. package/lib/Socket/username.js +234 -0
  39. package/lib/Store/index.js +10 -0
  40. package/lib/Store/keyed-db.js +108 -0
  41. package/lib/Store/make-cache-manager-store.js +85 -0
  42. package/lib/Store/make-in-memory-store.js +198 -0
  43. package/lib/Store/make-ordered-dictionary.js +75 -0
  44. package/lib/Store/object-repository.js +32 -0
  45. package/lib/Types/Auth.js +2 -0
  46. package/lib/Types/Bussines.js +2 -0
  47. package/lib/Types/Call.js +2 -0
  48. package/lib/Types/Chat.js +8 -0
  49. package/lib/Types/Contact.js +2 -0
  50. package/lib/Types/Events.js +2 -0
  51. package/lib/Types/GroupMetadata.js +2 -0
  52. package/lib/Types/Label.js +25 -0
  53. package/lib/Types/LabelAssociation.js +7 -0
  54. package/lib/Types/Message.js +11 -0
  55. package/lib/Types/Mex.js +37 -0
  56. package/lib/Types/Product.js +2 -0
  57. package/lib/Types/Signal.js +2 -0
  58. package/lib/Types/Socket.js +3 -0
  59. package/lib/Types/State.js +56 -0
  60. package/lib/Types/USync.js +2 -0
  61. package/lib/Types/index.js +26 -0
  62. package/lib/Utils/auth-utils.js +302 -0
  63. package/lib/Utils/browser-utils.js +49 -0
  64. package/lib/Utils/business.js +231 -0
  65. package/lib/Utils/chat-utils.js +872 -0
  66. package/lib/Utils/classify-disconnect.js +126 -0
  67. package/lib/Utils/companion-reg-client-utils.js +35 -0
  68. package/lib/Utils/crypto.js +118 -0
  69. package/lib/Utils/decode-wa-message.js +350 -0
  70. package/lib/Utils/event-buffer.js +622 -0
  71. package/lib/Utils/generics.js +403 -0
  72. package/lib/Utils/history.js +134 -0
  73. package/lib/Utils/identity-change-handler.js +50 -0
  74. package/lib/Utils/index.js +23 -0
  75. package/lib/Utils/link-preview.js +85 -0
  76. package/lib/Utils/logger.js +3 -0
  77. package/lib/Utils/lt-hash.js +8 -0
  78. package/lib/Utils/make-mutex.js +33 -0
  79. package/lib/Utils/message-composer.js +273 -0
  80. package/lib/Utils/message-retry-manager.js +265 -0
  81. package/lib/Utils/messages-media.js +793 -0
  82. package/lib/Utils/messages.js +1586 -0
  83. package/lib/Utils/noise-handler.js +201 -0
  84. package/lib/Utils/offline-node-processor.js +40 -0
  85. package/lib/Utils/pre-key-manager.js +106 -0
  86. package/lib/Utils/process-message.js +630 -0
  87. package/lib/Utils/rate-limiter.js +228 -0
  88. package/lib/Utils/reporting-utils.js +258 -0
  89. package/lib/Utils/signal.js +201 -0
  90. package/lib/Utils/stanza-ack.js +38 -0
  91. package/lib/Utils/sync-action-utils.js +49 -0
  92. package/lib/Utils/tc-token-utils.js +163 -0
  93. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  94. package/lib/Utils/validate-connection.js +203 -0
  95. package/lib/WABinary/constants.js +1301 -0
  96. package/lib/WABinary/decode.js +262 -0
  97. package/lib/WABinary/encode.js +220 -0
  98. package/lib/WABinary/generic-utils.js +204 -0
  99. package/lib/WABinary/index.js +6 -0
  100. package/lib/WABinary/jid-utils.js +98 -0
  101. package/lib/WABinary/types.js +2 -0
  102. package/lib/WAM/BinaryInfo.js +10 -0
  103. package/lib/WAM/constants.js +22853 -0
  104. package/lib/WAM/encode.js +150 -0
  105. package/lib/WAM/index.js +4 -0
  106. package/lib/WAUSync/Protocols/USyncContactProtocol.js +52 -0
  107. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  108. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  109. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  110. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  111. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  112. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  113. package/lib/WAUSync/Protocols/index.js +6 -0
  114. package/lib/WAUSync/USyncQuery.js +98 -0
  115. package/lib/WAUSync/USyncUser.js +31 -0
  116. package/lib/WAUSync/index.js +4 -0
  117. package/lib/index.js +37 -0
  118. package/package.json +150 -0
@@ -0,0 +1,228 @@
1
+ /**
2
+ * RateLimiter — tracks outgoing message pacing per-socket to avoid sending
3
+ * patterns that look automated (fixed delays, bursts, identical repeated
4
+ * content). Call `getDelay()` before sending, `record()` after sending.
5
+ *
6
+ * This does not send anything or touch the socket itself — it's a pure,
7
+ * self-contained pacing calculator. Wire it into your own send path.
8
+ *
9
+ * Ported to ESM from a third-party fork's `antiban.js` (CommonJS). Logic is
10
+ * unchanged from the original — only the module syntax was converted.
11
+ */
12
+
13
+ const TIME_CONSTANTS = {
14
+ MS_PER_SECOND: 1000,
15
+ MS_PER_MINUTE: 60000,
16
+ MS_PER_HOUR: 3600000,
17
+ MS_PER_DAY: 86400000,
18
+ BURST_RESET_MS: 30000,
19
+ IDENTICAL_WINDOW_MS: 3600000
20
+ };
21
+
22
+ const DEFAULT_CONFIG = {
23
+ maxPerMinute: 8,
24
+ maxPerHour: 200,
25
+ maxPerDay: 1500,
26
+ minDelayMs: 1500,
27
+ maxDelayMs: 5000,
28
+ newChatDelayMs: 3000,
29
+ maxIdenticalMessages: 3,
30
+ burstAllowance: 3,
31
+ identicalMessageWindowMs: TIME_CONSTANTS.IDENTICAL_WINDOW_MS
32
+ };
33
+
34
+ export class RateLimiter {
35
+ config;
36
+ messages = [];
37
+ identicalCount = new Map();
38
+ knownChats = new Set();
39
+ burstCount = 0;
40
+ lastMessageTime = 0;
41
+
42
+ constructor(config = {}) {
43
+ this.config = { ...DEFAULT_CONFIG, ...config };
44
+ }
45
+
46
+ /**
47
+ * Returns how many ms to wait before sending, or -1 if this send should
48
+ * be blocked entirely (limit exceeded / too many identical messages).
49
+ */
50
+ async getDelay(recipient, content) {
51
+ const now = Date.now();
52
+ this.cleanup(now);
53
+ const contentHash = this.hashContent(content);
54
+
55
+ const dayMessages = this.messages.filter(m => now - m.timestamp < TIME_CONSTANTS.MS_PER_DAY);
56
+ if (dayMessages.length >= this.config.maxPerDay) {
57
+ return -1;
58
+ }
59
+
60
+ const hourMessages = this.messages.filter(m => now - m.timestamp < TIME_CONSTANTS.MS_PER_HOUR);
61
+ if (hourMessages.length >= this.config.maxPerHour) {
62
+ hourMessages.sort((a, b) => a.timestamp - b.timestamp);
63
+ const oldestInHour = hourMessages[0];
64
+ const delay2 = oldestInHour
65
+ ? oldestInHour.timestamp + TIME_CONSTANTS.MS_PER_HOUR - now
66
+ : TIME_CONSTANTS.MS_PER_HOUR;
67
+ return Math.max(delay2, TIME_CONSTANTS.MS_PER_MINUTE);
68
+ }
69
+
70
+ const minuteMessages = this.messages.filter(m => now - m.timestamp < TIME_CONSTANTS.MS_PER_MINUTE);
71
+ if (minuteMessages.length >= this.config.maxPerMinute) {
72
+ minuteMessages.sort((a, b) => a.timestamp - b.timestamp);
73
+ const oldestInMinute = minuteMessages[0];
74
+ const delay2 = oldestInMinute
75
+ ? oldestInMinute.timestamp + TIME_CONSTANTS.MS_PER_MINUTE - now
76
+ : TIME_CONSTANTS.MS_PER_MINUTE;
77
+ return Math.max(delay2, TIME_CONSTANTS.MS_PER_SECOND);
78
+ }
79
+
80
+ const tracker = this.identicalCount.get(contentHash);
81
+ if (tracker) {
82
+ if (now - tracker.firstSeen < this.config.identicalMessageWindowMs) {
83
+ if (tracker.count >= this.config.maxIdenticalMessages) {
84
+ return -1;
85
+ }
86
+ }
87
+ }
88
+
89
+ let delay = 0;
90
+ if (this.burstCount < this.config.burstAllowance) {
91
+ this.burstCount++;
92
+ delay = this.jitter(this.config.minDelayMs * 0.5, this.config.minDelayMs);
93
+ }
94
+ else {
95
+ delay = this.jitter(this.config.minDelayMs, this.config.maxDelayMs);
96
+ }
97
+
98
+ const isInterop = recipient.endsWith('@interop');
99
+ if (!this.knownChats.has(recipient) || isInterop) {
100
+ delay += this.jitter(this.config.newChatDelayMs * 0.5, this.config.newChatDelayMs);
101
+ }
102
+
103
+ const timeSinceLast = now - this.lastMessageTime;
104
+ if (timeSinceLast < this.config.minDelayMs) {
105
+ delay = Math.max(delay, this.config.minDelayMs - timeSinceLast);
106
+ }
107
+
108
+ const typingDelay = Math.min(content.length * 30, 3000);
109
+ delay += this.jitter(typingDelay * 0.5, typingDelay);
110
+
111
+ return Math.round(delay);
112
+ }
113
+
114
+ /** Call this right after a message is actually sent. */
115
+ record(recipient, content) {
116
+ const now = Date.now();
117
+ // Guard against unbounded memory growth: cleanup() is normally
118
+ // triggered by getDelay(), but callers who only ever call record()
119
+ // (skipping getDelay(), e.g. only using this for stats) would never
120
+ // trim old entries otherwise. Cheap to check, only sweeps when the
121
+ // buffer has actually grown past a day's worth of entries.
122
+ if (this.messages.length > 0 && now - this.messages[0].timestamp > TIME_CONSTANTS.MS_PER_DAY) {
123
+ this.cleanup(now);
124
+ }
125
+ const contentHash = this.hashContent(content);
126
+ const timeSinceLast = now - this.lastMessageTime;
127
+ if (timeSinceLast > TIME_CONSTANTS.BURST_RESET_MS) {
128
+ this.burstCount = 0;
129
+ }
130
+ this.messages.push({ timestamp: now, recipient, contentHash });
131
+ this.knownChats.add(recipient);
132
+ this.lastMessageTime = now;
133
+
134
+ const tracker = this.identicalCount.get(contentHash);
135
+ if (tracker) {
136
+ if (now - tracker.firstSeen < this.config.identicalMessageWindowMs) {
137
+ tracker.count++;
138
+ tracker.lastSeen = now;
139
+ }
140
+ else {
141
+ this.identicalCount.set(contentHash, { count: 1, firstSeen: now, lastSeen: now });
142
+ }
143
+ }
144
+ else {
145
+ this.identicalCount.set(contentHash, { count: 1, firstSeen: now, lastSeen: now });
146
+ }
147
+ }
148
+
149
+ /**
150
+ * Combines getDelay() + record() into a single call so limits are
151
+ * respected correctly when queuing up several messages at once (e.g.
152
+ * `Promise.all(items.map(i => limiter.reserve(...)))` or a for-loop
153
+ * over a batch). Calling getDelay() alone multiple times before any
154
+ * record() will NOT see each other's pending sends — each call only
155
+ * "counts" once you actually record() it, so a batch processed via
156
+ * getDelay() first and record() second can burst past your configured
157
+ * limits. reserve() closes that gap by recording immediately, so each
158
+ * subsequent call in the same batch sees an up-to-date count.
159
+ *
160
+ * Returns -1 (same as getDelay) if the send should be blocked instead.
161
+ * Only record what you will actually send: if you decide not to send
162
+ * after getting a delay back, do not call reserve() for it.
163
+ */
164
+ async reserve(recipient, content) {
165
+ const delay = await this.getDelay(recipient, content);
166
+ if (delay === -1) {
167
+ return -1;
168
+ }
169
+ this.record(recipient, content);
170
+ return delay;
171
+ }
172
+
173
+ getStats() {
174
+ const now = Date.now();
175
+ this.cleanup(now);
176
+ return {
177
+ lastMinute: this.messages.filter(m => now - m.timestamp < TIME_CONSTANTS.MS_PER_MINUTE).length,
178
+ lastHour: this.messages.filter(m => now - m.timestamp < TIME_CONSTANTS.MS_PER_HOUR).length,
179
+ lastDay: this.messages.filter(m => now - m.timestamp < TIME_CONSTANTS.MS_PER_DAY).length,
180
+ limits: {
181
+ perMinute: this.config.maxPerMinute,
182
+ perHour: this.config.maxPerHour,
183
+ perDay: this.config.maxPerDay
184
+ },
185
+ knownChats: this.knownChats.size
186
+ };
187
+ }
188
+
189
+ getKnownChats() {
190
+ return this.knownChats;
191
+ }
192
+
193
+ /** Useful for restoring "known chat" state after a restart, so every
194
+ * chat isn't treated as brand-new (extra delay) after every reboot. */
195
+ restoreKnownChats(chats) {
196
+ for (const jid of chats) {
197
+ this.knownChats.add(jid);
198
+ }
199
+ }
200
+
201
+ cleanup(now) {
202
+ this.messages = this.messages.filter(m => now - m.timestamp < TIME_CONSTANTS.MS_PER_DAY);
203
+ for (const [hash, tracker] of this.identicalCount.entries()) {
204
+ if (now - tracker.lastSeen > this.config.identicalMessageWindowMs) {
205
+ this.identicalCount.delete(hash);
206
+ }
207
+ }
208
+ }
209
+
210
+ jitter(min, max) {
211
+ const u1 = Math.random();
212
+ const u2 = Math.random();
213
+ const normal = Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);
214
+ const normalized = (normal + 3) / 6;
215
+ const clamped = Math.max(0, Math.min(1, normalized));
216
+ return Math.round(min + clamped * (max - min));
217
+ }
218
+
219
+ hashContent(content) {
220
+ let hash = 0;
221
+ for (let i = 0; i < content.length; i++) {
222
+ const char = content.charCodeAt(i);
223
+ hash = (hash << 5) - hash + char;
224
+ hash |= 0;
225
+ }
226
+ return hash.toString(36);
227
+ }
228
+ }
@@ -0,0 +1,258 @@
1
+ import { createHmac } from 'crypto';
2
+ import { proto } from '../../WAProto/index.js';
3
+ import { hkdf } from './crypto.js';
4
+ const reportingFields = [
5
+ { f: 1 },
6
+ {
7
+ f: 3,
8
+ s: [{ f: 2 }, { f: 3 }, { f: 8 }, { f: 11 }, { f: 17, s: [{ f: 21 }, { f: 22 }] }, { f: 25 }]
9
+ },
10
+ { f: 4, s: [{ f: 1 }, { f: 16 }, { f: 17, s: [{ f: 21 }, { f: 22 }] }] },
11
+ { f: 5, s: [{ f: 3 }, { f: 4 }, { f: 5 }, { f: 16 }, { f: 17, s: [{ f: 21 }, { f: 22 }] }] },
12
+ { f: 6, s: [{ f: 1 }, { f: 17, s: [{ f: 21 }, { f: 22 }] }, { f: 30 }] },
13
+ { f: 7, s: [{ f: 2 }, { f: 7 }, { f: 10 }, { f: 17, s: [{ f: 21 }, { f: 22 }] }, { f: 20 }] },
14
+ { f: 8, s: [{ f: 2 }, { f: 7 }, { f: 9 }, { f: 17, s: [{ f: 21 }, { f: 22 }] }, { f: 21 }] },
15
+ { f: 9, s: [{ f: 2 }, { f: 6 }, { f: 7 }, { f: 13 }, { f: 17, s: [{ f: 21 }, { f: 22 }] }, { f: 20 }] },
16
+ { f: 12, s: [{ f: 1 }, { f: 2 }, { f: 14, m: true }, { f: 15 }] },
17
+ { f: 18, s: [{ f: 6 }, { f: 16 }, { f: 17, s: [{ f: 21 }, { f: 22 }] }] },
18
+ { f: 26, s: [{ f: 4 }, { f: 5 }, { f: 8 }, { f: 13 }, { f: 17, s: [{ f: 21 }, { f: 22 }] }] },
19
+ { f: 28, s: [{ f: 1 }, { f: 2 }, { f: 4 }, { f: 5 }, { f: 6 }, { f: 7, s: [{ f: 21 }, { f: 22 }] }] },
20
+ { f: 37, s: [{ f: 1, m: true }] },
21
+ {
22
+ f: 49,
23
+ s: [
24
+ { f: 2 },
25
+ { f: 3, s: [{ f: 1 }, { f: 2 }] },
26
+ { f: 5, s: [{ f: 21 }, { f: 22 }] },
27
+ { f: 8, s: [{ f: 1 }, { f: 2 }] }
28
+ ]
29
+ },
30
+ { f: 53, s: [{ f: 1, m: true }] },
31
+ { f: 55, s: [{ f: 1, m: true }] },
32
+ { f: 58, s: [{ f: 1, m: true }] },
33
+ { f: 59, s: [{ f: 1, m: true }] },
34
+ {
35
+ f: 60,
36
+ s: [
37
+ { f: 2 },
38
+ { f: 3, s: [{ f: 1 }, { f: 2 }] },
39
+ { f: 5, s: [{ f: 21 }, { f: 22 }] },
40
+ { f: 8, s: [{ f: 1 }, { f: 2 }] }
41
+ ]
42
+ },
43
+ {
44
+ f: 64,
45
+ s: [
46
+ { f: 2 },
47
+ { f: 3, s: [{ f: 1 }, { f: 2 }] },
48
+ { f: 5, s: [{ f: 21 }, { f: 22 }] },
49
+ { f: 8, s: [{ f: 1 }, { f: 2 }] }
50
+ ]
51
+ },
52
+ { f: 66, s: [{ f: 2 }, { f: 6 }, { f: 7 }, { f: 13 }, { f: 17, s: [{ f: 21 }, { f: 22 }] }, { f: 20 }] },
53
+ { f: 74, s: [{ f: 1, m: true }] },
54
+ { f: 87, s: [{ f: 1, m: true }] },
55
+ { f: 88, s: [{ f: 1 }, { f: 2, s: [{ f: 1 }] }, { f: 3, s: [{ f: 21 }, { f: 22 }] }] },
56
+ { f: 92, s: [{ f: 1, m: true }] },
57
+ { f: 93, s: [{ f: 1, m: true }] },
58
+ { f: 94, s: [{ f: 1, m: true }] }
59
+ ];
60
+ const compileReportingFields = (fields) => {
61
+ const map = new Map();
62
+ for (const f of fields) {
63
+ map.set(f.f, {
64
+ m: f.m,
65
+ children: f.s ? compileReportingFields(f.s) : undefined
66
+ });
67
+ }
68
+ return map;
69
+ };
70
+ const compiledReportingFields = compileReportingFields(reportingFields);
71
+ const EMPTY_MAP = new Map();
72
+ const ENC_SECRET_REPORT_TOKEN = 'Report Token';
73
+ const WIRE = {
74
+ VARINT: 0,
75
+ FIXED64: 1,
76
+ BYTES: 2,
77
+ FIXED32: 5
78
+ };
79
+ export const shouldIncludeReportingToken = (message) => !message.reactionMessage &&
80
+ !message.encReactionMessage &&
81
+ !message.encEventResponseMessage &&
82
+ !message.pollUpdateMessage;
83
+ const generateMsgSecretKey = (modificationType, origMsgId, origMsgSender, modificationSender, origMsgSecret) => {
84
+ const useCaseSecret = Buffer.concat([
85
+ Buffer.from(origMsgId, 'utf8'),
86
+ Buffer.from(origMsgSender, 'utf8'),
87
+ Buffer.from(modificationSender, 'utf8'),
88
+ Buffer.from(modificationType, 'utf8')
89
+ ]);
90
+ return hkdf(origMsgSecret, 32, { info: useCaseSecret.toString('latin1') });
91
+ };
92
+ const extractReportingTokenContent = (data, cfg) => {
93
+ const out = [];
94
+ let i = 0;
95
+ while (i < data.length) {
96
+ const tag = decodeVarint(data, i);
97
+ if (!tag.ok) {
98
+ return null;
99
+ }
100
+ const fieldNum = tag.value >> 3;
101
+ const wireType = tag.value & 0x7;
102
+ const fieldStart = i;
103
+ i += tag.bytes;
104
+ const fieldCfg = cfg.get(fieldNum);
105
+ const pushSlice = (end) => {
106
+ if (end > data.length) {
107
+ return false;
108
+ }
109
+ out.push({ num: fieldNum, bytes: data.subarray(fieldStart, end) });
110
+ i = end;
111
+ return true;
112
+ };
113
+ const skip = (end) => {
114
+ if (end > data.length) {
115
+ return false;
116
+ }
117
+ i = end;
118
+ return true;
119
+ };
120
+ if (wireType === WIRE.VARINT) {
121
+ const v = decodeVarint(data, i);
122
+ if (!v.ok) {
123
+ return null;
124
+ }
125
+ const end = i + v.bytes;
126
+ if (!fieldCfg) {
127
+ if (!skip(end)) {
128
+ return null;
129
+ }
130
+ continue;
131
+ }
132
+ if (!pushSlice(end)) {
133
+ return null;
134
+ }
135
+ continue;
136
+ }
137
+ if (wireType === WIRE.FIXED64) {
138
+ const end = i + 8;
139
+ if (!fieldCfg) {
140
+ if (!skip(end)) {
141
+ return null;
142
+ }
143
+ continue;
144
+ }
145
+ if (!pushSlice(end)) {
146
+ return null;
147
+ }
148
+ continue;
149
+ }
150
+ if (wireType === WIRE.FIXED32) {
151
+ const end = i + 4;
152
+ if (!fieldCfg) {
153
+ if (!skip(end)) {
154
+ return null;
155
+ }
156
+ continue;
157
+ }
158
+ if (!pushSlice(end)) {
159
+ return null;
160
+ }
161
+ continue;
162
+ }
163
+ if (wireType === WIRE.BYTES) {
164
+ const len = decodeVarint(data, i);
165
+ if (!len.ok) {
166
+ return null;
167
+ }
168
+ const valStart = i + len.bytes;
169
+ const valEnd = valStart + len.value;
170
+ if (valEnd > data.length) {
171
+ return null;
172
+ }
173
+ if (!fieldCfg) {
174
+ i = valEnd;
175
+ continue;
176
+ }
177
+ if (fieldCfg.m || fieldCfg.children) {
178
+ const sub = extractReportingTokenContent(data.subarray(valStart, valEnd), fieldCfg.children ?? EMPTY_MAP);
179
+ if (sub === null) {
180
+ return null;
181
+ }
182
+ if (sub.length > 0) {
183
+ const newTag = encodeVarint(tag.value);
184
+ const newLen = encodeVarint(sub.length);
185
+ out.push({
186
+ num: fieldNum,
187
+ bytes: Buffer.concat([newTag, newLen, sub])
188
+ });
189
+ }
190
+ i = valEnd;
191
+ continue;
192
+ }
193
+ out.push({ num: fieldNum, bytes: data.subarray(fieldStart, valEnd) });
194
+ i = valEnd;
195
+ continue;
196
+ }
197
+ return null;
198
+ }
199
+ if (out.length === 0) {
200
+ return Buffer.alloc(0);
201
+ }
202
+ out.sort((a, b) => a.num - b.num);
203
+ return Buffer.concat(out.map(f => f.bytes));
204
+ };
205
+ const decodeVarint = (buffer, offset) => {
206
+ let value = 0;
207
+ let bytes = 0;
208
+ let shift = 0;
209
+ while (offset + bytes < buffer.length) {
210
+ const current = buffer[offset + bytes];
211
+ value |= (current & 0x7f) << shift;
212
+ bytes++;
213
+ if ((current & 0x80) === 0) {
214
+ return { value, bytes, ok: true };
215
+ }
216
+ shift += 7;
217
+ if (shift > 35) {
218
+ return { value: 0, bytes: 0, ok: false };
219
+ }
220
+ }
221
+ return { value: 0, bytes: 0, ok: false };
222
+ };
223
+ const encodeVarint = (value) => {
224
+ const parts = [];
225
+ let remaining = value >>> 0;
226
+ while (remaining > 0x7f) {
227
+ parts.push((remaining & 0x7f) | 0x80);
228
+ remaining >>>= 7;
229
+ }
230
+ parts.push(remaining);
231
+ return Buffer.from(parts);
232
+ };
233
+ export const getMessageReportingToken = async (msgProtobuf, message, key) => {
234
+ const msgSecret = message.messageContextInfo?.messageSecret;
235
+ if (!msgSecret || !key.id) {
236
+ return null;
237
+ }
238
+ const from = key.fromMe ? key.remoteJid : key.participant || key.remoteJid;
239
+ const to = key.fromMe ? key.participant || key.remoteJid : key.remoteJid;
240
+ const reportingSecret = generateMsgSecretKey(ENC_SECRET_REPORT_TOKEN, key.id, from, to, msgSecret);
241
+ const content = extractReportingTokenContent(msgProtobuf, compiledReportingFields);
242
+ if (!content || content.length === 0) {
243
+ return null;
244
+ }
245
+ const reportingToken = createHmac('sha256', reportingSecret).update(content).digest().subarray(0, 16);
246
+ return {
247
+ tag: 'reporting',
248
+ attrs: {},
249
+ content: [
250
+ {
251
+ tag: 'reporting_token',
252
+ attrs: { v: '2' },
253
+ content: reportingToken
254
+ }
255
+ ]
256
+ };
257
+ };
258
+ //# sourceMappingURL=reporting-utils.js.map
@@ -0,0 +1,201 @@
1
+ import { KEY_BUNDLE_TYPE } from '../Defaults/index.js';
2
+ import { assertNodeErrorFree, getBinaryNodeChild, getBinaryNodeChildBuffer, getBinaryNodeChildren, getBinaryNodeChildUInt, getServerFromDomainType, jidDecode, S_WHATSAPP_NET, WAJIDDomains } from '../WABinary/index.js';
3
+ import { Curve, generateSignalPubKey } from './crypto.js';
4
+ import { encodeBigEndian } from './generics.js';
5
+ function chunk(array, size) {
6
+ const chunks = [];
7
+ for (let i = 0; i < array.length; i += size) {
8
+ chunks.push(array.slice(i, i + size));
9
+ }
10
+ return chunks;
11
+ }
12
+ export const createSignalIdentity = (wid, accountSignatureKey) => {
13
+ return {
14
+ identifier: { name: wid, deviceId: 0 },
15
+ identifierKey: generateSignalPubKey(accountSignatureKey)
16
+ };
17
+ };
18
+ export const getPreKeys = async ({ get }, min, limit) => {
19
+ const idList = [];
20
+ for (let id = min; id < limit; id++) {
21
+ idList.push(id.toString());
22
+ }
23
+ return get('pre-key', idList);
24
+ };
25
+ export const generateOrGetPreKeys = (creds, range) => {
26
+ const avaliable = creds.nextPreKeyId - creds.firstUnuploadedPreKeyId;
27
+ const remaining = range - avaliable;
28
+ const lastPreKeyId = creds.nextPreKeyId + remaining - 1;
29
+ const newPreKeys = {};
30
+ if (remaining > 0) {
31
+ for (let i = creds.nextPreKeyId; i <= lastPreKeyId; i++) {
32
+ newPreKeys[i] = Curve.generateKeyPair();
33
+ }
34
+ }
35
+ return {
36
+ newPreKeys,
37
+ lastPreKeyId,
38
+ preKeysRange: [creds.firstUnuploadedPreKeyId, range]
39
+ };
40
+ };
41
+ export const xmppSignedPreKey = (key) => ({
42
+ tag: 'skey',
43
+ attrs: {},
44
+ content: [
45
+ { tag: 'id', attrs: {}, content: encodeBigEndian(key.keyId, 3) },
46
+ { tag: 'value', attrs: {}, content: key.keyPair.public },
47
+ { tag: 'signature', attrs: {}, content: key.signature }
48
+ ]
49
+ });
50
+ export const xmppPreKey = (pair, id) => ({
51
+ tag: 'key',
52
+ attrs: {},
53
+ content: [
54
+ { tag: 'id', attrs: {}, content: encodeBigEndian(id, 3) },
55
+ { tag: 'value', attrs: {}, content: pair.public }
56
+ ]
57
+ });
58
+ const isValidUInt = (n) => typeof n === 'number' && Number.isInteger(n);
59
+ export const extractE2ESessionFromRetryReceipt = (receipt) => {
60
+ const keysNode = getBinaryNodeChild(receipt, 'keys');
61
+ if (!keysNode)
62
+ return null;
63
+ const typeBuf = getBinaryNodeChildBuffer(keysNode, 'type');
64
+ if (!typeBuf || typeBuf.length !== 1 || typeBuf[0] !== KEY_BUNDLE_TYPE[0])
65
+ return null;
66
+ const identity = getBinaryNodeChildBuffer(keysNode, 'identity');
67
+ const skey = getBinaryNodeChild(keysNode, 'skey');
68
+ if (!identity || identity.length !== 32 || !skey)
69
+ return null;
70
+ const registrationId = getBinaryNodeChildUInt(receipt, 'registration', 4);
71
+ if (!isValidUInt(registrationId))
72
+ return null;
73
+ const signedPubKey = getBinaryNodeChildBuffer(skey, 'value');
74
+ const signedSig = getBinaryNodeChildBuffer(skey, 'signature');
75
+ const signedKeyId = getBinaryNodeChildUInt(skey, 'id', 3);
76
+ if (!signedPubKey || signedPubKey.length !== 32 || !signedSig || !isValidUInt(signedKeyId)) {
77
+ return null;
78
+ }
79
+ const preKeyNode = getBinaryNodeChild(keysNode, 'key');
80
+ let preKey;
81
+ if (preKeyNode) {
82
+ const preKeyPub = getBinaryNodeChildBuffer(preKeyNode, 'value');
83
+ const preKeyId = getBinaryNodeChildUInt(preKeyNode, 'id', 3);
84
+ if (!preKeyPub || preKeyPub.length !== 32 || !isValidUInt(preKeyId)) {
85
+ return null;
86
+ }
87
+ preKey = { keyId: preKeyId, publicKey: generateSignalPubKey(preKeyPub) };
88
+ }
89
+ return {
90
+ registrationId,
91
+ identityKey: generateSignalPubKey(identity),
92
+ signedPreKey: {
93
+ keyId: signedKeyId,
94
+ publicKey: generateSignalPubKey(signedPubKey),
95
+ signature: signedSig
96
+ },
97
+ preKey
98
+ };
99
+ };
100
+ export const parseAndInjectE2ESessions = async (node, repository) => {
101
+ const extractKey = (key) => key
102
+ ? {
103
+ keyId: getBinaryNodeChildUInt(key, 'id', 3),
104
+ publicKey: generateSignalPubKey(getBinaryNodeChildBuffer(key, 'value')),
105
+ signature: getBinaryNodeChildBuffer(key, 'signature')
106
+ }
107
+ : undefined;
108
+ const nodes = getBinaryNodeChildren(getBinaryNodeChild(node, 'list'), 'user');
109
+ for (const node of nodes) {
110
+ assertNodeErrorFree(node);
111
+ }
112
+ // Most of the work in repository.injectE2ESession is CPU intensive, not IO
113
+ // So Promise.all doesn't really help here,
114
+ // but blocks even loop if we're using it inside keys.transaction, and it makes it "sync" actually
115
+ // This way we chunk it in smaller parts and between those parts we can yield to the event loop
116
+ // It's rare case when you need to E2E sessions for so many users, but it's possible
117
+ const chunkSize = 100;
118
+ const chunks = chunk(nodes, chunkSize);
119
+ for (const nodesChunk of chunks) {
120
+ for (const node of nodesChunk) {
121
+ const signedKey = getBinaryNodeChild(node, 'skey');
122
+ const key = getBinaryNodeChild(node, 'key');
123
+ const identity = getBinaryNodeChildBuffer(node, 'identity');
124
+ const jid = node.attrs.jid;
125
+ const registrationId = getBinaryNodeChildUInt(node, 'registration', 4);
126
+ await repository.injectE2ESession({
127
+ jid,
128
+ session: {
129
+ registrationId: registrationId,
130
+ identityKey: generateSignalPubKey(identity),
131
+ signedPreKey: extractKey(signedKey),
132
+ preKey: extractKey(key)
133
+ }
134
+ });
135
+ }
136
+ }
137
+ };
138
+ export const extractDeviceJids = (result, myJid, myLid, excludeZeroDevices) => {
139
+ const { user: myUser, device: myDevice } = jidDecode(myJid);
140
+ const extracted = [];
141
+ for (const userResult of result) {
142
+ const { devices, id } = userResult;
143
+ const decoded = jidDecode(id), { user, server } = decoded;
144
+ let { domainType } = decoded;
145
+ const deviceList = devices?.deviceList;
146
+ if (!Array.isArray(deviceList))
147
+ continue;
148
+ for (const { id: device, keyIndex, isHosted } of deviceList) {
149
+ if ((!excludeZeroDevices || device !== 0) && // if zero devices are not-excluded, or device is non zero
150
+ ((myUser !== user && myLid !== user) || myDevice !== device) && // either different user or if me user, not this device
151
+ (device === 0 || !!keyIndex) // ensure that "key-index" is specified for "non-zero" devices, produces a bad req otherwise
152
+ ) {
153
+ if (isHosted) {
154
+ domainType = domainType === WAJIDDomains.LID ? WAJIDDomains.HOSTED_LID : WAJIDDomains.HOSTED;
155
+ }
156
+ extracted.push({
157
+ user,
158
+ device,
159
+ domainType,
160
+ server: getServerFromDomainType(server, domainType)
161
+ });
162
+ }
163
+ }
164
+ }
165
+ return extracted;
166
+ };
167
+ /**
168
+ * get the next N keys for upload or processing
169
+ * @param count number of pre-keys to get or generate
170
+ */
171
+ export const getNextPreKeys = async ({ creds, keys }, count) => {
172
+ const { newPreKeys, lastPreKeyId, preKeysRange } = generateOrGetPreKeys(creds, count);
173
+ const update = {
174
+ nextPreKeyId: Math.max(lastPreKeyId + 1, creds.nextPreKeyId),
175
+ firstUnuploadedPreKeyId: Math.max(creds.firstUnuploadedPreKeyId, lastPreKeyId + 1)
176
+ };
177
+ await keys.set({ 'pre-key': newPreKeys });
178
+ const preKeys = await getPreKeys(keys, preKeysRange[0], preKeysRange[0] + preKeysRange[1]);
179
+ return { update, preKeys };
180
+ };
181
+ export const getNextPreKeysNode = async (state, count) => {
182
+ const { creds } = state;
183
+ const { update, preKeys } = await getNextPreKeys(state, count);
184
+ const node = {
185
+ tag: 'iq',
186
+ attrs: {
187
+ xmlns: 'encrypt',
188
+ type: 'set',
189
+ to: S_WHATSAPP_NET
190
+ },
191
+ content: [
192
+ { tag: 'registration', attrs: {}, content: encodeBigEndian(creds.registrationId) },
193
+ { tag: 'type', attrs: {}, content: KEY_BUNDLE_TYPE },
194
+ { tag: 'identity', attrs: {}, content: creds.signedIdentityKey.public },
195
+ { tag: 'list', attrs: {}, content: Object.keys(preKeys).map(k => xmppPreKey(preKeys[+k], +k)) },
196
+ xmppSignedPreKey(creds.signedPreKey)
197
+ ]
198
+ };
199
+ return { update, node };
200
+ };
201
+ //# sourceMappingURL=signal.js.map