@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,81 +1,81 @@
1
- const parseJsonObject = v => {
2
- if (!v) return {}
3
- if (typeof v === 'object') return v
4
- try { const p = JSON.parse(v); return p && typeof p === 'object' ? p : {} } catch { return {} }
5
- }
6
-
7
- export const parseNativeFlowResponse = message => {
8
- const content = message?.message || message
9
- const response = content?.interactiveResponseMessage?.nativeFlowResponseMessage || content?.nativeFlowResponseMessage
10
- if (!response) return null
11
- const params = parseJsonObject(response.paramsJson)
12
- const actionPayload = params.flow_action_payload || params.flowActionPayload || {}
13
- const data = params.data || params.response || params.form_data || params.formData || actionPayload.data || {}
14
- return {
15
- name: response.name || '',
16
- version: response.version,
17
- paramsJson: response.paramsJson || '',
18
- params,
19
- isFlow: response.name === 'galaxy_message' || response.name === 'flow' || !!(params.flow_id || params.flow_token || params.flow_message_version),
20
- flowId: params.flow_id || params.flowId,
21
- flowToken: params.flow_token || params.flowToken,
22
- screen: params.screen || actionPayload.screen,
23
- action: params.flow_action || params.flowAction || actionPayload.action,
24
- actionPayload,
25
- data,
26
- buttonId: params.id || params.button_id || params.buttonId,
27
- displayText: params.display_text || params.displayText,
28
- raw: response,
29
- }
30
- }
31
-
32
- export const parseWhatsAppFlowResponse = message => {
33
- const response = parseNativeFlowResponse(message)
34
- return response?.isFlow ? response : null
35
- }
36
-
37
- export const buildWhatsAppFlowButton = ({ flowId, flowToken, cta = 'Open form', action = 'navigate', actionPayload, mode = 'published', flowMessageVersion = '3', metadata, name = 'galaxy_message' } = {}) => {
38
- if (!flowId) throw new TypeError('flowId is required')
39
- if (!flowToken) throw new TypeError('flowToken is required')
40
- return {
41
- name,
42
- flow_message_version: String(flowMessageVersion),
43
- flow_token: String(flowToken),
44
- flow_id: String(flowId),
45
- flow_cta: String(cta),
46
- flow_action: action,
47
- ...(actionPayload ? { flow_action_payload: actionPayload } : {}),
48
- ...(metadata ? { flow_metadata: metadata } : {}),
49
- }
50
- }
51
-
52
- export const resolveNativeFlowButtons = (rawButtons) => {
53
- const buttons = Array.isArray(rawButtons) ? rawButtons : [rawButtons]
54
- return buttons.map(b => {
55
- if (b.name && b.buttonParamsJson) return b // already formatted
56
- const text = b.text ?? b.display_text ?? ''
57
- if (b.sections) return { name: 'single_select', buttonParamsJson: JSON.stringify({ title: text, sections: b.sections }) }
58
- if (b.url && b.useWebview) return { name: 'cta_open_webview', buttonParamsJson: JSON.stringify({ display_text: text, url: b.url }) }
59
- if (b.url) return { name: 'cta_url', buttonParamsJson: JSON.stringify({ display_text: text, url: b.url, merchant_url: b.merchantUrl ?? b.url }) }
60
- if (b.call) return { name: 'cta_call', buttonParamsJson: JSON.stringify({ display_text: text, phone_number: b.call }) }
61
- if (b.copy) return { name: 'cta_copy', buttonParamsJson: JSON.stringify({ display_text: text, copy_code: b.copy }) }
62
- if (b.flow_id ?? b.flowId) return { name: 'flow', buttonParamsJson: JSON.stringify({ display_text: text, flow_id: b.flow_id ?? b.flowId, flow_token: b.flow_token ?? b.flowToken ?? crypto.randomUUID() }) }
63
- if (b.remind) return { name: 'cta_reminder', buttonParamsJson: JSON.stringify({ display_text: text, ...b.remind }) }
64
- if (b.cancelReminder) return { name: 'cta_cancel_reminder', buttonParamsJson: JSON.stringify({ display_text: text }) }
65
- if (b.location) return { name: 'send_location', buttonParamsJson: JSON.stringify({ display_text: text }) }
66
- if (b.address) return { name: 'address_message', buttonParamsJson: JSON.stringify({ display_text: text }) }
67
- if (b.catalog) return { name: 'catalog_message', buttonParamsJson: JSON.stringify({ display_text: text, ...b.catalog }) }
68
- if (b.reviewAndPay) return { name: 'review_and_pay', buttonParamsJson: JSON.stringify({ display_text: text, ...b.reviewAndPay }) }
69
- if (b.reviewOrder) return { name: 'review_order', buttonParamsJson: JSON.stringify({ display_text: text, ...b.reviewOrder }) }
70
- if (b.orderDetails) return { name: 'order_details', buttonParamsJson: JSON.stringify({ display_text: text, ...b.orderDetails }) }
71
- if (b.paymentStatus) return { name: 'payment_status', buttonParamsJson: JSON.stringify({ display_text: text, ...b.paymentStatus }) }
72
- if (b.transactionDetails) return { name: 'transaction_details', buttonParamsJson: JSON.stringify({ display_text: text, ...b.transactionDetails }) }
73
- // default: quick_reply
74
- return { name: 'quick_reply', buttonParamsJson: JSON.stringify({ display_text: text, id: b.id ?? text }) }
75
- })
76
- }
77
-
78
- export const makeWhatsAppFlowButton = flow => ({
79
- name: flow?.nativeFlowName || 'galaxy_message',
80
- buttonParamsJson: JSON.stringify(buildWhatsAppFlowButton(flow)),
1
+ const parseJsonObject = v => {
2
+ if (!v) return {}
3
+ if (typeof v === 'object') return v
4
+ try { const p = JSON.parse(v); return p && typeof p === 'object' ? p : {} } catch { return {} }
5
+ }
6
+
7
+ export const parseNativeFlowResponse = message => {
8
+ const content = message?.message || message
9
+ const response = content?.interactiveResponseMessage?.nativeFlowResponseMessage || content?.nativeFlowResponseMessage
10
+ if (!response) return null
11
+ const params = parseJsonObject(response.paramsJson)
12
+ const actionPayload = params.flow_action_payload || params.flowActionPayload || {}
13
+ const data = params.data || params.response || params.form_data || params.formData || actionPayload.data || {}
14
+ return {
15
+ name: response.name || '',
16
+ version: response.version,
17
+ paramsJson: response.paramsJson || '',
18
+ params,
19
+ isFlow: response.name === 'galaxy_message' || response.name === 'flow' || !!(params.flow_id || params.flow_token || params.flow_message_version),
20
+ flowId: params.flow_id || params.flowId,
21
+ flowToken: params.flow_token || params.flowToken,
22
+ screen: params.screen || actionPayload.screen,
23
+ action: params.flow_action || params.flowAction || actionPayload.action,
24
+ actionPayload,
25
+ data,
26
+ buttonId: params.id || params.button_id || params.buttonId,
27
+ displayText: params.display_text || params.displayText,
28
+ raw: response,
29
+ }
30
+ }
31
+
32
+ export const parseWhatsAppFlowResponse = message => {
33
+ const response = parseNativeFlowResponse(message)
34
+ return response?.isFlow ? response : null
35
+ }
36
+
37
+ export const buildWhatsAppFlowButton = ({ flowId, flowToken, cta = 'Open form', action = 'navigate', actionPayload, mode = 'published', flowMessageVersion = '3', metadata, name = 'galaxy_message' } = {}) => {
38
+ if (!flowId) throw new TypeError('flowId is required')
39
+ if (!flowToken) throw new TypeError('flowToken is required')
40
+ return {
41
+ name,
42
+ flow_message_version: String(flowMessageVersion),
43
+ flow_token: String(flowToken),
44
+ flow_id: String(flowId),
45
+ flow_cta: String(cta),
46
+ flow_action: action,
47
+ ...(actionPayload ? { flow_action_payload: actionPayload } : {}),
48
+ ...(metadata ? { flow_metadata: metadata } : {}),
49
+ }
50
+ }
51
+
52
+ export const resolveNativeFlowButtons = (rawButtons) => {
53
+ const buttons = Array.isArray(rawButtons) ? rawButtons : [rawButtons]
54
+ return buttons.map(b => {
55
+ if (b.name && b.buttonParamsJson) return b // already formatted
56
+ const text = b.text ?? b.display_text ?? ''
57
+ if (b.sections) return { name: 'single_select', buttonParamsJson: JSON.stringify({ title: text, sections: b.sections }) }
58
+ if (b.url && b.useWebview) return { name: 'cta_open_webview', buttonParamsJson: JSON.stringify({ display_text: text, url: b.url }) }
59
+ if (b.url) return { name: 'cta_url', buttonParamsJson: JSON.stringify({ display_text: text, url: b.url, merchant_url: b.merchantUrl ?? b.url }) }
60
+ if (b.call) return { name: 'cta_call', buttonParamsJson: JSON.stringify({ display_text: text, phone_number: b.call }) }
61
+ if (b.copy) return { name: 'cta_copy', buttonParamsJson: JSON.stringify({ display_text: text, copy_code: b.copy }) }
62
+ if (b.flow_id ?? b.flowId) return { name: 'flow', buttonParamsJson: JSON.stringify({ display_text: text, flow_id: b.flow_id ?? b.flowId, flow_token: b.flow_token ?? b.flowToken ?? crypto.randomUUID() }) }
63
+ if (b.remind) return { name: 'cta_reminder', buttonParamsJson: JSON.stringify({ display_text: text, ...b.remind }) }
64
+ if (b.cancelReminder) return { name: 'cta_cancel_reminder', buttonParamsJson: JSON.stringify({ display_text: text }) }
65
+ if (b.location) return { name: 'send_location', buttonParamsJson: JSON.stringify({ display_text: text }) }
66
+ if (b.address) return { name: 'address_message', buttonParamsJson: JSON.stringify({ display_text: text }) }
67
+ if (b.catalog) return { name: 'catalog_message', buttonParamsJson: JSON.stringify({ display_text: text, ...b.catalog }) }
68
+ if (b.reviewAndPay) return { name: 'review_and_pay', buttonParamsJson: JSON.stringify({ display_text: text, ...b.reviewAndPay }) }
69
+ if (b.reviewOrder) return { name: 'review_order', buttonParamsJson: JSON.stringify({ display_text: text, ...b.reviewOrder }) }
70
+ if (b.orderDetails) return { name: 'order_details', buttonParamsJson: JSON.stringify({ display_text: text, ...b.orderDetails }) }
71
+ if (b.paymentStatus) return { name: 'payment_status', buttonParamsJson: JSON.stringify({ display_text: text, ...b.paymentStatus }) }
72
+ if (b.transactionDetails) return { name: 'transaction_details', buttonParamsJson: JSON.stringify({ display_text: text, ...b.transactionDetails }) }
73
+ // default: quick_reply
74
+ return { name: 'quick_reply', buttonParamsJson: JSON.stringify({ display_text: text, id: b.id ?? text }) }
75
+ })
76
+ }
77
+
78
+ export const makeWhatsAppFlowButton = flow => ({
79
+ name: flow?.nativeFlowName || 'galaxy_message',
80
+ buttonParamsJson: JSON.stringify(buildWhatsAppFlowButton(flow)),
81
81
  })
@@ -1,161 +1,161 @@
1
- import { Boom } from '@hapi/boom'
2
- import { proto } from '../../WAProto/index.js'
3
- import { NOISE_MODE, WA_CERT_DETAILS } from '../Defaults/index.js'
4
- import { decodeBinaryNode } from '../WABinary/index.js'
5
- import { aesDecryptGCM, aesEncryptGCM, Curve, hkdf, sha256 } from './crypto.js'
6
-
7
- const IV_LENGTH = 12
8
- const EMPTY_BUFFER = Buffer.alloc(0)
9
-
10
- class TransportState {
11
- constructor(encKey, decKey) {
12
- this.encKey = encKey
13
- this.decKey = decKey
14
- this.readCounter = 0
15
- this.writeCounter = 0
16
- this.iv = new Uint8Array(IV_LENGTH)
17
- }
18
-
19
- #writeIV(c) {
20
- this.iv[8] = (c >>> 24) & 0xff
21
- this.iv[9] = (c >>> 16) & 0xff
22
- this.iv[10] = (c >>> 8) & 0xff
23
- this.iv[11] = c & 0xff
24
- }
25
-
26
- encrypt(plaintext) { this.#writeIV(this.writeCounter++); return aesEncryptGCM(plaintext, this.encKey, this.iv, EMPTY_BUFFER) }
27
- decrypt(ciphertext) { this.#writeIV(this.readCounter++); return aesDecryptGCM(ciphertext, this.decKey, this.iv, EMPTY_BUFFER) }
28
- }
29
-
30
- const buildIntroHeader = (NOISE_HEADER, routingInfo) => {
31
- if (!routingInfo) return Buffer.from(NOISE_HEADER)
32
- const buf = Buffer.alloc(7 + routingInfo.byteLength + NOISE_HEADER.length)
33
- buf.write('ED', 0, 'utf8')
34
- buf.writeUint8(0, 2)
35
- buf.writeUint8(1, 3)
36
- buf.writeUint8(routingInfo.byteLength >> 16, 4)
37
- buf.writeUint16BE(routingInfo.byteLength & 65535, 5)
38
- buf.set(routingInfo, 7)
39
- buf.set(NOISE_HEADER, 7 + routingInfo.byteLength)
40
- return buf
41
- }
42
-
43
- export const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publicKey }, NOISE_HEADER, logger, routingInfo }) => {
44
- logger = logger.child({ class: 'ns' })
45
-
46
- const data = Buffer.from(NOISE_MODE)
47
- let hash = data.byteLength === 32 ? data : sha256(data)
48
- let salt = hash
49
- let encKey = hash
50
- let decKey = hash
51
- let counter = 0
52
- let sentIntro = false
53
-
54
- let inBytes = Buffer.alloc(0)
55
- let transport = null
56
- let isWaitingForTransport = false
57
- let pendingOnFrame = null
58
-
59
- const introHeader = buildIntroHeader(NOISE_HEADER, routingInfo)
60
-
61
- const generateIV = c => {
62
- const iv = new ArrayBuffer(IV_LENGTH)
63
- new DataView(iv).setUint32(8, c)
64
- return new Uint8Array(iv)
65
- }
66
-
67
- const authenticate = d => { if (!transport) hash = sha256(Buffer.concat([hash, d])) }
68
-
69
- const localHKDF = d => {
70
- const key = hkdf(Buffer.from(d), 64, { salt, info: '' })
71
- return [key.subarray(0, 32), key.subarray(32)]
72
- }
73
-
74
- const mixIntoKey = d => {
75
- const [write, read] = localHKDF(d)
76
- salt = write; encKey = read; decKey = read; counter = 0
77
- }
78
-
79
- const encrypt = plaintext => {
80
- if (transport) return transport.encrypt(plaintext)
81
- const result = aesEncryptGCM(plaintext, encKey, generateIV(counter++), hash)
82
- authenticate(result)
83
- return result
84
- }
85
-
86
- const decrypt = ciphertext => {
87
- if (transport) return transport.decrypt(ciphertext)
88
- const result = aesDecryptGCM(ciphertext, decKey, generateIV(counter++), hash)
89
- authenticate(ciphertext)
90
- return result
91
- }
92
-
93
- const processData = async onFrame => {
94
- while (inBytes.length >= 3) {
95
- const size = (inBytes[0] << 16) | (inBytes[1] << 8) | inBytes[2]
96
- if (inBytes.length < size + 3) return
97
- let frame = inBytes.subarray(3, size + 3)
98
- inBytes = inBytes.subarray(size + 3)
99
- if (transport) frame = await decodeBinaryNode(transport.decrypt(frame))
100
- onFrame(frame)
101
- }
102
- }
103
-
104
- const finishInit = async () => {
105
- isWaitingForTransport = true
106
- const [write, read] = localHKDF(new Uint8Array(0))
107
- transport = new TransportState(write, read)
108
- isWaitingForTransport = false
109
- if (pendingOnFrame) { await processData(pendingOnFrame); pendingOnFrame = null }
110
- }
111
-
112
- authenticate(NOISE_HEADER)
113
- authenticate(publicKey)
114
-
115
- return {
116
- encrypt,
117
- decrypt,
118
- authenticate,
119
- mixIntoKey,
120
- finishInit,
121
- processHandshake: ({ serverHello }, noiseKey) => {
122
- authenticate(serverHello.ephemeral)
123
- mixIntoKey(Curve.sharedKey(privateKey, serverHello.ephemeral))
124
-
125
- const decStaticContent = decrypt(serverHello.static)
126
- mixIntoKey(Curve.sharedKey(privateKey, decStaticContent))
127
-
128
- const { intermediate: certIntermediate, leaf } = proto.CertChain.decode(decrypt(serverHello.payload))
129
-
130
- if (!leaf?.details || !leaf?.signature) throw new Boom('invalid noise leaf certificate', { statusCode: 400 })
131
- if (!certIntermediate?.details || !certIntermediate?.signature) throw new Boom('invalid noise intermediate certificate', { statusCode: 400 })
132
-
133
- const details = proto.CertChain.NoiseCertificate.Details.decode(certIntermediate.details)
134
-
135
- if (!Curve.verify(details.key, leaf.details, leaf.signature)) throw new Boom('noise certificate signature invalid', { statusCode: 400 })
136
- if (!Curve.verify(WA_CERT_DETAILS.PUBLIC_KEY, certIntermediate.details, certIntermediate.signature)) throw new Boom('noise intermediate certificate signature invalid', { statusCode: 400 })
137
- if (details.issuerSerial !== WA_CERT_DETAILS.SERIAL) throw new Boom('certification match failed', { statusCode: 400 })
138
-
139
- const keyEnc = encrypt(noiseKey.public)
140
- mixIntoKey(Curve.sharedKey(noiseKey.private, serverHello.ephemeral))
141
- return keyEnc
142
- },
143
- encodeFrame: data => {
144
- if (transport) data = transport.encrypt(data)
145
- const dataLen = data.byteLength
146
- const introSize = sentIntro ? 0 : introHeader.length
147
- const frame = Buffer.allocUnsafe(introSize + 3 + dataLen)
148
- if (!sentIntro) { frame.set(introHeader); sentIntro = true }
149
- frame[introSize] = (dataLen >>> 16) & 0xff
150
- frame[introSize + 1] = (dataLen >>> 8) & 0xff
151
- frame[introSize + 2] = dataLen & 0xff
152
- frame.set(data, introSize + 3)
153
- return frame
154
- },
155
- decodeFrame: async (newData, onFrame) => {
156
- if (isWaitingForTransport) { inBytes = Buffer.concat([inBytes, newData]); pendingOnFrame = onFrame; return }
157
- inBytes = inBytes.length === 0 ? Buffer.from(newData) : Buffer.concat([inBytes, newData])
158
- await processData(onFrame)
159
- },
160
- }
1
+ import { Boom } from '@hapi/boom'
2
+ import { proto } from '../../WAProto/index.js'
3
+ import { NOISE_MODE, WA_CERT_DETAILS } from '../Defaults/index.js'
4
+ import { decodeBinaryNode } from '../WABinary/index.js'
5
+ import { aesDecryptGCM, aesEncryptGCM, Curve, hkdf, sha256 } from './crypto.js'
6
+
7
+ const IV_LENGTH = 12
8
+ const EMPTY_BUFFER = Buffer.alloc(0)
9
+
10
+ class TransportState {
11
+ constructor(encKey, decKey) {
12
+ this.encKey = encKey
13
+ this.decKey = decKey
14
+ this.readCounter = 0
15
+ this.writeCounter = 0
16
+ this.iv = new Uint8Array(IV_LENGTH)
17
+ }
18
+
19
+ #writeIV(c) {
20
+ this.iv[8] = (c >>> 24) & 0xff
21
+ this.iv[9] = (c >>> 16) & 0xff
22
+ this.iv[10] = (c >>> 8) & 0xff
23
+ this.iv[11] = c & 0xff
24
+ }
25
+
26
+ encrypt(plaintext) { this.#writeIV(this.writeCounter++); return aesEncryptGCM(plaintext, this.encKey, this.iv, EMPTY_BUFFER) }
27
+ decrypt(ciphertext) { this.#writeIV(this.readCounter++); return aesDecryptGCM(ciphertext, this.decKey, this.iv, EMPTY_BUFFER) }
28
+ }
29
+
30
+ const buildIntroHeader = (NOISE_HEADER, routingInfo) => {
31
+ if (!routingInfo) return Buffer.from(NOISE_HEADER)
32
+ const buf = Buffer.alloc(7 + routingInfo.byteLength + NOISE_HEADER.length)
33
+ buf.write('ED', 0, 'utf8')
34
+ buf.writeUint8(0, 2)
35
+ buf.writeUint8(1, 3)
36
+ buf.writeUint8(routingInfo.byteLength >> 16, 4)
37
+ buf.writeUint16BE(routingInfo.byteLength & 65535, 5)
38
+ buf.set(routingInfo, 7)
39
+ buf.set(NOISE_HEADER, 7 + routingInfo.byteLength)
40
+ return buf
41
+ }
42
+
43
+ export const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publicKey }, NOISE_HEADER, logger, routingInfo }) => {
44
+ logger = logger.child({ class: 'ns' })
45
+
46
+ const data = Buffer.from(NOISE_MODE)
47
+ let hash = data.byteLength === 32 ? data : sha256(data)
48
+ let salt = hash
49
+ let encKey = hash
50
+ let decKey = hash
51
+ let counter = 0
52
+ let sentIntro = false
53
+
54
+ let inBytes = Buffer.alloc(0)
55
+ let transport = null
56
+ let isWaitingForTransport = false
57
+ let pendingOnFrame = null
58
+
59
+ const introHeader = buildIntroHeader(NOISE_HEADER, routingInfo)
60
+
61
+ const generateIV = c => {
62
+ const iv = new ArrayBuffer(IV_LENGTH)
63
+ new DataView(iv).setUint32(8, c)
64
+ return new Uint8Array(iv)
65
+ }
66
+
67
+ const authenticate = d => { if (!transport) hash = sha256(Buffer.concat([hash, d])) }
68
+
69
+ const localHKDF = d => {
70
+ const key = hkdf(Buffer.from(d), 64, { salt, info: '' })
71
+ return [key.subarray(0, 32), key.subarray(32)]
72
+ }
73
+
74
+ const mixIntoKey = d => {
75
+ const [write, read] = localHKDF(d)
76
+ salt = write; encKey = read; decKey = read; counter = 0
77
+ }
78
+
79
+ const encrypt = plaintext => {
80
+ if (transport) return transport.encrypt(plaintext)
81
+ const result = aesEncryptGCM(plaintext, encKey, generateIV(counter++), hash)
82
+ authenticate(result)
83
+ return result
84
+ }
85
+
86
+ const decrypt = ciphertext => {
87
+ if (transport) return transport.decrypt(ciphertext)
88
+ const result = aesDecryptGCM(ciphertext, decKey, generateIV(counter++), hash)
89
+ authenticate(ciphertext)
90
+ return result
91
+ }
92
+
93
+ const processData = async onFrame => {
94
+ while (inBytes.length >= 3) {
95
+ const size = (inBytes[0] << 16) | (inBytes[1] << 8) | inBytes[2]
96
+ if (inBytes.length < size + 3) return
97
+ let frame = inBytes.subarray(3, size + 3)
98
+ inBytes = inBytes.subarray(size + 3)
99
+ if (transport) frame = await decodeBinaryNode(transport.decrypt(frame))
100
+ onFrame(frame)
101
+ }
102
+ }
103
+
104
+ const finishInit = async () => {
105
+ isWaitingForTransport = true
106
+ const [write, read] = localHKDF(new Uint8Array(0))
107
+ transport = new TransportState(write, read)
108
+ isWaitingForTransport = false
109
+ if (pendingOnFrame) { await processData(pendingOnFrame); pendingOnFrame = null }
110
+ }
111
+
112
+ authenticate(NOISE_HEADER)
113
+ authenticate(publicKey)
114
+
115
+ return {
116
+ encrypt,
117
+ decrypt,
118
+ authenticate,
119
+ mixIntoKey,
120
+ finishInit,
121
+ processHandshake: ({ serverHello }, noiseKey) => {
122
+ authenticate(serverHello.ephemeral)
123
+ mixIntoKey(Curve.sharedKey(privateKey, serverHello.ephemeral))
124
+
125
+ const decStaticContent = decrypt(serverHello.static)
126
+ mixIntoKey(Curve.sharedKey(privateKey, decStaticContent))
127
+
128
+ const { intermediate: certIntermediate, leaf } = proto.CertChain.decode(decrypt(serverHello.payload))
129
+
130
+ if (!leaf?.details || !leaf?.signature) throw new Boom('invalid noise leaf certificate', { statusCode: 400 })
131
+ if (!certIntermediate?.details || !certIntermediate?.signature) throw new Boom('invalid noise intermediate certificate', { statusCode: 400 })
132
+
133
+ const details = proto.CertChain.NoiseCertificate.Details.decode(certIntermediate.details)
134
+
135
+ if (!Curve.verify(details.key, leaf.details, leaf.signature)) throw new Boom('noise certificate signature invalid', { statusCode: 400 })
136
+ if (!Curve.verify(WA_CERT_DETAILS.PUBLIC_KEY, certIntermediate.details, certIntermediate.signature)) throw new Boom('noise intermediate certificate signature invalid', { statusCode: 400 })
137
+ if (details.issuerSerial !== WA_CERT_DETAILS.SERIAL) throw new Boom('certification match failed', { statusCode: 400 })
138
+
139
+ const keyEnc = encrypt(noiseKey.public)
140
+ mixIntoKey(Curve.sharedKey(noiseKey.private, serverHello.ephemeral))
141
+ return keyEnc
142
+ },
143
+ encodeFrame: data => {
144
+ if (transport) data = transport.encrypt(data)
145
+ const dataLen = data.byteLength
146
+ const introSize = sentIntro ? 0 : introHeader.length
147
+ const frame = Buffer.allocUnsafe(introSize + 3 + dataLen)
148
+ if (!sentIntro) { frame.set(introHeader); sentIntro = true }
149
+ frame[introSize] = (dataLen >>> 16) & 0xff
150
+ frame[introSize + 1] = (dataLen >>> 8) & 0xff
151
+ frame[introSize + 2] = dataLen & 0xff
152
+ frame.set(data, introSize + 3)
153
+ return frame
154
+ },
155
+ decodeFrame: async (newData, onFrame) => {
156
+ if (isWaitingForTransport) { inBytes = Buffer.concat([inBytes, newData]); pendingOnFrame = onFrame; return }
157
+ inBytes = inBytes.length === 0 ? Buffer.from(newData) : Buffer.concat([inBytes, newData])
158
+ await processData(onFrame)
159
+ },
160
+ }
161
161
  }
