@oxidezap/baileyrs 0.3.4 → 0.3.7

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
@@ -36,6 +36,25 @@ from the proto schema and compares the two libraries directly. Differences the
36
36
  fuzzers find are recorded with a reason and a review date, and known open ones
37
37
  are listed in `src/__fuzz__/harness/divergence.ts`.
38
38
 
39
+ ### Protobuf field names
40
+
41
+ The bridge and upstream Baileys generate their schemas from different sources, so a
42
+ field can keep its number and wire type and still be spelled differently. The `proto`
43
+ facade always uses the Baileys spelling:
44
+
45
+ | Type | Baileys | Bridge |
46
+ | -------------------------------------- | ------------------------ | -------------------------------- |
47
+ | `SyncActionValue.AgentAction` | `deviceID` | `deviceId` |
48
+ | `SyncActionValue.ChatAssignmentAction` | `deviceAgentID` | `deviceAgentId` |
49
+ | `Message.ExtendedTextMessage` | `faviconMMSMetadata` | `faviconMmsMetadata` |
50
+ | `Message.MessageHistoryMetadata` | `oldestMessageTimestamp` | `oldestMessageTimestampInWindow` |
51
+
52
+ Without the translation a write in the Baileys spelling is dropped by the codec and a
53
+ read never sets the public property. Both the facade and the send path translate, in
54
+ both directions, for fields nested at any depth. An own public property wins over the
55
+ bridge name, including an explicit `null` or `undefined`, and inputs are never
56
+ mutated. The bridge keeps its own names.
57
+
39
58
  ## Documentation
40
59
 
41
60
  The full API reference and guides live in the
@@ -268,6 +287,24 @@ preserved. No QR re-scan, no logged-out events.
268
287
 
269
288
  A few behaviors that differ from upstream — almost always to your advantage:
270
289
 
290
+ - **History contacts stay on `messaging-history.set`.** During HistorySync,
291
+ read the `contacts` array from that event to hydrate a contact store. baileyrs
292
+ does not re-emit those snapshot entries through `contacts.upsert`, including
293
+ push-name-only syncs. Semantic updates such as `contacts.update` still emit
294
+ normally for inbound push names and contact changes.
295
+
296
+ - **`shouldSyncHistoryMessage` is supported, on a partial notification view.**
297
+ The policy runs before the engine downloads or parses history content and
298
+ receives a decoded `HistorySyncNotification` carrying only that pre-download
299
+ metadata: `syncType`, `chunkOrder`, `progress`, `fileLength` (as `Long`) and
300
+ `peerDataRequestSessionId`. Media and key fields stay absent rather than
301
+ synthesized, and sync types outside the upstream processable set are rejected
302
+ after the callback runs. Returning `false` permanently acknowledges the
303
+ chunk — no retry — so it is not a transient load-shedding hook. Requesting
304
+ full history (`syncFullHistory`) stays engine-owned, and unlike upstream the
305
+ policy is not re-invoked to gate the initial-sync state machine: admission
306
+ covers received notifications only.
307
+
271
308
  - **An undecryptable message tells you what it was.** The CIPHERTEXT stub
272
309
  emitted on `messages.upsert` for a message that failed to decrypt carries
273
310
  `stanzaType`: the envelope's `type` attribute as the server stamped it on the
@@ -314,8 +351,8 @@ A few behaviors that differ from upstream — almost always to your advantage:
314
351
  authority — the type system requires each `SocketConfig` member to be
315
352
  classified, so it cannot fall behind — and it also covers `keepAliveIntervalMs`,
316
353
  `markOnlineOnConnect`, `maxMsgRetryCount`, `msgRetryCounterCache`,
317
- `retryRequestDelayMs`, `fireInitQueries`, `syncFullHistory`,
318
- `shouldSyncHistoryMessage`, `generateHighQualityLinkPreview`,
354
+ `retryRequestDelayMs`, `fireInitQueries`, `syncFullHistory`,
355
+ `generateHighQualityLinkPreview`,
319
356
  `linkPreviewImageThumbnailWidth`, `enableAutoSessionRecreation`,
320
357
  `enableRecentMessageCache`, `appStateMacVerification`,
321
358
  `patchMessageBeforeSending`, `customUploadHosts`, `countryCode`,
@@ -12,6 +12,16 @@
12
12
  * absorbed, so the strict contract stays true of the bridge and the tolerant
13
13
  * one stays true of this library.
14
14
  *
