@oxidezap/baileyrs 0.3.13 → 0.3.15
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 +179 -554
- package/lib/Bridge/schema.js +6 -4
- package/lib/Bridge/types.d.ts +3 -4
- package/lib/Compatibility/auth-state.js +10 -4
- package/lib/Compatibility/host-auth-state.js +4 -3
- package/lib/Compatibility/legacy-store/device.d.ts +2 -0
- package/lib/Compatibility/legacy-store/device.js +13 -1
- package/lib/Compatibility/proto-runtime.js +126 -23
- package/lib/Runtime/bytes.js +16 -4
- package/lib/Socket/core.js +4 -1
- package/lib/Socket/events-core.js +7 -4
- package/lib/Socket/transport.js +4 -1
- package/lib/Socket/unsupported-config.d.ts +1 -1
- package/lib/Socket/unsupported-config.js +1 -0
- package/lib/Types/Socket.d.ts +3 -0
- package/lib/Utils/atomic-store.d.ts +12 -1
- package/lib/Utils/event-buffer.js +20 -3
- package/lib/Utils/generics.js +21 -3
- package/lib/Utils/use-bridge-store.js +28 -15
- package/lib/Utils/use-memory-store.js +39 -8
- package/lib/Utils/use-multi-file-auth-state.js +6 -1
- package/lib/WABinary/generic-utils.js +45 -12
- package/lib/WABinary/jid-utils.js +32 -20
- package/lib/host-types.d.ts +2 -0
- package/package.json +18 -11
package/lib/Bridge/schema.js
CHANGED
|
@@ -379,11 +379,13 @@ const ADAPTERS = {
|
|
|
379
379
|
connected: asBoolOr(data?.connected, false)
|
|
380
380
|
}),
|
|
381
381
|
/**
|
|
382
|
-
*
|
|
383
|
-
*
|
|
384
|
-
* this becomes the same terminal close rather than a new signal to learn.
|
|
382
|
+
* QR exhaustion can leave a pair-code flow alive. Older bridges omit the
|
|
383
|
+
* flag, so preserve their terminal-timeout behavior by default.
|
|
385
384
|
*/
|
|
386
|
-
pairing_qr_codes_exhausted:
|
|
385
|
+
pairing_qr_codes_exhausted: data => ({
|
|
386
|
+
type: 'qrCodesExhausted',
|
|
387
|
+
disconnected: asBoolOr(data?.disconnected, true)
|
|
388
|
+
}),
|
|
387
389
|
/**
|
|
388
390
|
* Another linked device turned link previews on or off account-wide.
|
|
389
391
|
*
|
package/lib/Bridge/types.d.ts
CHANGED
|
@@ -495,13 +495,12 @@ export interface CanonicalLabelAssociation {
|
|
|
495
495
|
labeled: boolean;
|
|
496
496
|
}
|
|
497
497
|
/**
|
|
498
|
-
*
|
|
499
|
-
*
|
|
500
|
-
* Terminal: nothing else is coming on this socket, and the consumer builds a
|
|
501
|
-
* new one to be shown a fresh code.
|
|
498
|
+
* QR refs ran out, but an outstanding pair code may keep the socket alive.
|
|
502
499
|
*/
|
|
503
500
|
export interface CanonicalQrCodesExhausted {
|
|
504
501
|
type: 'qrCodesExhausted';
|
|
502
|
+
/** False when the engine keeps an outstanding pair-code flow alive. */
|
|
503
|
+
disconnected: boolean;
|
|
505
504
|
}
|
|
506
505
|
/**
|
|
507
506
|
* A batched app-state sync that did not leave every collection synced.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { assertStoreCallbacks } from '../Utils/atomic-store.js';
|
|
2
2
|
import { calculateSignature, generateKeyPair } from '@oxidezap/whatsapp-rust-bridge/host';
|
|
3
3
|
import { concatBytes } from '../Runtime/bytes.js';
|
|
4
|
-
import { createDeviceProjection } from './legacy-store/device.js';
|
|
4
|
+
import { createDeviceProjection, hasInlineDeviceAccount } from './legacy-store/device.js';
|
|
5
5
|
import { base64Encode, randomBytes, readU16BE } from '../Runtime/bytes.js';
|
|
6
6
|
const DEVICE_STORE = 'device';
|
|
7
7
|
const DEVICE_RECORDS = ['device', 'account'];
|
|
@@ -9,7 +9,7 @@ const newKeyPair = () => {
|
|
|
9
9
|
const pair = generateKeyPair();
|
|
10
10
|
return {
|
|
11
11
|
private: new Uint8Array(pair.privKey),
|
|
12
|
-
public:
|
|
12
|
+
public: pair.pubKey.slice(1)
|
|
13
13
|
};
|
|
14
14
|
};
|
|
15
15
|
/** Signal version-byte prefix, matching `Defaults.KEY_BUNDLE_TYPE` without importing Node's Buffer. */
|
|
@@ -33,14 +33,15 @@ const newSignedKeyPair = (identityKeyPair, keyId) => {
|
|
|
33
33
|
*/
|
|
34
34
|
export const initHostAuthCreds = () => {
|
|
35
35
|
const signedIdentityKey = newKeyPair();
|
|
36
|
-
const
|
|
36
|
+
const entropy = randomBytes(34);
|
|
37
|
+
const registration = readU16BE(entropy) & 0x3fff;
|
|
37
38
|
return {
|
|
38
39
|
noiseKey: newKeyPair(),
|
|
39
40
|
pairingEphemeralKeyPair: newKeyPair(),
|
|
40
41
|
signedIdentityKey,
|
|
41
42
|
signedPreKey: newSignedKeyPair(signedIdentityKey, 1),
|
|
42
43
|
registrationId: registration,
|
|
43
|
-
advSecretKey: base64Encode(
|
|
44
|
+
advSecretKey: base64Encode(entropy.slice(2)),
|
|
44
45
|
processedHistoryMessages: [],
|
|
45
46
|
nextPreKeyId: 1,
|
|
46
47
|
firstUnuploadedPreKeyId: 1,
|
|
@@ -55,11 +56,16 @@ export const initHostAuthCreds = () => {
|
|
|
55
56
|
};
|
|
56
57
|
const hydrateFromStore = async (store, creds) => {
|
|
57
58
|
const projection = createDeviceProjection(creds);
|
|
59
|
+
let inlineAccount = false;
|
|
58
60
|
for (const record of DEVICE_RECORDS) {
|
|
61
|
+
if (record === 'account' && inlineAccount)
|
|
62
|
+
continue;
|
|
59
63
|
const payload = await store.get(DEVICE_STORE, record);
|
|
60
64
|
if (!payload)
|
|
61
65
|
continue;
|
|
62
66
|
try {
|
|
67
|
+
if (record === 'device')
|
|
68
|
+
inlineAccount = hasInlineDeviceAccount(payload);
|
|
63
69
|
projection.prepare(record, payload)();
|
|
64
70
|
}
|
|
65
71
|
catch (error) {
|
|
@@ -6,7 +6,7 @@ import { base64Encode, concatBytes, randomBytes, readU16BE, utf8Decode } from '.
|
|
|
6
6
|
import { jidEncode } from '../WABinary/jid-utils.js';
|
|
7
7
|
const pair = () => {
|
|
8
8
|
const value = generateKeyPair();
|
|
9
|
-
return { private: new Uint8Array(value.privKey), public:
|
|
9
|
+
return { private: new Uint8Array(value.privKey), public: value.pubKey.slice(1) };
|
|
10
10
|
};
|
|
11
11
|
const signed = (identity) => {
|
|
12
12
|
const keyPair = pair();
|
|
@@ -15,13 +15,14 @@ const signed = (identity) => {
|
|
|
15
15
|
};
|
|
16
16
|
export const initHostAuthCreds = () => {
|
|
17
17
|
const identity = pair();
|
|
18
|
+
const entropy = randomBytes(34);
|
|
18
19
|
return {
|
|
19
20
|
noiseKey: pair(),
|
|
20
21
|
pairingEphemeralKeyPair: pair(),
|
|
21
22
|
signedIdentityKey: identity,
|
|
22
23
|
signedPreKey: signed(identity),
|
|
23
|
-
registrationId: readU16BE(
|
|
24
|
-
advSecretKey: base64Encode(
|
|
24
|
+
registrationId: readU16BE(entropy) & 0x3fff,
|
|
25
|
+
advSecretKey: base64Encode(entropy.slice(2)),
|
|
25
26
|
processedHistoryMessages: [],
|
|
26
27
|
nextPreKeyId: 1,
|
|
27
28
|
firstUnuploadedPreKeyId: 1,
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import type { AuthenticationCreds } from '../../Types/index.js';
|
|
2
2
|
import { type DeviceRecordKeyName } from './constants.js';
|
|
3
|
+
/** Only omission permits loading the historical account sidecar. */
|
|
4
|
+
export declare const hasInlineDeviceAccount: (payload: Uint8Array) => boolean;
|
|
3
5
|
export type DeviceProjection = {
|
|
4
6
|
read(key: DeviceRecordKeyName): Uint8Array | null;
|
|
5
7
|
prepare(key: DeviceRecordKeyName, payload: Uint8Array): () => void;
|
|
@@ -61,6 +61,7 @@ function deviceFromCreds(creds) {
|
|
|
61
61
|
return null;
|
|
62
62
|
const pn = legacyJidToNative(creds.me.id);
|
|
63
63
|
const lid = legacyJidToNative(creds.me.lid);
|
|
64
|
+
const account = accountBytes(creds);
|
|
64
65
|
return toJsonBytes({
|
|
65
66
|
pn,
|
|
66
67
|
lid,
|
|
@@ -75,7 +76,7 @@ function deviceFromCreds(creds) {
|
|
|
75
76
|
adv_secret_key: creds.advSecretKey
|
|
76
77
|
? bytesToNumbers(base64Decode(creds.advSecretKey))
|
|
77
78
|
: Array(SignalKeyLength.ADV_SECRET).fill(0),
|
|
78
|
-
account: null,
|
|
79
|
+
account: account ? bytesToNumbers(account) : null,
|
|
79
80
|
push_name: creds.me.name ?? '',
|
|
80
81
|
app_version_primary: APP_VERSION_PRIMARY,
|
|
81
82
|
app_version_secondary: APP_VERSION_SECONDARY,
|
|
@@ -100,6 +101,11 @@ const accountBytes = (creds) => {
|
|
|
100
101
|
};
|
|
101
102
|
function prepareNativeDevice(payload) {
|
|
102
103
|
const native = fromJsonBytes(payload);
|
|
104
|
+
// Inline presence is authoritative in the bridge. Omission alone permits
|
|
105
|
+
// the older account sidecar fallback; null explicitly retires the account.
|
|
106
|
+
const account = native.account == null
|
|
107
|
+
? native.account
|
|
108
|
+
: signedDeviceIdentityCodec.decode(new Uint8Array(requireByteArray(native.account, 'device account')));
|
|
103
109
|
const pn = nativeJidToString(native.pn);
|
|
104
110
|
const lid = nativeJidToString(native.lid);
|
|
105
111
|
const registrationId = native.registration_id === undefined
|
|
@@ -128,6 +134,10 @@ function prepareNativeDevice(payload) {
|
|
|
128
134
|
// Upstream marks the initial Signal material readonly on the public
|
|
129
135
|
// credential contract. Native-state hydration is the one internal owner
|
|
130
136
|
// allowed to replace that material after reading Rust's persisted device.
|
|
137
|
+
if (account === null)
|
|
138
|
+
delete creds.account;
|
|
139
|
+
else if (account !== undefined)
|
|
140
|
+
creds.account = account;
|
|
131
141
|
const mutableCreds = creds;
|
|
132
142
|
if (pn) {
|
|
133
143
|
mutableCreds.me = { ...creds.me, id: pn };
|
|
@@ -167,6 +177,8 @@ function prepareNativeDevice(payload) {
|
|
|
167
177
|
creds.routingInfo = publicBytes(new Uint8Array(routingInfo));
|
|
168
178
|
};
|
|
169
179
|
}
|
|
180
|
+
/** Only omission permits loading the historical account sidecar. */
|
|
181
|
+
export const hasInlineDeviceAccount = (payload) => Object.hasOwn(fromJsonBytes(payload), 'account');
|
|
170
182
|
export function parseDeviceRecordKey(value) {
|
|
171
183
|
if (value === DeviceRecordKey.DEVICE || value === DeviceRecordKey.ACCOUNT)
|
|
172
184
|
return value;
|
|
@@ -7,7 +7,7 @@ const EMPTY_ARRAY = Object.freeze([]);
|
|
|
7
7
|
const EMPTY_OBJECT = Object.freeze({});
|
|
8
8
|
const JSON_OPTIONS = Object.freeze({ longs: String, enums: String, bytes: String, json: true });
|
|
9
9
|
const WORD_BASE = 1n << 32n;
|
|
10
|
-
const hasOwn =
|
|
10
|
+
const hasOwn = Object.hasOwn;
|
|
11
11
|
const isObject = (value) => typeof value === 'object' && value !== null;
|
|
12
12
|
const isReaderLike = (value) => isObject(value) && value.buf instanceof Uint8Array && typeof value.pos === 'number' && typeof value.len === 'number';
|
|
13
13
|
const asUint8Array = (value) => {
|
|
@@ -530,13 +530,60 @@ export const projectProtoMessage = (path, message) => {
|
|
|
530
530
|
* null check, because an instance carries its defaults on the prototype: an absent
|
|
531
531
|
* public field reads as `0` there and the bridge key would never be reached.
|
|
532
532
|
*/
|
|
533
|
-
const fieldValue = (data, field, alias) =>
|
|
533
|
+
const fieldValue = (data, field, alias) =>
|
|
534
|
+
// The alias test first: only one field of a handful of schemas has a second
|
|
535
|
+
// spelling, and every other field is read without an own-property lookup.
|
|
536
|
+
alias !== undefined && alias[0] === field[0] && !hasOwn(data, field[0]) && hasOwn(data, alias[1])
|
|
534
537
|
? data[alias[1]]
|
|
535
538
|
: data[field[0]];
|
|
539
|
+
/**
|
|
540
|
+
* Schema positions of the fields `value` holds as own properties, ascending.
|
|
541
|
+
*
|
|
542
|
+
* `toObject` and `projectForEncode` only act on own fields (prototype defaults
|
|
543
|
+
* are empty collections or are excluded by `hasOwn`), so visiting these
|
|
544
|
+
* positions instead of every field in the schema gives the same result in the
|
|
545
|
+
* same order. `Message` has 95 fields and a typical one sets one or two, so the
|
|
546
|
+
* walk follows the message rather than its schema. Returns `undefined` when the
|
|
547
|
+
* object's own keys are not fewer than the candidate fields, or its prototype
|
|
548
|
+
* could carry a field value, so the caller keeps the full walk. Instances of
|
|
549
|
+
* this runtime's constructors qualify only when `allowInstances` is set: their
|
|
550
|
+
* prototype defaults are skipped by `toObject` and `projectForEncode`, but
|
|
551
|
+
* `fromObject` would convert them.
|
|
552
|
+
*/
|
|
553
|
+
const ownFieldPositions = (value, positions, candidates, allowInstances = true) => {
|
|
554
|
+
const prototype = Object.getPrototypeOf(value);
|
|
555
|
+
if (prototype !== null &&
|
|
556
|
+
prototype !== Object.prototype &&
|
|
557
|
+
!(allowInstances && hasOwn(prototype, INSTANCE_SCHEMA))) {
|
|
558
|
+
return undefined;
|
|
559
|
+
}
|
|
560
|
+
const keys = Object.getOwnPropertyNames(value);
|
|
561
|
+
if (keys.length >= candidates)
|
|
562
|
+
return undefined;
|
|
563
|
+
const found = [];
|
|
564
|
+
for (let k = 0; k < keys.length; k++) {
|
|
565
|
+
const position = positions.get(keys[k]);
|
|
566
|
+
if (position === undefined)
|
|
567
|
+
continue;
|
|
568
|
+
// Insertion sort: own keys are few and usually already in schema order.
|
|
569
|
+
let at = found.length;
|
|
570
|
+
while (at > 0 && found[at - 1] > position)
|
|
571
|
+
at--;
|
|
572
|
+
// Both spellings of an aliased field map to one position.
|
|
573
|
+
if (at > 0 && found[at - 1] === position)
|
|
574
|
+
continue;
|
|
575
|
+
found.splice(at, 0, position);
|
|
576
|
+
}
|
|
577
|
+
return found;
|
|
578
|
+
};
|
|
536
579
|
/** True when either spelling is an own property, which is what keeps prototype defaults out of `toObject`. */
|
|
537
580
|
const hasOwnField = (data, field, alias) => hasOwn(data, field[0]) || (alias !== undefined && alias[0] === field[0] && hasOwn(data, alias[1]));
|
|
538
581
|
class ProtoCompatibilityRuntime {
|
|
539
582
|
constructor(sourceNamespace) {
|
|
583
|
+
/** Schema position by field name (either spelling), built per schema on first use. */
|
|
584
|
+
this.fieldPositions = [];
|
|
585
|
+
/** Position in `messageFields` by field name, built per schema on first use. */
|
|
586
|
+
this.messageFieldPositions = [];
|
|
540
587
|
this.namespace = { ...sourceNamespace };
|
|
541
588
|
this.enums = PROTO_ENUM_SCHEMAS.map(([, entries]) => this.makeEnum(entries));
|
|
542
589
|
// Only the 64-bit names are indexed: `hydrate` looks up every key a partial or a
|
|
@@ -593,6 +640,32 @@ class ProtoCompatibilityRuntime {
|
|
|
593
640
|
return node.value;
|
|
594
641
|
});
|
|
595
642
|
}
|
|
643
|
+
fieldPositionsOf(schemaId) {
|
|
644
|
+
const existing = this.fieldPositions[schemaId];
|
|
645
|
+
if (existing)
|
|
646
|
+
return existing;
|
|
647
|
+
const fields = PROTO_MESSAGE_SCHEMAS[schemaId][1];
|
|
648
|
+
const alias = aliasFor(schemaId);
|
|
649
|
+
const positions = new Map();
|
|
650
|
+
for (let i = 0; i < fields.length; i++) {
|
|
651
|
+
positions.set(fields[i][0], i);
|
|
652
|
+
if (alias !== undefined && alias[0] === fields[i][0])
|
|
653
|
+
positions.set(alias[1], i);
|
|
654
|
+
}
|
|
655
|
+
this.fieldPositions[schemaId] = positions;
|
|
656
|
+
return positions;
|
|
657
|
+
}
|
|
658
|
+
messageFieldPositionsOf(schemaId) {
|
|
659
|
+
const existing = this.messageFieldPositions[schemaId];
|
|
660
|
+
if (existing)
|
|
661
|
+
return existing;
|
|
662
|
+
const fields = this.messageFields[schemaId];
|
|
663
|
+
const positions = new Map();
|
|
664
|
+
for (let i = 0; i < fields.length; i++)
|
|
665
|
+
positions.set(fields[i][0], i);
|
|
666
|
+
this.messageFieldPositions[schemaId] = positions;
|
|
667
|
+
return positions;
|
|
668
|
+
}
|
|
596
669
|
constructorFor(schemaId) {
|
|
597
670
|
var _a;
|
|
598
671
|
return ((_a = this.constructors)[schemaId] ?? (_a[schemaId] = this.makeConstructor(schemaId, PROTO_MESSAGE_SCHEMAS[schemaId][1], this.sourceCodecs[schemaId])));
|
|
@@ -615,15 +688,19 @@ class ProtoCompatibilityRuntime {
|
|
|
615
688
|
makeConstructor(schemaId, fields, sourceCodec) {
|
|
616
689
|
const convertToObject = (message) => this.toObject(schemaId, message, JSON_OPTIONS);
|
|
617
690
|
const path = PROTO_MESSAGE_SCHEMAS[schemaId][0];
|
|
691
|
+
// Only repeated and map fields get an own value per instance, so the
|
|
692
|
+
// constructor walks just those, in schema order, instead of every field:
|
|
693
|
+
// `Message` has 95 fields and none of them is a collection.
|
|
694
|
+
const collections = fields.filter(field => field[3] & (PROTO_FIELD_FLAG.repeated | PROTO_FIELD_FLAG.map));
|
|
618
695
|
// Indexed loops: these run for every constructed instance and stay on
|
|
619
696
|
// the megamorphic path at runtime, where V8 does not elide for..of
|
|
620
697
|
// iterator allocations.
|
|
621
698
|
const constructor = function (properties) {
|
|
622
|
-
for (let i = 0; i <
|
|
623
|
-
const field =
|
|
699
|
+
for (let i = 0; i < collections.length; i++) {
|
|
700
|
+
const field = collections[i];
|
|
624
701
|
if (field[3] & PROTO_FIELD_FLAG.repeated)
|
|
625
702
|
this[field[0]] = [];
|
|
626
|
-
else
|
|
703
|
+
else
|
|
627
704
|
this[field[0]] = {};
|
|
628
705
|
}
|
|
629
706
|
if (properties) {
|
|
@@ -776,8 +853,14 @@ class ProtoCompatibilityRuntime {
|
|
|
776
853
|
// allocations (~90 iterator results per WebMessageInfo envelope).
|
|
777
854
|
const fields = PROTO_MESSAGE_SCHEMAS[schemaId][1];
|
|
778
855
|
const alias = aliasFor(schemaId);
|
|
779
|
-
|
|
780
|
-
|
|
856
|
+
// A plain object reads `undefined` for every field it does not own, so
|
|
857
|
+
// only the positions it holds are visited, in schema order.
|
|
858
|
+
const positions = isObject(data)
|
|
859
|
+
? ownFieldPositions(data, this.fieldPositionsOf(schemaId), fields.length, false)
|
|
860
|
+
: undefined;
|
|
861
|
+
const count = positions === undefined ? fields.length : positions.length;
|
|
862
|
+
for (let n = 0; n < count; n++) {
|
|
863
|
+
const field = fields[positions === undefined ? n : positions[n]];
|
|
781
864
|
const value = fieldValue(data, field, alias);
|
|
782
865
|
if (value === null || value === undefined)
|
|
783
866
|
continue;
|
|
@@ -839,20 +922,29 @@ class ProtoCompatibilityRuntime {
|
|
|
839
922
|
const output = {};
|
|
840
923
|
const fields = PROTO_MESSAGE_SCHEMAS[schemaId][1];
|
|
841
924
|
const alias = aliasFor(schemaId);
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
925
|
+
// Without these options the pass below writes nothing; `toJSON` sets none of them.
|
|
926
|
+
if (options.arrays || options.defaults || options.objects) {
|
|
927
|
+
for (const field of fields) {
|
|
928
|
+
if (field[3] & PROTO_FIELD_FLAG.repeated) {
|
|
929
|
+
if (options.arrays || options.defaults)
|
|
930
|
+
output[field[0]] = [];
|
|
931
|
+
}
|
|
932
|
+
else if (field[3] & PROTO_FIELD_FLAG.map) {
|
|
933
|
+
if (options.objects || options.defaults)
|
|
934
|
+
output[field[0]] = {};
|
|
935
|
+
}
|
|
936
|
+
else if (options.defaults && !oneofName(field)) {
|
|
937
|
+
output[field[0]] = this.toObjectDefault(field, options);
|
|
938
|
+
}
|
|
853
939
|
}
|
|
854
940
|
}
|
|
855
|
-
|
|
941
|
+
// Only own fields can produce output, so a message with few of them visits
|
|
942
|
+
// just those positions, in schema order, and the output is unchanged.
|
|
943
|
+
const positions = ownFieldPositions(data, this.fieldPositionsOf(schemaId), fields.length);
|
|
944
|
+
const count = positions === undefined ? fields.length : positions.length;
|
|
945
|
+
// Indexed for the same reason as `fromObject`: no iterator result per field.
|
|
946
|
+
for (let n = 0; n < count; n++) {
|
|
947
|
+
const field = fields[positions === undefined ? n : positions[n]];
|
|
856
948
|
const value = fieldValue(data, field, alias);
|
|
857
949
|
if (field[3] & PROTO_FIELD_FLAG.repeated) {
|
|
858
950
|
if (value &&
|
|
@@ -874,9 +966,13 @@ class ProtoCompatibilityRuntime {
|
|
|
874
966
|
if (value === null || value === undefined || !hasOwnField(data, field, alias))
|
|
875
967
|
continue;
|
|
876
968
|
output[field[0]] = this.toObjectField(field, value, options);
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
969
|
+
// `oneofName` builds a string for every proto3-optional field, which is
|
|
970
|
+
// most of them, so it only runs when the option asks for the group.
|
|
971
|
+
if (options.oneofs) {
|
|
972
|
+
const group = oneofName(field);
|
|
973
|
+
if (group)
|
|
974
|
+
output[group] = field[0];
|
|
975
|
+
}
|
|
880
976
|
}
|
|
881
977
|
return output;
|
|
882
978
|
}
|
|
@@ -1006,7 +1102,14 @@ class ProtoCompatibilityRuntime {
|
|
|
1006
1102
|
(output ?? (output = { ...value }))[alias[1]] = value[alias[0]];
|
|
1007
1103
|
delete output[alias[0]];
|
|
1008
1104
|
}
|
|
1009
|
-
|
|
1105
|
+
const messageFields = this.messageFields[schemaId];
|
|
1106
|
+
// Only own fields are projected, so visiting the positions the message
|
|
1107
|
+
// actually holds keeps schema order (and which missing codec is reported
|
|
1108
|
+
// first) while skipping the rest of the schema.
|
|
1109
|
+
const positions = ownFieldPositions(value, this.messageFieldPositionsOf(schemaId), messageFields.length);
|
|
1110
|
+
const count = positions === undefined ? messageFields.length : positions.length;
|
|
1111
|
+
for (let n = 0; n < count; n++) {
|
|
1112
|
+
const field = messageFields[positions === undefined ? n : positions[n]];
|
|
1010
1113
|
if (!hasOwn(value, field[0]))
|
|
1011
1114
|
continue;
|
|
1012
1115
|
const nested = value[field[0]];
|
package/lib/Runtime/bytes.js
CHANGED
|
@@ -53,12 +53,24 @@ export const bytesEqual = (a, b) => {
|
|
|
53
53
|
};
|
|
54
54
|
export const utf8Encode = (text) => new TextEncoder().encode(text);
|
|
55
55
|
export const utf8Decode = (bytes) => new TextDecoder('utf-8', { fatal: false }).decode(bytes);
|
|
56
|
+
/**
|
|
57
|
+
* Two-digit lowercase hex for every byte value, so encoding does one append per
|
|
58
|
+
* byte. Built on first use: hosts with `Buffer` never need it.
|
|
59
|
+
*/
|
|
60
|
+
let hexPairs;
|
|
56
61
|
export const hexEncode = (bytes) => {
|
|
62
|
+
// Node's native encoder when the optional global exists. `hexSlice` reads any
|
|
63
|
+
// Uint8Array in place. A `Buffer.from(bytes.buffer, ...)` view is avoided on
|
|
64
|
+
// purpose: V8 keeps typed arrays of up to 64 bytes (hashes, IDs, keys) inside
|
|
65
|
+
// the JS heap, and reading `.buffer` moves their bytes to a new native allocation.
|
|
66
|
+
const hexSlice = globalThis.Buffer
|
|
67
|
+
?.prototype?.hexSlice;
|
|
68
|
+
if (typeof hexSlice === 'function')
|
|
69
|
+
return hexSlice.call(bytes, 0, bytes.length);
|
|
70
|
+
const pairs = (hexPairs ?? (hexPairs = Array.from({ length: 256 }, (_, byte) => HEX_DIGITS[byte >> 4] + HEX_DIGITS[byte & 0x0f])));
|
|
57
71
|
let out = '';
|
|
58
|
-
for (let i = 0; i < bytes.length; i++)
|
|
59
|
-
|
|
60
|
-
out += HEX_DIGITS[byte >> 4] + HEX_DIGITS[byte & 0x0f];
|
|
61
|
-
}
|
|
72
|
+
for (let i = 0; i < bytes.length; i++)
|
|
73
|
+
out += pairs[bytes[i]];
|
|
62
74
|
return out;
|
|
63
75
|
};
|
|
64
76
|
export const hexDecode = (text) => {
|
package/lib/Socket/core.js
CHANGED
|
@@ -595,7 +595,10 @@ const createWASocketFactoryInner = (runtime, config, claimEngineInitialization,
|
|
|
595
595
|
// other truthy value at construction, so a `!!`/ternary-style
|
|
596
596
|
// coercion could promote a malformed opt-out into an opt-in.
|
|
597
597
|
// Absent stays strict.
|
|
598
|
-
fullConfig.dangerSkipCertChainVerify,
|
|
598
|
+
fullConfig.dangerSkipCertChainVerify, {
|
|
599
|
+
...makeHistorySyncAdmission(shouldSyncHistoryMessage),
|
|
600
|
+
additionalStaticMediaHosts: fullConfig.additionalStaticMediaHosts
|
|
601
|
+
});
|
|
599
602
|
// `end()` can land while the client is still being built — a `sock.end()`
|
|
600
603
|
// or `await using` right after `makeWASocket()` does exactly that. When
|
|
601
604
|
// it has, `adopt` frees this client and tells us to stop: nothing else
|
|
@@ -674,10 +674,13 @@ const DISPATCHERS = {
|
|
|
674
674
|
connected: evt.connected
|
|
675
675
|
});
|
|
676
676
|
},
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
677
|
+
qrCodesExhausted: (evt, dispatchCtx) => {
|
|
678
|
+
// Rust owns pairing deadlines. A live pair code must survive QR expiry
|
|
679
|
+
// without a close or connecting update clearing it on the consumer.
|
|
680
|
+
if (!evt.disconnected)
|
|
681
|
+
return;
|
|
682
|
+
emitClose(dispatchCtx, 'QR refs attempts ended', DisconnectReason.timedOut);
|
|
683
|
+
},
|
|
681
684
|
// Straight onto upstream's own channel for this: `settings.update` already
|
|
682
685
|
// declares the `disableLinkPreviews` arm, and a consumer that reads it is
|
|
683
686
|
// reading the account-wide setting whichever device changed it.
|
package/lib/Socket/transport.js
CHANGED
|
@@ -153,12 +153,15 @@ export const makeTransport = (config) => {
|
|
|
153
153
|
};
|
|
154
154
|
export const makeHttpClient = (config) => ({
|
|
155
155
|
async execute(url, method, headers, body) {
|
|
156
|
-
const fetchOpts = { method, headers };
|
|
156
|
+
const fetchOpts = { method, headers, redirect: 'error' };
|
|
157
157
|
if (body)
|
|
158
158
|
fetchOpts.body = body;
|
|
159
159
|
if (config.options?.dispatcher)
|
|
160
160
|
fetchOpts.dispatcher = config.options.dispatcher;
|
|
161
161
|
const resp = await fetch(url, fetchOpts);
|
|
162
|
+
if (resp.status === 0 || resp.type === 'opaqueredirect') {
|
|
163
|
+
throw new Error('HTTP adapter received an unobservable redirect or network response');
|
|
164
|
+
}
|
|
162
165
|
const buf = new Uint8Array(await resp.arrayBuffer());
|
|
163
166
|
return { statusCode: resp.status, body: buf };
|
|
164
167
|
}
|
|
@@ -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", "shouldSyncHistoryMessage", "emitOwnEvents", "shouldIgnoreJid", "defaultQueryTimeoutMs", "transactionOpts", "makeSignalRepository"];
|
|
36
|
+
export declare const READ_CONFIG_KEYS: readonly ["waWebSocketUrl", "options", "logger", "version", "browser", "pushName", "auth", "cache", "additionalStaticMediaHosts", "deviceProps", "wantedPreKeyCount", "dangerSkipCertChainVerify", "shouldSyncHistoryMessage", "emitOwnEvents", "shouldIgnoreJid", "defaultQueryTimeoutMs", "transactionOpts", "makeSignalRepository"];
|
|
37
37
|
/**
|
|
38
38
|
* Which unsupported options this caller actually passed.
|
|
39
39
|
*
|
package/lib/Types/Socket.d.ts
CHANGED
|
@@ -59,6 +59,9 @@ export type SocketConfig = {
|
|
|
59
59
|
emitOwnEvents: boolean;
|
|
60
60
|
/** Custom media upload hosts. */
|
|
61
61
|
customUploadHosts: MediaConnInfo['hosts'];
|
|
62
|
+
/** Additional exact HTTPS authorities for static media. No schemes, paths,
|
|
63
|
+
* wildcards or redirects. Captured by the bridge at client construction. */
|
|
64
|
+
additionalStaticMediaHosts?: readonly string[];
|
|
62
65
|
/** provide an auth state object to maintain the auth state */
|
|
63
66
|
auth: AuthenticationState;
|
|
64
67
|
/**
|
|
@@ -4,6 +4,17 @@ export type OrdinaryStoreCallbacks = Omit<JsStoreCallbacks, keyof AtomicStoreCal
|
|
|
4
4
|
flush?(): Promise<void>;
|
|
5
5
|
};
|
|
6
6
|
export type AtomicRows = Map<string, Uint8Array>;
|
|
7
|
+
/**
|
|
8
|
+
* What an atomic change reads and writes. A full `AtomicRows` map satisfies it,
|
|
9
|
+
* and a store can instead pass a view that reads through to its own rows and
|
|
10
|
+
* stages the writes, so a change costs the rows it touches.
|
|
11
|
+
*/
|
|
12
|
+
export interface AtomicRowView {
|
|
13
|
+
get(key: string): Uint8Array | undefined;
|
|
14
|
+
has(key: string): boolean;
|
|
15
|
+
set(key: string, value: Uint8Array): unknown;
|
|
16
|
+
delete(key: string): boolean;
|
|
17
|
+
}
|
|
7
18
|
export declare const rowKey: (store: string, key: string) => string;
|
|
8
19
|
export declare const signedTimestamp: (value: string) => bigint;
|
|
9
20
|
export type TokenRow = {
|
|
@@ -14,7 +25,7 @@ export type TokenRow = {
|
|
|
14
25
|
export declare const decodeTokenRow: (bytes: Uint8Array) => TokenRow;
|
|
15
26
|
export declare const encodeTokenRow: (row: TokenRow) => Uint8Array;
|
|
16
27
|
/** The caller supplies a real transaction covering all reads and writes. */
|
|
17
|
-
export declare const atomicCallbacks: (transaction: (change: (rows:
|
|
28
|
+
export declare const atomicCallbacks: (transaction: (change: (rows: AtomicRowView) => void) => Promise<void>) => AtomicStoreCallbacks;
|
|
18
29
|
/** Validate migration requirements before hydration or other storage I/O. */
|
|
19
30
|
export declare function assertStoreCallbacks(store: unknown): asserts store is JsStoreCallbacks;
|
|
20
31
|
//# sourceMappingURL=atomic-store.d.ts.map
|
|
@@ -397,6 +397,10 @@ export const makeEventBuffer = (logger, timers = defaultEventBufferTimers, emitt
|
|
|
397
397
|
let bufferCount = 0;
|
|
398
398
|
let bufferTimeout;
|
|
399
399
|
let flushPendingTimeout;
|
|
400
|
+
// Whether a `messages.upsert` was buffered since the last release, and its
|
|
401
|
+
// type. Lets `emit` skip scanning the pending upserts on every message.
|
|
402
|
+
let hasPendingUpserts = false;
|
|
403
|
+
let pendingUpsertType;
|
|
400
404
|
ev.on('event', (events) => {
|
|
401
405
|
for (const event of Object.keys(events)) {
|
|
402
406
|
if (event === 'connection.update') {
|
|
@@ -459,6 +463,7 @@ export const makeEventBuffer = (logger, timers = defaultEventBufferTimers, emitt
|
|
|
459
463
|
if (Object.keys(consolidated).length)
|
|
460
464
|
ev.emit('event', consolidated);
|
|
461
465
|
data = next;
|
|
466
|
+
hasPendingUpserts = false;
|
|
462
467
|
logger.trace({ conditionalChatUpdatesLeft: conditionalUpdates }, 'released buffered events');
|
|
463
468
|
return true;
|
|
464
469
|
};
|
|
@@ -486,18 +491,29 @@ export const makeEventBuffer = (logger, timers = defaultEventBufferTimers, emitt
|
|
|
486
491
|
return () => ev.off('event', listener);
|
|
487
492
|
},
|
|
488
493
|
emit(event, eventData) {
|
|
489
|
-
|
|
490
|
-
|
|
494
|
+
const isUpsert = event === 'messages.upsert';
|
|
495
|
+
const upsertType = isUpsert ? eventData.type : undefined;
|
|
496
|
+
// Only a type change can release the pending upserts, so the pending map
|
|
497
|
+
// is materialized only then. Doing it on every upsert made a buffered
|
|
498
|
+
// burst quadratic: each message copied every message buffered before it.
|
|
499
|
+
if (isUpsert && hasPendingUpserts && pendingUpsertType !== upsertType) {
|
|
491
500
|
const pending = Object.values(data.messageUpserts);
|
|
492
|
-
if (pending.length && pending[0].type !==
|
|
501
|
+
if (pending.length && pending[0].type !== upsertType) {
|
|
493
502
|
ev.emit('event', {
|
|
494
503
|
'messages.upsert': { messages: pending.map(item => item.message), type: pending[0].type }
|
|
495
504
|
});
|
|
496
505
|
data.messageUpserts = {};
|
|
497
506
|
}
|
|
507
|
+
hasPendingUpserts = false;
|
|
498
508
|
}
|
|
499
509
|
if (buffering && BUFFERABLE_EVENT_SET.has(event)) {
|
|
500
510
|
append(data, historyCache, event, eventData, logger);
|
|
511
|
+
// Every upsert buffered since the last release shares this type: a
|
|
512
|
+
// different one releases the batch above before it is appended.
|
|
513
|
+
if (isUpsert) {
|
|
514
|
+
hasPendingUpserts = true;
|
|
515
|
+
pendingUpsertType = upsertType;
|
|
516
|
+
}
|
|
501
517
|
return true;
|
|
502
518
|
}
|
|
503
519
|
return ev.emit('event', { [event]: eventData });
|
|
@@ -538,6 +554,7 @@ export const makeEventBuffer = (logger, timers = defaultEventBufferTimers, emitt
|
|
|
538
554
|
timers.clearTimeout(flushPendingTimeout);
|
|
539
555
|
historyCache.clear();
|
|
540
556
|
data = makeBufferData();
|
|
557
|
+
hasPendingUpserts = false;
|
|
541
558
|
buffering = false;
|
|
542
559
|
bufferCount = 0;
|
|
543
560
|
ev.removeAllListeners();
|
package/lib/Utils/generics.js
CHANGED
|
@@ -13,7 +13,12 @@ export const getKeyAuthor = (key, meId = 'me') => (key?.fromMe ? meId : key?.par
|
|
|
13
13
|
export const isStringNullOrEmpty = (value) => value == null || value === '';
|
|
14
14
|
export const writeRandomPadMax16 = (msg) => {
|
|
15
15
|
const padLength = (randomBytes(1)[0] & 0x0f) + 1;
|
|
16
|
-
|
|
16
|
+
// One allocation, the same one `Buffer.concat` makes, without the zeroed
|
|
17
|
+
// pad buffer and the list it would be concatenated from.
|
|
18
|
+
const padded = Buffer.allocUnsafe(msg.length + padLength);
|
|
19
|
+
padded.set(msg, 0);
|
|
20
|
+
padded.fill(padLength, msg.length);
|
|
21
|
+
return padded;
|
|
17
22
|
};
|
|
18
23
|
export const unpadRandomMax16 = (e) => {
|
|
19
24
|
const bytes = new Uint8Array(e);
|
|
@@ -171,11 +176,24 @@ export const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connect
|
|
|
171
176
|
*/
|
|
172
177
|
export const BufferJSON = {
|
|
173
178
|
replacer: (_, value) => {
|
|
179
|
+
// Most calls see a primitive (every string, number and boolean in the
|
|
180
|
+
// tree), which none of the checks below can match.
|
|
181
|
+
if (value === null || typeof value !== 'object')
|
|
182
|
+
return value;
|
|
174
183
|
// Buffer.toJSON() fires before replacer sees the value, so by the time we
|
|
175
184
|
// get here the replacer mostly sees `{ type: 'Buffer', data: [..] }`. Cover
|
|
176
185
|
// both that case and the rare raw-Buffer case (e.g. inside a Map serializer).
|
|
177
|
-
|
|
178
|
-
|
|
186
|
+
// A Buffer is a Uint8Array, so one check covers both.
|
|
187
|
+
if (value instanceof Uint8Array) {
|
|
188
|
+
// A Buffer encodes itself. A large plain array is off-heap, so a view
|
|
189
|
+
// over it avoids a copy; reading `.buffer` on a small (<= 64 byte,
|
|
190
|
+
// on-heap) one would instead move its bytes to a new native allocation.
|
|
191
|
+
const data = Buffer.isBuffer(value)
|
|
192
|
+
? value.toString('base64')
|
|
193
|
+
: value.byteLength > 64
|
|
194
|
+
? Buffer.from(value.buffer, value.byteOffset, value.byteLength).toString('base64')
|
|
195
|
+
: Buffer.from(value).toString('base64');
|
|
196
|
+
return { type: 'Buffer', data };
|
|
179
197
|
}
|
|
180
198
|
if (value !== null && typeof value === 'object' && value.type === 'Buffer') {
|
|
181
199
|
const data = value.data;
|