@oxidezap/baileyrs 0.3.7 → 0.3.8

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 (129) hide show
  1. package/README.md +48 -8
  2. package/lib/Bridge/history-sync-wire.d.ts +2 -2
  3. package/lib/Bridge/history-sync-wire.js +4 -4
  4. package/lib/Bridge/schema.js +7 -1
  5. package/lib/Bridge/types.d.ts +7 -1
  6. package/lib/Compatibility/auth-state.d.ts +30 -0
  7. package/lib/Compatibility/auth-state.js +96 -0
  8. package/lib/Compatibility/encode-proto-core.d.ts +31 -0
  9. package/lib/Compatibility/encode-proto-core.js +51 -0
  10. package/lib/Compatibility/encode-proto.d.ts +0 -29
  11. package/lib/Compatibility/encode-proto.js +3 -50
  12. package/lib/Compatibility/host-auth-state.d.ts +6 -0
  13. package/lib/Compatibility/host-auth-state.js +162 -0
  14. package/lib/Compatibility/internal/auth-state.d.ts +3 -7
  15. package/lib/Compatibility/internal/auth-state.js +34 -1
  16. package/lib/Compatibility/internal/host-auth-state.d.ts +4 -0
  17. package/lib/Compatibility/internal/host-auth-state.js +14 -0
  18. package/lib/Compatibility/legacy-store/device.js +5 -5
  19. package/lib/Compatibility/message-ids.d.ts +17 -0
  20. package/lib/Compatibility/message-ids.js +47 -0
  21. package/lib/Compatibility/message-relay.d.ts +2 -2
  22. package/lib/Compatibility/message-relay.js +4 -4
  23. package/lib/Compatibility/proto-runtime.js +33 -11
  24. package/lib/Compatibility/socket-results.d.ts +1 -1
  25. package/lib/Compatibility/tagged-message-waiter.d.ts +5 -2
  26. package/lib/Compatibility/tagged-message-waiter.js +5 -5
  27. package/lib/Compatibility/usync/adapter.d.ts +1 -1
  28. package/lib/Compatibility/websocket-client.d.ts +11 -3
  29. package/lib/Compatibility/websocket-client.js +84 -11
  30. package/lib/Defaults/index.d.ts +8 -8
  31. package/lib/Defaults/index.js +8 -8
  32. package/lib/Media/content.d.ts +28 -0
  33. package/lib/Media/content.js +129 -0
  34. package/lib/Media/core.d.ts +34 -0
  35. package/lib/Media/core.js +120 -0
  36. package/lib/Media/mutations.d.ts +24 -0
  37. package/lib/Media/mutations.js +38 -0
  38. package/lib/Runtime/aes-gcm.d.ts +4 -0
  39. package/lib/Runtime/aes-gcm.js +11 -0
  40. package/lib/Runtime/bridge.d.ts +44 -0
  41. package/lib/Runtime/bridge.js +76 -0
  42. package/lib/Runtime/buffer.d.ts +9 -0
  43. package/lib/Runtime/buffer.js +22 -0
  44. package/lib/Runtime/bytes.d.ts +61 -0
  45. package/lib/Runtime/bytes.js +270 -0
  46. package/lib/Runtime/host.d.ts +22 -0
  47. package/lib/Runtime/host.js +43 -0
  48. package/lib/Runtime/long.d.ts +33 -0
  49. package/lib/Runtime/long.js +64 -0
  50. package/lib/Runtime/node-media-processors.d.ts +4 -0
  51. package/lib/Runtime/node-media-processors.js +29 -0
  52. package/lib/Runtime/node-media.d.ts +28 -0
  53. package/lib/Runtime/node-media.js +115 -0
  54. package/lib/Runtime/node.d.ts +14 -0
  55. package/lib/Runtime/node.js +81 -0
  56. package/lib/Runtime/paths.d.ts +4 -0
  57. package/lib/Runtime/paths.js +7 -0
  58. package/lib/Runtime/stream.d.ts +11 -0
  59. package/lib/Runtime/stream.js +25 -0
  60. package/lib/Runtime/types.d.ts +98 -0
  61. package/lib/Runtime/types.js +13 -0
  62. package/lib/Socket/core.d.ts +312 -0
  63. package/lib/Socket/core.js +1122 -0
  64. package/lib/Socket/events-core.d.ts +75 -0
  65. package/lib/Socket/events-core.js +1058 -0
  66. package/lib/Socket/events.d.ts +1 -63
  67. package/lib/Socket/events.js +4 -1047
  68. package/lib/Socket/groups.js +4 -3
  69. package/lib/Socket/index.d.ts +521 -103
  70. package/lib/Socket/index.js +10 -1007
  71. package/lib/Socket/messages-core.d.ts +41 -0
  72. package/lib/Socket/messages-core.js +270 -0
  73. package/lib/Socket/messages.d.ts +9 -36
  74. package/lib/Socket/messages.js +3 -260
  75. package/lib/Socket/newsletter.js +3 -3
  76. package/lib/Socket/profile.js +1 -1
  77. package/lib/Socket/terminal-close-reporter.d.ts +2 -0
  78. package/lib/Socket/terminal-close-reporter.js +3 -3
  79. package/lib/Socket/transport.d.ts +2 -0
  80. package/lib/Socket/transport.js +16 -1
  81. package/lib/Socket/types.d.ts +2 -0
  82. package/lib/Types/Auth.d.ts +11 -0
  83. package/lib/Types/Message.d.ts +1 -1
  84. package/lib/Types/Socket.d.ts +2 -2
  85. package/lib/Types/index.d.ts +6 -1
  86. package/lib/Utils/browser-utils.d.ts +4 -0
  87. package/lib/Utils/browser-utils.js +53 -2
  88. package/lib/Utils/crypto.d.ts +1 -0
  89. package/lib/Utils/crypto.js +1 -0
  90. package/lib/Utils/event-buffer.d.ts +6 -1
  91. package/lib/Utils/event-buffer.js +28 -27
  92. package/lib/Utils/link-preview.d.ts +4 -3
  93. package/lib/Utils/logger.d.ts +3 -0
  94. package/lib/Utils/logger.js +35 -6
  95. package/lib/Utils/messages-core.d.ts +174 -0
  96. package/lib/Utils/messages-core.js +1042 -0
  97. package/lib/Utils/messages-media-core.d.ts +73 -0
  98. package/lib/Utils/messages-media-core.js +319 -0
  99. package/lib/Utils/messages-media.d.ts +1 -72
  100. package/lib/Utils/messages-media.js +9 -358
  101. package/lib/Utils/messages.d.ts +1 -166
  102. package/lib/Utils/messages.js +7 -1040
  103. package/lib/Utils/optional-peer.js +14 -5
  104. package/lib/Utils/process-history-message-core.d.ts +36 -0
  105. package/lib/Utils/process-history-message-core.js +187 -0
  106. package/lib/Utils/process-history-message.d.ts +5 -43
  107. package/lib/Utils/process-history-message.js +11 -197
  108. package/lib/Utils/process-message-core.d.ts +29 -0
  109. package/lib/Utils/process-message-core.js +112 -0
  110. package/lib/Utils/process-message.d.ts +4 -24
  111. package/lib/Utils/process-message.js +6 -111
  112. package/lib/WABinary/generic-utils.js +7 -5
  113. package/lib/host-shared.d.ts +74 -0
  114. package/lib/host-shared.js +15 -0
  115. package/lib/host-socket-operations.d.ts +3 -0
  116. package/lib/host-socket-operations.js +2 -0
  117. package/lib/host-surface.d.ts +21 -0
  118. package/lib/host-surface.js +35 -0
  119. package/lib/host-types.d.ts +356 -0
  120. package/lib/host-types.js +2 -0
  121. package/lib/host.d.ts +33 -0
  122. package/lib/host.js +31 -0
  123. package/lib/node-surface.d.ts +9 -0
  124. package/lib/node-surface.js +15 -0
  125. package/lib/surface.d.ts +5 -0
  126. package/lib/surface.js +6 -0
  127. package/lib/wasm.d.ts +27 -0
  128. package/lib/wasm.js +27 -0
  129. package/package.json +18 -6