15
+ * The three do not all follow the same reference, and the difference is worth
16
+ * stating. The surrogate becomes a single U+FFFD — what any UTF-8 encoder
17
+ * produces, and what the client sends — while upstream protobufjs writes three
18
+ * WTF-8 bytes instead, which is the artifact `replaceLoneSurrogates` in the fuzz
19
+ * registry folds away when it compares. The empty string becoming `0` is the other
20
+ * direction: the client never writes it and the bridge refuses it on purpose, so
21
+ * that one substitution is Baileys compatibility rather than client compliance.
22
+ * It stays because a message that used to reach the server should not start
23
+ * throwing, and it is written down here so it is a decision rather than an accident.
24
+ *
15
25
  * Repair on failure rather than check on write: the ordinary encode is exactly
16
26
  * the call it was before, with no scan of any field, and the repair runs only
17
27
  * for a message that was already going to throw. `encodeProto` returns finished
@@ -1,5 +1,5 @@
1
1
  import { encodeProto } from '@oxidezap/whatsapp-rust-bridge';
2
- import { repairProtoMessage } from './proto-runtime.js';
2
+ import { projectProtoMessage, repairProtoMessage } from './proto-runtime.js';
3
3
  /**
4
4
  * `encodeProto`, with the three inputs the bridge codec refuses put back.
5
5
  *
@@ -14,24 +14,39 @@ import { repairProtoMessage } from './proto-runtime.js';
14
14
  * absorbed, so the strict contract stays true of the bridge and the tolerant
15
15
  * one stays true of this library.
16
16
  *
17
+ * The three do not all follow the same reference, and the difference is worth
18
+ * stating. The surrogate becomes a single U+FFFD — what any UTF-8 encoder
19
+ * produces, and what the client sends — while upstream protobufjs writes three
20
+ * WTF-8 bytes instead, which is the artifact `replaceLoneSurrogates` in the fuzz
21
+ * registry folds away when it compares. The empty string becoming `0` is the other
22
+ * direction: the client never writes it and the bridge refuses it on purpose, so
23
+ * that one substitution is Baileys compatibility rather than client compliance.
24
+ * It stays because a message that used to reach the server should not start
25
+ * throwing, and it is written down here so it is a decision rather than an accident.
26
+ *
17
27
  * Repair on failure rather than check on write: the ordinary encode is exactly
18
28
  * the call it was before, with no scan of any field, and the repair runs only
19
29
  * for a message that was already going to throw. `encodeProto` returns finished
20
30
  * bytes rather than a lazy writer, so one try/catch covers it.
21
31
  */
22
32
  export const encodeProtoCompat = (path, message) => {
33
+ // The codec drops a key it does not know without throwing, so a public spelling has
34
+ // to be translated before the encode: a repair after a throw never runs. Same
35
+ // reference when nothing is aliased.
36
+ const projected = projectProtoMessage(path, message);
23
37
  try {
24
- return encodeProto(path, message);
38
+ return encodeProto(path, projected);
25
39
  }
26
40
  catch (error) {
41
+ // Repaired from the caller's message: this repair walks the schema this library
42
+ // publishes, so the projected names would not be found and the failure would
43
+ // propagate instead of being absorbed.
27
44
  const repaired = repairProtoMessage(path, message);
28
45
  // Reference equality: nothing was coerced, so the failure is something this
29
- // does not explain — an unmodelled type, a number no int64 can hold, an
30
- // unknown enum name — and it has to keep propagating rather than be
31
- // retried into a second throw.
46
+ // does not explain and it has to keep propagating rather than be retried.
32
47
  if (repaired === message)
33
48
  throw error;
34
- return encodeProto(path, repaired);
49
+ return encodeProto(path, projectProtoMessage(path, repaired));
35
50
  }
36
51
  };
37
52
  //# sourceMappingURL=encode-proto.js.map
@@ -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
@@ -9,6 +9,11 @@ type DynamicObject = Record<PropertyKey, unknown>;
9
9
  * repair from a failure it does not understand.
10
10
  */
11
11
  export declare const repairProtoMessage: (path: string, message: unknown) => unknown;
12
+ /**
13
+ * The projection for a caller that addresses the codec by type name. Reference
14
+ * equality means nothing needed translating.
15
+ */
16
+ export declare const projectProtoMessage: (path: string, message: unknown) => unknown;
12
17
  export interface ProtoCompatibilityFacade {
13
18
  proto: DynamicObject;
14
19
  unsupportedCodecs: readonly string[];
@@ -161,6 +161,19 @@ class LongBinaryReader extends BinaryReader {
161
161
  }
162
162
  }
