@zervonexx/baileys 5.0.0 → 5.0.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.
Files changed (125) hide show
  1. package/LICENSE +22 -22
  2. package/README.md +4112 -4112
  3. package/WAProto/WAProtoCompile.js +322 -322
  4. package/WAProto/fetcher.js +67 -67
  5. package/WAProto/index.js +95 -95
  6. package/WAProto/parser.js +333 -333
  7. package/lib/Builders/AIRich.js +673 -673
  8. package/lib/Builders/auto.js +49 -49
  9. package/lib/Builders/base.js +144 -144
  10. package/lib/Builders/builders.js +588 -588
  11. package/lib/Builders/index.js +3 -3
  12. package/lib/Defaults/index.js +248 -248
  13. package/lib/Signal/index.js +2 -2
  14. package/lib/Signal/libsignal.js +526 -526
  15. package/lib/Signal/lid-mapping.js +282 -282
  16. package/lib/Socket/Client/index.js +1 -1
  17. package/lib/Socket/Client/types.js +9 -9
  18. package/lib/Socket/Client/websocket.js +83 -83
  19. package/lib/Socket/business.js +151 -151
  20. package/lib/Socket/chats.js +854 -854
  21. package/lib/Socket/communities.js +146 -146
  22. package/lib/Socket/groups.js +293 -293
  23. package/lib/Socket/index.js +14 -14
  24. package/lib/Socket/messages-recv.js +993 -993
  25. package/lib/Socket/messages-send.js +722 -722
  26. package/lib/Socket/mex.js +33 -33
  27. package/lib/Socket/newsletter.js +783 -783
  28. package/lib/Socket/registration.js +154 -154
  29. package/lib/Socket/socket.js +797 -797
  30. package/lib/Socket/spam-report.js +143 -143
  31. package/lib/Socket/username.js +81 -81
  32. package/lib/Socket/zervonex-handler.js +57 -57
  33. package/lib/Store/index.js +6 -6
  34. package/lib/Store/make-cache-manager-store.js +80 -80
  35. package/lib/Store/make-in-memory-store.js +426 -426
  36. package/lib/Store/make-ordered-dictionary.js +81 -81
  37. package/lib/Store/object-repository.js +30 -30
  38. package/lib/Store/reporting-info-store.js +37 -37
  39. package/lib/Types/Auth.js +1 -1
  40. package/lib/Types/Bussines.js +1 -1
  41. package/lib/Types/Call.js +1 -1
  42. package/lib/Types/Chat.js +7 -7
  43. package/lib/Types/Contact.js +1 -1
  44. package/lib/Types/Events.js +1 -1
  45. package/lib/Types/GroupMetadata.js +1 -1
  46. package/lib/Types/Label.js +24 -24
  47. package/lib/Types/LabelAssociation.js +6 -6
  48. package/lib/Types/Message.js +14 -14
  49. package/lib/Types/Newsletter.js +99 -99
  50. package/lib/Types/Product.js +1 -1
  51. package/lib/Types/Signal.js +1 -1
  52. package/lib/Types/Socket.js +14 -14
  53. package/lib/Types/State.js +26 -26
  54. package/lib/Types/USync.js +1 -1
  55. package/lib/Types/index.js +30 -30
  56. package/lib/Utils/auth-utils.js +159 -159
  57. package/lib/Utils/baileys-event-stream.js +32 -32
  58. package/lib/Utils/bot-capabilities.js +40 -40
  59. package/lib/Utils/bot-planning-replay.js +43 -43
  60. package/lib/Utils/browser-utils.js +29 -29
  61. package/lib/Utils/business.js +74 -74
  62. package/lib/Utils/chat-utils.js +316 -316
  63. package/lib/Utils/companion-reg-client-utils.js +19 -19
  64. package/lib/Utils/consumer-application.js +37 -37
  65. package/lib/Utils/crypto.js +52 -52
  66. package/lib/Utils/cstoken.js +14 -14
  67. package/lib/Utils/decode-wa-message.js +199 -199
  68. package/lib/Utils/event-buffer.js +272 -272
  69. package/lib/Utils/extras.js +186 -186
  70. package/lib/Utils/generics.js +194 -194
  71. package/lib/Utils/history.js +50 -50
  72. package/lib/Utils/identity-change-handler.js +18 -18
  73. package/lib/Utils/index.js +40 -40
  74. package/lib/Utils/link-preview.js +50 -50
  75. package/lib/Utils/logger.js +2 -2
  76. package/lib/Utils/lt-hash.js +3 -3
  77. package/lib/Utils/make-mutex.js +15 -15
  78. package/lib/Utils/message-composer.js +61 -61
  79. package/lib/Utils/message-retry-manager.js +47 -47
  80. package/lib/Utils/messages-media.js +501 -501
  81. package/lib/Utils/messages.js +942 -942
  82. package/lib/Utils/meta-ai-msmsg.js +121 -121
  83. package/lib/Utils/meta-compositing.js +74 -74
  84. package/lib/Utils/modern-messages.js +234 -234
  85. package/lib/Utils/native-flow.js +80 -80
  86. package/lib/Utils/noise-handler.js +160 -160
  87. package/lib/Utils/pre-key-manager.js +75 -75
  88. package/lib/Utils/process-message.js +400 -400
  89. package/lib/Utils/reporting-utils.js +170 -170
  90. package/lib/Utils/signal.js +166 -166
  91. package/lib/Utils/spam-report-utils.js +165 -165
  92. package/lib/Utils/sync-action-utils.js +33 -33
  93. package/lib/Utils/tc-token-utils.js +153 -153
  94. package/lib/Utils/use-keyv-auth-state.js +199 -199
  95. package/lib/Utils/use-multi-file-auth-state.js +83 -83
  96. package/lib/Utils/validate-connection.js +171 -171
  97. package/lib/WABinary/constants.js +1320 -1320
  98. package/lib/WABinary/decode.js +151 -151
  99. package/lib/WABinary/encode.js +139 -139
  100. package/lib/WABinary/generic-utils.js +202 -202
  101. package/lib/WABinary/index.js +6 -6
  102. package/lib/WABinary/jid-utils.js +235 -235
  103. package/lib/WABinary/types.js +4 -4
  104. package/lib/WAM/BinaryInfo.js +9 -9
  105. package/lib/WAM/constants.js +22852 -22852
  106. package/lib/WAM/encode.js +149 -149
  107. package/lib/WAM/index.js +3 -3
  108. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +30 -30
  109. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +48 -48
  110. package/lib/WAUSync/Protocols/USyncContactProtocol.js +23 -23
  111. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +28 -28
  112. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +15 -15
  113. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +24 -24
  114. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +9 -9
  115. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +21 -21
  116. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +19 -19
  117. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +19 -19
  118. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +22 -22
  119. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +16 -16
  120. package/lib/WAUSync/Protocols/index.js +12 -12
  121. package/lib/WAUSync/USyncQuery.js +88 -88
  122. package/lib/WAUSync/USyncUser.js +20 -20
  123. package/lib/WAUSync/index.js +3 -3
  124. package/lib/index.js +66 -66
  125. package/package.json +191 -192