package/README.md CHANGED
@@ -28,13 +28,18 @@ so existing integrations can migrate with minimal changes. See
28
28
  | Key management | JS auth state | Rust `PersistenceManager` |
29
29
  | Auto-reconnect | Manual `startSock()` loop | Transient drops retried in Rust (fibonacci backoff); terminal ones still yours |
30
30
 
31
- Compatibility is checked rather than assumed: a declaration audit against
32
- upstream's `.d.ts`, a wire-fidelity audit of the send path, ~50 behavioural
33
- compatibility suites, and a
34
- [differential fuzz suite](src/__fuzz__/README.md) that generates its own inputs
35
- from the proto schema and compares the two libraries directly. Differences the
36
- fuzzers find are recorded with a reason and a review date, and known open ones
37
- are listed in `src/__fuzz__/harness/divergence.ts`.
31
+ Compatibility is checked rather than assumed: CI compiles and runs consumer code
32
+ against the locally packed npm tarball under the upstream package name, exercises
33
+ published deep imports and verifies host initialization in workerd with
34
+ `nodejs_compat` disabled. It also runs the proto-runtime, wire-fidelity and
35
+ lifecycle contract audits. The strict declaration audit is available as
36
+ `npm run compat:audit:strict`; it currently reports known declaration gaps and
37
+ is not a green gate yet. Layer ownership is checked by `npm run compat:layers`
38
+ when sibling core and bridge checkouts are available.
39
+ Behavioural suites and a [differential fuzz suite](src/__fuzz__/README.md)
40
+ generate inputs from the proto schema and compare the two libraries directly.
41
+ Differences the fuzzers find are recorded with a reason and a review date, and
42
+ known open ones are listed in `src/__fuzz__/harness/divergence.ts`.
38
43
 
39
44
  ### Protobuf field names
40
45
 
@@ -64,7 +69,7 @@ error handling, memory monitoring, and more.
64
69
 
65
70
  ## Installation
66
71
 
67
- Requires Node.js 22 or newer.
72
+ Requires Node.js 22.3 or newer for the Node API. A runtime-neutral `/host` entrypoint is available for Workers, Deno, and browser-like hosts.
68
73
 
69
74
  ### New project
70
75
 
@@ -76,6 +81,41 @@ npm install @oxidezap/baileyrs
76
81
  import makeWASocket from '@oxidezap/baileyrs'
