@oxidezap/baileyrs 0.3.18 → 0.4.1
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 +20 -4
- package/lib/Bridge/schema.js +4 -0
- package/lib/Compatibility/field-aliases.d.ts +7 -0
- package/lib/Compatibility/field-aliases.js +12 -0
- package/lib/Compatibility/legacy-store/adapter.js +56 -20
- package/lib/Compatibility/legacy-store/multi-file.js +1 -0
- package/lib/Compatibility/legacy-store/routing.d.ts +1 -0
- package/lib/Compatibility/legacy-store/routing.js +7 -0
- package/lib/Compatibility/legacy-store/snapshot.js +20 -1
- package/lib/Compatibility/legacy-store/types.d.ts +2 -0
- package/lib/Compatibility/proto-runtime.js +39 -14
- package/lib/Media/content.js +41 -23
- package/lib/Socket/core.js +2 -1
- package/lib/Socket/events-core.js +10 -1
- package/lib/Socket/messages-core.js +12 -5
- package/lib/Socket/unsupported-config.d.ts +2 -2
- package/lib/Socket/unsupported-config.js +1 -2
- package/lib/Types/Auth.d.ts +1 -0
- package/lib/Types/Message.d.ts +10 -0
- package/lib/Utils/atomic-store.d.ts +6 -5
- package/lib/Utils/atomic-store.js +36 -1
- package/lib/Utils/messages-core.d.ts +3 -16
- package/lib/Utils/messages-core.js +50 -130
- package/lib/Utils/transactional-file-store.js +1 -0
- package/lib/Utils/use-memory-store.js +11 -1
- package/lib/WAProto/compatibility-schema.d.ts +7 -1
- package/lib/WAProto/compatibility-schema.js +75 -4
- package/lib/WAProto/runtime.d.ts +12721 -3769
- package/lib/host-types.d.ts +1 -0
- package/package.json +8 -8
package/README.md
CHANGED
|
@@ -100,6 +100,15 @@ Memory storage is temporary. For persistent sessions, supply a byte-preserving
|
|
|
100
100
|
existing device record, including its registration ID, after a failed read.
|
|
101
101
|
This entrypoint uses no filesystem auth or Node streams.
|
|
102
102
|
|
|
103
|
+
With bridge `0.27.0`, a custom `JsStoreCallbacks` store must implement
|
|
104
|
+
`commitSnapshot(name, state, entries, maintainIndex)`. In the same transaction
|
|
105
|
+
used for `commitPatch`, replace all `mutation_mac` rows whose keys start with
|
|
106
|
+
`name + ':'`, write `sync_version[name]` and update the matching keys in
|
|
107
|
+
`meta[mutation_mac_keys]` when requested. An empty `entries` array clears the
|
|
108
|
+
collection's MACs. Resolve after persistence and propagate any commit error.
|
|
109
|
+
The built-in memory and file stores implement this callback and can reopen
|
|
110
|
+
their existing auth data.
|
|
111
|
+
|
|
103
112
|
Standalone AES-backed media retry helpers require `initWasmEngine()` before use
|
|
104
113
|
if no socket has initialized the engine, after `initSync()` on hosts. With a
|
|
105
114
|
custom runtime, pass `makeMediaCryptoRuntime(runtime)` as the final argument to
|
|
@@ -122,9 +131,14 @@ URLs for PRs and commits. They are unreleased code with version
|
|
|
122
131
|
## Migrating from upstream Baileys
|
|
123
132
|
|
|
124
133
|
Custom upstream `{ creds, keys }` auth states require `keys.bridgeTransaction`
|
|
125
|
-
with backend-wide isolation and durable atomic commits.
|
|
126
|
-
|
|
127
|
-
|
|
134
|
+
with backend-wide isolation and durable atomic commits. Provide
|
|
135
|
+
`listKeys(type, prefix)` on the transaction view so snapshot commits can find
|
|
136
|
+
every matching row in `bridge-mutation-mac`, including historical rows missing
|
|
137
|
+
from the index. `useLegacyMultiFileAuthState` supplies both methods. Keep
|
|
138
|
+
persisting `creds.update` with your loader's `saveCreds`.
|
|
139
|
+
|
|
140
|
+
The adapter stores status-scoped Signal sessions and identities in the
|
|
141
|
+
`bridge-native-*` records. Include these records in auth backups.
|
|
128
142
|
|
|
129
143
|
For an existing upstream JSON directory, use `useLegacyMultiFileAuthState`.
|
|
130
144
|
`useMultiFileAuthState` uses native binary storage and does not import upstream JSON.
|
|
@@ -195,10 +209,12 @@ unless you retain the same `messageId`. Application traffic pacing is your respo
|
|
|
195
209
|
|
|
196
210
|
- History contacts arrive through `messaging-history.set`, not `contacts.upsert`.
|
|
197
211
|
- `shouldSyncHistoryMessage` receives pre-download metadata only: `syncType`, `chunkOrder`, `progress`, `fileLength` as `Long`, and `peerDataRequestSessionId`. Returning `false` permanently acknowledges the chunk. It does not gate the initial-sync state machine.
|
|
212
|
+
- `markOnlineOnConnect: false` stops the engine from sending `available` on connect and after the push name sync, and the socket sends `unavailable` on open, as upstream does. While the account is available, the phone gets no notifications.
|
|
198
213
|
- Engine-owned options such as `getMessage` and `cachedGroupMetadata` are accepted but do not override engine behavior. Socket construction warns about ignored options; see the [option catalog](src/Socket/unsupported-config.ts).
|
|
199
214
|
- Undecryptable-message stubs may carry `stanzaType` independently of `messageStubParameters`.
|
|
200
215
|
- Duplicate delivery suppression is temporary and in memory. For durable side effects, deduplicate with the full key: `remoteJid`, `id`, `fromMe` and `participant`.
|
|
201
|
-
- The `proto` facade
|
|
216
|
+
- The `proto` facade preserves all Baileys field names, merges additive `whatsapp-rust` protobuf fields and messages on top of that baseline, and translates bridge aliases in both directions without mutating inputs. See [compatibility rules](src/Compatibility/README.md).
|
|
217
|
+
- Audio stickers can be sent via `sock.sendMessage(jid, { sticker, audio })` (accepting a `WAMediaUpload` or `{ media: WAMediaUpload, mimetype?, seconds?, ptt?, waveform?, backgroundArgb? }` via `StickerAudioContent`, e.g. `{ media: { url: 'audio.ogg' }, seconds: 3 }`), which uploads both tracks and wraps the sticker with `audioMessage` inside `audioStickerMessage`.
|
|
202
218
|
- Group and community listings fetch full metadata per entry and reject on failed fetches before emitting `groups.update`.
|
|
203
219
|
- `reachoutTimeLock` reports server state without imposing send policy. Unknown enforcement names are preserved; an absent `isActive` is unknown.
|
|
204
220
|
- Newsletter `mute_state` controls channel-update notifications, independently of follower-activity notifications. History may omit `messageId`; `serverId` and large counters are strings. Packed live events do not carry the newsletter server ID.
|
package/lib/Bridge/schema.js
CHANGED
|
@@ -528,6 +528,10 @@ const ADAPTERS = {
|
|
|
528
528
|
};
|
|
529
529
|
},
|
|
530
530
|
// ── Acknowledged but no Baileys equivalent (noop) ──
|
|
531
|
+
// The response acknowledges the request. History arrives through history_sync.
|
|
532
|
+
full_history_sync_on_demand_response: () => ({ type: 'noop', bridgeType: 'full_history_sync_on_demand_response' }),
|
|
533
|
+
scheduled_message_posted: () => ({ type: 'noop', bridgeType: 'scheduled_message_posted' }),
|
|
534
|
+
scheduled_message_revealed: () => ({ type: 'noop', bridgeType: 'scheduled_message_revealed' }),
|
|
531
535
|
self_push_name_updated: () => ({ type: 'noop', bridgeType: 'self_push_name_updated' }),
|
|
532
536
|
client_expiration_changed: () => ({ type: 'noop', bridgeType: 'client_expiration_changed' }),
|
|
533
537
|
offline_sync_completed: data => ({
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bridge field spellings already mapped to upstream public field names by
|
|
3
|
+
* `src/Compatibility/proto-runtime.ts`. Shared with `waproto-facade.ts` so the
|
|
4
|
+
* generated facade and runtime never drift out of sync.
|
|
5
|
+
*/
|
|
6
|
+
export declare const FIELD_ALIASES: Readonly<Record<string, readonly [publicName: string, bridgeName: string]>>;
|
|
7
|
+
//# sourceMappingURL=field-aliases.d.ts.map
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bridge field spellings already mapped to upstream public field names by
|
|
3
|
+
* `src/Compatibility/proto-runtime.ts`. Shared with `waproto-facade.ts` so the
|
|
4
|
+
* generated facade and runtime never drift out of sync.
|
|
5
|
+
*/
|
|
6
|
+
export const FIELD_ALIASES = {
|
|
7
|
+
'SyncActionValue.AgentAction': ['deviceID', 'deviceId'],
|
|
8
|
+
'SyncActionValue.ChatAssignmentAction': ['deviceAgentID', 'deviceAgentId'],
|
|
9
|
+
'Message.ExtendedTextMessage': ['faviconMMSMetadata', 'faviconMmsMetadata'],
|
|
10
|
+
'Message.MessageHistoryMetadata': ['oldestMessageTimestamp', 'oldestMessageTimestampInWindow']
|
|
11
|
+
};
|
|
12
|
+
//# sourceMappingURL=field-aliases.js.map
|
|
@@ -6,10 +6,14 @@ import { NativeStore, RouteKind } from './constants.js';
|
|
|
6
6
|
import { decodeNativeEnvelope, encodeNativeEnvelope, encodeNativeOnlyEnvelope, envelopeMatchesLegacy, toBytes } from './common.js';
|
|
7
7
|
import { createLegacyCodecs } from './codecs/index.js';
|
|
8
8
|
import { createDeviceProjection, parseDeviceRecordKey } from './device.js';
|
|
9
|
-
import { isProjectedStoreName, legacyKey, parseNativeStoreName, resolveRoute } from './routing.js';
|
|
9
|
+
import { isProjectedStoreName, isStatusSignalAddress, legacyKey, parseNativeStoreName, resolveRoute } from './routing.js';
|
|
10
10
|
import { NATIVE_ONLY_PROJECTION } from './types.js';
|
|
11
11
|
const emptyBucket = () => Object.create(null);
|
|
12
12
|
const ownValue = (bucket, key) => Object.prototype.hasOwnProperty.call(bucket, key) ? bucket[key] : null;
|
|
13
|
+
// The pinned Baileys store has no key for the SDK's separate status Signal scope.
|
|
14
|
+
const projectionKey = (store, key) => (store === NativeStore.SESSION || store === NativeStore.IDENTITY) && isStatusSignalAddress(key)
|
|
15
|
+
? null
|
|
16
|
+
: legacyKey(store, key);
|
|
13
17
|
function uniqueKeys(keys, label) {
|
|
14
18
|
const seen = new Set();
|
|
15
19
|
for (const key of keys) {
|
|
@@ -40,6 +44,7 @@ function withPendingCallbacks(store) {
|
|
|
40
44
|
delete: (...args) => track(Promise.resolve(store.delete(...args))),
|
|
41
45
|
deleteMany: (...args) => track(Promise.resolve(store.deleteMany(...args))),
|
|
42
46
|
commitPatch: (...args) => track(Promise.resolve(store.commitPatch(...args))),
|
|
47
|
+
commitSnapshot: (...args) => track(Promise.resolve(store.commitSnapshot(...args))),
|
|
43
48
|
storeReceivedTcToken: (...args) => track(Promise.resolve(store.storeReceivedTcToken(...args))),
|
|
44
49
|
touchTcTokenSenderTimestamp: (...args) => track(Promise.resolve(store.touchTcTokenSenderTimestamp(...args))),
|
|
45
50
|
async flush() {
|
|
@@ -104,17 +109,22 @@ export async function wrapLegacyStore(state, saveCreds, logger) {
|
|
|
104
109
|
const route = resolveRoute(store);
|
|
105
110
|
if (route.kind !== RouteKind.PROJECTED)
|
|
106
111
|
throw new TypeError(`${store} is not a projected store`);
|
|
107
|
-
const translated = requested.map(key => [key,
|
|
108
|
-
|
|
112
|
+
const translated = requested.map(key => [key, projectionKey(store, key)]);
|
|
113
|
+
const legacyIds = translated.map(([, key]) => key).filter(key => key !== null);
|
|
114
|
+
uniqueKeys(legacyIds, `${store} legacy-key projection`);
|
|
109
115
|
const [nativeBucket, legacyBucket] = await Promise.all([
|
|
110
116
|
readBucket(route.nativeType, requested),
|
|
111
|
-
readBucket(route.legacyType,
|
|
117
|
+
readBucket(route.legacyType, legacyIds)
|
|
112
118
|
]);
|
|
113
119
|
const mirrorUpdates = emptyBucket();
|
|
114
120
|
const imported = new Map();
|
|
115
121
|
for (const [nativeKey, translatedKey] of translated) {
|
|
116
|
-
const legacyValue = ownValue(legacyBucket, translatedKey);
|
|
117
122
|
const envelope = decodeNativeEnvelope(ownValue(nativeBucket, nativeKey));
|
|
123
|
+
if (translatedKey === null) {
|
|
124
|
+
imported.set(nativeKey, envelope?.payload ?? null);
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
const legacyValue = ownValue(legacyBucket, translatedKey);
|
|
118
128
|
if (envelope && envelopeMatchesLegacy(envelope, legacyValue)) {
|
|
119
129
|
imported.set(nativeKey, envelope.payload);
|
|
120
130
|
continue;
|
|
@@ -191,18 +201,20 @@ export async function wrapLegacyStore(state, saveCreds, logger) {
|
|
|
191
201
|
throw new TypeError(`${store} is not a projected store`);
|
|
192
202
|
const nativeBucket = emptyBucket();
|
|
193
203
|
const legacyBucket = emptyBucket();
|
|
194
|
-
const projected = entries.map(([key, value]) =>
|
|
195
|
-
key
|
|
196
|
-
value
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
}));
|
|
200
|
-
uniqueKeys(
|
|
201
|
-
const nativeOnly = projected.
|
|
202
|
-
const existingLegacy =
|
|
203
|
-
? emptyBucket()
|
|
204
|
-
: await readBucket(route.legacyType, nativeOnly.map(({ translatedKey }) => translatedKey));
|
|
204
|
+
const projected = entries.map(([key, value]) => {
|
|
205
|
+
const translatedKey = projectionKey(store, key);
|
|
206
|
+
const legacyValue = translatedKey === null ? NATIVE_ONLY_PROJECTION : codecs[store].toLegacy(key, value);
|
|
207
|
+
return { key, value, translatedKey, legacyValue };
|
|
208
|
+
});
|
|
209
|
+
const legacyIds = projected.map(({ translatedKey }) => translatedKey).filter(key => key !== null);
|
|
210
|
+
uniqueKeys(legacyIds, `${store} legacy-key projection`);
|
|
211
|
+
const nativeOnly = projected.flatMap(({ legacyValue, translatedKey }) => legacyValue === NATIVE_ONLY_PROJECTION && translatedKey !== null ? [translatedKey] : []);
|
|
212
|
+
const existingLegacy = await readBucket(route.legacyType, nativeOnly);
|
|
205
213
|
for (const { key, value, translatedKey, legacyValue } of projected) {
|
|
214
|
+
if (translatedKey === null) {
|
|
215
|
+
nativeBucket[key] = encodeNativeOnlyEnvelope(value, null);
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
206
218
|
if (legacyValue === NATIVE_ONLY_PROJECTION) {
|
|
207
219
|
nativeBucket[key] = encodeNativeOnlyEnvelope(value, ownValue(existingLegacy, translatedKey));
|
|
208
220
|
continue;
|
|
@@ -265,13 +277,16 @@ export async function wrapLegacyStore(state, saveCreds, logger) {
|
|
|
265
277
|
throw new TypeError(`${store} is not a projected store`);
|
|
266
278
|
const nativeBucket = emptyBucket();
|
|
267
279
|
const legacyBucket = emptyBucket();
|
|
268
|
-
const translated = requested.map(key =>
|
|
280
|
+
const translated = requested.map(key => projectionKey(store, key)).filter(key => key !== null);
|
|
269
281
|
uniqueKeys(translated, `${store} legacy-key projection`);
|
|
270
282
|
for (const key of requested)
|
|
271
283
|
nativeBucket[key] = null;
|
|
272
284
|
for (const key of translated)
|
|
273
285
|
legacyBucket[key] = null;
|
|
274
|
-
|
|
286
|
+
const updates = { [route.nativeType]: nativeBucket };
|
|
287
|
+
if (translated.length > 0)
|
|
288
|
+
updates[route.legacyType] = legacyBucket;
|
|
289
|
+
await persist(updates);
|
|
275
290
|
}
|
|
276
291
|
async function removeMany(storeValue, requested) {
|
|
277
292
|
if (requested.length === 0)
|
|
@@ -300,8 +315,22 @@ export async function wrapLegacyStore(state, saveCreds, logger) {
|
|
|
300
315
|
}
|
|
301
316
|
}, saveCreds, logger);
|
|
302
317
|
const rows = new Map();
|
|
303
|
-
for (const
|
|
304
|
-
|
|
318
|
+
for (const selection of stores) {
|
|
319
|
+
const { store } = selection;
|
|
320
|
+
if ('prefix' in selection) {
|
|
321
|
+
if (typeof transactionalKeys.listKeys !== 'function')
|
|
322
|
+
throw new TypeError('legacy app-state snapshots require listKeys(type, prefix) inside keys.bridgeTransaction');
|
|
323
|
+
const { prefix } = selection;
|
|
324
|
+
const requested = await transactionalKeys.listKeys(resolveRoute(selection.store).nativeType, prefix);
|
|
325
|
+
if (!Array.isArray(requested))
|
|
326
|
+
throw new TypeError('legacy listKeys must return a key array');
|
|
327
|
+
for (const key of requested)
|
|
328
|
+
if (typeof key !== 'string' || !key.startsWith(prefix))
|
|
329
|
+
throw new TypeError('legacy listKeys returned a MAC key outside the snapshot collection');
|
|
330
|
+
await adapter.deleteMany(store, requested);
|
|
331
|
+
continue;
|
|
332
|
+
}
|
|
333
|
+
for (const [key, value] of await adapter.getMany(store, selection.keys))
|
|
305
334
|
rows.set(rowKey(store, key), value);
|
|
306
335
|
}
|
|
307
336
|
const before = new Map(rows);
|
|
@@ -331,6 +360,13 @@ export async function wrapLegacyStore(state, saveCreds, logger) {
|
|
|
331
360
|
{ store: 'meta', keys: maintainIndex ? ['mutation_mac_keys'] : [] }
|
|
332
361
|
]).commitPatch(name, stateBytes, removed, added, maintainIndex);
|
|
333
362
|
},
|
|
363
|
+
commitSnapshot(name, stateBytes, entries, maintainIndex) {
|
|
364
|
+
return atomicMethods([
|
|
365
|
+
{ store: 'sync_version', keys: [name] },
|
|
366
|
+
{ store: 'mutation_mac', prefix: `${name}:` },
|
|
367
|
+
{ store: 'meta', keys: maintainIndex ? ['mutation_mac_keys'] : [] }
|
|
368
|
+
]).commitSnapshot(name, stateBytes, entries, maintainIndex);
|
|
369
|
+
},
|
|
334
370
|
touchTcTokenSenderTimestamp(jid, timestamp) {
|
|
335
371
|
return atomicMethods([
|
|
336
372
|
{ store: 'tc_token', keys: [jid] },
|
|
@@ -68,6 +68,7 @@ export async function useLegacyMultiFileAuthState(folder, options = {}) {
|
|
|
68
68
|
]));
|
|
69
69
|
},
|
|
70
70
|
set: data => backend.set(data),
|
|
71
|
+
...(backend.listKeys ? { listKeys: (type, prefix) => backend.listKeys(type, prefix) } : {}),
|
|
71
72
|
...(backend.bridgeTransaction
|
|
72
73
|
? {
|
|
73
74
|
bridgeTransaction: (work) => backend.bridgeTransaction(keys => work(normalizeKeys(keys)))
|
|
@@ -3,6 +3,7 @@ import type { ProjectedStoreName } from './constants.js';
|
|
|
3
3
|
import type { StoreRoute } from './types.js';
|
|
4
4
|
export declare function parseNativeStoreName(value: string): NativeStoreName;
|
|
5
5
|
export declare function resolveRoute(store: NativeStoreName): StoreRoute;
|
|
6
|
+
export declare function isStatusSignalAddress(address: string): boolean;
|
|
6
7
|
export declare function legacyKey(store: ProjectedStoreName, key: string): string;
|
|
7
8
|
export declare function nativeKey(store: ProjectedStoreName, key: string): string;
|
|
8
9
|
export declare function projectedStoreForLegacyType(type: string): ProjectedStoreName | null;
|
|
@@ -48,6 +48,13 @@ function legacySignalAddress(address) {
|
|
|
48
48
|
: `${parsed.user}${SignalAddressSyntax.DOMAIN_TYPE}${parsed.domainType}`;
|
|
49
49
|
return `${user}${SignalAddressSyntax.SIGNAL_DEVICE}${parsed.device}`;
|
|
50
50
|
}
|
|
51
|
+
export function isStatusSignalAddress(address) {
|
|
52
|
+
const suffix = '_status.0';
|
|
53
|
+
if (!address.endsWith(suffix))
|
|
54
|
+
return false;
|
|
55
|
+
const { domainType } = parseBridgeSignalAddress(`${address.slice(0, -suffix.length)}.0`);
|
|
56
|
+
return domainType === SignalDomainType.PN || domainType === SignalDomainType.LID;
|
|
57
|
+
}
|
|
51
58
|
/** A sender key is `<chatJid>:<signalAddress>`, and the chat is a group, status
|
|
52
59
|
* or a broadcast list. Which chats fan out through sender keys is the core's
|
|
53
60
|
* namespace, so the boundary validates the JID shape, not the domain. No JID
|
|
@@ -4,7 +4,8 @@ import { readFile, readdir } from 'node:fs/promises';
|
|
|
4
4
|
import { join } from 'node:path';
|
|
5
5
|
import { createSnapshotTransactions } from '../../Utils/snapshot-transactions.js';
|
|
6
6
|
import { defaultSyncDir } from '../../Utils/durable-directory.js';
|
|
7
|
-
import { rowKey } from '../../Utils/atomic-store.js';
|
|
7
|
+
import { rowKey, rowPrefix } from '../../Utils/atomic-store.js';
|
|
8
|
+
import { LegacyMultiFile } from './constants.js';
|
|
8
9
|
import { BufferJSON } from '../../Utils/generics.js';
|
|
9
10
|
/** All legacy and native-mirror writes share the same persistent snapshot.
|
|
10
11
|
* The original JSON files are migration backups after the first commit.
|
|
@@ -24,6 +25,24 @@ export const legacySnapshotKeys = async (folder, fileName, options = {}) => {
|
|
|
24
25
|
const decode = (bytes) => bytes ? JSON.parse(Buffer.from(bytes).toString(), BufferJSON.reviver) : null;
|
|
25
26
|
const transactionView = (rows, mutated) => ({
|
|
26
27
|
get: async (type, ids) => Object.fromEntries(ids.map(id => [id, decode(rows.get(rowKey('legacy', fileName(type, id))))])),
|
|
28
|
+
listKeys: (type, prefix) => {
|
|
29
|
+
// MAC row keys have the form collection:hex. Their suffix survives legacy filename encoding.
|
|
30
|
+
const suffixLength = LegacyMultiFile.EXTENSION.length;
|
|
31
|
+
const filenamePrefix = fileName(type, prefix).slice(0, -suffixLength);
|
|
32
|
+
const encodedPrefix = rowPrefix('legacy', filenamePrefix);
|
|
33
|
+
const matches = [];
|
|
34
|
+
for (const key of rows.keys()) {
|
|
35
|
+
if (!key.startsWith(encodedPrefix))
|
|
36
|
+
continue;
|
|
37
|
+
const [, filename] = JSON.parse(key);
|
|
38
|
+
if (!filename.endsWith(LegacyMultiFile.EXTENSION))
|
|
39
|
+
continue;
|
|
40
|
+
const suffix = filename.slice(filenamePrefix.length, -suffixLength);
|
|
41
|
+
if (!suffix.includes(LegacyMultiFile.COLON_REPLACEMENT))
|
|
42
|
+
matches.push(prefix + suffix);
|
|
43
|
+
}
|
|
44
|
+
return matches;
|
|
45
|
+
},
|
|
27
46
|
set: async (data) => {
|
|
28
47
|
for (const [type, values] of Object.entries(data))
|
|
29
48
|
for (const [id, value] of Object.entries(values ?? {})) {
|
|
@@ -11,6 +11,8 @@ type Awaitable<T> = T | PromiseLike<T>;
|
|
|
11
11
|
export type LegacyKeysStore = {
|
|
12
12
|
get(type: string, ids: string[]): Awaitable<Record<string, unknown>>;
|
|
13
13
|
set(data: Record<string, Record<string, unknown>>): Awaitable<void>;
|
|
14
|
+
/** Enumerate all matching IDs inside the current transaction for snapshot replacement. */
|
|
15
|
+
listKeys?(type: string, prefix: string): Awaitable<string[]>;
|
|
14
16
|
bridgeTransaction?<T>(work: (keys: LegacyKeysStore) => Promise<T>): Promise<T>;
|
|
15
17
|
};
|
|
16
18
|
export interface WrappedLegacyStore extends JsStoreCallbacks {
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import LongRuntime from '../Runtime/long.js';
|
|
2
2
|
import { BinaryReader } from '@oxidezap/whatsapp-rust-bridge/host';
|
|
3
3
|
import { base64Decode, base64Encode, publicBytes } from '../Runtime/bytes.js';
|
|
4
|
-
import {
|
|
5
|
-
|
|
4
|
+
import { FIELD_ALIASES } from './field-aliases.js';
|
|
5
|
+
import { PROTO_ENUM_SCHEMAS, PROTO_FIELD_FLAG, PROTO_FIELD_KIND, PROTO_INSTANCE_SCHEMA as INSTANCE_SCHEMA, PROTO_MESSAGE_SCHEMAS } from '../WAProto/compatibility-schema.js';
|
|
6
6
|
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 });
|
|
@@ -329,14 +329,6 @@ const schemaIdFor = (path) => {
|
|
|
329
329
|
lastSchemaId = schemaIdsByPath.get(path);
|
|
330
330
|
return lastSchemaId;
|
|
331
331
|
};
|
|
332
|
-
// Bridge names stay neutral. Both sides put these at the same number and wire type,
|
|
333
|
-
// so only the spelling differs.
|
|
334
|
-
const FIELD_ALIASES = {
|
|
335
|
-
'SyncActionValue.AgentAction': ['deviceID', 'deviceId'],
|
|
336
|
-
'SyncActionValue.ChatAssignmentAction': ['deviceAgentID', 'deviceAgentId'],
|
|
337
|
-
'Message.ExtendedTextMessage': ['faviconMMSMetadata', 'faviconMmsMetadata'],
|
|
338
|
-
'Message.MessageHistoryMetadata': ['oldestMessageTimestamp', 'oldestMessageTimestampInWindow']
|
|
339
|
-
};
|
|
340
332
|
// Indexed by schema id because its readers run per message.
|
|
341
333
|
let aliasBySchema;
|
|
342
334
|
const aliasFor = (schemaId) => (aliasBySchema ?? (aliasBySchema = PROTO_MESSAGE_SCHEMAS.map(([path]) => FIELD_ALIASES[path])))[schemaId];
|
|
@@ -681,7 +673,8 @@ class ProtoCompatibilityRuntime {
|
|
|
681
673
|
throw new Error('invalid generated protobuf enum');
|
|
682
674
|
publicValue[name] = value;
|
|
683
675
|
valuesByName.set(name, value);
|
|
684
|
-
namesByValue.
|
|
676
|
+
if (!namesByValue.has(value))
|
|
677
|
+
namesByValue.set(value, name);
|
|
685
678
|
}
|
|
686
679
|
return { publicValue, valuesByName, namesByValue, firstValue: entries[1] ?? 0 };
|
|
687
680
|
}
|
|
@@ -691,7 +684,7 @@ class ProtoCompatibilityRuntime {
|
|
|
691
684
|
// Only repeated and map fields get an own value per instance, so the
|
|
692
685
|
// constructor walks just those, in schema order, instead of every field:
|
|
693
686
|
// `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));
|
|
687
|
+
const collections = fields.filter(field => !(field[3] & PROTO_FIELD_FLAG.bridgeAddition) && field[3] & (PROTO_FIELD_FLAG.repeated | PROTO_FIELD_FLAG.map));
|
|
695
688
|
// Indexed loops: these run for every constructed instance and stay on
|
|
696
689
|
// the megamorphic path at runtime, where V8 does not elide for..of
|
|
697
690
|
// iterator allocations.
|
|
@@ -717,6 +710,35 @@ class ProtoCompatibilityRuntime {
|
|
|
717
710
|
Object.assign(constructor, sourceCodec ?? {});
|
|
718
711
|
Object.defineProperty(constructor.prototype, INSTANCE_SCHEMA, { value: schemaId });
|
|
719
712
|
for (const field of fields) {
|
|
713
|
+
if (field[3] & PROTO_FIELD_FLAG.bridgeAddition && field[3] & (PROTO_FIELD_FLAG.repeated | PROTO_FIELD_FLAG.map)) {
|
|
714
|
+
const isRepeated = (field[3] & PROTO_FIELD_FLAG.repeated) !== 0;
|
|
715
|
+
Object.defineProperty(constructor.prototype, field[0], {
|
|
716
|
+
get() {
|
|
717
|
+
if (this === constructor.prototype || !Object.isExtensible(this)) {
|
|
718
|
+
return isRepeated ? EMPTY_ARRAY : EMPTY_OBJECT;
|
|
719
|
+
}
|
|
720
|
+
const empty = isRepeated ? [] : {};
|
|
721
|
+
Object.defineProperty(this, field[0], {
|
|
722
|
+
value: empty,
|
|
723
|
+
writable: true,
|
|
724
|
+
enumerable: true,
|
|
725
|
+
configurable: true
|
|
726
|
+
});
|
|
727
|
+
return empty;
|
|
728
|
+
},
|
|
729
|
+
set(value) {
|
|
730
|
+
Object.defineProperty(this, field[0], {
|
|
731
|
+
value,
|
|
732
|
+
writable: true,
|
|
733
|
+
enumerable: true,
|
|
734
|
+
configurable: true
|
|
735
|
+
});
|
|
736
|
+
},
|
|
737
|
+
enumerable: true,
|
|
738
|
+
configurable: true
|
|
739
|
+
});
|
|
740
|
+
continue;
|
|
741
|
+
}
|
|
720
742
|
Object.defineProperty(constructor.prototype, field[0], {
|
|
721
743
|
value: this.prototypeDefault(field),
|
|
722
744
|
writable: true,
|
|
@@ -925,6 +947,8 @@ class ProtoCompatibilityRuntime {
|
|
|
925
947
|
// Without these options the pass below writes nothing; `toJSON` sets none of them.
|
|
926
948
|
if (options.arrays || options.defaults || options.objects) {
|
|
927
949
|
for (const field of fields) {
|
|
950
|
+
if (field[3] & PROTO_FIELD_FLAG.bridgeAddition && !hasOwnField(data, field, alias))
|
|
951
|
+
continue;
|
|
928
952
|
if (field[3] & PROTO_FIELD_FLAG.repeated) {
|
|
929
953
|
if (options.arrays || options.defaults)
|
|
930
954
|
output[field[0]] = [];
|
|
@@ -938,13 +962,14 @@ class ProtoCompatibilityRuntime {
|
|
|
938
962
|
}
|
|
939
963
|
}
|
|
940
964
|
}
|
|
941
|
-
//
|
|
942
|
-
// just those positions, in schema order, and the output is unchanged.
|
|
965
|
+
// Visit only own fields when the prototype carries no populated collections.
|
|
943
966
|
const positions = ownFieldPositions(data, this.fieldPositionsOf(schemaId), fields.length);
|
|
944
967
|
const count = positions === undefined ? fields.length : positions.length;
|
|
945
968
|
// Indexed for the same reason as `fromObject`: no iterator result per field.
|
|
946
969
|
for (let n = 0; n < count; n++) {
|
|
947
970
|
const field = fields[positions === undefined ? n : positions[n]];
|
|
971
|
+
if (field[3] & PROTO_FIELD_FLAG.bridgeAddition && !hasOwnField(data, field, alias))
|
|
972
|
+
continue;
|
|
948
973
|
const value = fieldValue(data, field, alias);
|
|
949
974
|
if (field[3] & PROTO_FIELD_FLAG.repeated) {
|
|
950
975
|
if (value &&
|
package/lib/Media/content.js
CHANGED
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
* behavioral change: the differential suite pins both functions against
|
|
10
10
|
* the originals.
|
|
11
11
|
*/
|
|
12
|
+
import { BASELINE_FUTURE_PROOF_FIELDS, BRIDGE_FUTURE_PROOF_FIELDS, PROTO_INSTANCE_SCHEMA, getOrderedFutureProofMessage } from '../WAProto/compatibility-schema.js';
|
|
12
13
|
/**
|
|
13
14
|
* The content keys that carry almost every message on a live socket, settled by
|
|
14
15
|
* identity before the structural predicate runs. Every name here already
|
|
@@ -58,15 +59,12 @@ export const getContentType = (content) => {
|
|
|
58
59
|
}
|
|
59
60
|
return undefined;
|
|
60
61
|
};
|
|
61
|
-
const
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
message?.associatedChildMessage ||
|
|
68
|
-
message?.groupStatusMessage ||
|
|
69
|
-
message?.groupStatusMessageV2;
|
|
62
|
+
const { getOwnPropertyNames, getPrototypeOf, hasOwn } = Object;
|
|
63
|
+
const objectPrototype = Object.prototype;
|
|
64
|
+
const wrapperFields = [...BASELINE_FUTURE_PROOF_FIELDS, ...BRIDGE_FUTURE_PROOF_FIELDS];
|
|
65
|
+
const wrapperIndices = Object.create(null);
|
|
66
|
+
for (let i = 0; i < wrapperFields.length; i++)
|
|
67
|
+
wrapperIndices[wrapperFields[i]] = i;
|
|
70
68
|
const extractFromTemplateMessage = (msg) => {
|
|
71
69
|
if (msg.imageMessage) {
|
|
72
70
|
return { imageMessage: msg.imageMessage };
|
|
@@ -98,11 +96,38 @@ export const normalizeMessageContent = (content) => {
|
|
|
98
96
|
}
|
|
99
97
|
// set max iterations to prevent an infinite loop
|
|
100
98
|
for (let i = 0; i < 5; i++) {
|
|
101
|
-
|
|
99
|
+
let inner;
|
|
100
|
+
const prototype = getPrototypeOf(content);
|
|
101
|
+
if (prototype === objectPrototype || (prototype !== null && hasOwn(prototype, PROTO_INSTANCE_SCHEMA))) {
|
|
102
|
+
// Plain objects and facade instances store message fields as own properties.
|
|
103
|
+
const keys = getOwnPropertyNames(content);
|
|
104
|
+
if (keys.length === 1) {
|
|
105
|
+
const field = keys[0];
|
|
106
|
+
const index = wrapperIndices[field];
|
|
107
|
+
if (index === undefined)
|
|
108
|
+
break;
|
|
109
|
+
inner = content[field];
|
|
110
|
+
if (index >= BASELINE_FUTURE_PROOF_FIELDS.length && !inner?.message)
|
|
111
|
+
break;
|
|
112
|
+
}
|
|
113
|
+
else {
|
|
114
|
+
let j = 0;
|
|
115
|
+
while (j < keys.length && wrapperIndices[keys[j]] === undefined)
|
|
116
|
+
j++;
|
|
117
|
+
if (j === keys.length)
|
|
118
|
+
break;
|
|
119
|
+
inner = getOrderedFutureProofMessage(content);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
else {
|
|
123
|
+
inner = getOrderedFutureProofMessage(content);
|
|
124
|
+
}
|
|
102
125
|
if (!inner) {
|
|
103
126
|
break;
|
|
104
127
|
}
|
|
105
128
|
content = inner.message;
|
|
129
|
+
if (!content)
|
|
130
|
+
break;
|
|
106
131
|
}
|
|
107
132
|
return content;
|
|
108
133
|
};
|
|
@@ -112,18 +137,11 @@ export const normalizeMessageContent = (content) => {
|
|
|
112
137
|
*/
|
|
113
138
|
export const extractMessageContent = (content) => {
|
|
114
139
|
content = normalizeMessageContent(content);
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
if (content?.templateMessage?.hydratedTemplate) {
|
|
122
|
-
return extractFromTemplateMessage(content?.templateMessage?.hydratedTemplate);
|
|
123
|
-
}
|
|
124
|
-
if (content?.templateMessage?.fourRowTemplate) {
|
|
125
|
-
return extractFromTemplateMessage(content?.templateMessage?.fourRowTemplate);
|
|
126
|
-
}
|
|
127
|
-
return content;
|
|
140
|
+
const buttons = content?.buttonsMessage;
|
|
141
|
+
if (buttons)
|
|
142
|
+
return extractFromTemplateMessage(buttons);
|
|
143
|
+
const template = content?.templateMessage;
|
|
144
|
+
const hydrated = template?.hydratedFourRowTemplate || template?.hydratedTemplate || template?.fourRowTemplate;
|
|
145
|
+
return hydrated ? extractFromTemplateMessage(hydrated) : content;
|
|
128
146
|
};
|
|
129
147
|
//# sourceMappingURL=content.js.map
|
package/lib/Socket/core.js
CHANGED
|
@@ -597,7 +597,8 @@ const createWASocketFactoryInner = (runtime, config, claimEngineInitialization,
|
|
|
597
597
|
// Absent stays strict.
|
|
598
598
|
fullConfig.dangerSkipCertChainVerify, {
|
|
599
599
|
...makeHistorySyncAdmission(shouldSyncHistoryMessage),
|
|
600
|
-
additionalStaticMediaHosts: fullConfig.additionalStaticMediaHosts
|
|
600
|
+
additionalStaticMediaHosts: fullConfig.additionalStaticMediaHosts,
|
|
601
|
+
presencePolicy: fullConfig.markOnlineOnConnect === false ? 'manual' : 'automatic'
|
|
601
602
|
});
|
|
602
603
|
// `end()` can land while the client is still being built — a `sock.end()`
|
|
603
604
|
// or `await using` right after `makeWASocket()` does exactly that. When
|
|
@@ -218,7 +218,16 @@ const describeTempBan = (code) => {
|
|
|
218
218
|
const emitConnectionUpdate = (ctx, update) => ctx.ev.emit('connection.update', update);
|
|
219
219
|
const DISPATCHERS = {
|
|
220
220
|
// ── Connection lifecycle ──
|
|
221
|
-
connected: (_, { ctx }) =>
|
|
221
|
+
connected: (_, { ctx }) => {
|
|
222
|
+
// Upstream marks the account unavailable on open when it is not marked online,
|
|
223
|
+
// from a listener that runs before the caller's, so a caller's presence wins.
|
|
224
|
+
if (ctx.fullConfig.markOnlineOnConnect === false) {
|
|
225
|
+
ctx
|
|
226
|
+
.withClient(client => client.sendPresence('unavailable'))
|
|
227
|
+
.catch(error => ctx.reportUnexpectedError(error, 'presence update requests'));
|
|
228
|
+
}
|
|
229
|
+
emitConnectionUpdate(ctx, { connection: 'open' });
|
|
230
|
+
},
|
|
222
231
|
offlineSyncCompleted: (_, { ctx }) => emitConnectionUpdate(ctx, {
|
|
223
232
|
receivedPendingNotifications: true
|
|
224
233
|
}),
|
|
@@ -87,7 +87,7 @@ export const makeMessageMethodsCore = (ctx, encode, runtimeLong) => {
|
|
|
87
87
|
return fullMsg;
|
|
88
88
|
}
|
|
89
89
|
}
|
|
90
|
-
const msgBytes = encode('Message', msg);
|
|
90
|
+
const msgBytes = encode('Message', (fullMsg.message ?? msg));
|
|
91
91
|
// The with-options sends are the same core send as the plain ones, with
|
|
92
92
|
// the stanza id supplied by the caller instead of drawn by the engine.
|
|
93
93
|
// The id resolves through the same place `relayMessage` resolves it.
|
|
@@ -121,14 +121,21 @@ export const makeMessageMethodsCore = (ctx, encode, runtimeLong) => {
|
|
|
121
121
|
if (!mediaKey) {
|
|
122
122
|
throw new Boom('Message has no media key', { statusCode: 400 });
|
|
123
123
|
}
|
|
124
|
-
const
|
|
125
|
-
if (!
|
|
124
|
+
const { id, remoteJid, fromMe, participant } = message.key;
|
|
125
|
+
if (!id || !remoteJid)
|
|
126
126
|
throw new Boom('Media message key requires id and remoteJid', { statusCode: 400 });
|
|
127
|
-
const
|
|
127
|
+
const reuploadTrack = (trackKey) => client.requestMediaReupload(id, remoteJid, trackKey instanceof Uint8Array ? trackKey : new Uint8Array(trackKey), !!fromMe, participant ?? null);
|
|
128
|
+
const audioContent = content?.stickerMessage?.audioMessage;
|
|
129
|
+
// The core allows one pending media key per wire message ID.
|
|
130
|
+
const newDirectPath = await reuploadTrack(mediaKey);
|
|
131
|
+
const audioDirectPath = audioContent?.mediaKey ? await reuploadTrack(audioContent.mediaKey) : undefined;
|
|
128
132
|
// Update the message with the new direct path
|
|
129
133
|
// (download uses directPath via Rust bridge, url is informational)
|
|
130
134
|
mediaContent.directPath = newDirectPath;
|
|
131
|
-
|
|
135
|
+
if (audioContent && audioDirectPath) {
|
|
136
|
+
audioContent.directPath = audioDirectPath;
|
|
137
|
+
}
|
|
138
|
+
ctx.logger.debug({ directPath: newDirectPath, msgId: id }, 'media reupload successful');
|
|
132
139
|
ctx.ev.emit('messages.update', [
|
|
133
140
|
{
|
|
134
141
|
key: message.key,
|
|
@@ -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", "
|
|
27
|
+
export declare const UNSUPPORTED_CONFIG_KEYS: readonly ["keepAliveIntervalMs", "maxMsgRetryCount", "msgRetryCounterCache", "retryRequestDelayMs", "fireInitQueries", "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", "additionalStaticMediaHosts", "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", "markOnlineOnConnect", "emitOwnEvents", "shouldIgnoreJid", "defaultQueryTimeoutMs", "transactionOpts", "makeSignalRepository"];
|
|
37
37
|
/**
|
|
38
38
|
* Which unsupported options this caller actually passed.
|
|
39
39
|
*
|
|
@@ -35,8 +35,6 @@ export const UNSUPPORTED_CONFIG_KEYS = [
|
|
|
35
35
|
'retryRequestDelayMs',
|
|
36
36
|
// The engine decides its own post-login queries.
|
|
37
37
|
'fireInitQueries',
|
|
38
|
-
// Presence is explicit here: call `sendPresenceUpdate` after `open`.
|
|
39
|
-
'markOnlineOnConnect',
|
|
40
38
|
// Full-history requests are driven by the engine. The per-notification
|
|
41
39
|
// admission policy is translated by Socket/index.ts.
|
|
42
40
|
'syncFullHistory',
|
|
@@ -101,6 +99,7 @@ export const READ_CONFIG_KEYS = [
|
|
|
101
99
|
'wantedPreKeyCount',
|
|
102
100
|
'dangerSkipCertChainVerify',
|
|
103
101
|
'shouldSyncHistoryMessage',
|
|
102
|
+
'markOnlineOnConnect',
|
|
104
103
|
'emitOwnEvents',
|
|
105
104
|
'shouldIgnoreJid',
|
|
106
105
|
'defaultQueryTimeoutMs',
|
package/lib/Types/Auth.d.ts
CHANGED
|
@@ -111,6 +111,7 @@ type Awaitable<T> = T | Promise<T>;
|
|
|
111
111
|
export type SignalKeyStore = {
|
|
112
112
|
/** Backend transaction, isolated against every writer in the device scope.
|
|
113
113
|
* Must commit all mutations durably or none, including native mirror rows.
|
|
114
|
+
* Snapshot replacement uses the transaction view's `listKeys(type, prefix)`.
|
|
114
115
|
* The upstream adapter-local transaction helper does not meet this contract. */
|
|
115
116
|
bridgeTransaction?<T>(work: (keys: LegacyKeysStore) => Promise<T>): Promise<T>;
|
|
116
117
|
get<T extends keyof SignalDataTypeMap>(type: T, ids: string[]): Awaitable<{
|