@@ -1,2 +1,2 @@
1
- export {};
1
+ export {};
2
2
  //# sourceMappingURL=Product.js.map
@@ -1,2 +1,2 @@
1
- import { proto } from '../../WAProto/index.js';
1
+ import { proto } from '../../WAProto/index.js';
2
2
  //# sourceMappingURL=Signal.js.map
@@ -1,14 +1,14 @@
1
- import { proto } from '../../WAProto/index.js';
2
- import {} from './Message.js';
3
- //# sourceMappingURL=Socket.js.map
4
- export const AIProvenanceType = Object.freeze({
5
- NONE: 0,
6
- CREATED_WITH_GEN_AI: 1,
7
- EDITED_WITH_GEN_AI: 2,
8
- })
9
-
10
- export const DeviceCapabilityLevel = Object.freeze({
11
- NONE: 0,
12
- INFRA: 1,
13
- FULL: 2,
14
- })
1
+ import { proto } from '../../WAProto/index.js';
2
+ import {} from './Message.js';
3
+ //# sourceMappingURL=Socket.js.map
4
+ export const AIProvenanceType = Object.freeze({
5
+ NONE: 0,
6
+ CREATED_WITH_GEN_AI: 1,
7
+ EDITED_WITH_GEN_AI: 2,
8
+ })
9
+
10
+ export const DeviceCapabilityLevel = Object.freeze({
11
+ NONE: 0,
12
+ INFRA: 1,
13
+ FULL: 2,
14
+ })
@@ -1,26 +1,26 @@
1
- export const SyncState = Object.freeze({ Connecting: 0, AwaitingInitialSync: 1, Syncing: 2, Online: 3 })
2
-
3
- export const ReachoutTimelockEnforcementType = Object.freeze({
4
- BIZ_COMMERCE_VIOLATION_ALCOHOL: 'BIZ_COMMERCE_VIOLATION_ALCOHOL',
5
- BIZ_COMMERCE_VIOLATION_ADULT: 'BIZ_COMMERCE_VIOLATION_ADULT',
6
- BIZ_COMMERCE_VIOLATION_ANIMALS: 'BIZ_COMMERCE_VIOLATION_ANIMALS',
7
- BIZ_COMMERCE_VIOLATION_BODY_PARTS_FLUIDS: 'BIZ_COMMERCE_VIOLATION_BODY_PARTS_FLUIDS',
8
- BIZ_COMMERCE_VIOLATION_DATING: 'BIZ_COMMERCE_VIOLATION_DATING',
9
- BIZ_COMMERCE_VIOLATION_DIGITAL_SERVICES_PRODUCTS: 'BIZ_COMMERCE_VIOLATION_DIGITAL_SERVICES_PRODUCTS',
10
- BIZ_COMMERCE_VIOLATION_DRUGS: 'BIZ_COMMERCE_VIOLATION_DRUGS',
11
- BIZ_COMMERCE_VIOLATION_DRUGS_ONLY_OTC: 'BIZ_COMMERCE_VIOLATION_DRUGS_ONLY_OTC',
12
- BIZ_COMMERCE_VIOLATION_GAMBLING: 'BIZ_COMMERCE_VIOLATION_GAMBLING',
13
- BIZ_COMMERCE_VIOLATION_HEALTHCARE: 'BIZ_COMMERCE_VIOLATION_HEALTHCARE',
14
- BIZ_COMMERCE_VIOLATION_REAL_FAKE_CURRENCY: 'BIZ_COMMERCE_VIOLATION_REAL_FAKE_CURRENCY',
15
- BIZ_COMMERCE_VIOLATION_SUPPLEMENTS: 'BIZ_COMMERCE_VIOLATION_SUPPLEMENTS',
16
- BIZ_COMMERCE_VIOLATION_TOBACCO: 'BIZ_COMMERCE_VIOLATION_TOBACCO',
17
- BIZ_COMMERCE_VIOLATION_VIOLENT_CONTENT: 'BIZ_COMMERCE_VIOLATION_VIOLENT_CONTENT',
18
- BIZ_COMMERCE_VIOLATION_WEAPONS: 'BIZ_COMMERCE_VIOLATION_WEAPONS',
19
- BIZ_QUALITY: 'BIZ_QUALITY',
20
- DEFAULT: 'DEFAULT',
21
- WEB_COMPANION_ONLY: 'WEB_COMPANION_ONLY',
22
- })
23
-
24
- export const NewChatMessageCappingStatusType = Object.freeze({ NONE:'NONE', FIRST_WARNING:'FIRST_WARNING', SECOND_WARNING:'SECOND_WARNING', CAPPED:'CAPPED' })
25
- export const NewChatMessageCappingMVStatusType = Object.freeze({ NOT_ELIGIBLE:'NOT_ELIGIBLE', NOT_ACTIVE:'NOT_ACTIVE', ACTIVE:'ACTIVE', ACTIVE_UPGRADE_AVAILABLE:'ACTIVE_UPGRADE_AVAILABLE' })
26
- export const NewChatMessageCappingOTEStatusType = Object.freeze({ NOT_ELIGIBLE:'NOT_ELIGIBLE', ELIGIBLE:'ELIGIBLE', ACTIVE_IN_CURRENT_CYCLE:'ACTIVE_IN_CURRENT_CYCLE', EXHAUSTED:'EXHAUSTED' })
1
+ export const SyncState = Object.freeze({ Connecting: 0, AwaitingInitialSync: 1, Syncing: 2, Online: 3 })
2
+
3
+ export const ReachoutTimelockEnforcementType = Object.freeze({
4
+ BIZ_COMMERCE_VIOLATION_ALCOHOL: 'BIZ_COMMERCE_VIOLATION_ALCOHOL',
5
+ BIZ_COMMERCE_VIOLATION_ADULT: 'BIZ_COMMERCE_VIOLATION_ADULT',
6
+ BIZ_COMMERCE_VIOLATION_ANIMALS: 'BIZ_COMMERCE_VIOLATION_ANIMALS',
7
+ BIZ_COMMERCE_VIOLATION_BODY_PARTS_FLUIDS: 'BIZ_COMMERCE_VIOLATION_BODY_PARTS_FLUIDS',
8
+ BIZ_COMMERCE_VIOLATION_DATING: 'BIZ_COMMERCE_VIOLATION_DATING',
9
+ BIZ_COMMERCE_VIOLATION_DIGITAL_SERVICES_PRODUCTS: 'BIZ_COMMERCE_VIOLATION_DIGITAL_SERVICES_PRODUCTS',
10
+ BIZ_COMMERCE_VIOLATION_DRUGS: 'BIZ_COMMERCE_VIOLATION_DRUGS',
11
+ BIZ_COMMERCE_VIOLATION_DRUGS_ONLY_OTC: 'BIZ_COMMERCE_VIOLATION_DRUGS_ONLY_OTC',
12
+ BIZ_COMMERCE_VIOLATION_GAMBLING: 'BIZ_COMMERCE_VIOLATION_GAMBLING',
13
+ BIZ_COMMERCE_VIOLATION_HEALTHCARE: 'BIZ_COMMERCE_VIOLATION_HEALTHCARE',
14
+ BIZ_COMMERCE_VIOLATION_REAL_FAKE_CURRENCY: 'BIZ_COMMERCE_VIOLATION_REAL_FAKE_CURRENCY',
15
+ BIZ_COMMERCE_VIOLATION_SUPPLEMENTS: 'BIZ_COMMERCE_VIOLATION_SUPPLEMENTS',
16
+ BIZ_COMMERCE_VIOLATION_TOBACCO: 'BIZ_COMMERCE_VIOLATION_TOBACCO',
17
+ BIZ_COMMERCE_VIOLATION_VIOLENT_CONTENT: 'BIZ_COMMERCE_VIOLATION_VIOLENT_CONTENT',
18
+ BIZ_COMMERCE_VIOLATION_WEAPONS: 'BIZ_COMMERCE_VIOLATION_WEAPONS',
19
+ BIZ_QUALITY: 'BIZ_QUALITY',
20
+ DEFAULT: 'DEFAULT',
21
+ WEB_COMPANION_ONLY: 'WEB_COMPANION_ONLY',
22
+ })
23
+
24
+ export const NewChatMessageCappingStatusType = Object.freeze({ NONE:'NONE', FIRST_WARNING:'FIRST_WARNING', SECOND_WARNING:'SECOND_WARNING', CAPPED:'CAPPED' })
25
+ export const NewChatMessageCappingMVStatusType = Object.freeze({ NOT_ELIGIBLE:'NOT_ELIGIBLE', NOT_ACTIVE:'NOT_ACTIVE', ACTIVE:'ACTIVE', ACTIVE_UPGRADE_AVAILABLE:'ACTIVE_UPGRADE_AVAILABLE' })
26
+ export const NewChatMessageCappingOTEStatusType = Object.freeze({ NOT_ELIGIBLE:'NOT_ELIGIBLE', ELIGIBLE:'ELIGIBLE', ACTIVE_IN_CURRENT_CYCLE:'ACTIVE_IN_CURRENT_CYCLE', EXHAUSTED:'EXHAUSTED' })
@@ -1,2 +1,2 @@
1
- import { USyncUser } from '../WAUSync/index.js';
1
+ import { USyncUser } from '../WAUSync/index.js';
2
2
  //# sourceMappingURL=USync.js.map