77
82
  ```
78
83
 
84
+ ### Host-neutral entrypoint
85
+
86
+ For Workers, Deno, or browser-like runtimes, import `/host` and initialize the bridge
87
+ WASM before creating a socket. Provide a caller-owned `JsStoreCallbacks` auth store;
88
+ this path does not use filesystem auth or Node streams.
89
+
90
+ ```ts
91
+ import makeWASocket, { createAuthenticationState, useMemoryStore } from '@oxidezap/baileyrs/host'
92
+ import wasm from '@oxidezap/baileyrs/wasm'
93
+ import { initSync } from '@oxidezap/whatsapp-rust-bridge/host'
94
+
95
+ initSync({ module: wasm })
96
+ const store = useMemoryStore()
97
+ const auth = await createAuthenticationState(store)
98
+ const socket = makeWASocket({ auth })
99
+ ```
100
+
101
+ The socket initializes the bridge crypto engine during startup. If you call the
102
+ standalone AES-backed media retry helpers without creating a socket, initialize
103
+ the bridge engine yourself first (`initWasmEngine()`; after `initSync()` on
104
+ hosts).
105
+
106
+ For a custom host runtime, bind media helpers to its bridge and random source once:
107
+ `makeMediaCryptoRuntime(runtime)` returns a capability you can pass as the final
108
+ argument to `/host`'s `getMediaKeys`, `encryptMediaRetryRequest`, and
109
+ `decryptMediaRetryData` helpers. This keeps HKDF and AES-GCM on the selected
110
+ bridge instead of the default host singleton.
111
+
112
+ Reuse the same byte-preserving store on restart: `await createAuthenticationState(store)`
113
+ rehydrates the device written by the Rust engine, including its registration ID
114
+ (which may exceed the 14-bit ID used to seed fresh Baileys-style credentials).
115
+ Do not reset or truncate an existing device record to work around a failed read.
116
+ Node consumers should continue using the root entrypoint and
117
+ `useMultiFileAuthState` unchanged.
118
+
79
119
  ### Drop-in replacement for upstream Baileys
80
120
 
81
121
  baileyrs is API-compatible with [@whiskeysockets/baileys](https://github.com/WhiskeySockets/Baileys).
@@ -1,4 +1,4 @@
1
- import { type HistorySyncWireBatch, type WhatsAppEvent } from '@oxidezap/whatsapp-rust-bridge';
1
+ import { BinaryReader as DefaultBinaryReader, type HistorySyncWireBatch, type WhatsAppEvent } from '@oxidezap/whatsapp-rust-bridge/host';
2
2
  import type { ILogger } from '../Utils/logger.js';
3
3
  declare const HISTORY_SYNC_EVENT_TYPE: 'history_sync';
4
4
  export interface DecodedHistorySyncWireBatch {
@@ -12,6 +12,6 @@ export interface DecodedHistorySyncWireBatch {
12
12
  * consumed by baileyrs. The bridge owns only bounded inflate/framing; all
13
13
  * Baileys-specific normalization remains on this side of the boundary.
14
14
  */
15
- export declare const decodeHistorySyncWireBatch: (batch: HistorySyncWireBatch, logger: ILogger) => DecodedHistorySyncWireBatch;
15
+ export declare const decodeHistorySyncWireBatch: (batch: HistorySyncWireBatch, logger: ILogger, Reader?: typeof DefaultBinaryReader) => DecodedHistorySyncWireBatch;
16
16
  export {};
17
17
  //# sourceMappingURL=history-sync-wire.d.ts.map
@@ -1,6 +1,6 @@
1
- import { BinaryReader } from '@oxidezap/whatsapp-rust-bridge';
1
+ import { BinaryReader as DefaultBinaryReader } from '@oxidezap/whatsapp-rust-bridge/host';
2
2
  import { proto as WAProto } from '@oxidezap/whatsapp-rust-bridge/proto-types';
3
- import { isConversationHistorySync } from '../Utils/process-history-message.js';
3
+ import { isConversationHistorySync } from '../Utils/process-history-message-core.js';
4
4
  import { createSparseArray } from '../Utils/sparse-array.js';
5
5
  const HISTORY_SYNC_EVENT_TYPE = 'history_sync';
6
6
  /**
@@ -8,7 +8,7 @@ const HISTORY_SYNC_EVENT_TYPE = 'history_sync';
8
8
  * consumed by baileyrs. The bridge owns only bounded inflate/framing; all
9
9
  * Baileys-specific normalization remains on this side of the boundary.
10
10
  */
11
- export const decodeHistorySyncWireBatch = (batch, logger) => {
11
+ export const decodeHistorySyncWireBatch = (batch, logger, Reader = DefaultBinaryReader) => {
12
12
  const wireData = batch.conversationData;
13
13
  const wireOffsets = batch.conversationOffsets;
14
14
  const shouldDecodeConversations = isConversationHistorySync(batch.syncType);
@@ -19,7 +19,7 @@ export const decodeHistorySyncWireBatch = (batch, logger) => {
19
19
  let decodedConversations = 0;
20
20
  let skippedConversations = 0;
21
21
  if (shouldDecodeConversations) {
22
- const reader = new BinaryReader(wireData);
22
+ const reader = new Reader(wireData);
23
23
  for (let index = 0; index < conversationCount; index++) {
24
24
  try {
25
25
  const start = wireOffsets[index];
@@ -22,7 +22,7 @@
22
22
  * `asNumber`, `asString`) at those leak points only — not boilerplate
23
23
  * everywhere.
24
24
  */
25
- import { processHistoryMessage } from '../Utils/process-history-message.js';
25
+ import { processHistoryMessage } from '../Utils/process-history-message-core.js';
26
26
  import { isJidGroup } from '../WABinary/jid-utils.js';
27
27
  import { absoluteFromDuration, asBool, asBoolOr, asStringArray, asDurationSeconds, asInt64, asJidAddressString, asJidString, asNumber, asString, asUnixSeconds, isObject, normalizeDiscriminator } from './primitives.js';
28
28
  /**
@@ -287,6 +287,12 @@ const ADAPTERS = {
287
287
  return null;
288
288
  return { type: 'markChatAsReadUpdate', jid, read: asBoolOr(extractAction(data)?.read, true) };
289
289
  },
290
+ lock_chat_update: data => {
291
+ const jid = asJidString(data?.jid);
292
+ if (!jid)
293
+ return null;
294
+ return { type: 'lockChatUpdate', jid, locked: asBoolOr(extractAction(data)?.locked, true) };
295
+ },
290
296
  label_edit_update: data => {
291
297
  const labelId = asString(data?.label_id);
292
298
  if (!labelId)
@@ -413,6 +413,12 @@ export interface CanonicalPinUpdate {
413
413
  /** `false` when the user unpinned. Drives `chats.update.pinned: undefined`. */
414
414
  pinned: boolean;
415
415
  }
416
+ /** Mirrors upstream `chats.lock`: the hidden locked-chats folder membership of one chat. */
417
+ export interface CanonicalLockChatUpdate {
418
+ type: 'lockChatUpdate';
419
+ jid: string;
420
+ locked: boolean;
421
+ }
416
422
  export interface CanonicalMuteUpdate {
417
423
  type: 'muteUpdate';
418
424
  jid: string;
@@ -726,5 +732,5 @@ export interface CanonicalServerAck {
726
732
  timestamp?: number;
727
733
  error?: string;
728
734
  }
729
- 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 | CanonicalLabelEdit | CanonicalLabelAssociation | CanonicalAppStateSyncFailed | CanonicalQrCodesExhausted | CanonicalSettingUpdate | CanonicalIncomingCall | CanonicalUndecryptableMessage | CanonicalLidMappingUpdate | CanonicalNewsletterLiveUpdate | CanonicalChatDelete | CanonicalChatClear | CanonicalMessageDelete | CanonicalDisappearingModeChanged | CanonicalHistorySync | CanonicalOfflineSyncCompleted | CanonicalDirtyState | CanonicalRawNode | CanonicalNotification | CanonicalMexNotification | CanonicalServerAck | CanonicalNoop;
735
+ 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 | CanonicalIncomingCall | CanonicalUndecryptableMessage | CanonicalLidMappingUpdate | CanonicalNewsletterLiveUpdate | CanonicalChatDelete | CanonicalChatClear | CanonicalMessageDelete | CanonicalDisappearingModeChanged | CanonicalHistorySync | CanonicalOfflineSyncCompleted | CanonicalDirtyState | CanonicalRawNode | CanonicalNotification | CanonicalMexNotification | CanonicalServerAck | CanonicalNoop;
730
736
  //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1,30 @@
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
+ */
12
+ import type { JsStoreCallbacks } from '@oxidezap/whatsapp-rust-bridge/host';
13
+ import type { AuthenticationCreds, AuthenticationState } from '../Types/index.js';
14
+ /**
15
+ * Seed a fresh `auth.creds` mirror with valid key material.
16
+ *
17
+ * Stays a mirror: effective crypto state lives in the engine. Values match
18
+ * `Utils/generics.ts:initAuthCreds` field for field (registration id is 14
19
+ * bits, `advSecretKey` is 32 random bytes as base64) without touching
20
+ * `node:crypto` or `Buffer`.
21
+ */
22
+ export declare const initHostAuthCreds: () => AuthenticationCreds;
23
+ /**
24
+ * Build `{ creds, keys, store }` from a caller-owned byte store — the only
25
+ * auth shape the host entrypoint accepts. Pass the result straight to
26
+ * `makeWASocket({ auth })`: no filesystem, no legacy `{ creds, keys }`
27
+ * wrap, no `Buffer`.
28
+ */
29
+ export declare const createAuthenticationState: (store: JsStoreCallbacks, keys?: AuthenticationState['keys']) => Promise<AuthenticationState>;
30
+ //# sourceMappingURL=auth-state.d.ts.map
@@ -0,0 +1,96 @@
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
+ */
12
+ import { calculateSignature, generateKeyPair } from '@oxidezap/whatsapp-rust-bridge/host';
13
+ import { concatBytes } from '../Runtime/bytes.js';
14
+ import { createDeviceProjection } from './legacy-store/device.js';
15
+ import { base64Encode, randomBytes, readU16BE } from '../Runtime/bytes.js';
16
+ const DEVICE_STORE = 'device';
17
+ const DEVICE_RECORDS = ['device', 'account'];
18
+ const newKeyPair = () => {
19
+ const pair = generateKeyPair();
20
+ return {
21
+ private: new Uint8Array(pair.privKey),
22
+ public: new Uint8Array(pair.pubKey.subarray(1))
23
+ };
24
+ };
25
+ /** Signal version-byte prefix, matching `Defaults.KEY_BUNDLE_TYPE` without importing Node's Buffer. */
26
+ const KEY_BUNDLE_PREFIX = new Uint8Array([5]);
27
+ const generateSignalPubKey = (pubKey) => pubKey.length === 33 ? pubKey : concatBytes([KEY_BUNDLE_PREFIX, pubKey]);
28
+ const newSignedKeyPair = (identityKeyPair, keyId) => {
29
+ const keyPair = newKeyPair();
30
+ return {
31
+ keyPair,
32
+ signature: new Uint8Array(calculateSignature(identityKeyPair.private, generateSignalPubKey(keyPair.public))),
33
+ keyId
34
+ };
35
+ };
36
+ /**
37
+ * Seed a fresh `auth.creds` mirror with valid key material.
38
+ *
39
+ * Stays a mirror: effective crypto state lives in the engine. Values match
40
+ * `Utils/generics.ts:initAuthCreds` field for field (registration id is 14
41
+ * bits, `advSecretKey` is 32 random bytes as base64) without touching
42
+ * `node:crypto` or `Buffer`.
43
+ */
44
+ export const initHostAuthCreds = () => {
45
+ const signedIdentityKey = newKeyPair();
46
+ const registration = readU16BE(randomBytes(2)) & 0x3fff;
47
+ return {
48
+ noiseKey: newKeyPair(),
49
+ pairingEphemeralKeyPair: newKeyPair(),
50
+ signedIdentityKey,
51
+ signedPreKey: newSignedKeyPair(signedIdentityKey, 1),
52
+ registrationId: registration,
53
+ advSecretKey: base64Encode(randomBytes(32)),
54
+ processedHistoryMessages: [],
55
+ nextPreKeyId: 1,
56
+ firstUnuploadedPreKeyId: 1,
57
+ accountSyncCounter: 0,
58
+ accountSettings: { unarchiveChats: false },
59
+ registered: false,
60
+ pairingCode: undefined,
61
+ lastPropHash: undefined,
62
+ routingInfo: undefined,
63
+ additionalData: undefined
64
+ };
65
+ };
66
+ const hydrateFromStore = async (store, creds) => {
67
+ const projection = createDeviceProjection(creds);
68
+ for (const record of DEVICE_RECORDS) {
69
+ const payload = await store.get(DEVICE_STORE, record);
70
+ if (!payload)
71
+ continue;
72
+ try {
73
+ projection.prepare(record, payload)();
74
+ }
75
+ catch (error) {
76
+ throw new Error(`failed to hydrate persisted auth record '${record}'`, { cause: error });
77
+ }
78
+ }
79
+ };
80
+ /**
81
+ * Build `{ creds, keys, store }` from a caller-owned byte store — the only
82
+ * auth shape the host entrypoint accepts. Pass the result straight to
83
+ * `makeWASocket({ auth })`: no filesystem, no legacy `{ creds, keys }`
84
+ * wrap, no `Buffer`.
85
+ */
86
+ export const createAuthenticationState = async (store, keys) => {
87
+ const creds = initHostAuthCreds();
88
+ await hydrateFromStore(store, creds);
89
+ const { projectNativeStore } = await import('./legacy-store/native-projection.js');
90
+ return {
91
+ creds,
92
+ keys: keys ?? projectNativeStore(store, creds),
93
+ store: store
94
+ };
95
+ };
96
+ //# sourceMappingURL=auth-state.js.map
@@ -0,0 +1,31 @@
1
+ /**
2
+ * `encodeProto`, with the three inputs the bridge codec refuses put back.
3
+ *
4
+ * From 0.8.0 the codec refuses an empty string where the schema declares a
5
+ * 64-bit integer, and an unpaired surrogate in a text field. Both were written
6
+ * before — as `0` and as U+FFFD — and upstream Baileys still encodes both, so a
7
+ * message that used to reach the server would now throw in the caller's face.
8
+ * The codec also refuses enum names where the schema declares an enum
9
+ * (issue #109: `"NONE"` where an int32 goes on the wire), which upstream's
10
+ * `fromObject` resolves and its direct `encode` coerces — that repair lives in
11
+ * `repairProtoMessage`, next to the other two. This is where all three are
12
+ * absorbed, so the strict contract stays true of the bridge and the tolerant
13
+ * one stays true of this library.
14
+ *
15
+ * The three do not all follow the same reference, and the difference is worth
16
+ * stating. The surrogate becomes a single U+FFFD — what any UTF-8 encoder
17
+ * produces, and what the client sends — while upstream protobufjs writes three
18
+ * WTF-8 bytes instead, which is the artifact `replaceLoneSurrogates` in the fuzz
19
+ * registry folds away when it compares. The empty string becoming `0` is the other
20
+ * direction: the client never writes it and the bridge refuses it on purpose, so
21
+ * that one substitution is Baileys compatibility rather than client compliance.
22
+ * It stays because a message that used to reach the server should not start
23
+ * throwing, and it is written down here so it is a decision rather than an accident.
24
+ *
25
+ * Repair on failure rather than check on write: the ordinary encode is exactly
26
+ * the call it was before, with no scan of any field, and the repair runs only
27
+ * for a message that was already going to throw. `encodeProto` returns finished
28
+ * bytes rather than a lazy writer, so one try/catch covers it.
29
+ */
30
+ export declare const encodeProtoCompat: (path: string, message: unknown, encode: (path: string, message: unknown) => Uint8Array) => Uint8Array;
31
+ //# sourceMappingURL=encode-proto-core.d.ts.map
@@ -0,0 +1,51 @@
1
+ import { projectProtoMessage, repairProtoMessage } from './proto-runtime.js';
2
+ /**
3
+ * `encodeProto`, with the three inputs the bridge codec refuses put back.
4
+ *
5
+ * From 0.8.0 the codec refuses an empty string where the schema declares a
6
+ * 64-bit integer, and an unpaired surrogate in a text field. Both were written
7
+ * before — as `0` and as U+FFFD — and upstream Baileys still encodes both, so a
8
+ * message that used to reach the server would now throw in the caller's face.
9
+ * The codec also refuses enum names where the schema declares an enum
10
+ * (issue #109: `"NONE"` where an int32 goes on the wire), which upstream's
11
+ * `fromObject` resolves and its direct `encode` coerces — that repair lives in
12
+ * `repairProtoMessage`, next to the other two. This is where all three are
13
+ * absorbed, so the strict contract stays true of the bridge and the tolerant
14
+ * one stays true of this library.
15
+ *
16
+ * The three do not all follow the same reference, and the difference is worth
17
+ * stating. The surrogate becomes a single U+FFFD — what any UTF-8 encoder
18
+ * produces, and what the client sends — while upstream protobufjs writes three
19
+ * WTF-8 bytes instead, which is the artifact `replaceLoneSurrogates` in the fuzz
20
+ * registry folds away when it compares. The empty string becoming `0` is the other
21
+ * direction: the client never writes it and the bridge refuses it on purpose, so
22
+ * that one substitution is Baileys compatibility rather than client compliance.
23
+ * It stays because a message that used to reach the server should not start
24
+ * throwing, and it is written down here so it is a decision rather than an accident.
25
+ *
26
+ * Repair on failure rather than check on write: the ordinary encode is exactly
27
+ * the call it was before, with no scan of any field, and the repair runs only
28
+ * for a message that was already going to throw. `encodeProto` returns finished
29
+ * bytes rather than a lazy writer, so one try/catch covers it.
30
+ */
31
+ export const encodeProtoCompat = (path, message, encode) => {
32
+ // The codec drops a key it does not know without throwing, so a public spelling has
33
+ // to be translated before the encode: a repair after a throw never runs. Same
34
+ // reference when nothing is aliased.
35
+ const projected = projectProtoMessage(path, message);
36
+ try {
37
+ return encode(path, projected);
38
+ }
39
+ catch (error) {
40
+ // Repaired from the caller's message: this repair walks the schema this library
41
+ // publishes, so the projected names would not be found and the failure would
42
+ // propagate instead of being absorbed.
43
+ const repaired = repairProtoMessage(path, message);
44
+ // Reference equality: nothing was coerced, so the failure is something this
45
+ // does not explain and it has to keep propagating rather than be retried.
46
+ if (repaired === message)
47
+ throw error;
48
+ return encode(path, projectProtoMessage(path, repaired));
49
+ }
50
+ };
51
+ //# sourceMappingURL=encode-proto-core.js.map
@@ -1,31 +1,2 @@
1
- /**
2
- * `encodeProto`, with the three inputs the bridge codec refuses put back.
3
- *
4
- * From 0.8.0 the codec refuses an empty string where the schema declares a
5
- * 64-bit integer, and an unpaired surrogate in a text field. Both were written
6
- * before — as `0` and as U+FFFD — and upstream Baileys still encodes both, so a
7
- * message that used to reach the server would now throw in the caller's face.
8
- * The codec also refuses enum names where the schema declares an enum
9
- * (issue #109: `"NONE"` where an int32 goes on the wire), which upstream's
10
- * `fromObject` resolves and its direct `encode` coerces — that repair lives in
11
- * `repairProtoMessage`, next to the other two. This is where all three are
12
- * absorbed, so the strict contract stays true of the bridge and the tolerant
13
- * one stays true of this library.
14
- *
15
- * The three do not all follow the same reference, and the difference is worth
16
- * stating. The surrogate becomes a single U+FFFD — what any UTF-8 encoder
17
- * produces, and what the client sends — while upstream protobufjs writes three
18
- * WTF-8 bytes instead, which is the artifact `replaceLoneSurrogates` in the fuzz
19
- * registry folds away when it compares. The empty string becoming `0` is the other
20
- * direction: the client never writes it and the bridge refuses it on purpose, so
21
- * that one substitution is Baileys compatibility rather than client compliance.
22
- * It stays because a message that used to reach the server should not start
23
- * throwing, and it is written down here so it is a decision rather than an accident.
24
- *
25
- * Repair on failure rather than check on write: the ordinary encode is exactly
26
- * the call it was before, with no scan of any field, and the repair runs only
27
- * for a message that was already going to throw. `encodeProto` returns finished
28
- * bytes rather than a lazy writer, so one try/catch covers it.
29
- */
30
1
  export declare const encodeProtoCompat: (path: string, message: unknown) => Uint8Array;
31
2
  //# sourceMappingURL=encode-proto.d.ts.map
@@ -1,52 +1,5 @@
1
+ /** Node-facing deep-import wrapper; preserves bridge auto-initialization. */
1
2
  import { encodeProto } from '@oxidezap/whatsapp-rust-bridge';
2
- import { projectProtoMessage, repairProtoMessage } from './proto-runtime.js';
3
- /**
4
- * `encodeProto`, with the three inputs the bridge codec refuses put back.
5
- *
6
- * From 0.8.0 the codec refuses an empty string where the schema declares a
7
- * 64-bit integer, and an unpaired surrogate in a text field. Both were written
8
- * before — as `0` and as U+FFFD — and upstream Baileys still encodes both, so a
9
- * message that used to reach the server would now throw in the caller's face.
10
- * The codec also refuses enum names where the schema declares an enum
11
- * (issue #109: `"NONE"` where an int32 goes on the wire), which upstream's
12
- * `fromObject` resolves and its direct `encode` coerces — that repair lives in
13
- * `repairProtoMessage`, next to the other two. This is where all three are
14
- * absorbed, so the strict contract stays true of the bridge and the tolerant
15
- * one stays true of this library.
16
- *
17
- * The three do not all follow the same reference, and the difference is worth
18
- * stating. The surrogate becomes a single U+FFFD — what any UTF-8 encoder
19
- * produces, and what the client sends — while upstream protobufjs writes three
20
- * WTF-8 bytes instead, which is the artifact `replaceLoneSurrogates` in the fuzz
21
- * registry folds away when it compares. The empty string becoming `0` is the other
22
- * direction: the client never writes it and the bridge refuses it on purpose, so
23
- * that one substitution is Baileys compatibility rather than client compliance.
24
- * It stays because a message that used to reach the server should not start
25
- * throwing, and it is written down here so it is a decision rather than an accident.
26
- *
27
- * Repair on failure rather than check on write: the ordinary encode is exactly
28
- * the call it was before, with no scan of any field, and the repair runs only
29
- * for a message that was already going to throw. `encodeProto` returns finished
30
- * bytes rather than a lazy writer, so one try/catch covers it.
31
- */
32
- export const encodeProtoCompat = (path, message) => {
33
- // The codec drops a key it does not know without throwing, so a public spelling has
34
- // to be translated before the encode: a repair after a throw never runs. Same
35
- // reference when nothing is aliased.
36
- const projected = projectProtoMessage(path, message);
37
- try {
38
- return encodeProto(path, projected);
39
- }
40
- catch (error) {
41
- // Repaired from the caller's message: this repair walks the schema this library
42
- // publishes, so the projected names would not be found and the failure would
43
- // propagate instead of being absorbed.
44
- const repaired = repairProtoMessage(path, message);
45
- // Reference equality: nothing was coerced, so the failure is something this
46
- // does not explain and it has to keep propagating rather than be retried.
47
- if (repaired === message)
48
- throw error;
49
- return encodeProto(path, projectProtoMessage(path, repaired));
50
- }
51
- };
3
+ import { encodeProtoCompat as encodeProtoCompatCore } from './encode-proto-core.js';
4
+ export const encodeProtoCompat = (path, message) => encodeProtoCompatCore(path, message, encodeProto);
52
5
  //# sourceMappingURL=encode-proto.js.map
@@ -0,0 +1,6 @@
1
+ import type { HostAuthenticationState, HostStoreCallbacks } from '../host-types.js';
2
+ export declare const initHostAuthCreds: () => HostAuthenticationState['creds'];
3
+ export declare const hydrateHostAuthCreds: (store: HostStoreCallbacks, creds: HostAuthenticationState['creds']) => Promise<void>;
4
+ /** Build host auth from the caller-owned native byte store. Rust remains the Signal authority. */
5
+ export declare const createAuthenticationState: (store: HostStoreCallbacks) => Promise<HostAuthenticationState>;
6
+ //# sourceMappingURL=host-auth-state.d.ts.map
@@ -0,0 +1,162 @@
1
+ /** Host-only auth bootstrap. It deliberately does not import legacy-store codecs. */
2
+ import { calculateSignature, generateKeyPair } from '@oxidezap/whatsapp-rust-bridge/host';
3
+ import { proto } from '@oxidezap/whatsapp-rust-bridge/proto-types';
4
+ import { base64Encode, concatBytes, randomBytes, readU16BE, utf8Decode } from '../Runtime/bytes.js';
5
+ import { jidEncode } from '../WABinary/jid-utils.js';
6
+ const pair = () => {
7
+ const value = generateKeyPair();
8
+ return { private: new Uint8Array(value.privKey), public: new Uint8Array(value.pubKey.subarray(1)) };
9
+ };
10
+ const signed = (identity) => {
11
+ const keyPair = pair();
12
+ const publicKey = keyPair.public.length === 33 ? keyPair.public : concatBytes([new Uint8Array([5]), keyPair.public]);
13
+ return { keyPair, keyId: 1, signature: new Uint8Array(calculateSignature(identity.private, publicKey)) };
14
+ };
15
+ export const initHostAuthCreds = () => {
16
+ const identity = pair();
17
+ return {
18
+ noiseKey: pair(),
19
+ pairingEphemeralKeyPair: pair(),
20
+ signedIdentityKey: identity,
21
+ signedPreKey: signed(identity),
22
+ registrationId: readU16BE(randomBytes(2)) & 0x3fff,
23
+ advSecretKey: base64Encode(randomBytes(32)),
24
+ processedHistoryMessages: [],
25
+ nextPreKeyId: 1,
26
+ firstUnuploadedPreKeyId: 1,
27
+ accountSyncCounter: 0,
28
+ accountSettings: { unarchiveChats: false },
29
+ registered: false,
30
+ pairingCode: undefined,
31
+ lastPropHash: undefined,
32
+ routingInfo: undefined,
33
+ additionalData: undefined
34
+ };
35
+ };
36
+ const PERSISTED_JID_DOMAINS = {
37
+ pn: new Set(['c.us', 's.whatsapp.net', 'hosted']),
38
+ lid: new Set(['lid', 'hosted.lid'])
39
+ };
40
+ const parsePersistedJid = (record, field) => {
41
+ const value = record[field];
42
+ if (value == null)
43
+ return undefined;
44
+ if (typeof value !== 'object')
45
+ throw new Error(`persisted auth record contains an invalid ${field} JID`);
46
+ const candidate = value;
47
+ if (typeof candidate.user !== 'string' ||
48
+ candidate.user.length === 0 ||
49
+ typeof candidate.server !== 'string' ||
50
+ !PERSISTED_JID_DOMAINS[field].has(candidate.server) ||
51
+ (candidate.device !== undefined &&
52
+ (typeof candidate.device !== 'number' || !Number.isSafeInteger(candidate.device) || candidate.device < 0))) {
53
+ throw new Error(`persisted auth record contains an invalid ${field} JID`);
54
+ }
55
+ return {
56
+ user: candidate.user,
57
+ server: candidate.server,
58
+ ...(candidate.device === undefined ? {} : { device: candidate.device })
59
+ };
60
+ };
61
+ export const hydrateHostAuthCreds = async (store, creds) => {
62
+ const [payload, accountPayload] = await Promise.all([store.get('device', 'device'), store.get('device', 'account')]);
63
+ if (!payload) {
64
+ if (accountPayload)
65
+ creds.account = proto.ADVSignedDeviceIdentity.decode(accountPayload);
66
+ return;
67
+ }
68
+ let record;
69
+ try {
70
+ record = JSON.parse(utf8Decode(payload));
71
+ }
72
+ catch (error) {
73
+ throw new Error("failed to hydrate persisted auth record 'device'", { cause: error });
74
+ }
75
+ // Validate both identities before mutating the caller's credential mirror.
76
+ const pn = parsePersistedJid(record, 'pn');
77
+ const lid = parsePersistedJid(record, 'lid');
78
+ const mutable = creds;
79
+ const asBytes = (value) => Array.isArray(value) && value.every(byte => Number.isInteger(byte) && byte >= 0 && byte <= 255)
80
+ ? new Uint8Array(value)
81
+ : undefined;
82
+ const keyPair = (value) => {
83
+ const bytes = asBytes(value);
84
+ if (!bytes || bytes.length !== 64 || bytes.every(byte => byte === 0))
85
+ return undefined;
86
+ return { private: bytes.slice(0, 32), public: bytes.slice(32, 64) };
87
+ };
88
+ const safeUnsigned = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
89
+ const registration = record.registration_id;
90
+ // Fresh Baileys mirrors use 14 bits; persisted devices come from Rust's 1..=2^31-1 generator.
91
+ if ('registration_id' in record && (!safeUnsigned(registration) || registration > 2147483647)) {
92
+ throw new Error('invalid persisted registration id');
93
+ }
94
+ if (safeUnsigned(registration))
95
+ mutable.registrationId = registration;
96
+ const noiseKey = keyPair(record.noise_key);
97
+ if ('noise_key' in record && !noiseKey) {
98
+ throw new Error('persisted auth record contains an invalid noise key');
99
+ }
100
+ const identityKey = keyPair(record.identity_key);
101
+ const signedPreKey = keyPair(record.signed_pre_key);
102
+ const hasSigningRecord = ['identity_key', 'signed_pre_key', 'signed_pre_key_id', 'signed_pre_key_signature'].some(field => field in record);
103
+ const signature = asBytes(record.signed_pre_key_signature);
104
+ const keyId = record.signed_pre_key_id;
105
+ if (hasSigningRecord &&
106
+ (!identityKey || !signedPreKey || !signature || signature.length !== 64 || !safeUnsigned(keyId))) {
107
+ throw new Error('persisted auth record contains an incomplete signing bundle');
108
+ }
109
+ if (noiseKey)
110
+ mutable.noiseKey = noiseKey;
111
+ if (hasSigningRecord) {
112
+ mutable.signedIdentityKey = identityKey;
113
+ mutable.signedPreKey = { keyPair: signedPreKey, keyId: keyId, signature: signature };
114
+ }
115
+ const advSecret = asBytes(record.adv_secret_key);
116
+ if ('adv_secret_key' in record && (!advSecret || advSecret.length !== 32)) {
117
+ throw new Error('persisted auth record contains an invalid adv secret');
118
+ }
119
+ if (advSecret)
120
+ mutable.advSecretKey = base64Encode(advSecret);
121
+ if ('next_pre_key_id' in record && !safeUnsigned(record.next_pre_key_id))
122
+ throw new Error('invalid persisted pre-key counter');
123
+ if (safeUnsigned(record.next_pre_key_id)) {
124
+ mutable.nextPreKeyId = record.next_pre_key_id;
125
+ mutable.firstUnuploadedPreKeyId = record.next_pre_key_id;
126
+ }
127
+ if (typeof record.props_hash === 'string')
128
+ mutable.lastPropHash = record.props_hash;
129
+ if (pn) {
130
+ const id = jidEncode(pn.user, pn.server, pn.device);
131
+ mutable.me = {
132
+ id,
133
+ name: typeof record.push_name === 'string' ? record.push_name : undefined,
134
+ ...(lid ? { lid: jidEncode(lid.user, lid.server, lid.device) } : {})
135
+ };
136
+ }
137
+ else if (typeof record.push_name === 'string') {
138
+ mutable.me = { id: '', name: record.push_name };
139
+ }
140
+ if (mutable.me?.id)
141
+ mutable.registered = true;
142
+ if (typeof record.platform === 'string')
143
+ mutable.platform = record.platform;
144
+ const routingInfo = record.edge_routing_info;
145
+ const routingBytes = asBytes(routingInfo);
146
+ if ('edge_routing_info' in record && routingInfo !== null && !routingBytes) {
147
+ throw new Error('persisted auth record contains invalid routing info');
148
+ }
149
+ if (routingInfo === null)
150
+ mutable.routingInfo = undefined;
151
+ else if (routingBytes)
152
+ mutable.routingInfo = routingBytes;
153
+ if (accountPayload)
154
+ creds.account = proto.ADVSignedDeviceIdentity.decode(accountPayload);
155
+ };
156
+ /** Build host auth from the caller-owned native byte store. Rust remains the Signal authority. */
157
+ export const createAuthenticationState = async (store) => {
158
+ const creds = initHostAuthCreds();
159
+ await hydrateHostAuthCreds(store, creds);
160
+ return { creds: creds, store };
161
+ };
162
+ //# sourceMappingURL=host-auth-state.js.map
@@ -1,9 +1,6 @@
1
- import type { AuthenticationState } from '../../Types/index.js';
2
- type NativeAuthenticationState = {
3
- store: NonNullable<AuthenticationState['store']>;
4
- creds?: AuthenticationState['creds'];
5
- keys?: AuthenticationState['keys'];
6
- };
1
+ import type { AuthenticationState, NativeAuthenticationState } from '../../Types/index.js';
2
+ export declare const refreshSocketAuthenticationState: (state: AuthenticationState) => Promise<void>;
3
+ export declare const waitForSocketAuthenticationState: (state: AuthenticationState) => Promise<void>;
7
4
  /**
8
5
  * Complete the public authentication view used by the socket when callers use
9
6
  * the native byte-store path. The byte store remains authoritative: the key
@@ -11,5 +8,4 @@ type NativeAuthenticationState = {
11
8
  * public, in-process mirror updated by socket events.
12
9
  */
13
10
  export declare const normalizeSocketAuthenticationState: (input: AuthenticationState | NativeAuthenticationState) => AuthenticationState;
14
- export {};
15
11
  //# sourceMappingURL=auth-state.d.ts.map