Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b69ecc004d | |||
| 5351dce3a5 |
+18
-26
@@ -18,21 +18,14 @@ try {
|
|||||||
'\tif (typeof value === "number") {\n' +
|
'\tif (typeof value === "number") {\n' +
|
||||||
'\t\treturn String(value);\n' +
|
'\t\treturn String(value);\n' +
|
||||||
'\t}\n' +
|
'\t}\n' +
|
||||||
'\t// Fast path: convert Long {low, high} directly via native BigInt\n' +
|
'\tif (!$util.Long) {\n' +
|
||||||
'\t// BigInt.toString() is a native C++ operation, much faster than Long\'s pure JS division loops\n' +
|
'\t\treturn String(value);\n' +
|
||||||
'\tif (value && typeof value.low === "number" && typeof value.high === "number") {\n' +
|
|
||||||
'\t\t// Normalize high to signed int32 so the sign-bit check works for inputs\n' +
|
|
||||||
'\t\t// where high is stored unsigned (e.g. raw {low, high} JSON).\n' +
|
|
||||||
'\t\tconst high = value.high | 0;\n' +
|
|
||||||
'\t\tconst lo = BigInt(value.low >>> 0);\n' +
|
|
||||||
'\t\tconst hi = BigInt(value.high >>> 0);\n' +
|
|
||||||
'\t\tconst combined = (hi << 32n) | lo;\n' +
|
|
||||||
'\t\tif (!unsigned && high < 0) {\n' +
|
|
||||||
'\t\t\treturn (combined - (1n << 64n)).toString();\n' +
|
|
||||||
'\t\t}\n' +
|
|
||||||
'\t\treturn combined.toString();\n' +
|
|
||||||
'\t}\n' +
|
'\t}\n' +
|
||||||
'\treturn String(value);\n' +
|
'\tconst normalized = $util.Long.fromValue(value);\n' +
|
||||||
|
'\tconst prepared = unsigned && normalized && typeof normalized.toUnsigned === "function"\n' +
|
||||||
|
'\t\t? normalized.toUnsigned()\n' +
|
||||||
|
'\t\t: normalized;\n' +
|
||||||
|
'\treturn prepared.toString();\n' +
|
||||||
'}\n\n'
|
'}\n\n'
|
||||||
const longToNumberHelper =
|
const longToNumberHelper =
|
||||||
'function longToNumber(value, unsigned) {\n' +
|
'function longToNumber(value, unsigned) {\n' +
|
||||||
@@ -40,20 +33,19 @@ try {
|
|||||||
'\t\treturn value;\n' +
|
'\t\treturn value;\n' +
|
||||||
'\t}\n' +
|
'\t}\n' +
|
||||||
'\tif (typeof value === "string") {\n' +
|
'\tif (typeof value === "string") {\n' +
|
||||||
|
'\t\tconst numeric = Number(value);\n' +
|
||||||
|
'\t\treturn numeric;\n' +
|
||||||
|
'\t}\n' +
|
||||||
|
'\tif (!$util.Long) {\n' +
|
||||||
'\t\treturn Number(value);\n' +
|
'\t\treturn Number(value);\n' +
|
||||||
'\t}\n' +
|
'\t}\n' +
|
||||||
'\t// Fast path: convert Long {low, high} directly via native BigInt\n' +
|
'\tconst normalized = $util.Long.fromValue(value);\n' +
|
||||||
'\tif (value && typeof value.low === "number" && typeof value.high === "number") {\n' +
|
'\tconst prepared = unsigned && normalized && typeof normalized.toUnsigned === "function"\n' +
|
||||||
'\t\tconst high = value.high | 0;\n' +
|
'\t\t? normalized.toUnsigned()\n' +
|
||||||
'\t\tconst lo = BigInt(value.low >>> 0);\n' +
|
'\t\t: typeof normalized.toSigned === "function"\n' +
|
||||||
'\t\tconst hi = BigInt(value.high >>> 0);\n' +
|
'\t\t\t? normalized.toSigned()\n' +
|
||||||
'\t\tconst combined = (hi << 32n) | lo;\n' +
|
'\t\t\t: normalized;\n' +
|
||||||
'\t\tif (!unsigned && high < 0) {\n' +
|
'\treturn prepared.toNumber();\n' +
|
||||||
'\t\t\treturn Number(combined - (1n << 64n));\n' +
|
|
||||||
'\t\t}\n' +
|
|
||||||
'\t\treturn Number(combined);\n' +
|
|
||||||
'\t}\n' +
|
|
||||||
'\treturn Number(value);\n' +
|
|
||||||
'}\n\n'
|
'}\n\n'
|
||||||
|
|
||||||
if (!content.includes('function longToString(')) {
|
if (!content.includes('function longToString(')) {
|
||||||
|
|||||||
+18
-26
@@ -12,21 +12,14 @@ function longToString(value, unsigned) {
|
|||||||
if (typeof value === "number") {
|
if (typeof value === "number") {
|
||||||
return String(value);
|
return String(value);
|
||||||
}
|
}
|
||||||
// Fast path: convert Long {low, high} directly via native BigInt
|
if (!$util.Long) {
|
||||||
// BigInt.toString() is a native C++ operation, much faster than Long's pure JS division loops
|
|
||||||
if (value && typeof value.low === "number" && typeof value.high === "number") {
|
|
||||||
// Normalize high to signed int32 so the sign-bit check works for inputs
|
|
||||||
// where high is stored unsigned (e.g. raw {low, high} JSON).
|
|
||||||
const high = value.high | 0;
|
|
||||||
const lo = BigInt(value.low >>> 0);
|
|
||||||
const hi = BigInt(value.high >>> 0);
|
|
||||||
const combined = (hi << 32n) | lo;
|
|
||||||
if (!unsigned && high < 0) {
|
|
||||||
return (combined - (1n << 64n)).toString();
|
|
||||||
}
|
|
||||||
return combined.toString();
|
|
||||||
}
|
|
||||||
return String(value);
|
return String(value);
|
||||||
|
}
|
||||||
|
const normalized = $util.Long.fromValue(value);
|
||||||
|
const prepared = unsigned && normalized && typeof normalized.toUnsigned === "function"
|
||||||
|
? normalized.toUnsigned()
|
||||||
|
: normalized;
|
||||||
|
return prepared.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
function longToNumber(value, unsigned) {
|
function longToNumber(value, unsigned) {
|
||||||
@@ -34,20 +27,19 @@ function longToNumber(value, unsigned) {
|
|||||||
return value;
|
return value;
|
||||||
}
|
}
|
||||||
if (typeof value === "string") {
|
if (typeof value === "string") {
|
||||||
|
const numeric = Number(value);
|
||||||
|
return numeric;
|
||||||
|
}
|
||||||
|
if (!$util.Long) {
|
||||||
return Number(value);
|
return Number(value);
|
||||||
}
|
}
|
||||||
// Fast path: convert Long {low, high} directly via native BigInt
|
const normalized = $util.Long.fromValue(value);
|
||||||
if (value && typeof value.low === "number" && typeof value.high === "number") {
|
const prepared = unsigned && normalized && typeof normalized.toUnsigned === "function"
|
||||||
const high = value.high | 0;
|
? normalized.toUnsigned()
|
||||||
const lo = BigInt(value.low >>> 0);
|
: typeof normalized.toSigned === "function"
|
||||||
const hi = BigInt(value.high >>> 0);
|
? normalized.toSigned()
|
||||||
const combined = (hi << 32n) | lo;
|
: normalized;
|
||||||
if (!unsigned && high < 0) {
|
return prepared.toNumber();
|
||||||
return Number(combined - (1n << 64n));
|
|
||||||
}
|
|
||||||
return Number(combined);
|
|
||||||
}
|
|
||||||
return Number(value);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const proto = $root.proto = (() => {
|
export const proto = $root.proto = (() => {
|
||||||
|
|||||||
+5
-4
@@ -1060,21 +1060,22 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** fetch AB props */
|
/** sending non-abt props may fix QR scan fail if server expects */
|
||||||
const fetchProps = async () => {
|
const fetchProps = async () => {
|
||||||
|
//TODO: implement both protocol 1 and protocol 2 prop fetching, specially for abKey for WM
|
||||||
const resultNode = await query({
|
const resultNode = await query({
|
||||||
tag: 'iq',
|
tag: 'iq',
|
||||||
attrs: {
|
attrs: {
|
||||||
to: S_WHATSAPP_NET,
|
to: S_WHATSAPP_NET,
|
||||||
xmlns: 'abt',
|
xmlns: 'w',
|
||||||
type: 'get'
|
type: 'get'
|
||||||
},
|
},
|
||||||
content: [
|
content: [
|
||||||
{
|
{
|
||||||
tag: 'props',
|
tag: 'props',
|
||||||
attrs: {
|
attrs: {
|
||||||
protocol: '1',
|
protocol: '2',
|
||||||
...(authState?.creds?.lastPropHash ? { hash: authState.creds.lastPropHash } : {})
|
hash: authState?.creds?.lastPropHash || ''
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|||||||
+17
-34
@@ -2124,6 +2124,12 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
if (resolvedRemoteJid) key.remoteJid = resolvedRemoteJid
|
if (resolvedRemoteJid) key.remoteJid = resolvedRemoteJid
|
||||||
if (resolvedParticipant) key.participant = resolvedParticipant
|
if (resolvedParticipant) key.participant = resolvedParticipant
|
||||||
|
|
||||||
|
if (shouldIgnoreJid(remoteJid!) && remoteJid !== S_WHATSAPP_NET) {
|
||||||
|
logger.trace({ remoteJid }, 'ignoring receipt from jid')
|
||||||
|
await sendMessageAck(node)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
const ids = [attrs.id!]
|
const ids = [attrs.id!]
|
||||||
if (Array.isArray(content)) {
|
if (Array.isArray(content)) {
|
||||||
const items = getBinaryNodeChildren(content[0], 'item')
|
const items = getBinaryNodeChildren(content[0], 'item')
|
||||||
@@ -2199,6 +2205,11 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
|
|
||||||
const handleNotification = async (node: BinaryNode) => {
|
const handleNotification = async (node: BinaryNode) => {
|
||||||
const remoteJid = node.attrs.from
|
const remoteJid = node.attrs.from
|
||||||
|
if (shouldIgnoreJid(remoteJid!) && remoteJid !== S_WHATSAPP_NET) {
|
||||||
|
logger.trace({ remoteJid }, 'ignored notification')
|
||||||
|
await sendMessageAck(node)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await Promise.all([
|
await Promise.all([
|
||||||
@@ -2235,6 +2246,12 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const handleMessage = async (node: BinaryNode) => {
|
const handleMessage = async (node: BinaryNode) => {
|
||||||
|
if (shouldIgnoreJid(node.attrs.from!) && node.attrs.from !== S_WHATSAPP_NET) {
|
||||||
|
logger.trace({ from: node.attrs.from }, 'ignored message')
|
||||||
|
await sendMessageAck(node)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
const encNode = getBinaryNodeChild(node, 'enc')
|
const encNode = getBinaryNodeChild(node, 'enc')
|
||||||
const unavailableNode = getBinaryNodeChild(node, 'unavailable')
|
const unavailableNode = getBinaryNodeChild(node, 'unavailable')
|
||||||
|
|
||||||
@@ -3088,40 +3105,6 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
identifier: string,
|
identifier: string,
|
||||||
exec: (node: BinaryNode) => Promise<void>
|
exec: (node: BinaryNode) => Promise<void>
|
||||||
) => {
|
) => {
|
||||||
// Fast path: ack and drop ignored JIDs before entering the buffer/queue.
|
|
||||||
// Skips type='call' so call events are never silently dropped via
|
|
||||||
// shouldIgnoreJid (preserves InfiniteAPI's pre-existing behavior).
|
|
||||||
// Wrapped in try/catch so a throw from shouldIgnoreJid (user callback)
|
|
||||||
// or sendMessageAck (e.g. websocket closed) is routed through
|
|
||||||
// onUnexpectedError instead of becoming an unhandled rejection —
|
|
||||||
// matches the protection processNodeWithBuffer provides.
|
|
||||||
if (type !== 'call') {
|
|
||||||
try {
|
|
||||||
const from = node.attrs.from
|
|
||||||
let ignoreJid = from
|
|
||||||
if (type === 'receipt' && from) {
|
|
||||||
const attrs = node.attrs
|
|
||||||
const isLid = attrs.from!.includes('lid')
|
|
||||||
const isNodeFromMe = areJidsSameUser(
|
|
||||||
attrs.participant || attrs.from,
|
|
||||||
isLid ? authState.creds.me?.lid : authState.creds.me?.id
|
|
||||||
)
|
|
||||||
ignoreJid = !isNodeFromMe || isJidGroup(attrs.from) ? attrs.from : attrs.recipient
|
|
||||||
}
|
|
||||||
|
|
||||||
if (ignoreJid && ignoreJid !== S_WHATSAPP_NET && shouldIgnoreJid(ignoreJid)) {
|
|
||||||
// Plain ack (no NACK error code) preserves InfiniteAPI's prior
|
|
||||||
// behavior — ignored stanzas are an intentional drop, not a
|
|
||||||
// processing failure, so we don't want server-side retries.
|
|
||||||
await sendMessageAck(node)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
onUnexpectedError(error as Error, identifier)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const isOffline = !!node.attrs.offline
|
const isOffline = !!node.attrs.offline
|
||||||
|
|
||||||
if (isOffline) {
|
if (isOffline) {
|
||||||
|
|||||||
+11
-11
@@ -1,6 +1,5 @@
|
|||||||
import { pipeline } from 'stream/promises'
|
|
||||||
import { promisify } from 'util'
|
import { promisify } from 'util'
|
||||||
import { createInflate, inflate } from 'zlib'
|
import { inflate } from 'zlib'
|
||||||
import { proto } from '../../WAProto/index.js'
|
import { proto } from '../../WAProto/index.js'
|
||||||
import type { Chat, Contact, LIDMapping, WAMessage } from '../Types'
|
import type { Chat, Contact, LIDMapping, WAMessage } from '../Types'
|
||||||
import { WAMessageStubType } from '../Types'
|
import { WAMessageStubType } from '../Types'
|
||||||
@@ -30,15 +29,16 @@ const inflatePromise = promisify(inflate)
|
|||||||
*/
|
*/
|
||||||
export const downloadHistory = async (msg: proto.Message.IHistorySyncNotification, options: RequestInit) => {
|
export const downloadHistory = async (msg: proto.Message.IHistorySyncNotification, options: RequestInit) => {
|
||||||
const stream = await downloadContentFromMessage(msg, 'md-msg-hist', { options })
|
const stream = await downloadContentFromMessage(msg, 'md-msg-hist', { options })
|
||||||
// Pipe decrypted stream directly through zlib inflate.
|
const bufferArray: Buffer[] = []
|
||||||
// Avoids allocating an intermediate buffer for the compressed payload —
|
for await (const chunk of stream) {
|
||||||
// memory peaks during 50MB history syncs drop ~50% (PR upstream #2333).
|
bufferArray.push(chunk)
|
||||||
const inflater = createInflate()
|
}
|
||||||
const chunks: Buffer[] = []
|
|
||||||
inflater.on('data', (chunk: Buffer) => chunks.push(chunk))
|
let buffer: Buffer = Buffer.concat(bufferArray)
|
||||||
await pipeline(stream, inflater)
|
|
||||||
|
// decompress buffer
|
||||||
|
buffer = await inflatePromise(buffer)
|
||||||
|
|
||||||
const buffer = Buffer.concat(chunks)
|
|
||||||
const syncData = proto.HistorySync.decode(buffer)
|
const syncData = proto.HistorySync.decode(buffer)
|
||||||
return syncData
|
return syncData
|
||||||
}
|
}
|
||||||
@@ -361,7 +361,7 @@ export const processHistoryMessage = (item: proto.IHistorySync, logger?: ILogger
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
chats.push(chat)
|
chats.push({ ...chat })
|
||||||
}
|
}
|
||||||
|
|
||||||
break
|
break
|
||||||
|
|||||||
@@ -618,7 +618,7 @@ export const downloadEncryptedContent = async (
|
|||||||
|
|
||||||
const output = new Transform({
|
const output = new Transform({
|
||||||
transform(chunk, _, callback) {
|
transform(chunk, _, callback) {
|
||||||
let data = remainingBytes.length ? Buffer.concat([remainingBytes, chunk]) : chunk
|
let data = Buffer.concat([remainingBytes, chunk])
|
||||||
|
|
||||||
const decryptLength = toSmallestChunkSize(data.length)
|
const decryptLength = toSmallestChunkSize(data.length)
|
||||||
remainingBytes = data.slice(decryptLength)
|
remainingBytes = data.slice(decryptLength)
|
||||||
|
|||||||
@@ -1,209 +0,0 @@
|
|||||||
import Long from 'long'
|
|
||||||
import $protobuf from 'protobufjs/minimal.js'
|
|
||||||
|
|
||||||
const $util = $protobuf.util
|
|
||||||
|
|
||||||
// proto implementation
|
|
||||||
function longToStringOld(value: any, unsigned?: boolean): string {
|
|
||||||
if (typeof value === 'string') return value
|
|
||||||
if (typeof value === 'number') return String(value)
|
|
||||||
if (!$util.Long) return String(value)
|
|
||||||
const normalized = ($util.Long as any).fromValue(value)
|
|
||||||
const prepared =
|
|
||||||
unsigned && normalized && typeof normalized.toUnsigned === 'function' ? normalized.toUnsigned() : normalized
|
|
||||||
return prepared.toString()
|
|
||||||
}
|
|
||||||
|
|
||||||
// bigint implementation
|
|
||||||
function longToStringNew(value: any, unsigned?: boolean): string {
|
|
||||||
if (typeof value === 'string') return value
|
|
||||||
if (typeof value === 'number') return String(value)
|
|
||||||
if (value && typeof value.low === 'number' && typeof value.high === 'number') {
|
|
||||||
const high = value.high | 0
|
|
||||||
const lo = BigInt(value.low >>> 0)
|
|
||||||
const hi = BigInt(value.high >>> 0)
|
|
||||||
const combined = (hi << 32n) | lo
|
|
||||||
if (!unsigned && high < 0) {
|
|
||||||
return (combined - (1n << 64n)).toString()
|
|
||||||
}
|
|
||||||
|
|
||||||
return combined.toString()
|
|
||||||
}
|
|
||||||
|
|
||||||
return String(value)
|
|
||||||
}
|
|
||||||
|
|
||||||
function longToNumberOld(value: any, unsigned?: boolean): number {
|
|
||||||
if (typeof value === 'number') return value
|
|
||||||
if (typeof value === 'string') return Number(value)
|
|
||||||
if (!$util.Long) return Number(value)
|
|
||||||
const normalized = ($util.Long as any).fromValue(value)
|
|
||||||
const prepared =
|
|
||||||
unsigned && normalized && typeof normalized.toUnsigned === 'function'
|
|
||||||
? normalized.toUnsigned()
|
|
||||||
: typeof normalized.toSigned === 'function'
|
|
||||||
? normalized.toSigned()
|
|
||||||
: normalized
|
|
||||||
return prepared.toNumber()
|
|
||||||
}
|
|
||||||
|
|
||||||
function longToNumberNew(value: any, unsigned?: boolean): number {
|
|
||||||
if (typeof value === 'number') return value
|
|
||||||
if (typeof value === 'string') return Number(value)
|
|
||||||
if (value && typeof value.low === 'number' && typeof value.high === 'number') {
|
|
||||||
const high = value.high | 0
|
|
||||||
const lo = BigInt(value.low >>> 0)
|
|
||||||
const hi = BigInt(value.high >>> 0)
|
|
||||||
const combined = (hi << 32n) | lo
|
|
||||||
if (!unsigned && high < 0) {
|
|
||||||
return Number(combined - (1n << 64n))
|
|
||||||
}
|
|
||||||
|
|
||||||
return Number(combined)
|
|
||||||
}
|
|
||||||
|
|
||||||
return Number(value)
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('BigInt vs Long equivalence validation', () => {
|
|
||||||
// Test cases: [description, Long value, unsigned flag]
|
|
||||||
const testCases: [string, Long, boolean][] = [
|
|
||||||
// Basic values
|
|
||||||
['zero unsigned', Long.fromNumber(0, true), true],
|
|
||||||
['zero signed', Long.fromNumber(0, false), false],
|
|
||||||
['one unsigned', Long.fromNumber(1, true), true],
|
|
||||||
['one signed', Long.fromNumber(1, false), false],
|
|
||||||
|
|
||||||
// Typical WhatsApp timestamps (seconds since epoch)
|
|
||||||
['timestamp 2023', Long.fromNumber(1700000000, true), true],
|
|
||||||
['timestamp 2025', Long.fromNumber(1750000000, true), true],
|
|
||||||
['timestamp as signed', Long.fromNumber(1700000000, false), false],
|
|
||||||
|
|
||||||
// File sizes
|
|
||||||
['small file', Long.fromNumber(1024, true), true],
|
|
||||||
['medium file 10MB', Long.fromNumber(10485760, true), true],
|
|
||||||
['large file 2GB', Long.fromNumber(2147483648, true), true],
|
|
||||||
|
|
||||||
// Boundary values - 32-bit
|
|
||||||
['max int32', Long.fromNumber(2147483647, false), false],
|
|
||||||
['min int32', Long.fromNumber(-2147483648, false), false],
|
|
||||||
['max uint32', Long.fromNumber(4294967295, true), true],
|
|
||||||
|
|
||||||
// Around MAX_SAFE_INTEGER
|
|
||||||
['MAX_SAFE_INTEGER', Long.fromString('9007199254740991', false), false],
|
|
||||||
['MAX_SAFE_INTEGER + 1', Long.fromString('9007199254740992', false), false],
|
|
||||||
['MAX_SAFE_INTEGER unsigned', Long.fromString('9007199254740991', true), true],
|
|
||||||
|
|
||||||
// Large unsigned values
|
|
||||||
['large unsigned', Long.fromString('9999999999999999999', true), true],
|
|
||||||
['max uint64', Long.fromString('18446744073709551615', true), true],
|
|
||||||
['max uint64 - 1', Long.fromString('18446744073709551614', true), true],
|
|
||||||
|
|
||||||
// Signed negative values
|
|
||||||
['negative one', Long.fromNumber(-1, false), false],
|
|
||||||
['negative small', Long.fromNumber(-100, false), false],
|
|
||||||
['negative large', Long.fromNumber(-2147483648, false), false],
|
|
||||||
['min int64', Long.fromString('-9223372036854775808', false), false],
|
|
||||||
['max int64', Long.fromString('9223372036854775807', false), false],
|
|
||||||
['-1 as signed Long', Long.fromBits(-1, -1, false), false],
|
|
||||||
|
|
||||||
// Tricky bit patterns
|
|
||||||
['high=1, low=0', Long.fromBits(0, 1, true), true],
|
|
||||||
['high=0, low=-1 (0xFFFFFFFF)', Long.fromBits(-1, 0, true), true],
|
|
||||||
['high=-1, low=-1 unsigned (max uint64)', Long.fromBits(-1, -1, true), true],
|
|
||||||
['high=0x7FFFFFFF, low=0xFFFFFFFF (max int64)', Long.fromBits(-1, 0x7fffffff, false), false],
|
|
||||||
['high=0x80000000, low=0 (min int64)', Long.fromBits(0, -2147483648, false), false],
|
|
||||||
|
|
||||||
// Powers of 2
|
|
||||||
['2^32', Long.fromString('4294967296', true), true],
|
|
||||||
['2^32 signed', Long.fromString('4294967296', false), false],
|
|
||||||
['2^48', Long.fromString('281474976710656', true), true],
|
|
||||||
['2^63', Long.fromString('9223372036854775808', true), true]
|
|
||||||
]
|
|
||||||
|
|
||||||
describe('longToString equivalence', () => {
|
|
||||||
for (const [desc, longVal, unsigned] of testCases) {
|
|
||||||
it(`${desc}: Long(${longVal.low}, ${longVal.high}, ${unsigned})`, () => {
|
|
||||||
const oldResult = longToStringOld(longVal, unsigned)
|
|
||||||
const newResult = longToStringNew(longVal, unsigned)
|
|
||||||
expect(newResult).toBe(oldResult)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('longToNumber equivalence', () => {
|
|
||||||
for (const [desc, longVal, unsigned] of testCases) {
|
|
||||||
it(`${desc}: Long(${longVal.low}, ${longVal.high}, ${unsigned})`, () => {
|
|
||||||
const oldResult = longToNumberOld(longVal, unsigned)
|
|
||||||
const newResult = longToNumberNew(longVal, unsigned)
|
|
||||||
// For large values, both may lose precision equally (Number limitation)
|
|
||||||
// So we compare string representations
|
|
||||||
expect(newResult.toString()).toBe(oldResult.toString())
|
|
||||||
})
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('non-Long inputs (fallback paths)', () => {
|
|
||||||
it('string passthrough', () => {
|
|
||||||
expect(longToStringNew('12345')).toBe('12345')
|
|
||||||
expect(longToStringNew('0')).toBe('0')
|
|
||||||
})
|
|
||||||
it('number passthrough', () => {
|
|
||||||
expect(longToStringNew(42)).toBe('42')
|
|
||||||
expect(longToStringNew(0)).toBe('0')
|
|
||||||
expect(longToStringNew(-1)).toBe('-1')
|
|
||||||
})
|
|
||||||
it('null/undefined fallback', () => {
|
|
||||||
expect(longToStringNew(null)).toBe('null')
|
|
||||||
expect(longToStringNew(undefined)).toBe('undefined')
|
|
||||||
})
|
|
||||||
it('object without low/high', () => {
|
|
||||||
expect(longToStringNew({ foo: 'bar' })).toBe('[object Object]')
|
|
||||||
})
|
|
||||||
|
|
||||||
// Defensive: a raw {low, high} JSON object can carry `high` as an
|
|
||||||
// unsigned 32-bit value (Long.fromBits would normalize via `| 0`,
|
|
||||||
// but plain JSON deserialization does not). Without `value.high | 0`
|
|
||||||
// the sign-bit check fails and the result is interpreted as unsigned.
|
|
||||||
// Upstream Baileys PR #2333 has this latent bug; InfiniteAPI fixes it.
|
|
||||||
it('signed sign-bit detection on raw unsigned high (-1 as {low: -1, high: 4294967295})', () => {
|
|
||||||
const raw = { low: -1, high: 0xffffffff }
|
|
||||||
// signed: -1
|
|
||||||
expect(longToStringNew(raw, false)).toBe('-1')
|
|
||||||
// unsigned: max uint64
|
|
||||||
expect(longToStringNew(raw, true)).toBe('18446744073709551615')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('signed sign-bit detection on raw unsigned high (-4294967296 as {low: 0, high: 4294967295})', () => {
|
|
||||||
const raw = { low: 0, high: 0xffffffff }
|
|
||||||
// signed: -4294967296 (high word = -1 after normalization)
|
|
||||||
expect(longToStringNew(raw, false)).toBe('-4294967296')
|
|
||||||
// unsigned: 0xFFFFFFFF00000000 = 18446744069414584320
|
|
||||||
expect(longToStringNew(raw, true)).toBe('18446744069414584320')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('fuzz: random Long values', () => {
|
|
||||||
it('100 random unsigned values match', () => {
|
|
||||||
for (let i = 0; i < 100; i++) {
|
|
||||||
const low = (Math.random() * 0xffffffff) | 0
|
|
||||||
const high = (Math.random() * 0xffffffff) | 0
|
|
||||||
const longVal = Long.fromBits(low, high, true)
|
|
||||||
const oldResult = longToStringOld(longVal, true)
|
|
||||||
const newResult = longToStringNew(longVal, true)
|
|
||||||
expect(newResult).toBe(oldResult)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
it('100 random signed values match', () => {
|
|
||||||
for (let i = 0; i < 100; i++) {
|
|
||||||
const low = (Math.random() * 0xffffffff) | 0
|
|
||||||
const high = (Math.random() * 0xffffffff) | 0
|
|
||||||
const longVal = Long.fromBits(low, high, false)
|
|
||||||
const oldResult = longToStringOld(longVal, false)
|
|
||||||
const newResult = longToStringNew(longVal, false)
|
|
||||||
expect(newResult).toBe(oldResult)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
@@ -1,146 +0,0 @@
|
|||||||
import { jest } from '@jest/globals'
|
|
||||||
import { proto, type WAMessage } from '../..'
|
|
||||||
import { DEFAULT_CONNECTION_CONFIG } from '../../Defaults'
|
|
||||||
import makeWASocket from '../../Socket'
|
|
||||||
import { makeSession, mockWebSocket } from '../TestUtils/session'
|
|
||||||
|
|
||||||
mockWebSocket()
|
|
||||||
|
|
||||||
// chats.ts treats a connection as a reconnection when EITHER signal is true:
|
|
||||||
// 1. authState.creds.accountSyncCounter > 0
|
|
||||||
// (at least one full history sync completed in a previous session)
|
|
||||||
// 2. socketSkippedOfflineBuffer (forwarded from socket.ts as `skipOfflineBuffer`)
|
|
||||||
// (socket.ts already decided to skip the offline buffer, e.g. because
|
|
||||||
// routingInfo was stale and was discarded on startup)
|
|
||||||
// On reconnection, AwaitingInitialSync is skipped and the buffer is flushed
|
|
||||||
// immediately so live messages are not held in the initial-sync window.
|
|
||||||
describe('Reconnection Sync Skip', () => {
|
|
||||||
it('should skip the history sync wait on reconnection (accountSyncCounter > 0)', async () => {
|
|
||||||
const { state, clear } = await makeSession()
|
|
||||||
|
|
||||||
state.creds.me = { id: '1234567890:1@s.whatsapp.net', name: 'Test User' }
|
|
||||||
// Simulate a session that has already synced before
|
|
||||||
state.creds.accountSyncCounter = 1
|
|
||||||
|
|
||||||
const sock = makeWASocket({
|
|
||||||
...DEFAULT_CONNECTION_CONFIG,
|
|
||||||
auth: state
|
|
||||||
})
|
|
||||||
|
|
||||||
const messageListener = jest.fn()
|
|
||||||
sock.ev.on('messages.upsert', messageListener)
|
|
||||||
|
|
||||||
// Simulate receiving pending notifications (triggers AwaitingInitialSync)
|
|
||||||
sock.ev.emit('connection.update', { receivedPendingNotifications: true })
|
|
||||||
|
|
||||||
// Emit a message immediately after — if the wait is skipped,
|
|
||||||
// the buffer should already be flushed and this message should be delivered.
|
|
||||||
const msg = proto.WebMessageInfo.fromObject({
|
|
||||||
key: { remoteJid: '1234567890@s.whatsapp.net', fromMe: false, id: 'MSG_AFTER_RECONNECT' },
|
|
||||||
messageTimestamp: Date.now() / 1000,
|
|
||||||
message: { conversation: 'Hello after reconnect' }
|
|
||||||
}) as WAMessage
|
|
||||||
sock.ev.emit('messages.upsert', { messages: [msg], type: 'notify' })
|
|
||||||
|
|
||||||
await new Promise(resolve => setTimeout(resolve, 50))
|
|
||||||
|
|
||||||
// Message should be delivered immediately, NOT buffered
|
|
||||||
expect(messageListener).toHaveBeenCalledTimes(1)
|
|
||||||
expect(messageListener).toHaveBeenCalledWith(
|
|
||||||
expect.objectContaining({
|
|
||||||
messages: expect.arrayContaining([expect.objectContaining({ key: msg.key })]),
|
|
||||||
type: 'notify'
|
|
||||||
})
|
|
||||||
)
|
|
||||||
|
|
||||||
await sock.end(new Error('Test completed'))
|
|
||||||
await clear()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should skip the history sync wait when socketSkippedOfflineBuffer is true (stale routingInfo, accountSyncCounter === 0)', async () => {
|
|
||||||
const { state, clear } = await makeSession()
|
|
||||||
|
|
||||||
state.creds.me = { id: '1234567890:1@s.whatsapp.net', name: 'Test User' }
|
|
||||||
// Fresh-looking session from the counter perspective
|
|
||||||
state.creds.accountSyncCounter = 0
|
|
||||||
// But routingInfo is present and we ask the socket to discard it on start.
|
|
||||||
// socket.ts will set hadStaleRoutingInfo=true → skipOfflineBuffer=true,
|
|
||||||
// which chats.ts forwards as socketSkippedOfflineBuffer. Without this
|
|
||||||
// branch, the buffers would be misaligned (offline buffer skipped while
|
|
||||||
// AwaitingInitialSync still waits) and live messages would stall.
|
|
||||||
state.creds.routingInfo = Buffer.from([1, 2, 3, 4])
|
|
||||||
|
|
||||||
const sock = makeWASocket({
|
|
||||||
...DEFAULT_CONNECTION_CONFIG,
|
|
||||||
auth: state,
|
|
||||||
clearRoutingInfoOnStart: true
|
|
||||||
})
|
|
||||||
|
|
||||||
const messageListener = jest.fn()
|
|
||||||
sock.ev.on('messages.upsert', messageListener)
|
|
||||||
|
|
||||||
sock.ev.emit('connection.update', { receivedPendingNotifications: true })
|
|
||||||
|
|
||||||
const msg = proto.WebMessageInfo.fromObject({
|
|
||||||
key: { remoteJid: '1234567890@s.whatsapp.net', fromMe: false, id: 'MSG_AFTER_STALE_ROUTING' },
|
|
||||||
messageTimestamp: Date.now() / 1000,
|
|
||||||
message: { conversation: 'Hello after stale routing reconnect' }
|
|
||||||
}) as WAMessage
|
|
||||||
sock.ev.emit('messages.upsert', { messages: [msg], type: 'notify' })
|
|
||||||
|
|
||||||
await new Promise(resolve => setTimeout(resolve, 50))
|
|
||||||
|
|
||||||
expect(messageListener).toHaveBeenCalledTimes(1)
|
|
||||||
expect(messageListener).toHaveBeenCalledWith(
|
|
||||||
expect.objectContaining({
|
|
||||||
messages: expect.arrayContaining([expect.objectContaining({ key: msg.key })]),
|
|
||||||
type: 'notify'
|
|
||||||
})
|
|
||||||
)
|
|
||||||
|
|
||||||
await sock.end(new Error('Test completed'))
|
|
||||||
await clear()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should still wait for history sync on fresh pairing (both signals false)', async () => {
|
|
||||||
const { state, clear } = await makeSession()
|
|
||||||
|
|
||||||
state.creds.me = { id: '1234567890:1@s.whatsapp.net', name: 'Test User' }
|
|
||||||
// Fresh pairing — both reconnect signals are false:
|
|
||||||
// accountSyncCounter is 0 (default) and no stale routingInfo to clear.
|
|
||||||
state.creds.accountSyncCounter = 0
|
|
||||||
|
|
||||||
const sock = makeWASocket({
|
|
||||||
...DEFAULT_CONNECTION_CONFIG,
|
|
||||||
auth: state
|
|
||||||
})
|
|
||||||
|
|
||||||
const messageListener = jest.fn()
|
|
||||||
sock.ev.on('messages.upsert', messageListener)
|
|
||||||
|
|
||||||
sock.ev.emit('connection.update', { receivedPendingNotifications: true })
|
|
||||||
|
|
||||||
const msg = proto.WebMessageInfo.fromObject({
|
|
||||||
key: { remoteJid: '1234567890@s.whatsapp.net', fromMe: false, id: 'MSG_DURING_INITIAL_SYNC' },
|
|
||||||
messageTimestamp: Date.now() / 1000,
|
|
||||||
message: { conversation: 'Hello during initial sync' }
|
|
||||||
}) as WAMessage
|
|
||||||
sock.ev.emit('messages.upsert', { messages: [msg], type: 'notify' })
|
|
||||||
|
|
||||||
await new Promise(resolve => setTimeout(resolve, 50))
|
|
||||||
|
|
||||||
// Message should be BUFFERED (not delivered) because we're waiting for history sync
|
|
||||||
expect(messageListener).toHaveBeenCalledTimes(0)
|
|
||||||
|
|
||||||
// Drain the 2s AwaitingInitialSync timeout (chats.ts:1522) so its callback
|
|
||||||
// doesn't fire after Jest considers the test done — otherwise we get a
|
|
||||||
// "Cannot log after tests are done" warning from the post-teardown flush
|
|
||||||
// and the suite is flagged with --detectOpenHandles. After the timer
|
|
||||||
// fires, syncState becomes Online and the buffer flushes; that delivery
|
|
||||||
// is post-assertion and irrelevant to the test goal.
|
|
||||||
await new Promise(resolve => setTimeout(resolve, 2_100))
|
|
||||||
|
|
||||||
await sock.end(new Error('Test completed'))
|
|
||||||
await clear()
|
|
||||||
}, 10_000)
|
|
||||||
})
|
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
import Long from 'long'
|
|
||||||
import '../index.js'
|
import '../index.js'
|
||||||
import { proto } from '../../WAProto/index.js'
|
import { proto } from '../../WAProto/index.js'
|
||||||
|
|
||||||
@@ -29,91 +28,4 @@ describe('proto serialization', () => {
|
|||||||
const json = message.toJSON()
|
const json = message.toJSON()
|
||||||
expect(json.message?.imageMessage?.fileLength).toBe('1234567890123456789')
|
expect(json.message?.imageMessage?.fileLength).toBe('1234567890123456789')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('converts Long objects to strings correctly via BigInt fast path', () => {
|
|
||||||
const message = proto.WebMessageInfo.fromObject({
|
|
||||||
key: {
|
|
||||||
remoteJid: '123@s.whatsapp.net',
|
|
||||||
id: 'ABC123',
|
|
||||||
fromMe: false
|
|
||||||
},
|
|
||||||
messageTimestamp: Long.fromNumber(1700000000, true),
|
|
||||||
message: {
|
|
||||||
imageMessage: {
|
|
||||||
fileLength: Long.fromString('9876543210', true)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
const json = message.toJSON()
|
|
||||||
expect(json.messageTimestamp).toBe('1700000000')
|
|
||||||
expect(json.message?.imageMessage?.fileLength).toBe('9876543210')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('handles large unsigned Long values (> MAX_SAFE_INTEGER)', () => {
|
|
||||||
const message = proto.WebMessageInfo.fromObject({
|
|
||||||
key: {
|
|
||||||
remoteJid: '123@s.whatsapp.net',
|
|
||||||
id: 'ABC123',
|
|
||||||
fromMe: false
|
|
||||||
},
|
|
||||||
messageTimestamp: Long.fromString('18446744073709551615', true), // max uint64
|
|
||||||
message: {
|
|
||||||
imageMessage: {
|
|
||||||
fileLength: Long.fromString('9999999999999999999', true)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
const json = message.toJSON()
|
|
||||||
expect(json.messageTimestamp).toBe('18446744073709551615')
|
|
||||||
expect(json.message?.imageMessage?.fileLength).toBe('9999999999999999999')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('handles zero and small Long values', () => {
|
|
||||||
const message = proto.WebMessageInfo.fromObject({
|
|
||||||
key: {
|
|
||||||
remoteJid: '123@s.whatsapp.net',
|
|
||||||
id: 'ABC123',
|
|
||||||
fromMe: false
|
|
||||||
},
|
|
||||||
messageTimestamp: Long.fromNumber(0, true),
|
|
||||||
message: {
|
|
||||||
imageMessage: {
|
|
||||||
fileLength: Long.fromNumber(1, true)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
const json = message.toJSON()
|
|
||||||
expect(json.messageTimestamp).toBe('0')
|
|
||||||
expect(json.message?.imageMessage?.fileLength).toBe('1')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('roundtrips encode/decode with Long fields preserving values (> MAX_SAFE_INTEGER)', () => {
|
|
||||||
// Use uint64 values above Number.MAX_SAFE_INTEGER (2^53 - 1) so the
|
|
||||||
// roundtrip actually exercises the BigInt fast path on decode->toJSON.
|
|
||||||
// Safe integers would silently work even if longToString fell back to
|
|
||||||
// Number(value).
|
|
||||||
const original = proto.WebMessageInfo.fromObject({
|
|
||||||
key: {
|
|
||||||
remoteJid: '123@s.whatsapp.net',
|
|
||||||
id: 'ABC123',
|
|
||||||
fromMe: false
|
|
||||||
},
|
|
||||||
messageTimestamp: Long.fromString('18446744073709551615', true),
|
|
||||||
message: {
|
|
||||||
imageMessage: {
|
|
||||||
fileLength: Long.fromString('9999999999999999999', true)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
const encoded = proto.WebMessageInfo.encode(original).finish()
|
|
||||||
const decoded = proto.WebMessageInfo.decode(encoded)
|
|
||||||
const json = decoded.toJSON()
|
|
||||||
|
|
||||||
expect(json.messageTimestamp).toBe('18446744073709551615')
|
|
||||||
expect(json.message?.imageMessage?.fileLength).toBe('9999999999999999999')
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|||||||
Reference in New Issue
Block a user