@oxidezap/baileyrs 0.3.4 → 0.3.6

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.
package/README.md CHANGED
@@ -268,6 +268,24 @@ preserved. No QR re-scan, no logged-out events.
268
268
 
269
269
  A few behaviors that differ from upstream — almost always to your advantage:
270
270
 
271
+ - **History contacts stay on `messaging-history.set`.** During HistorySync,
272
+ read the `contacts` array from that event to hydrate a contact store. baileyrs
273
+ does not re-emit those snapshot entries through `contacts.upsert`, including
274
+ push-name-only syncs. Semantic updates such as `contacts.update` still emit
275
+ normally for inbound push names and contact changes.
276
+
277
+ - **`shouldSyncHistoryMessage` is supported, on a partial notification view.**
278
+ The policy runs before the engine downloads or parses history content and
279
+ receives a decoded `HistorySyncNotification` carrying only that pre-download
280
+ metadata: `syncType`, `chunkOrder`, `progress`, `fileLength` (as `Long`) and
281
+ `peerDataRequestSessionId`. Media and key fields stay absent rather than
282
+ synthesized, and sync types outside the upstream processable set are rejected
283
+ after the callback runs. Returning `false` permanently acknowledges the
284
+ chunk — no retry — so it is not a transient load-shedding hook. Requesting
285
+ full history (`syncFullHistory`) stays engine-owned, and unlike upstream the
286
+ policy is not re-invoked to gate the initial-sync state machine: admission
287
+ covers received notifications only.
288
+
271
289
  - **An undecryptable message tells you what it was.** The CIPHERTEXT stub
272
290
  emitted on `messages.upsert` for a message that failed to decrypt carries
273
291
  `stanzaType`: the envelope's `type` attribute as the server stamped it on the
@@ -314,8 +332,8 @@ A few behaviors that differ from upstream — almost always to your advantage:
314
332
  authority — the type system requires each `SocketConfig` member to be
315
333
  classified, so it cannot fall behind — and it also covers `keepAliveIntervalMs`,
316
334
  `markOnlineOnConnect`, `maxMsgRetryCount`, `msgRetryCounterCache`,
317
- `retryRequestDelayMs`, `fireInitQueries`, `syncFullHistory`,
318
- `shouldSyncHistoryMessage`, `generateHighQualityLinkPreview`,
335
+ `retryRequestDelayMs`, `fireInitQueries`, `syncFullHistory`,
336
+ `generateHighQualityLinkPreview`,
319
337
  `linkPreviewImageThumbnailWidth`, `enableAutoSessionRecreation`,
320
338
  `enableRecentMessageCache`, `appStateMacVerification`,
321
339
  `patchMessageBeforeSending`, `customUploadHosts`, `countryCode`,