@@ -1,30 +1,30 @@
1
- export * from './Auth.js'
2
- export * from './GroupMetadata.js'
3
- export * from './Chat.js'
4
- export * from './Contact.js'
5
- export * from './State.js'
6
- export * from './Message.js'
7
- export * from './Socket.js'
8
- export * from './Events.js'
9
- export * from './Product.js'
10
- export * from './Call.js'
11
- export * from './Signal.js'
12
- export * from './Newsletter.js'
13
- export * from './Label.js'
14
- export * from './LabelAssociation.js'
15
- export * from './USync.js'
16
-
17
- export const DisconnectReason = Object.freeze({
18
- connectionClosed: 428,
19
- connectionLost: 408,
20
- connectionReplaced: 440,
21
- timedOut: 408,
22
- loggedOut: 401,
23
- badSession: 500,
24
- restartRequired: 515,
25
- multideviceMismatch: 411,
26
- forbidden: 403,
27
- unavailableService: 503,
28
- })
29
-
30
-
1
+ export * from './Auth.js'
2
+ export * from './GroupMetadata.js'
3
+ export * from './Chat.js'
4
+ export * from './Contact.js'
5
+ export * from './State.js'
6
+ export * from './Message.js'
7
+ export * from './Socket.js'
8
+ export * from './Events.js'
9
+ export * from './Product.js'
10
+ export * from './Call.js'
11
+ export * from './Signal.js'
12
+ export * from './Newsletter.js'
13
+ export * from './Label.js'
14
+ export * from './LabelAssociation.js'
15
+ export * from './USync.js'
16
+
17
+ export const DisconnectReason = Object.freeze({
18
+ connectionClosed: 428,
19
+ connectionLost: 408,
20
+ connectionReplaced: 440,
21
+ timedOut: 408,
22
+ loggedOut: 401,
23
+ badSession: 500,
24
+ restartRequired: 515,
25
+ multideviceMismatch: 411,
26
+ forbidden: 403,
27
+ unavailableService: 503,
28
+ })
29
+
30
+
@@ -1,159 +1,159 @@
1
- import NodeCache from '@cacheable/node-cache'
2
- import { AsyncLocalStorage } from 'async_hooks'
3
- import { Mutex } from 'async-mutex'
4
- import { randomBytes } from 'crypto'
5
- import PQueue from 'p-queue'
6
- import { v4 } from 'uuid'
7
- import { DEFAULT_CACHE_TTLS } from '../Defaults/index.js'
8
- import { Curve, signedKeyPair } from './crypto.js'
9
- import { delay, generateRegistrationId, BufferJSON } from './generics.js'
10
- import { PreKeyManager } from './pre-key-manager.js'
11
- import { proto } from '../../WAProto/index.js'
12
-
13
- export function makeCacheableSignalKeyStore(store, logger, _cache) {
14
- const cache = _cache || new NodeCache({ stdTTL: DEFAULT_CACHE_TTLS.SIGNAL_STORE, useClones: false, deleteOnExpire: true })
15
- const cacheMutex = new Mutex()
16
- const uid = (type, id) => `${type}.${id}`
17
- return {
18
- async get(type, ids) {
19
- return cacheMutex.runExclusive(async () => {
20
- const data = {}, missing = []
21
- for (const id of ids) { const item = await cache.get(uid(type, id)); if (typeof item !== 'undefined') data[id] = item; else missing.push(id) }
22
- if (missing.length) { logger?.trace({ items: missing.length }, 'loading from store'); const fetched = await store.get(type, missing); for (const id of missing) { if (fetched[id]) { data[id] = fetched[id]; cache.set(uid(type, id), fetched[id]) } } }
23
- return data
24
- })
25
- },
26
- async set(data) {
27
- return cacheMutex.runExclusive(async () => {
28
- let keys = 0
29
- for (const type in data) { for (const id in data[type]) { await cache.set(uid(type, id), data[type][id]); keys++ } }
30
- logger?.trace({ keys }, 'updated cache')
31
- await store.set(data)
32
- })
33
- },
34
- async clear() { await cache.flushAll(); await store.clear?.() }
35
- }
36
- }
37
-
38
- export const addTransactionCapability = (state, logger, { maxCommitRetries, delayBetweenTriesMs }) => {
39
- const txStorage = new AsyncLocalStorage()
40
- const keyQueues = new Map()
41
- const txMutexes = new Map()
42
- const preKeyManager = new PreKeyManager(state, logger)
43
-
44
- const getQueue = key => { if (!keyQueues.has(key)) keyQueues.set(key, new PQueue({ concurrency: 1 })); return keyQueues.get(key) }
45
- const getTxMutex = key => { if (!txMutexes.has(key)) txMutexes.set(key, new Mutex()); return txMutexes.get(key) }
46
- const isInTransaction = () => !!txStorage.getStore()
47
-
48
- const EXPECTED_ERRORS = ['InvalidPreKeyId', 'SessionNotFound', 'InvalidMessage', 'no sender key state', 'memory access out of bounds', 'old counter', 'DuplicatedMessage', 'BadMac', 'Connection Closed']
49
- const isExpectedError = msg => EXPECTED_ERRORS.some(e => msg.includes(e))
50
-
51
- async function commitWithRetry(mutations) {
52
- if (Object.keys(mutations).length === 0) { logger.trace('no mutations in transaction'); return }
53
- logger.trace('committing transaction')
54
- for (let attempt = 0; attempt < maxCommitRetries; attempt++) {
55
- try {
56
- await state.set(mutations)
57
- logger.trace({ mutationCount: Object.keys(mutations).length }, 'committed transaction')
58
- return
59
- } catch (error) {
60
- const msg = error?.message || (typeof error === 'string' ? error : '') || ''
61
- if (isExpectedError(msg)) { logger?.debug?.({ error: msg }, 'transaction skipped — expected decrypt error'); return }
62
- if (attempt < maxCommitRetries - 1) { await delay(delayBetweenTriesMs); continue }
63
- logger?.error?.({ error: msg || error }, 'transaction failed after retries')
64
- throw error
65
- }
66
- }
67
- }
68
-
69
- return {
70
- get: async (type, ids) => {
71
- const ctx = txStorage.getStore()
72
- if (!ctx) return state.get(type, ids)
73
- const cached = ctx.cache[type] || {}
74
- const missing = ids.filter(id => !(id in cached))
75
- if (missing.length) { ctx.dbQueries++; logger.trace({ type, count: missing.length }, 'fetching missing keys in transaction'); const fetched = await getTxMutex(type).runExclusive(() => state.get(type, missing)); ctx.cache[type] = ctx.cache[type] || {}; Object.assign(ctx.cache[type], fetched) }
76
- const result = {}
77
- for (const id of ids) { const value = ctx.cache[type]?.[id]; if (value !== undefined && value !== null) result[id] = value }
78
- return result
79
- },
80
- set: async (data) => {
81
- const ctx = txStorage.getStore()
82
- if (!ctx) {
83
- const types = Object.keys(data)
84
- for (const type of types) { if (type === 'pre-key') await preKeyManager.validateDeletions(data, type) }
85
- await Promise.all(types.map(type => getQueue(type).add(async () => state.set({ [type]: data[type] }))))
86
- return
87
- }
88
- logger.trace({ types: Object.keys(data) }, 'caching in transaction')
89
- for (const key in data) {
90
- ctx.cache[key] = ctx.cache[key] || {}
91
- ctx.mutations[key] = ctx.mutations[key] || {}
92
- if (key === 'pre-key') await preKeyManager.processOperations(data, key, ctx.cache, ctx.mutations, true)
93
- else { Object.assign(ctx.cache[key], data[key]); Object.assign(ctx.mutations[key], data[key]) }
94
- }
95
- },
96
- isInTransaction,
97
- transaction: async (work, key) => {
98
- const existing = txStorage.getStore()
99
- if (existing) { logger.trace('reusing existing transaction context'); return work() }
100
- return getTxMutex(key).runExclusive(async () => {
101
- const ctx = { cache: {}, mutations: {}, dbQueries: 0 }
102
- logger.trace('entering transaction')
103
- try {
104
- const result = await txStorage.run(ctx, work)
105
- await commitWithRetry(ctx.mutations)
106
- logger.trace({ dbQueries: ctx.dbQueries }, 'transaction completed')
107
- return result
108
- } catch (error) {
109
- const msg = error?.message || (typeof error === 'string' ? error : '') || ''
110
- ; (isExpectedError(msg) ? logger?.debug?.bind(logger) : logger?.error?.bind(logger))?.({ error: msg || error }, 'transaction failed, rolling back')
111
- throw error
112
- }
113
- })
114
- }
115
- }
116
- }
117
-
118
- export const initAuthCreds = () => {
119
- const identityKey = Curve.generateKeyPair()
120
- return {
121
- noiseKey: Curve.generateKeyPair(),
122
- pairingEphemeralKeyPair: Curve.generateKeyPair(),
123
- signedIdentityKey: identityKey,
124
- signedPreKey: signedKeyPair(identityKey, 1),
125
- registrationId: generateRegistrationId(),
126
- advSecretKey: randomBytes(32).toString('base64'),
127
- processedHistoryMessages: [],
128
- nextPreKeyId: 1,
129
- firstUnuploadedPreKeyId: 1,
130
- accountSyncCounter: 0,
131
- accountSettings: { unarchiveChats: false },
132
- deviceId: Buffer.from(v4().replace(/-/g, ''), 'hex').toString('base64url'),
133
- phoneId: v4(),
134
- identityId: randomBytes(20),
135
- registered: false,
136
- backupToken: randomBytes(20),
137
- registration: {},
138
- pairingCode: undefined,
139
- lastPropHash: undefined,
140
- routingInfo: undefined,
141
- additionalData: undefined
142
- }
143
- }
144
-
145
-
146
- export const bootstrapCreds = raw => raw ?? initAuthCreds()
147
- export const patchAppStateKey = (type, v) => type === 'app-state-sync-key' && v ? proto.Message.AppStateSyncKeyData.fromObject(v) : v
148
- export const ser = v => v == null ? null : JSON.parse(JSON.stringify(v, BufferJSON.replacer))
149
- export const deser = raw => {
150
- if (raw == null) return null
151
- let p = typeof raw === 'string'
152
- ? (() => { try { return JSON.parse(raw) } catch { return raw } })()
153
- : raw
154
- let depth = 0
155
- while (depth++ < 3 && p && typeof p === 'object' && !Array.isArray(p) && Object.keys(p).length === 1 && 'value' in p) p = p.value
156
- if (p == null) return null
157
- if (typeof p === 'object' && '__checksum' in p && 'data' in p) p = p.data
158
- return JSON.parse(JSON.stringify(p), BufferJSON.reviver)
159
- }
1
+ import NodeCache from '@cacheable/node-cache'
2
+ import { AsyncLocalStorage } from 'async_hooks'
3
+ import { Mutex } from 'async-mutex'
4
+ import { randomBytes } from 'crypto'
5
+ import PQueue from 'p-queue'
6
+ import { v4 } from 'uuid'
7
+ import { DEFAULT_CACHE_TTLS } from '../Defaults/index.js'
8
+ import { Curve, signedKeyPair } from './crypto.js'
9
+ import { delay, generateRegistrationId, BufferJSON } from './generics.js'
10
+ import { PreKeyManager } from './pre-key-manager.js'
11
+ import { proto } from '../../WAProto/index.js'
12
+
13
+ export function makeCacheableSignalKeyStore(store, logger, _cache) {
14
+ const cache = _cache || new NodeCache({ stdTTL: DEFAULT_CACHE_TTLS.SIGNAL_STORE, useClones: false, deleteOnExpire: true })
15
+ const cacheMutex = new Mutex()
16
+ const uid = (type, id) => `${type}.${id}`
17
+ return {
18
+ async get(type, ids) {
19
+ return cacheMutex.runExclusive(async () => {
20
+ const data = {}, missing = []
21
+ for (const id of ids) { const item = await cache.get(uid(type, id)); if (typeof item !== 'undefined') data[id] = item; else missing.push(id) }
22
+ if (missing.length) { logger?.trace({ items: missing.length }, 'loading from store'); const fetched = await store.get(type, missing); for (const id of missing) { if (fetched[id]) { data[id] = fetched[id]; cache.set(uid(type, id), fetched[id]) } } }
23
+ return data
24
+ })
25
+ },
26
+ async set(data) {
27
+ return cacheMutex.runExclusive(async () => {
28
+ let keys = 0
29
+ for (const type in data) { for (const id in data[type]) { await cache.set(uid(type, id), data[type][id]); keys++ } }
30
+ logger?.trace({ keys }, 'updated cache')
31
+ await store.set(data)
32
+ })
33
+ },
34
+ async clear() { await cache.flushAll(); await store.clear?.() }
35
+ }
36
+ }
37
+
38
+ export const addTransactionCapability = (state, logger, { maxCommitRetries, delayBetweenTriesMs }) => {
39
+ const txStorage = new AsyncLocalStorage()
40
+ const keyQueues = new Map()
41
+ const txMutexes = new Map()
42
+ const preKeyManager = new PreKeyManager(state, logger)
43
+
44
+ const getQueue = key => { if (!keyQueues.has(key)) keyQueues.set(key, new PQueue({ concurrency: 1 })); return keyQueues.get(key) }
45
+ const getTxMutex = key => { if (!txMutexes.has(key)) txMutexes.set(key, new Mutex()); return txMutexes.get(key) }
46
+ const isInTransaction = () => !!txStorage.getStore()
47
+
48
+ const EXPECTED_ERRORS = ['InvalidPreKeyId', 'SessionNotFound', 'InvalidMessage', 'no sender key state', 'memory access out of bounds', 'old counter', 'DuplicatedMessage', 'BadMac', 'Connection Closed']
49
+ const isExpectedError = msg => EXPECTED_ERRORS.some(e => msg.includes(e))
50
+
51
+ async function commitWithRetry(mutations) {
52
+ if (Object.keys(mutations).length === 0) { logger.trace('no mutations in transaction'); return }
53
+ logger.trace('committing transaction')
54
+ for (let attempt = 0; attempt < maxCommitRetries; attempt++) {
55
+ try {
56
+ await state.set(mutations)
57
+ logger.trace({ mutationCount: Object.keys(mutations).length }, 'committed transaction')
58
+ return
59
+ } catch (error) {
60
+ const msg = error?.message || (typeof error === 'string' ? error : '') || ''
61
+ if (isExpectedError(msg)) { logger?.debug?.({ error: msg }, 'transaction skipped — expected decrypt error'); return }
62
+ if (attempt < maxCommitRetries - 1) { await delay(delayBetweenTriesMs); continue }
63
+ logger?.error?.({ error: msg || error }, 'transaction failed after retries')
64
+ throw error
65
+ }
66
+ }
67
+ }
68
+
69
+ return {
70
+ get: async (type, ids) => {
71
+ const ctx = txStorage.getStore()
72
+ if (!ctx) return state.get(type, ids)
73
+ const cached = ctx.cache[type] || {}
74
+ const missing = ids.filter(id => !(id in cached))
75
+ if (missing.length) { ctx.dbQueries++; logger.trace({ type, count: missing.length }, 'fetching missing keys in transaction'); const fetched = await getTxMutex(type).runExclusive(() => state.get(type, missing)); ctx.cache[type] = ctx.cache[type] || {}; Object.assign(ctx.cache[type], fetched) }
76
+ const result = {}
77
+ for (const id of ids) { const value = ctx.cache[type]?.[id]; if (value !== undefined && value !== null) result[id] = value }
78
+ return result
79
+ },
80
+ set: async (data) => {
81
+ const ctx = txStorage.getStore()
82
+ if (!ctx) {
83
+ const types = Object.keys(data)
84
+ for (const type of types) { if (type === 'pre-key') await preKeyManager.validateDeletions(data, type) }
85
+ await Promise.all(types.map(type => getQueue(type).add(async () => state.set({ [type]: data[type] }))))
86
+ return
87
+ }
88
+ logger.trace({ types: Object.keys(data) }, 'caching in transaction')
89
+ for (const key in data) {
90
+ ctx.cache[key] = ctx.cache[key] || {}
91
+ ctx.mutations[key] = ctx.mutations[key] || {}
92
+ if (key === 'pre-key') await preKeyManager.processOperations(data, key, ctx.cache, ctx.mutations, true)
93
+ else { Object.assign(ctx.cache[key], data[key]); Object.assign(ctx.mutations[key], data[key]) }
94
+ }
95
+ },
96
+ isInTransaction,
97
+ transaction: async (work, key) => {
98
+ const existing = txStorage.getStore()
99
+ if (existing) { logger.trace('reusing existing transaction context'); return work() }
100
+ return getTxMutex(key).runExclusive(async () => {
101
+ const ctx = { cache: {}, mutations: {}, dbQueries: 0 }
102
+ logger.trace('entering transaction')
103
+ try {
104
+ const result = await txStorage.run(ctx, work)
105
+ await commitWithRetry(ctx.mutations)
106
+ logger.trace({ dbQueries: ctx.dbQueries }, 'transaction completed')
107
+ return result
108
+ } catch (error) {
109
+ const msg = error?.message || (typeof error === 'string' ? error : '') || ''
110
+ ; (isExpectedError(msg) ? logger?.debug?.bind(logger) : logger?.error?.bind(logger))?.({ error: msg || error }, 'transaction failed, rolling back')
111
+ throw error
112
+ }
113
+ })
114
+ }
115
+ }
116
+ }
117
+
118
+ export const initAuthCreds = () => {
119
+ const identityKey = Curve.generateKeyPair()
120
+ return {
121
+ noiseKey: Curve.generateKeyPair(),
122
+ pairingEphemeralKeyPair: Curve.generateKeyPair(),
123
+ signedIdentityKey: identityKey,
124
+ signedPreKey: signedKeyPair(identityKey, 1),
125
+ registrationId: generateRegistrationId(),
126
+ advSecretKey: randomBytes(32).toString('base64'),
127
+ processedHistoryMessages: [],
128
+ nextPreKeyId: 1,
129
+ firstUnuploadedPreKeyId: 1,
130
+ accountSyncCounter: 0,
131
+ accountSettings: { unarchiveChats: false },
132
+ deviceId: Buffer.from(v4().replace(/-/g, ''), 'hex').toString('base64url'),
133
+ phoneId: v4(),
134
+ identityId: randomBytes(20),
135
+ registered: false,
136
+ backupToken: randomBytes(20),
137
+ registration: {},
138
+ pairingCode: undefined,
139
+ lastPropHash: undefined,
140
+ routingInfo: undefined,
141
+ additionalData: undefined
142
+ }
143
+ }
144
+
145
+
146
+ export const bootstrapCreds = raw => raw ?? initAuthCreds()
147
+ export const patchAppStateKey = (type, v) => type === 'app-state-sync-key' && v ? proto.Message.AppStateSyncKeyData.fromObject(v) : v
148
+ export const ser = v => v == null ? null : JSON.parse(JSON.stringify(v, BufferJSON.replacer))
149
+ export const deser = raw => {
150
+ if (raw == null) return null
151
+ let p = typeof raw === 'string'
152
+ ? (() => { try { return JSON.parse(raw) } catch { return raw } })()
153
+ : raw
154
+ let depth = 0
155
+ while (depth++ < 3 && p && typeof p === 'object' && !Array.isArray(p) && Object.keys(p).length === 1 && 'value' in p) p = p.value
156
+ if (p == null) return null
157
+ if (typeof p === 'object' && '__checksum' in p && 'data' in p) p = p.data
158
+ return JSON.parse(JSON.stringify(p), BufferJSON.reviver)
159
+ }
@@ -1,33 +1,33 @@
1
- import EventEmitter from 'events'
2
- import { createReadStream } from 'fs'
3
- import { writeFile } from 'fs/promises'
4
- import { createInterface } from 'readline'
5
- import { delay } from './generics.js'
6
- import { makeMutex } from './make-mutex.js'
7
-
8
- export const captureEventStream = (ev, filename) => {
9
- const oldEmit = ev.emit.bind(ev)
10
- const writeMutex = makeMutex()
11
- ev.emit = (...args) => {
12
- const content = JSON.stringify({ timestamp: Date.now(), event: args[0], data: args[1] }) + '\n'
13
- const result = oldEmit(...args)
14
- writeMutex.mutex(() => writeFile(filename, content, { flag: 'a' }))
15
- return result
16
- }
17
- }
18
-
19
- export const readAndEmitEventStream = (filename, delayIntervalMs = 0) => {
20
- const ev = new EventEmitter()
21
- const fireEvents = async () => {
22
- const fileStream = createReadStream(filename)
23
- const rl = createInterface({ input: fileStream, crlfDelay: Infinity })
24
- for await (const line of rl) {
25
- if (!line) continue
26
- const { event, data } = JSON.parse(line)
27
- ev.emit(event, data)
28
- if (delayIntervalMs) await delay(delayIntervalMs)
29
- }
30
- fileStream.destroy()
31
- }
32
- return { ev, task: fireEvents() }
1
+ import EventEmitter from 'events'
2
+ import { createReadStream } from 'fs'
3
+ import { writeFile } from 'fs/promises'
4
+ import { createInterface } from 'readline'
5
+ import { delay } from './generics.js'
6
+ import { makeMutex } from './make-mutex.js'
7
+
8
+ export const captureEventStream = (ev, filename) => {
9
+ const oldEmit = ev.emit.bind(ev)
10
+ const writeMutex = makeMutex()
11
+ ev.emit = (...args) => {
12
+ const content = JSON.stringify({ timestamp: Date.now(), event: args[0], data: args[1] }) + '\n'
13
+ const result = oldEmit(...args)
14
+ writeMutex.mutex(() => writeFile(filename, content, { flag: 'a' }))
15
+ return result
16
+ }
17
+ }
18
+
19
+ export const readAndEmitEventStream = (filename, delayIntervalMs = 0) => {
20
+ const ev = new EventEmitter()
21
+ const fireEvents = async () => {
22
+ const fileStream = createReadStream(filename)
23
+ const rl = createInterface({ input: fileStream, crlfDelay: Infinity })
24
+ for await (const line of rl) {
25
+ if (!line) continue
26
+ const { event, data } = JSON.parse(line)
27
+ ev.emit(event, data)
28
+ if (delayIntervalMs) await delay(delayIntervalMs)
29
+ }
30
+ fileStream.destroy()
31
+ }
32
+ return { ev, task: fireEvents() }
33
33
  }
@@ -1,41 +1,41 @@
1
- import { proto } from '../../WAProto/index.js'
2
- import { BOT_RENDERING_CONFIG_METADATA } from '../Defaults/index.js'
3
-
4
- export const BotCapabilityType = proto.BotCapabilityMetadata.BotCapabilityType
5
- export const RichSubMessageType = proto.AIRichResponseSubMessageType
6
-
7
- const capabilityNames = new Set(Object.keys(BotCapabilityType).filter(n => Number.isNaN(Number(n))))
8
-
9
- export const normalizeBotCapabilities = (capabilities = []) => {
10
- if (!Array.isArray(capabilities)) throw new TypeError('capabilities must be an array')
11
- const values = capabilities.map(c => {
12
- if (typeof c === 'string') { if (!capabilityNames.has(c)) throw new TypeError(`Unknown bot capability: ${c}`); return BotCapabilityType[c] }
13
- if (Number.isInteger(c) && BotCapabilityType[c] !== undefined) return c
14
- throw new TypeError(`Invalid bot capability: ${String(c)}`)
15
- })
16
- return [...new Set(values)]
17
- }
18
-
19
- export const buildBotCapabilityMetadata = (capabilities = []) => ({ capabilities: normalizeBotCapabilities(capabilities) })
20
-
21
- // Use AIRich builder for complex multi-section responses
22
- export const buildBotRichResponse = ({ text, submessages, capabilities = [], botMetadata = {}, botJid = '867051314767696@bot', richResponse = {} } = {}) => {
23
- const resolved = submessages || (text == null ? [] : [{ messageType: proto.AIRichResponseSubMessageType.AI_RICH_RESPONSE_TEXT, messageText: String(text) }])
24
- return {
25
- messageContextInfo: {
26
- botMetadata: { ...botMetadata, capabilityMetadata: buildBotCapabilityMetadata(capabilities), botRenderingConfigMetadata: BOT_RENDERING_CONFIG_METADATA }
27
- },
28
- botForwardedMessage: {
29
- message: {
30
- richResponseMessage: {
31
- messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD,
32
- submessages: resolved,
33
- ...richResponse,
34
- contextInfo: { isForwarded: true, forwardingScore: 1, forwardedAiBotMessageInfo: { botJid }, forwardOrigin: 4, ...(richResponse.contextInfo || {}) }
35
- }
36
- }
37
- }
38
- }
39
- }
40
-
1
+ import { proto } from '../../WAProto/index.js'
2
+ import { BOT_RENDERING_CONFIG_METADATA } from '../Defaults/index.js'
3
+
4
+ export const BotCapabilityType = proto.BotCapabilityMetadata.BotCapabilityType
5
+ export const RichSubMessageType = proto.AIRichResponseSubMessageType
6
+
7
+ const capabilityNames = new Set(Object.keys(BotCapabilityType).filter(n => Number.isNaN(Number(n))))
8
+
9
+ export const normalizeBotCapabilities = (capabilities = []) => {
10
+ if (!Array.isArray(capabilities)) throw new TypeError('capabilities must be an array')
11
+ const values = capabilities.map(c => {
12
+ if (typeof c === 'string') { if (!capabilityNames.has(c)) throw new TypeError(`Unknown bot capability: ${c}`); return BotCapabilityType[c] }
13
+ if (Number.isInteger(c) && BotCapabilityType[c] !== undefined) return c
14
+ throw new TypeError(`Invalid bot capability: ${String(c)}`)
15
+ })
16
+ return [...new Set(values)]
17
+ }
18
+
19
+ export const buildBotCapabilityMetadata = (capabilities = []) => ({ capabilities: normalizeBotCapabilities(capabilities) })
20
+
21
+ // Use AIRich builder for complex multi-section responses
22
+ export const buildBotRichResponse = ({ text, submessages, capabilities = [], botMetadata = {}, botJid = '867051314767696@bot', richResponse = {} } = {}) => {
23
+ const resolved = submessages || (text == null ? [] : [{ messageType: proto.AIRichResponseSubMessageType.AI_RICH_RESPONSE_TEXT, messageText: String(text) }])
24
+ return {
25
+ messageContextInfo: {
26
+ botMetadata: { ...botMetadata, capabilityMetadata: buildBotCapabilityMetadata(capabilities), botRenderingConfigMetadata: BOT_RENDERING_CONFIG_METADATA }
27
+ },
28
+ botForwardedMessage: {
29
+ message: {
30
+ richResponseMessage: {
31
+ messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD,
32
+ submessages: resolved,
33
+ ...richResponse,
34
+ contextInfo: { isForwarded: true, forwardingScore: 1, forwardedAiBotMessageInfo: { botJid }, forwardOrigin: 4, ...(richResponse.contextInfo || {}) }
35
+ }
36
+ }
37
+ }
38
+ }
39
+ }
40
+
41
41
  export const capability = name => { if (!capabilityNames.has(name)) throw new TypeError(`Unknown bot capability: ${name}`); return BotCapabilityType[name] }