@oxidezap/baileyrs 0.3.10 → 0.3.12

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.
Files changed (55) hide show
  1. package/lib/Bridge/schema.js +42 -16
  2. package/lib/Bridge/types.d.ts +13 -2
  3. package/lib/Compatibility/auth-state.js +2 -11
  4. package/lib/Compatibility/host-auth-state.js +2 -0
  5. package/lib/Compatibility/internal/auth-state.js +6 -0
  6. package/lib/Compatibility/internal/host-auth-state.js +3 -0
  7. package/lib/Compatibility/legacy-store/adapter.js +137 -3
  8. package/lib/Compatibility/legacy-store/codecs/basic.js +5 -8
  9. package/lib/Compatibility/legacy-store/multi-file.d.ts +12 -1
  10. package/lib/Compatibility/legacy-store/multi-file.js +37 -25
  11. package/lib/Compatibility/legacy-store/record-files.d.ts +3 -0
  12. package/lib/Compatibility/legacy-store/record-files.js +5 -0
  13. package/lib/Compatibility/legacy-store/rollback.d.ts +8 -0
  14. package/lib/Compatibility/legacy-store/rollback.js +16 -0
  15. package/lib/Compatibility/legacy-store/snapshot.d.ts +7 -0
  16. package/lib/Compatibility/legacy-store/snapshot.js +53 -0
  17. package/lib/Compatibility/legacy-store/types.d.ts +4 -1
  18. package/lib/Socket/chat-actions.js +1 -1
  19. package/lib/Socket/events-core.js +9 -1
  20. package/lib/Socket/index.d.ts +3 -717
  21. package/lib/Types/Auth.d.ts +5 -0
  22. package/lib/Types/Events.d.ts +6 -1
  23. package/lib/Utils/atomic-store.d.ts +20 -0
  24. package/lib/Utils/atomic-store.js +116 -0
  25. package/lib/Utils/durable-directory.d.ts +3 -0
  26. package/lib/Utils/durable-directory.js +35 -0
  27. package/lib/Utils/flush-deadline.d.ts +19 -0
  28. package/lib/Utils/flush-deadline.js +97 -0
  29. package/lib/Utils/index.d.ts +1 -0
  30. package/lib/Utils/index.js +1 -0
  31. package/lib/Utils/native-auth-rollback.d.ts +14 -0
  32. package/lib/Utils/native-auth-rollback.js +17 -0
  33. package/lib/Utils/process-file-lock.d.ts +6 -0
  34. package/lib/Utils/process-file-lock.js +38 -0
  35. package/lib/Utils/snapshot-rollback-proof.d.ts +9 -0
  36. package/lib/Utils/snapshot-rollback-proof.js +43 -0
  37. package/lib/Utils/snapshot-rollback.d.ts +5 -0
  38. package/lib/Utils/snapshot-rollback.js +69 -0
  39. package/lib/Utils/snapshot-transactions.d.ts +10 -0
  40. package/lib/Utils/snapshot-transactions.js +108 -0
  41. package/lib/Utils/store-migration.d.ts +10 -0
  42. package/lib/Utils/store-migration.js +16 -0
  43. package/lib/Utils/transactional-file-store.d.ts +7 -0
  44. package/lib/Utils/transactional-file-store.js +157 -0
  45. package/lib/Utils/use-bridge-store.d.ts +3 -49
  46. package/lib/Utils/use-bridge-store.js +121 -109
  47. package/lib/Utils/use-memory-store.js +17 -4
  48. package/lib/Utils/use-multi-file-auth-state.d.ts +2 -1
  49. package/lib/Utils/use-multi-file-auth-state.js +2 -2
  50. package/lib/Utils/wrap-legacy-store.d.ts +1 -0
  51. package/lib/Utils/wrap-legacy-store.js +1 -0
  52. package/lib/host-types.d.ts +1 -15
  53. package/lib/node-surface.d.ts +2 -1
  54. package/lib/node-surface.js +2 -1
  55. package/package.json +12 -10
@@ -216,10 +216,12 @@ const ADAPTERS = {
216
216
  const from = asJidString(data?.from);
217
217
  if (!from)
218
218
  return null;
219
+ if (data?.status !== 'available' && data?.status !== 'unavailable')
220
+ return null;
219
221
  return {
220
222
  type: 'presence',
221
223
  from,
222
- unavailable: asBoolOr(data?.unavailable, false),
224
+ unavailable: data?.status === 'unavailable',
223
225
  lastSeen: asUnixSeconds(data?.last_seen)
224
226
  };
225
227
  },