@@ -0,0 +1,55 @@
1
+ import type { HistorySyncAdmissionMetadata } from '@oxidezap/whatsapp-rust-bridge';
2
+ import type { proto } from '../WAProto/runtime.js';
3
+ export type SocketHistoryPolicy = (message: proto.Message.IHistorySyncNotification) => boolean;
4
+ /**
5
+ * Rebuilds the Baileys notification view from the metadata the bridge can
6
+ * inspect before downloading or parsing history-sync content.
7
+ *
8
+ * Partial view, by design: only `syncType`, `chunkOrder`, `progress`,
9
+ * `fileLength` and `peerDataRequestSessionId` cross the pre-download
10
+ * boundary. Media and key fields (`fileSha256`, `mediaKey`, `fileEncSha256`,
11
+ * `directPath`, `oldestMsgInChunkTimestampSec`,
12
+ * `fullHistorySyncOnDemandRequestMetadata`, `encHandle`, …) stay absent —
13
+ * never synthesized — so a policy filtering on them sees `undefined`, not a
14
+ * fabricated value.
15
+ *
16
+ * Only present fields become own properties: the result is a decoded
17
+ * `HistorySyncNotification` instance, so `Object.keys`, `Object.hasOwn` and
18
+ * `instanceof` match what Baileys hands its own policy.
19
+ */
20
+ export declare const historySyncNotificationFromMetadata: (metadata: HistorySyncAdmissionMetadata) => proto.Message.IHistorySyncNotification;
21
+ /**
22
+ * Resolve the configured policy, falling back to the default when the caller
23
+ * spread an explicit `undefined` over it. Without this the shallow config
24
+ * merge would replace the default with `undefined` and the first history
25
+ * notification would die as a callback `TypeError` — rejected and permanently
26
+ * acknowledged by the bridge.
27
+ */
28
+ export declare const resolveHistorySyncPolicy: (configured: SocketHistoryPolicy | undefined) => SocketHistoryPolicy;
29
+ /**
30
+ * Probe whether the policy rejects every upstream-processable sync type.
31
+ * Mirrors the upstream socket-construction check, including its call pattern:
32
+ * the policy runs once per processable type against a synthetic
33
+ * `{ syncType }` notification. Disabling everything also drops the initial
34
+ * LID mappings, which destabilizes sessions — hence the warning at the call
35
+ * site.
36
+ *
37
+ * One deliberate deviation: a probe call that throws is treated as
38
+ * potentially enabling rather than propagating. The probe is diagnostic-only,
39
+ * and a socket must never fail to build over a diagnostic — upstream lets
40
+ * that throw out of construction. Stateful policies still observe these
41
+ * calls, exactly as they do upstream.
42
+ */
43
+ export declare const isHistorySyncFullyDisabled: (shouldSyncHistoryMessage: SocketHistoryPolicy) => boolean;
44
+ /**
45
+ * Adapt the Baileys history policy to the bridge's pre-download policy.
46
+ *
47
+ * Order matches upstream: the callback runs first, then the processable-type
48
+ * gate. Unknown or absent `syncType` values are therefore rejected even when
49
+ * the callback accepts them, because the core enqueues whatever this policy
50
+ * admits with no further type filtering.
51
+ */
52
+ export declare const makeHistorySyncAdmission: (shouldSyncHistoryMessage: SocketHistoryPolicy) => {
53
+ historySyncAdmission: (metadata: HistorySyncAdmissionMetadata) => boolean;
54
+ };
55
+ //# sourceMappingURL=history-sync-admission.d.ts.map
@@ -0,0 +1,84 @@
1
+ import Long from 'long';
2
+ import { DEFAULT_CONNECTION_CONFIG, PROCESSABLE_HISTORY_TYPES } from '../Defaults/index.js';
3
+ import { proto as protoRuntime } from '../WAProto/runtime.js';
4
+ /**
5
+ * Rebuilds the Baileys notification view from the metadata the bridge can
6
+ * inspect before downloading or parsing history-sync content.
7
+ *
8
+ * Partial view, by design: only `syncType`, `chunkOrder`, `progress`,
9
+ * `fileLength` and `peerDataRequestSessionId` cross the pre-download
10
+ * boundary. Media and key fields (`fileSha256`, `mediaKey`, `fileEncSha256`,
11
+ * `directPath`, `oldestMsgInChunkTimestampSec`,
12
+ * `fullHistorySyncOnDemandRequestMetadata`, `encHandle`, …) stay absent —
13
+ * never synthesized — so a policy filtering on them sees `undefined`, not a
14
+ * fabricated value.
15
+ *
16
+ * Only present fields become own properties: the result is a decoded
17
+ * `HistorySyncNotification` instance, so `Object.keys`, `Object.hasOwn` and
18
+ * `instanceof` match what Baileys hands its own policy.
19
+ */
20
+ export const historySyncNotificationFromMetadata = (metadata) => {
21
+ const fields = {};
22
+ if (metadata.syncType !== undefined) {
23
+ fields.syncType = metadata.syncType;
24
+ }
25
+ if (metadata.chunkOrder !== undefined) {
26
+ fields.chunkOrder = metadata.chunkOrder;
27
+ }
28
+ if (metadata.progress !== undefined) {
29
+ fields.progress = metadata.progress;
30
+ }
31
+ if (metadata.fileLength !== undefined) {
32
+ fields.fileLength = Long.fromString(metadata.fileLength, true);
33
+ }
34
+ if (metadata.peerDataRequestSessionId !== undefined) {
35
+ fields.peerDataRequestSessionId = metadata.peerDataRequestSessionId;
36
+ }
37
+ return protoRuntime.Message.HistorySyncNotification.create(fields);
38
+ };
39
+ /**
40
+ * Resolve the configured policy, falling back to the default when the caller
41
+ * spread an explicit `undefined` over it. Without this the shallow config
42
+ * merge would replace the default with `undefined` and the first history
43
+ * notification would die as a callback `TypeError` — rejected and permanently
44
+ * acknowledged by the bridge.
45
+ */
46
+ export const resolveHistorySyncPolicy = (configured) => configured ?? DEFAULT_CONNECTION_CONFIG.shouldSyncHistoryMessage;
47
+ /**
48
+ * Probe whether the policy rejects every upstream-processable sync type.
49
+ * Mirrors the upstream socket-construction check, including its call pattern:
50
+ * the policy runs once per processable type against a synthetic
51
+ * `{ syncType }` notification. Disabling everything also drops the initial
52
+ * LID mappings, which destabilizes sessions — hence the warning at the call
53
+ * site.
54
+ *
55
+ * One deliberate deviation: a probe call that throws is treated as
56
+ * potentially enabling rather than propagating. The probe is diagnostic-only,
57
+ * and a socket must never fail to build over a diagnostic — upstream lets
58
+ * that throw out of construction. Stateful policies still observe these
59
+ * calls, exactly as they do upstream.
60
+ */
61
+ export const isHistorySyncFullyDisabled = (shouldSyncHistoryMessage) => PROCESSABLE_HISTORY_TYPES.every(syncType => {
62
+ try {
63
+ return shouldSyncHistoryMessage({ syncType }) === false;
64
+ }
65
+ catch {
66
+ return false;
67
+ }
68
+ });
69
+ /**
70
+ * Adapt the Baileys history policy to the bridge's pre-download policy.
71
+ *
72
+ * Order matches upstream: the callback runs first, then the processable-type
73
+ * gate. Unknown or absent `syncType` values are therefore rejected even when
74
+ * the callback accepts them, because the core enqueues whatever this policy
75
+ * admits with no further type filtering.
76
+ */
77
+ export const makeHistorySyncAdmission = (shouldSyncHistoryMessage) => ({
78
+ historySyncAdmission: metadata => {
79
+ const notification = historySyncNotificationFromMetadata(metadata);
80
+ const accepted = shouldSyncHistoryMessage(notification);
81
+ return accepted && PROCESSABLE_HISTORY_TYPES.includes(notification.syncType);
82
+ }
83
+ });
84
+ //# sourceMappingURL=history-sync-admission.js.map
@@ -866,15 +866,10 @@ const DISPATCHERS = {
866
866
  lidPnMappings: evt.lidPnMappings.length > 0 ? evt.lidPnMappings : undefined
867
867
  };
