Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(baileys): read a stored message timestamp as the string it is

Yudhi Armyndharis50e06fdbb461
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ab66df764..bb12ce0c5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -29,6 +29,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- A WebSocket client that emits without an ack callback now receives command replies at all. The gateway answered by returning a frame, which Socket.IO delivers through the ack callback and nowhere else, so a client written to the documented `message` event saw no subscribe confirmation, no pong, and none of the refusals, including the session-scope denial. Replies now go out on `message` as well as through the ack.
- A Baileys message the account sent from its phone is no longer lost when the message store cannot be read. The repeat-delivery check threw on a locked database or an unparseable row and the message was dropped with it, and WhatsApp does not re-deliver one it has already acked; the check now fails open, so at worst such a message is reported twice rather than never.
- Baileys `editMessage` answers with the edited message's id and original send time instead of the edit envelope's. The id named a message no route could address, and both fields disagreed with the whatsapp-web.js engine, which reports the message rather than the edit.
+- Deleting a Baileys message for yourself works again. `DELETE /api/sessions/:sessionId/messages/:messageId` with `forEveryone=false` builds the request from the stored message's send time, and the message store returns that field as a string rather than the number its type promises, so every such call failed with `500` before anything reached WhatsApp.
- Saved Baileys contacts are no longer evicted by peers seen once in a group or a broadcast. Both populations shared one capped map, so a busy session answered `GET /api/sessions/:sessionId/contacts` with fewer and fewer of the contacts the account actually saved. `BAILEYS_SESSION_STORE_MAX_ENTRIES` now bounds the peer side of that map; the saved side is bounded by the account's own address book.
- A Baileys business prompt no longer offers a call-to-action as a clickable choice. A button that opens a URL or dials a number reached `buttons[]` on `message.received` and was accepted by `POST /api/sessions/:sessionId/messages/click-button`, although WhatsApp has no reply form for it.
- A webhook or automation filter written against an `@lid` chat or sender keeps matching once the gateway learns that identity's phone number. Only the event side was resolved through the lid mapping, so an exclusion started delivering the chat it was meant to keep off the wire, and an inclusion stopped delivering, with the rule still reading correctly in the dashboard.
diff --git a/src/engine/adapters/baileys-history.ts b/src/engine/adapters/baileys-history.ts
index d92d1f6ca..0489d0e41 100644
--- a/src/engine/adapters/baileys-history.ts
+++ b/src/engine/adapters/baileys-history.ts
@@ -42,12 +42,30 @@ export interface BaileysHistoryHost {
getOnHistoryMessages(): EngineEventCallbacks['onHistoryMessages'];
}
-/** Baileys timestamps are `number | Long`; normalize to unix seconds. */
-export function toUnixSeconds(ts: number | { toNumber(): number } | null | undefined): number {
+/**
+ * Baileys timestamps are `number | Long`; normalize to unix seconds.
+ *
+ * A third shape reaches here that the proto type does not admit: a decimal STRING. The library
+ * decodes `messageTimestamp` as a Long, and a Long serializes to its decimal string, so every
+ * message read back out of `baileys_messages` (a JSON round trip) carries a string where the type
+ * says number. Delete-for-me and edit both read that field off a stored message, so without this
+ * arm they threw `ts.toNumber is not a function` on a shape the store always produces.
+ *
+ * A string that is not a number falls back to now, like an absent value: a timestamp is never worth
+ * failing an operation over, and NaN would poison every arithmetic consumer downstream.
+ */
+export function toUnixSeconds(ts: number | string | { toNumber(): number } | null | undefined): number {
if (ts == null) {
return Math.floor(Date.now() / 1000);
}
- return typeof ts === 'number' ? ts : ts.toNumber();
+ if (typeof ts === 'number') {
+ return ts;
+ }
+ if (typeof ts === 'string') {
+ const parsed = Number(ts);
+ return Number.isFinite(parsed) ? parsed : Math.floor(Date.now() / 1000);
+ }
+ return ts.toNumber();
}
export class BaileysHistory {
diff --git a/src/engine/adapters/baileys-messaging.ts b/src/engine/adapters/baileys-messaging.ts
index ab62ced4b..2a9edbe93 100644
--- a/src/engine/adapters/baileys-messaging.ts
+++ b/src/engine/adapters/baileys-messaging.ts
@@ -44,7 +44,7 @@ export interface BaileysMessagingHost {
/** The chat's cached disappearing-messages timer (#473), or undefined when none is known. */
getEphemeralExpiration(chatId: string): number | undefined;
/** Baileys timestamps are `number | Long`; normalize to unix seconds. */
- toUnixSeconds(ts: number | { toNumber(): number } | null | undefined): number;
+ toUnixSeconds(ts: number | string | { toNumber(): number } | null | undefined): number;
/** Lazily loaded @whiskeysockets/baileys module (ESM-only; loaded on first connect, not at boot). */
loadLib(): Promise<typeof BaileysLib>;
/** Persist a just-sent message to the store; undefined when no store is configured. */
diff --git a/src/engine/adapters/baileys-status.ts b/src/engine/adapters/baileys-status.ts
index a9f57986c..75b44e21f 100644
--- a/src/engine/adapters/baileys-status.ts
+++ b/src/engine/adapters/baileys-status.ts
@@ -17,7 +17,7 @@ export interface BaileysStatusHost {
toEngineJid(jid: string): string;
normalizedSelfJid(): string;
/** Baileys timestamps are `number | Long`; normalize to unix seconds. */
- toUnixSeconds(ts: number | { toNumber(): number } | null | undefined): number;
+ toUnixSeconds(ts: number | string | { toNumber(): number } | null | undefined): number;
/** Record the id of a message this session just sent, so its library echo is recognised as ours. */
rememberOwnSend(id: string | null | undefined): void;
}
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index ce50ccc6d..12cf58415 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -3519,8 +3519,11 @@ describe('BaileysAdapter store-backed ops', () => {
const ownStored = {
key: { id: 'TARGET', remoteJid: '[email protected]', fromMe: true },
message: { conversation: 'hi' },
- // Distinct from the edit envelope's send time below, so a spec cannot pass on either one.
- messageTimestamp: 1700000000,
+ // A STRING, which is what the store gives back: Baileys decodes `messageTimestamp` as a Long, and
+ // a Long serializes to its decimal string, so the JSON round trip through `baileys_messages` never
+ // returns the number the proto type advertises. Also distinct from the edit envelope's send time
+ // below, so a spec cannot pass on either one.
+ messageTimestamp: '1700000000',
};
it('replyToMessage quotes the stored message', async () => {
@@ -3713,7 +3716,8 @@ describe('BaileysAdapter store-backed ops', () => {
});
it('deleteMessage for-me (forEveryone=false) deletes via chatModify({ deleteForMe })', async () => {
- fakeStore.getMessage.mockResolvedValue({ ...stored, messageTimestamp: 1700000007 });
+ // The stored timestamp is a STRING, which is the only shape the store returns: see toUnixSeconds.
+ fakeStore.getMessage.mockResolvedValue({ ...stored, messageTimestamp: '1700000007' });
const adapter = await ready();
await adapter.deleteMessage('[email protected]', 'TARGET', false);
expect(fakeSock.chatModify).toHaveBeenCalledWith(
@@ -3723,6 +3727,17 @@ describe('BaileysAdapter store-backed ops', () => {
expect(fakeSock.sendMessage).not.toHaveBeenCalled();
});
+ it('deleteMessage for-me sends a usable timestamp when the stored one is unreadable', async () => {
+ // A row written by an older build, or hand-edited: better a slightly wrong instant than NaN on
+ // the wire, which WhatsApp would reject and which no consumer downstream can do arithmetic on.
+ fakeStore.getMessage.mockResolvedValue({ ...stored, messageTimestamp: 'not-a-number' });
+ const adapter = await ready();
+ await adapter.deleteMessage('[email protected]', 'TARGET', false);
+ const [payload] = fakeSock.chatModify.mock.calls[0] as [{ deleteForMe: { timestamp: number } }];
+ expect(Number.isFinite(payload.deleteForMe.timestamp)).toBe(true);
+ expect(payload.deleteForMe.timestamp).toBeGreaterThan(1_600_000_000);
+ });
+
it('editMessage re-applies participant tags to the new body', async () => {
// An edit REPLACES the content, so a body that still reads "@62811" needs the tag list resent or
// the rewritten message loses the tag the original had.