@@ -231,21 +233,15 @@ const ADAPTERS = {
231
233
  const sender = asJidString(src.sender);
232
234
  if (!chat || !sender)
233
235
  return null;
234
- // Bridge sends `media: ''` for "no media" — normalize to undefined
235
- // so consumers can rely on field omission as the absence signal.
236
- const media = asString(data?.media);
237
- // Bridge `state` MUST be one of the two canonical values; defaulting
238
- // to 'composing' on an unknown/missing value would synthesize a
239
- // false typing indicator. Drop the event instead.
240
236
  const rawState = asString(data?.state);
241
- if (rawState !== 'composing' && rawState !== 'paused')
237
+ if (rawState !== 'typing' && rawState !== 'recording_audio' && rawState !== 'idle')
242
238
  return null;
243
239
  return {
244
240
  type: 'chatPresence',
245
241
  chatJid: chat,
246
242
  senderJid: sender,
247
- state: rawState,
248
- media: media === 'audio' ? 'audio' : undefined
243
+ state: rawState === 'idle' ? 'paused' : 'composing',
244
+ media: rawState === 'recording_audio' ? 'audio' : undefined
249
245
  };
250
246
  },
251
247
  // ── Groups ──
@@ -294,7 +290,29 @@ const ADAPTERS = {
294
290
  return null;
295
291
  return { type: 'lockChatUpdate', jid, locked: asBoolOr(extractAction(data)?.locked, true) };
296
292
  },