868
868
  ctx.ev.emit('messaging-history.set', payload);
869
- // Also fan out to `chats.upsert` / `contacts.upsert` so bots that
870
- // wire those (instead of, or in addition to, messaging-history.set)
871
- // get hydrated. Upstream emits both channels from different code
872
- // paths; we collapse them here so consumers picking either pattern
873
- // see the same data on the first pair.
869
+ // Keep the chat hydration fan-out for compatibility. Contacts are part
870
+ // of the history snapshot and must not be re-emitted as mutations.
874
871
  if (evt.chats.length > 0)
875
872
  ctx.ev.emit('chats.upsert', evt.chats);
876
- if (evt.contacts.length > 0)
877
- ctx.ev.emit('contacts.upsert', evt.contacts);
878
873
  }
879
874
  };
880
875
  const dispatchCanonicalEvent = (canonical, dispatchCtx) => {
@@ -20,6 +20,7 @@ import { Boom } from '../Utils/boom.js';
20
20
  import { makeEventBuffer } from '../Utils/event-buffer.js';
21
21
  import { _registerActiveBridgeClient, _unregisterActiveBridgeClient, downloadMediaMessage, MEDIA_DOWNLOAD_TYPES } from '../Utils/messages.js';
22
22
  import { makeNativeCryptoProvider } from '../Utils/native-crypto-provider.js';
23
+ import { makeHistorySyncAdmission, resolveHistorySyncPolicy, isHistorySyncFullyDisabled } from '../Compatibility/history-sync-admission.js';
23
24
  import { wrapLegacyStore } from '../Utils/wrap-legacy-store.js';
24
25
  import { assertNodeErrorFree } from '../WABinary/generic-utils.js';
25
26
  import { makeBlockingMethods } from './blocking.js';
@@ -104,6 +105,13 @@ const makeWASocket = (config) => {
104
105
  // is worth naming. Merging the defaults first would report every unsupported
105
106
  // option on every socket, including the ones nobody chose.
106
107
  warnUnsupportedConfig(config, logger);
108
+ // `Partial<SocketConfig>` lets an explicit `undefined` overwrite the default
109
+ // in the shallow merge above; resolve against the raw config so the socket
110
+ // keeps the default policy instead of throwing on the first notification.
111
+ const shouldSyncHistoryMessage = resolveHistorySyncPolicy(config.shouldSyncHistoryMessage);
112
+ if (isHistorySyncFullyDisabled(shouldSyncHistoryMessage)) {
113
+ logger.warn('⚠️ DANGER: DISABLING ALL SYNC BY shouldSyncHistoryMsg PREVENTS BAILEYS FROM ACCESSING INITIAL LID MAPPINGS, LEADING TO INSTABILIY AND SESSION ERRORS');
114
+ }
107
115
  const auth = normalizeSocketAuthenticationState(fullConfig.auth);
108
116
  const getExposedKeys = makeLazyTransactionKeyStore(auth.keys, logger, fullConfig.transactionOpts);
109
117
  const ev = makeEventBuffer(logger);
@@ -492,7 +500,7 @@ const makeWASocket = (config) => {
492
500
  // other truthy value at construction, so a `!!`/ternary-style
493
501
  // coercion could promote a malformed opt-out into an opt-in.
494
502
  // Absent stays strict.
495
- fullConfig.dangerSkipCertChainVerify);
503
+ fullConfig.dangerSkipCertChainVerify, makeHistorySyncAdmission(shouldSyncHistoryMessage));
496
504
  // `end()` can land while the client is still being built — a `sock.end()`
497
505
  // or `await using` right after `makeWASocket()` does exactly that. When
498
506
  // it has, `adopt` frees this client and tells us to stop: nothing else
@@ -24,7 +24,7 @@
24
24
  * a type would look supported. A test anchors every entry to `SocketConfig`, so
25
25
  * an option that starts being read here fails the audit for whoever removes it.
26
26
  */
27
- export declare const UNSUPPORTED_CONFIG_KEYS: readonly ["keepAliveIntervalMs", "maxMsgRetryCount", "msgRetryCounterCache", "retryRequestDelayMs", "fireInitQueries", "markOnlineOnConnect", "syncFullHistory", "shouldSyncHistoryMessage", "generateHighQualityLinkPreview", "linkPreviewImageThumbnailWidth", "enableAutoSessionRecreation", "enableRecentMessageCache", "appStateMacVerification", "cachedGroupMetadata", "getMessage", "patchMessageBeforeSending", "customUploadHosts", "countryCode", "connectTimeoutMs", "qrTimeout", "agent", "fetchAgent", "mobile", "printQRInTerminal", "ignoreOfflineMessages", "downloadHistory", "mediaCache", "userDevicesCache", "callOfferCache", "placeholderResendCache"];
27
+ export declare const UNSUPPORTED_CONFIG_KEYS: readonly ["keepAliveIntervalMs", "maxMsgRetryCount", "msgRetryCounterCache", "retryRequestDelayMs", "fireInitQueries", "markOnlineOnConnect", "syncFullHistory", "generateHighQualityLinkPreview", "linkPreviewImageThumbnailWidth", "enableAutoSessionRecreation", "enableRecentMessageCache", "appStateMacVerification", "cachedGroupMetadata", "getMessage", "patchMessageBeforeSending", "customUploadHosts", "countryCode", "connectTimeoutMs", "qrTimeout", "agent", "fetchAgent", "mobile", "printQRInTerminal", "ignoreOfflineMessages", "downloadHistory", "mediaCache", "userDevicesCache", "callOfferCache", "placeholderResendCache"];
28
28
  /**
29
29
  * The other half: options something on this side actually reads.
30
30
  *
@@ -33,7 +33,7 @@ export declare const UNSUPPORTED_CONFIG_KEYS: readonly ["keepAliveIntervalMs", "
33
33
  * member of `SocketConfig` belongs to neither list — which is exactly how the
34
34
  * first version of the catalog shipped twelve keys short.
35
35
  */
36
- export declare const READ_CONFIG_KEYS: readonly ["waWebSocketUrl", "options", "logger", "version", "browser", "pushName", "auth", "cache", "deviceProps", "wantedPreKeyCount", "dangerSkipCertChainVerify", "emitOwnEvents", "shouldIgnoreJid", "defaultQueryTimeoutMs", "transactionOpts", "makeSignalRepository"];
36
+ export declare const READ_CONFIG_KEYS: readonly ["waWebSocketUrl", "options", "logger", "version", "browser", "pushName", "auth", "cache", "deviceProps", "wantedPreKeyCount", "dangerSkipCertChainVerify", "shouldSyncHistoryMessage", "emitOwnEvents", "shouldIgnoreJid", "defaultQueryTimeoutMs", "transactionOpts", "makeSignalRepository"];
37
37
  /**
38
38
  * Which unsupported options this caller actually passed.
39
39
  *
@@ -37,9 +37,9 @@ export const UNSUPPORTED_CONFIG_KEYS = [
37
37
  'fireInitQueries',
38
38
  // Presence is explicit here: call `sendPresenceUpdate` after `open`.
39
39
  'markOnlineOnConnect',
40
- // History sync is driven by the engine.
40
+ // Full-history requests are driven by the engine. The per-notification
41
+ // admission policy is translated by Socket/index.ts.
41
42
  'syncFullHistory',
42
- 'shouldSyncHistoryMessage',
43
43
  // Link previews are not generated on this side.
44
44
  'generateHighQualityLinkPreview',
45
45
  'linkPreviewImageThumbnailWidth',
@@ -99,6 +99,7 @@ export const READ_CONFIG_KEYS = [
99
99
  'deviceProps',
100
100
  'wantedPreKeyCount',
101
101
  'dangerSkipCertChainVerify',
102
+ 'shouldSyncHistoryMessage',
102
103
  'emitOwnEvents',
103
104
  'shouldIgnoreJid',
104
105
  'defaultQueryTimeoutMs',
@@ -130,7 +130,17 @@ export type SocketConfig = {
130
130
  countryCode: string;
131
131
  /** @deprecated History download policy lives in the bridge. */
132
132
  downloadHistory?: boolean;
133
- /** Decide whether a history notification should be processed. */
133
+ /**
134
+ * Decide whether a history notification should be processed.
135
+ *
136
+ * Partial notification view: the callback receives a decoded
137
+ * `HistorySyncNotification` carrying only pre-download metadata
138
+ * (`syncType`, `chunkOrder`, `progress`, `fileLength` as `Long`,
139
+ * `peerDataRequestSessionId`). Media and key fields stay absent rather
140
+ * than synthesized, and types outside the upstream processable set are
141
+ * rejected after the callback runs. `false` permanently acknowledges the
142
+ * chunk — no retry — so this is not a transient load-shedding hook.
143
+ */
134
144
  shouldSyncHistoryMessage: (msg: proto.Message.IHistorySyncNotification) => boolean;
135
145
  /** @deprecated QR rendering is the caller's responsibility — listen on `connection.update` for the QR string. */
136
146
  printQRInTerminal?: boolean;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@oxidezap/baileyrs",
3
3
  "type": "module",
4
- "version": "0.3.4",
4
+ "version": "0.3.6",
5
5
  "description": "A Rust-powered WhatsApp Web library for JavaScript, with a Baileys-compatible API",
6
6
  "keywords": [
7
7
  "whatsapp",
@@ -82,7 +82,7 @@
82
82
  "test:e2e": "NODE_TLS_REJECT_UNAUTHORIZED=0 ADV_SECRET_KEY=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= node --expose-gc --test --test-concurrency=1 ./src/__tests__/e2e/*.test-e2e.ts ./scripts/compatibility/__tests__/*.test-e2e.ts"
83
83
  },
84
84
  "dependencies": {
85
- "@oxidezap/whatsapp-rust-bridge": "0.21.4",
85
+ "@oxidezap/whatsapp-rust-bridge": "0.22.0",
86
86
  "long": "^5.3.2"
87
87
  },
88
88
  "devDependencies": {