@@ -1,76 +1,76 @@
1
- import PQueue from 'p-queue'
2
-
3
- export class PreKeyManager {
4
- constructor(store, logger) {
5
- this.store = store
6
- this.logger = logger
7
- this.queues = new Map()
8
- }
9
-
10
- getQueue(keyType) {
11
- if (!this.queues.has(keyType)) this.queues.set(keyType, new PQueue({ concurrency: 1 }))
12
- return this.queues.get(keyType)
13
- }
14
-
15
- async processOperations(data, keyType, transactionCache, mutations, isInTransaction) {
16
- const keyData = data[keyType]
17
- if (!keyData) return
18
- return this.getQueue(keyType).add(async () => {
19
- transactionCache[keyType] ||= {}
20
- mutations[keyType] ||= {}
21
-
22
- const deletions = []
23
- const updates = {}
24
- for (const keyId in keyData) {
25
- if (keyData[keyId] === null) deletions.push(keyId)
26
- else updates[keyId] = keyData[keyId]
27
- }
28
-
29
- if (Object.keys(updates).length > 0) {
30
- Object.assign(transactionCache[keyType], updates)
31
- Object.assign(mutations[keyType], updates)
32
- }
33
-
34
- if (deletions.length > 0) await this.processDeletions(keyType, deletions, transactionCache, mutations, isInTransaction)
35
- })
36
- }
37
-
38
- async processDeletions(keyType, ids, transactionCache, mutations, isInTransaction) {
39
- if (isInTransaction) {
40
- for (const keyId of ids) {
41
- if (transactionCache[keyType]?.[keyId]) {
42
- transactionCache[keyType][keyId] = null
43
- mutations[keyType][keyId] = null
44
- } else {
45
- this.logger.warn(`Skipping deletion of non-existent ${keyType} in transaction: ${keyId}`)
46
- }
47
- }
48
- } else {
49
- const existingKeys = await this.store.get(keyType, ids)
50
- for (const keyId of ids) {
51
- if (existingKeys[keyId]) {
52
- transactionCache[keyType][keyId] = null
53
- mutations[keyType][keyId] = null
54
- } else {
55
- this.logger.warn(`Skipping deletion of non-existent ${keyType}: ${keyId}`)
56
- }
57
- }
58
- }
59
- }
60
-
61
- async validateDeletions(data, keyType) {
62
- const keyData = data[keyType]
63
- if (!keyData) return
64
- return this.getQueue(keyType).add(async () => {
65
- const deletionIds = Object.keys(keyData).filter(id => keyData[id] === null)
66
- if (deletionIds.length === 0) return
67
- const existingKeys = await this.store.get(keyType, deletionIds)
68
- for (const keyId of deletionIds) {
69
- if (!existingKeys[keyId]) {
70
- this.logger.warn(`Skipping deletion of non-existent ${keyType}: ${keyId}`)
71
- delete data[keyType][keyId]
72
- }
73
- }
74
- })
75
- }
1
+ import PQueue from 'p-queue'
2
+
3
+ export class PreKeyManager {
4
+ constructor(store, logger) {
5
+ this.store = store
6
+ this.logger = logger
7
+ this.queues = new Map()
8
+ }
9
+
10
+ getQueue(keyType) {
11
+ if (!this.queues.has(keyType)) this.queues.set(keyType, new PQueue({ concurrency: 1 }))
12
+ return this.queues.get(keyType)
13
+ }
14
+
15
+ async processOperations(data, keyType, transactionCache, mutations, isInTransaction) {
16
+ const keyData = data[keyType]
17
+ if (!keyData) return
18
+ return this.getQueue(keyType).add(async () => {
19
+ transactionCache[keyType] ||= {}
20
+ mutations[keyType] ||= {}
21
+
22
+ const deletions = []
23
+ const updates = {}
24
+ for (const keyId in keyData) {
25
+ if (keyData[keyId] === null) deletions.push(keyId)
26
+ else updates[keyId] = keyData[keyId]
27
+ }
28
+
29
+ if (Object.keys(updates).length > 0) {
30
+ Object.assign(transactionCache[keyType], updates)
31
+ Object.assign(mutations[keyType], updates)
32
+ }
33
+
34
+ if (deletions.length > 0) await this.processDeletions(keyType, deletions, transactionCache, mutations, isInTransaction)
35
+ })
36
+ }
37
+
38
+ async processDeletions(keyType, ids, transactionCache, mutations, isInTransaction) {
39
+ if (isInTransaction) {
40
+ for (const keyId of ids) {
41
+ if (transactionCache[keyType]?.[keyId]) {
42
+ transactionCache[keyType][keyId] = null
43
+ mutations[keyType][keyId] = null
44
+ } else {
45
+ this.logger.warn(`Skipping deletion of non-existent ${keyType} in transaction: ${keyId}`)
46
+ }
47
+ }
48
+ } else {
49
+ const existingKeys = await this.store.get(keyType, ids)
50
+ for (const keyId of ids) {
51
+ if (existingKeys[keyId]) {
52
+ transactionCache[keyType][keyId] = null
53
+ mutations[keyType][keyId] = null
54
+ } else {
55
+ this.logger.warn(`Skipping deletion of non-existent ${keyType}: ${keyId}`)
56
+ }
57
+ }
58
+ }
59
+ }
60
+
61
+ async validateDeletions(data, keyType) {
62
+ const keyData = data[keyType]
63
+ if (!keyData) return
64
+ return this.getQueue(keyType).add(async () => {
65
+ const deletionIds = Object.keys(keyData).filter(id => keyData[id] === null)
66
+ if (deletionIds.length === 0) return
67
+ const existingKeys = await this.store.get(keyType, deletionIds)
68
+ for (const keyId of deletionIds) {
69
+ if (!existingKeys[keyId]) {
70
+ this.logger.warn(`Skipping deletion of non-existent ${keyType}: ${keyId}`)
71
+ delete data[keyType][keyId]
72
+ }
73
+ }
74
+ })
75
+ }
76
76
  }