293
+ label_sublist_update: data => {
294
+ const actionTimestamp = asString(data?.action_timestamp);
295
+ const chatJid = asJidString(data?.chat_jid);
296
+ const predefinedId = asNumber(data?.predefined_id);
297
+ const change = data?.change;
298
+ const subListId = isObject(change) && isObject(change.Upsert) ? asNumber(change.Upsert.sub_list_id) : undefined;
299
+ if (!chatJid ||
300
+ predefinedId === undefined ||
301
+ !Number.isInteger(predefinedId) ||
302
+ (change !== 'Remove' && (subListId === undefined || !Number.isInteger(subListId))))
303
+ return null;
304
+ return {
305
+ type: 'labelSublist',
306
+ predefinedId,
307
+ chatJid,
308
+ change: change === 'Remove' ? 'remove' : 'upsert',
309
+ ...(change === 'Remove' ? {} : { subListId }),
310
+ ...(actionTimestamp !== undefined ? { actionTimestamp } : {}),
311
+ fromFullSync: asBoolOr(data?.from_full_sync, false)
312
+ };
313
+ },
297
314
  label_edit_update: data => {
315
+ const actionTimestamp = asString(data?.action_timestamp);
298
316
  const labelId = asString(data?.label_id);
299
317
  if (!labelId)
300
318
  return { type: 'noop', bridgeType: 'label_edit_update' };
@@ -304,6 +322,7 @@ const ADAPTERS = {
304
322
  const predefined = asNumber(action?.predefinedId) ?? asNumber(action?.predefined_id);
305
323
  return {
306
324
  type: 'labelEdit',
325
+ ...(actionTimestamp !== undefined ? { actionTimestamp } : {}),
307
326
  labelId,
308
327
  name: asString(action?.name) ?? '',
309
328
  color: asNumber(action?.color) ?? 0,
@@ -312,18 +331,26 @@ const ADAPTERS = {
312
331
  };
313
332
  },
314
333
  label_association_update: data => {
334
+ const actionTimestamp = asString(data?.action_timestamp);
315
335
  const labelId = asString(data?.label_id);
316
336
  const chatJid = asJidString(data?.chat_jid);
317
337
  if (!labelId || !chatJid)
318
338
  return { type: 'noop', bridgeType: 'label_association_update' };
319
339
  // `action.labeled === true` → label added to the chat, else removed.
320
- return { type: 'labelAssociation', labelId, chatJid, labeled: asBoolOr(extractAction(data)?.labeled, true) };
340
+ return {
341
+ type: 'labelAssociation',
342
+ ...(actionTimestamp !== undefined ? { actionTimestamp } : {}),
343
+ labelId,
344
+ chatJid,
345
+ labeled: asBoolOr(extractAction(data)?.labeled, true)
346
+ };
321
347
  },
322
348
  /**
323
349
  * The per-message half of `labels.association`, which used to have no path.
324
350
  * Same canonical event as the chat one, told apart by carrying a message.
325
351
  */
326
352
  message_label_association_update: data => {
353
+ const actionTimestamp = asString(data?.action_timestamp);
327
354
  const labelId = asString(data?.label_id);
328
355
  const chatJid = asJidString(data?.chat_jid);
329
356
  const messageId = asString(data?.message_id);
@@ -332,6 +359,7 @@ const ADAPTERS = {
332
359
  }
333
360
  return {
334
361
  type: 'labelAssociation',
362
+ ...(actionTimestamp !== undefined ? { actionTimestamp } : {}),
335
363
  labelId,
336
364
  chatJid,
337
365
  messageId,
@@ -946,13 +974,11 @@ const adaptIncomingCall = (data, logger) => {
946
974
  logger?.debug({ data }, 'incoming_call adapter: missing action.type/call_id');
947
975
  return null;
948
976
  }
949
- // The call offer is timeline-ordered by its timestamp downstream; an
950
- // unparseable one drops the event rather than dating it at the epoch.
977
+ // Core can omit timestamps on call control stanzas. Preserve the action;
978
+ // a present malformed timestamp remains invalid input.
951
979
  const timestamp = asUnixSeconds(data.timestamp);
952
- if (timestamp === undefined) {
953
- logger?.debug(invalidTimestampDetail('incoming_call', data.timestamp), 'incoming_call adapter: missing or invalid timestamp');
980
+ if (data.timestamp != null && timestamp === undefined)
954
981
  return null;
955
- }
956
982
  const canonicalAction = {
957
983
  type: actionType,
958
984
  callId,
@@ -455,8 +455,18 @@ export interface CanonicalMarkChatAsReadUpdate {
455
455
  * A label was created, renamed/recolored, or deleted on a linked device
456
456
  * (bridge `label_edit_update`). Maps to upstream `labels.edit` (`Label`).
457
457
  */
458
+ export interface CanonicalLabelSublist {
459
+ type: 'labelSublist';
460
+ predefinedId: number;
461
+ chatJid: string;
462
+ change: 'upsert' | 'remove';
463
+ subListId?: number;
464
+ actionTimestamp?: string;
465
+ fromFullSync: boolean;
466
+ }
458
467
  export interface CanonicalLabelEdit {
459
468
  type: 'labelEdit';
469
+ actionTimestamp?: string;
460
470
  labelId: string;
461
471
  name: string;
462
472
  color: number;
@@ -470,6 +480,7 @@ export interface CanonicalLabelEdit {
470
480
  */
471
481
  export interface CanonicalLabelAssociation {
472
482
  type: 'labelAssociation';
483
+ actionTimestamp?: string;
473
484
  labelId: string;
474
485
  chatJid: string;
475
486
  /**
@@ -555,7 +566,7 @@ export interface CanonicalCallAction {
555
566
  export interface CanonicalIncomingCall {
556
567
  type: 'incomingCall';
557
568
  from: string;
558
- timestamp: number;
569
+ timestamp?: number;
559
570
  offline: boolean;
560
571
  /** Stanza-level `id` (distinct from `action.callId`). */
561
572
  stanzaId?: string;
@@ -742,5 +753,5 @@ export interface CanonicalServerAck {
742
753
  timestamp?: number;
743
754
  error?: string;
744
755
  }
745
- export type CanonicalEvent = CanonicalConnected | CanonicalDisconnected | CanonicalQR | CanonicalPairSuccess | CanonicalPairError | CanonicalLoggedOut | CanonicalConnectFailure | CanonicalStreamError | CanonicalStreamReplaced | CanonicalClientOutdated | CanonicalTemporaryBan | CanonicalQrScannedWithoutMultidevice | CanonicalMessage | CanonicalReceipt | CanonicalContactUpdate | CanonicalPictureUpdate | CanonicalPresence | CanonicalChatPresence | CanonicalGroupUpdate | CanonicalArchiveUpdate | CanonicalPinUpdate | CanonicalMuteUpdate | CanonicalStarUpdate | CanonicalMarkChatAsReadUpdate | CanonicalLockChatUpdate | CanonicalLabelEdit | CanonicalLabelAssociation | CanonicalAppStateSyncFailed | CanonicalQrCodesExhausted | CanonicalSettingUpdate | CanonicalReachoutTimelock | CanonicalUnarchiveChatsSetting | CanonicalIncomingCall | CanonicalUndecryptableMessage | CanonicalLidMappingUpdate | CanonicalNewsletterLiveUpdate | CanonicalChatDelete | CanonicalChatClear | CanonicalMessageDelete | CanonicalDisappearingModeChanged | CanonicalHistorySync | CanonicalOfflineSyncCompleted | CanonicalDirtyState | CanonicalRawNode | CanonicalNotification | CanonicalMexNotification | CanonicalServerAck | CanonicalNoop;
756
+ export type CanonicalEvent = CanonicalConnected | CanonicalDisconnected | CanonicalQR | CanonicalPairSuccess | CanonicalPairError | CanonicalLoggedOut | CanonicalConnectFailure | CanonicalStreamError | CanonicalStreamReplaced | CanonicalClientOutdated | CanonicalTemporaryBan | CanonicalQrScannedWithoutMultidevice | CanonicalMessage | CanonicalReceipt | CanonicalContactUpdate | CanonicalPictureUpdate | CanonicalPresence | CanonicalChatPresence | CanonicalGroupUpdate | CanonicalArchiveUpdate | CanonicalPinUpdate | CanonicalMuteUpdate | CanonicalStarUpdate | CanonicalMarkChatAsReadUpdate | CanonicalLockChatUpdate | CanonicalLabelSublist | CanonicalLabelEdit | CanonicalLabelAssociation | CanonicalAppStateSyncFailed | CanonicalQrCodesExhausted | CanonicalSettingUpdate | CanonicalReachoutTimelock | CanonicalUnarchiveChatsSetting | CanonicalIncomingCall | CanonicalUndecryptableMessage | CanonicalLidMappingUpdate | CanonicalNewsletterLiveUpdate | CanonicalChatDelete | CanonicalChatClear | CanonicalMessageDelete | CanonicalDisappearingModeChanged | CanonicalHistorySync | CanonicalOfflineSyncCompleted | CanonicalDirtyState | CanonicalRawNode | CanonicalNotification | CanonicalMexNotification | CanonicalServerAck | CanonicalNoop;
746
757
  //# sourceMappingURL=types.d.ts.map
@@ -1,14 +1,4 @@
1
- /**
2
- * Host-neutral credential seeding + store hydration for `auth: { store }`.
3
- *
4
- * `createAuthenticationState(store)` builds the public auth view the socket
5
- * consumes — `initAuthCreds()` for the credential mirror, the native store
6
- * projection for the key facade — and hydrates the mirror from the device
7
- * the engine persisted, so a restarted session reports `registered: true`
8
- * instead of a fresh placeholder. Key generation goes through the bridge
9
- * (`/host` entrypoint, already initialized by the caller), never
10
- * `node:crypto`; byte helpers come from `Runtime/bytes.ts`, never Buffer.
11
- */
1
+ import { assertStoreCallbacks } from '../Utils/atomic-store.js';
12
2
  import { calculateSignature, generateKeyPair } from '@oxidezap/whatsapp-rust-bridge/host';
13
3
  import { concatBytes } from '../Runtime/bytes.js';
14
4
  import { createDeviceProjection } from './legacy-store/device.js';
@@ -84,6 +74,7 @@ const hydrateFromStore = async (store, creds) => {
84
74
  * wrap, no `Buffer`.
85
75
  */
86
76
  export const createAuthenticationState = async (store, keys) => {
77
+ assertStoreCallbacks(store);
87
78
  const creds = initHostAuthCreds();
88
79
  await hydrateFromStore(store, creds);
89
80
  const { projectNativeStore } = await import('./legacy-store/native-projection.js');
@@ -1,3 +1,4 @@
1
+ import { assertStoreCallbacks } from '../Utils/atomic-store.js';
1
2
  /** Host-only auth bootstrap. It deliberately does not import legacy-store codecs. */
2
3
  import { calculateSignature, generateKeyPair } from '@oxidezap/whatsapp-rust-bridge/host';
3
4
  import { proto } from '@oxidezap/whatsapp-rust-bridge/proto-types';
@@ -155,6 +156,7 @@ export const hydrateHostAuthCreds = async (store, creds) => {
155
156
  };
156
157
  /** Build host auth from the caller-owned native byte store. Rust remains the Signal authority. */
157
158
  export const createAuthenticationState = async (store) => {
159
+ assertStoreCallbacks(store);
158
160
  const creds = initHostAuthCreds();
159
161
  await hydrateHostAuthCreds(store, creds);
160
162
  return { creds: creds, store };
@@ -1,3 +1,4 @@
1
+ import { assertStoreCallbacks } from '../../Utils/atomic-store.js';
1
2
  import { Buffer } from 'node:buffer';
2
3
  import { initAuthCreds } from '../../Utils/generics.js';
3
4
  import { hydrateHostAuthCreds } from '../host-auth-state.js';
@@ -35,6 +36,11 @@ export const normalizeSocketAuthenticationState = (input) => {
35
36
  throw new TypeError('auth must provide either { creds, keys } or a native store');
36
37
  }
37
38
  const store = input.store;
39
+ if (store)
40
+ assertStoreCallbacks(store);
41
+ else if (input.keys && typeof input.keys.bridgeTransaction !== 'function') {
42
+ throw new TypeError('legacy auth requires keys.bridgeTransaction with backend-wide atomicity; stop old writers and load file auth with useLegacyMultiFileAuthState(folder, { migrate: true })');
43
+ }
38
44
  const creds = input.creds ?? (store ? initAuthCreds() : undefined);
39
45
  const keys = input.keys ?? (store && creds ? projectNativeStore(store, creds) : undefined);
40
46
  if (!creds || !keys) {
@@ -1,7 +1,10 @@
1
+ import { assertStoreCallbacks } from '../../Utils/atomic-store.js';
1
2
  /** Host normalization: native stores remain Rust-owned and expose no legacy key facade. */
2
3
  export const normalizeHostAuthenticationState = (input) => {
3
4
  if (!input || typeof input !== 'object')
4
5
  throw new TypeError('auth must provide either { creds, keys } or a native store');
6
+ if (input.store)
7
+ assertStoreCallbacks(input.store);
5
8
  if (input.creds && input.keys)
6
9
  return input;
7
10
  if (input.store && input.creds)
@@ -1,3 +1,5 @@
1
+ import { settleBeforeFlushDeadline, flushDeadlineError, settledFlushError } from '../../Utils/flush-deadline.js';
2
+ import { atomicCallbacks, rowKey } from '../../Utils/atomic-store.js';
1
3
  // Baileys legacy auth-state projection onto the bridge's neutral byte store.
2
4
  import { Buffer } from 'node:buffer';
3
5
  import { NativeStore, RouteKind } from './constants.js';
@@ -19,6 +21,47 @@ function uniqueKeys(keys, label) {
19
21
  function createWarn(logger) {
20
22
  return logger ? (message, error) => logger.warn({ err: error }, message) : () => { };
21
23
  }
24
+ // Track complete callbacks, including backend commit barriers. A socket flush
25
+ // must join work already admitted even when its caller has not awaited it yet.
26
+ function withPendingCallbacks(store) {
27
+ const pending = new Set();
28
+ const track = (operation) => {
29
+ pending.add(operation);
30
+ void operation.then(() => pending.delete(operation), () => { } // Retain failure until a flush observes it.
31
+ );
32
+ return operation;
33
+ };
34
+ return {
35
+ ...store,
36
+ get: (...args) => track(Promise.resolve(store.get(...args))),
37
+ getMany: (...args) => track(Promise.resolve(store.getMany(...args))),
38
+ set: (...args) => track(Promise.resolve(store.set(...args))),
39
+ setMany: (...args) => track(Promise.resolve(store.setMany(...args))),
40
+ delete: (...args) => track(Promise.resolve(store.delete(...args))),
41
+ deleteMany: (...args) => track(Promise.resolve(store.deleteMany(...args))),
42
+ commitPatch: (...args) => track(Promise.resolve(store.commitPatch(...args))),
43
+ storeReceivedTcToken: (...args) => track(Promise.resolve(store.storeReceivedTcToken(...args))),
44
+ touchTcTokenSenderTimestamp: (...args) => track(Promise.resolve(store.touchTcTokenSenderTimestamp(...args))),
45
+ async flush() {
46
+ const deadline = Date.now() + 30000;
47
+ const errors = new Map();
48
+ for (;;) {
49
+ const admitted = [...pending];
50
+ await settleBeforeFlushDeadline(admitted, deadline, 'legacy store flush', errors);
51
+ for (const operation of admitted)
52
+ pending.delete(operation);
53
+ await new Promise(resolve => setImmediate(resolve));
54
+ if (pending.size === 0) {
55
+ if (errors.size)
56
+ throw settledFlushError('legacy store flush failed', errors.values());
57
+ return;
58
+ }
59
+ if (Date.now() >= deadline)
60
+ throw flushDeadlineError('legacy store flush', errors);
61
+ }
62
+ }
63
+ };
64
+ }
22
65
  export async function wrapLegacyStore(state, saveCreds, logger) {
23
66
  if (!state.creds || !state.keys) {
24
67
  throw new TypeError('wrapLegacyStore requires legacy creds and keys');
@@ -78,7 +121,11 @@ export async function wrapLegacyStore(state, saveCreds, logger) {
78
121
  }
79
122
  const nativeValue = legacyValue == null ? null : codecs[store].fromLegacy(nativeKey, legacyValue);
80
123
  imported.set(nativeKey, nativeValue);
81
- mirrorUpdates[nativeKey] = nativeValue == null ? null : encodeNativeEnvelope(nativeValue, legacyValue);
124
+ // A negative lookup has nothing to persist when neither side exists.
125
+ // Retain deletion when a stale native mirror actually needs removing.
126
+ if (nativeValue != null || ownValue(nativeBucket, nativeKey) != null) {
127
+ mirrorUpdates[nativeKey] = nativeValue == null ? null : encodeNativeEnvelope(nativeValue, legacyValue);
128
+ }
82
129
  }
83
130
  if (Object.keys(mirrorUpdates).length > 0)
84
131
  await persist({ [route.nativeType]: mirrorUpdates });
@@ -104,7 +151,9 @@ export async function wrapLegacyStore(state, saveCreds, logger) {
104
151
  continue;
105
152
  }
106
153
  imported.set(rawKey, legacyValue);
107
- mirrorUpdates[rawKey] = legacyValue ? encodeNativeEnvelope(legacyValue, legacyValue) : null;
154
+ if (legacyValue != null || ownValue(nativeBucket, rawKey) != null) {
155
+ mirrorUpdates[rawKey] = legacyValue ? encodeNativeEnvelope(legacyValue, legacyValue) : null;
156
+ }
108
157
  }
109
158
  if (Object.keys(mirrorUpdates).length > 0)
110
159
  await persist({ [route.nativeType]: mirrorUpdates });
@@ -238,7 +287,62 @@ export async function wrapLegacyStore(state, saveCreds, logger) {
238
287
  throw new TypeError(`${store} has no projected codec`);
239
288
  return deleteProjected(store, requested);
240
289
  }
241
- return {
290
+ const atomic = async (stores, change) => {
291
+ if (!keys.bridgeTransaction)
292
+ throw new TypeError('legacy storage requires bridgeTransaction with backend-wide isolation and atomic durable commit');
293
+ await keys
294
+ .bridgeTransaction(async (transactionalKeys) => {
295
+ const adapter = await wrapLegacyStore({
296
+ ...state,
297
+ keys: {
298
+ get: (type, ids) => transactionalKeys.get(type, ids),
299
+ set: data => transactionalKeys.set(data)
300
+ }
301
+ }, saveCreds, logger);
302
+ const rows = new Map();
303
+ for (const { store, keys: requested } of stores) {
304
+ for (const [key, value] of await adapter.getMany(store, requested))
305
+ rows.set(rowKey(store, key), value);
306
+ }
307
+ const before = new Map(rows);
308
+ change(rows);
309
+ for (const key of before.keys())
310
+ if (!rows.has(key)) {
311
+ const [store, id] = JSON.parse(key);
312
+ await adapter.delete(store, id);
313
+ }
314
+ for (const [key, value] of rows)
315
+ if (before.get(key) !== value) {
316
+ const [store, id] = JSON.parse(key);
317
+ await adapter.set(store, id, value);
318
+ }
319
+ })
320
+ .catch(error => {
321
+ warn('atomic legacy transaction failed', error);
322
+ throw error;
323
+ });
324
+ };
325
+ const atomicMethods = (stores) => atomicCallbacks(change => atomic(stores, change));
326
+ const result = {
327
+ commitPatch(name, stateBytes, removed, added, maintainIndex) {
328
+ return atomicMethods([
329
+ { store: 'sync_version', keys: [name] },
330
+ { store: 'mutation_mac', keys: [...new Set([...removed, ...added.map(([key]) => key)])] },
331
+ { store: 'meta', keys: maintainIndex ? ['mutation_mac_keys'] : [] }
332
+ ]).commitPatch(name, stateBytes, removed, added, maintainIndex);
333
+ },
334
+ touchTcTokenSenderTimestamp(jid, timestamp) {
335
+ return atomicMethods([
336
+ { store: 'tc_token', keys: [jid] },
337
+ { store: 'meta', keys: ['tc_token_jids'] }
338
+ ]).touchTcTokenSenderTimestamp(jid, timestamp);
339
+ },
340
+ storeReceivedTcToken(jid, token, timestamp) {
341
+ return atomicMethods([
342
+ { store: 'tc_token', keys: [jid] },
343
+ { store: 'meta', keys: ['tc_token_jids'] }
344
+ ]).storeReceivedTcToken(jid, token, timestamp);
345
+ },
242
346
  async get(store, key) {
243
347
  try {
244
348
  return (await readMany(store, [key]))[0]?.[1] ?? null;
@@ -297,5 +401,35 @@ export async function wrapLegacyStore(state, saveCreds, logger) {
297
401
  async flush() { },
298
402
  dispose() { }
299
403
  };
404
+ if (!keys.bridgeTransaction)
405
+ return withPendingCallbacks(result);
406
+ const transaction = (work) => keys.bridgeTransaction(async (transactionalKeys) => work(await wrapLegacyStore({
407
+ ...state,
408
+ keys: {
409
+ get: (type, ids) => transactionalKeys.get(type, ids),
410
+ set: data => transactionalKeys.set(data)
411
+ }
412
+ }, saveCreds, logger)));
413
+ return withPendingCallbacks({
414
+ ...result,
415
+ get: (store, key) => transaction(adapter => adapter.get(store, key)),
416
+ getMany: (store, requested) => {
417
+ const snapshot = [...requested];
418
+ return transaction(adapter => adapter.getMany(store, snapshot));
419
+ },
420
+ set: (store, key, value) => {
421
+ const snapshot = Uint8Array.from(value);
422
+ return transaction(adapter => adapter.set(store, key, snapshot));
423
+ },
424
+ setMany: (store, entries) => {
425
+ const snapshot = entries.map(([key, value]) => [key, Uint8Array.from(value)]);
426
+ return transaction(adapter => adapter.setMany(store, snapshot));
427
+ },
428
+ delete: (store, key) => transaction(adapter => adapter.delete(store, key)),
429
+ deleteMany: (store, requested) => {
430
+ const snapshot = [...requested];
431
+ return transaction(adapter => adapter.deleteMany(store, snapshot));
432
+ }
433
+ });
300
434
  }
301
435
  //# sourceMappingURL=adapter.js.map
@@ -1,3 +1,4 @@
1
+ import { decodeTokenRow, encodeTokenRow, signedTimestamp } from '../../../Utils/atomic-store.js';
1
2
  // Basic value codecs for the Baileys legacy-store projection.
2
3
  import { Buffer } from 'node:buffer';
3
4
  import { proto } from '@oxidezap/whatsapp-rust-bridge/proto-types';
@@ -90,18 +91,14 @@ function tcTokenCodec() {
90
91
  return {
91
92
  fromLegacy(_key, value) {
92
93
  const token = value;
93
- return toJsonBytes({
94
+ return encodeTokenRow({
94
95
  token: bytesToNumbers(requireBytes(token.token, 'TC token')),
95
- token_timestamp: token.timestamp
96
- ? parseUnsignedDecimal(token.timestamp, 'TC token timestamp')
97
- : TimeValue.UNKNOWN_SECONDS,
98
- sender_timestamp: token.senderTimestamp
99
- ? parseUnsignedDecimal(token.senderTimestamp, 'TC token sender timestamp')
100
- : null
96
+ token_timestamp: signedTimestamp(token.timestamp ?? '0'),
97
+ sender_timestamp: token.senderTimestamp == null ? null : signedTimestamp(token.senderTimestamp)
101
98
  });
102
99
  },
103
100
  toLegacy(_key, value) {
104
- const native = fromJsonBytes(value);
101
+ const native = decodeTokenRow(value);
105
102
  // Added rather than set to `undefined`, matching upstream, which
106
103
  // only carries the field when it has a value. An undefined-valued
107
104
  // key survives in memory but not through a store, and the mirror
@@ -1,5 +1,16 @@
1
+ import type { StoreMigrationOptions } from '../../Utils/store-migration.js';
1
2
  import type { AuthenticationState } from '../../Types/index.js';
2
- export declare function useLegacyMultiFileAuthState(folder: string): Promise<{
3
+ /** Load an upstream JSON auth directory using durable backend-wide transactions.
4
+ * Existing key records require an explicit offline migration:
5
+ *
6
+ * await useLegacyMultiFileAuthState(folder, { migrate: true })
7
+ *
8
+ * Stop every old writer and back up the entire directory before opting in.
9
+ * The new snapshot becomes authoritative; retained JSON files are backups.
10
+ * To hand the directory back to upstream, stop all writers and first call
11
+ * prepareLegacyAuthRollback(folder, { offline: true }).
12
+ */
13
+ export declare function useLegacyMultiFileAuthState(folder: string, options?: StoreMigrationOptions): Promise<{
3
14
  state: AuthenticationState;
4
15
  saveCreds: () => Promise<void>;
5
16
  }>;
@@ -1,4 +1,5 @@
1
- import { mkdir, readFile, stat, unlink, writeFile } from 'node:fs/promises';
1
+ import { legacySnapshotKeys } from './snapshot.js';
2
+ import { mkdir, readFile, stat, writeFile } from 'node:fs/promises';
2
3
  import { join } from 'node:path';
3
4
  import { proto } from '@oxidezap/whatsapp-rust-bridge/proto-types';
4
5
  import { BufferJSON } from '../../Utils/generics.js';
@@ -14,7 +15,17 @@ function safeLegacyFileName(file) {
14
15
  }
15
16
  const keyFile = (type, id) => `${type}${LegacyMultiFile.TYPE_SEPARATOR}${id}${LegacyMultiFile.EXTENSION}`;
16
17
  const isMissingFile = (error) => error instanceof Error && 'code' in error && error.code === 'ENOENT';
17
- export async function useLegacyMultiFileAuthState(folder) {
18
+ /** Load an upstream JSON auth directory using durable backend-wide transactions.
19
+ * Existing key records require an explicit offline migration:
20
+ *
21
+ * await useLegacyMultiFileAuthState(folder, { migrate: true })
22
+ *
23
+ * Stop every old writer and back up the entire directory before opting in.
24
+ * The new snapshot becomes authoritative; retained JSON files are backups.
25
+ * To hand the directory back to upstream, stop all writers and first call
26
+ * prepareLegacyAuthRollback(folder, { offline: true }).
27
+ */
28
+ export async function useLegacyMultiFileAuthState(folder, options = {}) {
18
29
  const folderInfo = await stat(folder).catch(error => {
19
30
  if (isMissingFile(error))
20
31
  return null;
@@ -39,43 +50,44 @@ export async function useLegacyMultiFileAuthState(folder) {
39
50
  const writeData = async (data, file) => {
40
51
  await writeFile(join(folder, safeLegacyFileName(file)), JSON.stringify(data, BufferJSON.replacer));
41
52
  };
42
- const removeData = async (file) => {
43
- try {
44
- await unlink(join(folder, safeLegacyFileName(file)));
45
- }
46
- catch (error) {
47
- if (!isMissingFile(error))
48
- throw error;
49
- }
50
- };
51
53
  const creds = (await readData(LegacyMultiFile.CREDS_FILE));
52
54
  if (!creds) {
53
55
  throw new Error(`no ${LegacyMultiFile.CREDS_FILE} found in legacy auth directory: ${folder}`);
54
56
  }
57
+ const rawSnapshot = await legacySnapshotKeys(folder, (type, id) => safeLegacyFileName(keyFile(type, id)), options);
58
+ // The transaction view must use the same protobuf revival as ordinary
59
+ // reads. Persisted protobuf toJSON bytes are base64 strings, not Buffers.
60
+ const normalizeKeys = (backend) => ({
61
+ get: async (type, ids) => {
62
+ const values = await backend.get(type, ids);
63
+ if (type !== LegacyStore.SYNC_KEY)
64
+ return values;
65
+ return Object.fromEntries(Object.entries(values).map(([id, value]) => [
66
+ id,
67
+ value ? proto.Message.AppStateSyncKeyData.fromObject(value) : value
68
+ ]));
69
+ },
70
+ set: data => backend.set(data),
71
+ ...(backend.bridgeTransaction
72
+ ? {
73
+ bridgeTransaction: (work) => backend.bridgeTransaction(keys => work(normalizeKeys(keys)))
74
+ }
75
+ : {})
76
+ });
77
+ const snapshot = normalizeKeys(rawSnapshot);
55
78
  return {
56
79
  state: {
57
80
  creds,
58
81
  keys: {
59
82
  get: async (type, ids) => {
60
83
  const entries = await Promise.all(ids.map(async (id) => {
61
- let value = await readData(keyFile(type, id));
62
- if (type === LegacyStore.SYNC_KEY && value) {
63
- value = proto.Message.AppStateSyncKeyData.fromObject(value);
64
- }
84
+ const value = (await snapshot.get(type, [id]))[id];
65
85
  return [id, value];
66
86
  }));
67
87
  return Object.fromEntries(entries);
68
88
  },
69
- set: async (data) => {
70
- const writes = [];
71
- for (const [type, values] of Object.entries(data)) {
72
- for (const [id, value] of Object.entries(values ?? {})) {
73
- const file = keyFile(type, id);
74
- writes.push(value == null ? removeData(file) : writeData(value, file));
75
- }
76
- }
77
- await Promise.all(writes);
78
- }
89
+ set: async (data) => await snapshot.set(data),
90
+ bridgeTransaction: snapshot.bridgeTransaction
79
91
  }
80
92
  },
81
93
  saveCreds: () => writeData(creds, LegacyMultiFile.CREDS_FILE)
@@ -0,0 +1,3 @@
1
+ /** Only reserved auth-record filenames belong to the snapshot or its rollback. */
2
+ export declare const isLegacyAuthRecordFile: (name: string) => boolean;
3
+ //# sourceMappingURL=record-files.d.ts.map
@@ -0,0 +1,5 @@
1
+ import { LegacyStore, MirrorStore, RawStore } from './constants.js';
2
+ const prefixes = [...Object.values(LegacyStore), ...Object.values(MirrorStore), ...Object.values(RawStore)].map(type => `${type}-`);
3
+ /** Only reserved auth-record filenames belong to the snapshot or its rollback. */
4
+ export const isLegacyAuthRecordFile = (name) => !/[\\/\0]/.test(name) && name.endsWith('.json') && prefixes.some(prefix => name.startsWith(prefix));
5
+ //# sourceMappingURL=record-files.js.map
@@ -0,0 +1,8 @@
1
+ /** Offline rollback only. Stop every writer first. A rejection means upstream
2
+ * must not open this directory yet. The snapshot remains authoritative until
3
+ * every legacy record/deletion is durable, then is archived for recovery.
4
+ */
5
+ export declare function prepareLegacyAuthRollback(folder: string, options: {
6
+ offline: true;
7
+ }): Promise<void>;
8
+ //# sourceMappingURL=rollback.d.ts.map
@@ -0,0 +1,16 @@
1
+ import { exportAuthSnapshot } from '../../Utils/snapshot-rollback.js';
2
+ import { isLegacyAuthRecordFile } from './record-files.js';
3
+ /** Offline rollback only. Stop every writer first. A rejection means upstream
4
+ * must not open this directory yet. The snapshot remains authoritative until
5
+ * every legacy record/deletion is durable, then is archived for recovery.
6
+ */
7
+ export async function prepareLegacyAuthRollback(folder, options) {
8
+ if (options?.offline !== true)
9
+ throw new TypeError('legacy rollback requires { offline: true } after stopping every auth writer');
10
+ await exportAuthSnapshot(folder, 'bridge-legacy-v1.json', new Set(['legacy']), (_namespace, name) => {
11
+ if (/[\\/\0]/.test(name))
12
+ throw new Error('invalid legacy rollback filename');
13
+ return isLegacyAuthRecordFile(name) ? name : undefined;
14
+ }, isLegacyAuthRecordFile);
15
+ }
16
+ //# sourceMappingURL=rollback.js.map
@@ -0,0 +1,7 @@
1
+ import { type StoreMigrationOptions } from '../../Utils/store-migration.js';
2
+ import type { LegacyKeysStore } from './types.js';
3
+ /** All legacy and native-mirror writes share the same persistent snapshot.
4
+ * The original JSON files are migration backups after the first commit.
5
+ */
6
+ export declare const legacySnapshotKeys: (folder: string, fileName: (type: string, id: string) => string, options?: StoreMigrationOptions) => Promise<LegacyKeysStore>;
7
+ //# sourceMappingURL=snapshot.d.ts.map