163
163
  const longFromValue = (value, unsigned) => LongRuntime.fromValue(value, unsigned);
164
+ /**
165
+ * The neutral codec hands a 64-bit field back as a number while the value is exact as
166
+ * a double, and as a word split past that, where upstream declares a `Long` whose
167
+ * methods callers use. The decode reader above exists for the same reason.
168
+ */
169
+ const hydratedScalar = (kind, value) => {
170
+ if (value instanceof LongRuntime)
171
+ return value;
172
+ const split = isObject(value) && typeof value.low === 'number' && typeof value.high === 'number';
173
+ if (typeof value !== 'number' && typeof value !== 'string' && !split)
174
+ return value;
175
+ return longFromValue(value, kind === PROTO_FIELD_KIND.unsigned64);
176
+ };
164
177
  const longToBigInt = (value, unsigned) => {
165
178
  if (typeof value === 'bigint')
166
179
  return value;
@@ -279,17 +292,32 @@ const defineLazyValue = (target, key, build) => {
279
292
  });
280
293
  };
281
294
  /**
282
- * Type path to schema index, built on first use.
283
- *
284
- * Only the repair path needs it, and that path is only reached after an encode
285
- * has already failed — so an importer that never sends a refused value never
286
- * pays for the 498 entries.
295
+ * Type path to schema index, built on first use. The projection reads it per send,
296
+ * so the first encoded message builds it.
287
297
  */
288
298
  let schemaIdsByPath;
299
+ let lastSchemaPath;
300
+ let lastSchemaId;
301
+ // The send path asks for one type repeatedly, so the last answer is kept.
289
302
  const schemaIdFor = (path) => {
303
+ if (path === lastSchemaPath)
304
+ return lastSchemaId;
290
305
  schemaIdsByPath ?? (schemaIdsByPath = new Map(PROTO_MESSAGE_SCHEMAS.map(([name], index) => [name, index])));
291
- return schemaIdsByPath.get(path);
306
+ lastSchemaPath = path;
307
+ lastSchemaId = schemaIdsByPath.get(path);
308
+ return lastSchemaId;
292
309
  };
310
+ // Bridge names stay neutral. Both sides put these at the same number and wire type,
311
+ // so only the spelling differs.
312
+ const FIELD_ALIASES = {
313
+ 'SyncActionValue.AgentAction': ['deviceID', 'deviceId'],
314
+ 'SyncActionValue.ChatAssignmentAction': ['deviceAgentID', 'deviceAgentId'],
315
+ 'Message.ExtendedTextMessage': ['faviconMMSMetadata', 'faviconMmsMetadata'],
316
+ 'Message.MessageHistoryMetadata': ['oldestMessageTimestamp', 'oldestMessageTimestampInWindow']
317
+ };
318
+ // Indexed by schema id because its readers run per message.
319
+ let aliasBySchema;
320
+ const aliasFor = (schemaId) => (aliasBySchema ?? (aliasBySchema = PROTO_MESSAGE_SCHEMAS.map(([path]) => FIELD_ALIASES[path])))[schemaId];
293
321
  /**
294
322
  * Coerces the three inputs the bridge codec refuses back to what upstream
295
323
  * Baileys writes, and returns `value` itself when there was nothing to coerce.
@@ -318,10 +346,18 @@ const repairMessage = (schemaId, value, ancestors) => {
318
346
  return value;
319
347
  seen.add(value);
320
348
  let output;
349
+ const alias = aliasFor(schemaId);
321
350
  for (const field of fields) {
322
- if (!hasOwn(value, field[0]))
351
+ // Either spelling reaches the same field number, so a refused value has to be
352
+ // coerced under whichever name it arrived with.
353
+ const fieldKey = hasOwn(value, field[0])
354
+ ? field[0]
355
+ : alias !== undefined && alias[0] === field[0] && hasOwn(value, alias[1])
356
+ ? alias[1]
357
+ : undefined;
358
+ if (fieldKey === undefined)
323
359
  continue;
324
- const current = value[field[0]];
360
+ const current = value[fieldKey];
325
361
  if (current === null || current === undefined)
326
362
  continue;
327
363
  const repair = (item) => {
@@ -361,7 +397,7 @@ const repairMessage = (schemaId, value, ancestors) => {
361
397
  converted = repair(current);
362
398
  }
363
399
  if (converted !== current)
364
- (output ?? (output = { ...value }))[field[0]] = converted;
400
+ (output ?? (output = { ...value }))[fieldKey] = converted;
365
401
  }
366
402
  // The ancestor path, not everything ever visited: the same object reached
367
403
  // twice in different branches is legitimate and must still be repaired.
@@ -381,10 +417,117 @@ export const repairProtoMessage = (path, message) => {
381
417
  const schemaId = schemaIdFor(path);
382
418
  return schemaId === undefined ? message : repairMessage(schemaId, message);
383
419
  };
420
+ /**
421
+ * Message-typed fields by name, built on first use. Keyed by the message rather than
422
+ * the schema, which is what keeps the send-path walk proportional to the message.
423
+ */
424
+ const messageFieldsByNameBySchema = [];
425
+ const messageFieldsOf = (schemaId) => {
426
+ const existing = messageFieldsByNameBySchema[schemaId];
427
+ if (existing)
428
+ return existing;
429
+ const index = new Map();
430
+ for (const field of PROTO_MESSAGE_SCHEMAS[schemaId]?.[1] ?? []) {
431
+ if (field[1] === PROTO_FIELD_KIND.message)
432
+ index.set(field[0], field);
433
+ }
434
+ messageFieldsByNameBySchema[schemaId] = index;
435
+ return index;
436
+ };
437
+ /**
438
+ * Rewrites an aliased field's public spelling to the name the codec writes. The send
439
+ * path reaches `encodeProto` directly and that codec drops an unknown key without
440
+ * throwing, so this runs before the encode rather than after a failure. Copy-on-write,
441
+ * like `repairMessage`.
442
+ */
443
+ const projectAliases = (schemaId, value) => {
444
+ if (!isObject(value))
445
+ return value;
446
+ const messageFields = messageFieldsOf(schemaId);
447
+ const alias = aliasFor(schemaId);
448
+ let output;
449
+ if (alias && hasOwn(value, alias[0])) {
450
+ const moved = value[alias[0]];
451
+ // Walked, not just renamed: an aliased message type may carry one of its own.
452
+ const field = messageFields.get(alias[0]);
453
+ (output ?? (output = { ...value }))[alias[1]] =
454
+ field && moved !== null && moved !== undefined ? projectAliases(field[2], moved) : moved;
455
+ delete output[alias[0]];
456
+ }
457
+ // The message's own keys, so the cost follows the message.
458
+ for (const key of Object.keys(value)) {
459
+ if (key === alias?.[0])
460
+ continue;
461
+ const field = messageFields.get(key);
462
+ if (!field)
463
+ continue;
464
+ const current = value[key];
465
+ if (current === null || current === undefined)
466
+ continue;
467
+ let converted = current;
468
+ if (field[3] & PROTO_FIELD_FLAG.repeated) {
469
+ if (Array.isArray(current)) {
470
+ let items;
471
+ for (let index = 0; index < current.length; index++) {
472
+ const item = projectAliases(field[2], current[index]);
473
+ if (item !== current[index])
474
+ (items ?? (items = current.slice()))[index] = item;
475
+ }
476
+ converted = items ?? current;
477
+ }
478
+ }
479
+ else if (field[3] & PROTO_FIELD_FLAG.map) {
480
+ if (isObject(current)) {
481
+ let entries;
482
+ for (const entry in current) {
483
+ const item = projectAliases(field[2], current[entry]);
484
+ if (item !== current[entry])
485
+ (entries ?? (entries = { ...current }))[entry] = item;
486
+ }
487
+ converted = entries ?? current;
488
+ }
489
+ }
490
+ else {
491
+ converted = projectAliases(field[2], current);
492
+ }
493
+ if (converted !== current)
494
+ (output ?? (output = { ...value }))[key] = converted;
495
+ }
496
+ return output ?? value;
497
+ };
498
+ /**
499
+ * The projection for a caller that addresses the codec by type name. Reference
500
+ * equality means nothing needed translating.
501
+ */
502
+ export const projectProtoMessage = (path, message) => {
503
+ const schemaId = schemaIdFor(path);
504
+ return schemaId === undefined ? message : projectAliases(schemaId, message);
505
+ };
506
+ /**
507
+ * The value a field reads out of `data`, taking either spelling. `hasOwn` and not a
508
+ * null check, because an instance carries its defaults on the prototype: an absent
509
+ * public field reads as `0` there and the bridge key would never be reached.
510
+ */
511
+ const fieldValue = (data, field, alias) => !hasOwn(data, field[0]) && alias !== undefined && alias[0] === field[0] && hasOwn(data, alias[1])
512
+ ? data[alias[1]]
513
+ : data[field[0]];
514
+ /** True when either spelling is an own property, which is what keeps prototype defaults out of `toObject`. */
515
+ const hasOwnField = (data, field, alias) => hasOwn(data, field[0]) || (alias !== undefined && alias[0] === field[0] && hasOwn(data, alias[1]));
384
516
  class ProtoCompatibilityRuntime {
385
517
  constructor(sourceNamespace) {
386
518
  this.namespace = { ...sourceNamespace };
387
519
  this.enums = PROTO_ENUM_SCHEMAS.map(([, entries]) => this.makeEnum(entries));
520
+ // Only the 64-bit names are indexed: `hydrate` looks up every key a partial or a
521
+ // decode produced, and the rest of them need no conversion.
522
+ this.int64FieldsByName = PROTO_MESSAGE_SCHEMAS.map(([, fields]) => {
523
+ const indexed = Object.create(null);
524
+ for (const field of fields) {
525
+ if (field[1] === PROTO_FIELD_KIND.signed64 || field[1] === PROTO_FIELD_KIND.unsigned64) {
526
+ indexed[field[0]] = field[1];
527
+ }
528
+ }
529
+ return indexed;
530
+ });
388
531
  this.messageFields = PROTO_MESSAGE_SCHEMAS.map(([, fields]) => fields.filter(field => field[1] === PROTO_FIELD_KIND.message));
389
532
  this.messageFieldsByName = this.messageFields.map(fields => {
390
533
  const indexed = Object.create(null);
@@ -496,7 +639,11 @@ class ProtoCompatibilityRuntime {
496
639
  constructor.toObject = (message, options) => this.toObject(schemaId, message, options);
497
640
  constructor.getTypeUrl = (prefix = 'type.googleapis.com') => `${prefix}/proto.${path}`;
498
641
  constructor.fromPartial = message => {
499
- const partial = sourceCodec?.fromPartial ? sourceCodec.fromPartial(message) : message;
642
+ // A partial is not written, so it must not inherit encode's codec
643
+ // requirement: the bridge accepts holders of types it does not implement
644
+ // and simply drops them. Only the alias translation is needed here.
645
+ const projected = this.projectForEncode(schemaId, message, false);
646
+ const partial = sourceCodec?.fromPartial ? sourceCodec.fromPartial(projected) : projected;
500
647
  return this.hydrate(schemaId, isObject(partial) ? partial : {});
501
648
  };
502
649
  constructor.encode = (message, writer) => {
@@ -606,9 +753,10 @@ class ProtoCompatibilityRuntime {
606
753
  // megamorphic path, where V8 does not elide for..of iterator
607
754
  // allocations (~90 iterator results per WebMessageInfo envelope).
608
755
  const fields = PROTO_MESSAGE_SCHEMAS[schemaId][1];
756
+ const alias = aliasFor(schemaId);
609
757
  for (let i = 0; i < fields.length; i++) {
610
758
  const field = fields[i];
611
- const value = data[field[0]];
759
+ const value = fieldValue(data, field, alias);
612
760
  if (value === null || value === undefined)
613
761
  continue;
614
762
  if (field[3] & PROTO_FIELD_FLAG.repeated) {
@@ -668,6 +816,7 @@ class ProtoCompatibilityRuntime {
668
816
  const data = input;
669
817
  const output = {};
670
818
  const fields = PROTO_MESSAGE_SCHEMAS[schemaId][1];
819
+ const alias = aliasFor(schemaId);
671
820
  for (const field of fields) {
672
821
  if (field[3] & PROTO_FIELD_FLAG.repeated) {
673
822
  if (options.arrays || options.defaults)
@@ -682,7 +831,7 @@ class ProtoCompatibilityRuntime {
682
831
  }
683
832
  }
684
833
  for (const field of fields) {
685
- const value = data[field[0]];
834
+ const value = fieldValue(data, field, alias);
686
835
  if (field[3] & PROTO_FIELD_FLAG.repeated) {
687
836
  if (value &&
688
837
  typeof value.length === 'number' &&
@@ -700,7 +849,7 @@ class ProtoCompatibilityRuntime {
700
849
  }
701
850
  continue;
702
851
  }
703
- if (value === null || value === undefined || !hasOwn(data, field[0]))
852
+ if (value === null || value === undefined || !hasOwnField(data, field, alias))
704
853
  continue;
705
854
  output[field[0]] = this.toObjectField(field, value, options);
706
855
  const group = oneofName(field);
@@ -788,11 +937,15 @@ class ProtoCompatibilityRuntime {
788
937
  const source = isObject(value) ? value : {};
789
938
  const instance = Object.create(this.constructorFor(schemaId).prototype);
790
939
  const messageFields = this.messageFieldsByName[schemaId];
791
- for (const key in source) {
792
- const nested = source[key];
940
+ const int64Fields = this.int64FieldsByName[schemaId];
941
+ const alias = aliasFor(schemaId);
942
+ for (const sourceKey in source) {
943
+ const key = alias && sourceKey === alias[1] ? alias[0] : sourceKey;
944
+ const nested = source[sourceKey];
793
945
  const field = messageFields[key];
794
946
  if (!field) {
795
- instance[key] = nested;
947
+ const kind = int64Fields[key];
948
+ instance[key] = kind === undefined ? nested : hydratedScalar(kind, nested);
796
949
  }
797
950
  else if (field[3] & PROTO_FIELD_FLAG.repeated) {
798
951
  if (Array.isArray(nested)) {
@@ -818,19 +971,26 @@ class ProtoCompatibilityRuntime {
818
971
  }
819
972
  return instance;
820
973
  }
821
- projectForEncode(schemaId, value) {
974
+ projectForEncode(schemaId, value, requireCodecs = true) {
822
975
  if (!isObject(value))
823
976
  return value;
824
977
  let output;
825
978
  if (typeof value[INSTANCE_SCHEMA] === 'number')
826
979
  output = { ...value };
980
+ const alias = aliasFor(schemaId);
981
+ // An own public field wins, including an explicit null or undefined.
982
+ if (alias && hasOwn(value, alias[0])) {
983
+ ;
984
+ (output ?? (output = { ...value }))[alias[1]] = value[alias[0]];
985
+ delete output[alias[0]];
986
+ }
827
987
  for (const field of this.messageFields[schemaId]) {
828
988
  if (!hasOwn(value, field[0]))
829
989
  continue;
830
990
  const nested = value[field[0]];
831
991
  if (nested === null || nested === undefined)
832
992
  continue;
833
- if (!this.sourceCodecs[field[2]]) {
993
+ if (requireCodecs && !this.sourceCodecs[field[2]]) {
834
994
  throw new Error(`protobuf codec unavailable for ${PROTO_MESSAGE_SCHEMAS[field[2]][0]}`);
835
995
  }
836
996
  let converted = nested;
@@ -838,7 +998,7 @@ class ProtoCompatibilityRuntime {
838
998
  if (Array.isArray(nested)) {
839
999
  let items;
840
1000
  for (let index = 0; index < nested.length; index++) {
841
- const item = this.projectForEncode(field[2], nested[index]);
1001
+ const item = this.projectForEncode(field[2], nested[index], requireCodecs);
842
1002
  if (item !== nested[index])
843
1003
  (items ?? (items = nested.slice()))[index] = item;
844
1004
  }
@@ -849,7 +1009,7 @@ class ProtoCompatibilityRuntime {
849
1009
  if (isObject(nested)) {
850
1010
  let entries;
851
1011
  for (const key in nested) {
852
- const item = this.projectForEncode(field[2], nested[key]);
1012
+ const item = this.projectForEncode(field[2], nested[key], requireCodecs);
853
1013
  if (item !== nested[key])
854
1014
  (entries ?? (entries = { ...nested }))[key] = item;
855
1015
  }
@@ -857,7 +1017,7 @@ class ProtoCompatibilityRuntime {
857
1017
  }
858
1018
  }
859
1019
  else {
860
- converted = this.projectForEncode(field[2], nested);
1020
+ converted = this.projectForEncode(field[2], nested, requireCodecs);
861
1021
  }
862
1022
  if (converted !== nested)
863
1023
  (output ?? (output = { ...value }))[field[0]] = converted;
@@ -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.7",
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": {
@@ -93,8 +93,8 @@
93
93
  "jimp": "^1.6.0",
94
94
  "link-preview-js": "^5.0.0",
95
95
  "music-metadata": "^11.14.0",
96
- "oxfmt": "^0.66.0",
97
- "oxlint": "1.81.0",
96
+ "oxfmt": "^0.67.0",
97
+ "oxlint": "1.82.0",
98
98
  "pino": "^10.3.1",
99
99
  "pino-pretty": "^13.1.3",
100
100
  "pkg-pr-new": "^0.0.88",