@skycodee/baileys 8.0.4 → 8.0.6

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 (224) hide show
  1. package/LICENSE +1 -1
  2. package/WAProto/WAProto.proto +352 -520
  3. package/WAProto/index.js +558 -4154
  4. package/lib/Defaults/index.js +123 -0
  5. package/lib/Defaults/index.js.bak +123 -0
  6. package/lib/KeyDB/BinarySearch.js +20 -0
  7. package/lib/KeyDB/KeyedDB.js +167 -0
  8. package/lib/KeyDB/index.js +4 -0
  9. package/lib/Signal/Group/ciphertext-message.js +13 -0
  10. package/lib/Signal/Group/group-session-builder.js +32 -0
  11. package/lib/Signal/Group/group_cipher.js +84 -0
  12. package/lib/Signal/Group/index.js +13 -0
  13. package/lib/Signal/Group/keyhelper.js +20 -0
  14. package/lib/Signal/Group/sender-chain-key.js +28 -0
  15. package/lib/Signal/Group/sender-key-distribution-message.js +65 -0
  16. package/lib/Signal/Group/sender-key-message.js +68 -0
  17. package/lib/Signal/Group/sender-key-name.js +52 -0
  18. package/lib/Signal/Group/sender-key-record.js +43 -0
  19. package/lib/Signal/Group/sender-key-state.js +86 -0
  20. package/lib/Signal/Group/sender-message-key.js +28 -0
  21. package/lib/Signal/libsignal.js +324 -0
  22. package/lib/Signal/lid-mapping.js +155 -0
  23. package/lib/Socket/Client/index.js +4 -0
  24. package/lib/Socket/Client/types.js +13 -0
  25. package/lib/Socket/Client/websocket.js +52 -0
  26. package/lib/Socket/Client/websocket.js.bak +53 -0
  27. package/lib/Socket/business.js +377 -0
  28. package/lib/Socket/chats.js +885 -0
  29. package/lib/Socket/communities.js +413 -0
  30. package/lib/Socket/groups.js +312 -0
  31. package/lib/Socket/index.js +16 -0
  32. package/lib/Socket/messages-recv.js +1163 -0
  33. package/lib/Socket/messages-send.js +1100 -0
  34. package/lib/Socket/mex.js +45 -0
  35. package/lib/Socket/newsletter.js +247 -0
  36. package/lib/Socket/socket.js +820 -0
  37. package/lib/Store/index.js +6 -0
  38. package/lib/Store/make-cache-manager-store.js +75 -0
  39. package/lib/Store/make-in-memory-store.js +290 -0
  40. package/lib/Store/make-ordered-dictionary.js +79 -0
  41. package/lib/Store/object-repository.js +25 -0
  42. package/lib/Types/Auth.js +3 -0
  43. package/lib/Types/Bussines.js +3 -0
  44. package/lib/Types/Call.js +3 -0
  45. package/lib/Types/Chat.js +9 -0
  46. package/lib/Types/Contact.js +3 -0
  47. package/lib/Types/Events.js +3 -0
  48. package/lib/Types/GroupMetadata.js +3 -0
  49. package/lib/Types/Label.js +25 -0
  50. package/lib/Types/LabelAssociation.js +7 -0
  51. package/lib/Types/Message.js +12 -0
  52. package/lib/Types/Newsletter.js +33 -0
  53. package/lib/Types/Newsletter.js.bak +33 -0
  54. package/lib/Types/Product.js +3 -0
  55. package/lib/Types/Signal.js +3 -0
  56. package/lib/Types/Socket.js +4 -0
  57. package/lib/Types/State.js +11 -0
  58. package/lib/Types/USync.js +3 -0
  59. package/lib/Types/index.js +28 -0
  60. package/lib/Utils/auth-utils.js +219 -0
  61. package/lib/Utils/baileys-event-stream.js +44 -0
  62. package/lib/Utils/browser-utils.js +25 -0
  63. package/lib/Utils/business.js +233 -0
  64. package/lib/Utils/chat-utils.js +752 -0
  65. package/lib/Utils/crypto.js +130 -0
  66. package/lib/Utils/decode-wa-message.js +267 -0
  67. package/lib/Utils/event-buffer.js +528 -0
  68. package/lib/Utils/generics.js +355 -0
  69. package/lib/Utils/history.js +87 -0
  70. package/lib/Utils/index.js +21 -0
  71. package/lib/Utils/link-preview.js +81 -0
  72. package/lib/Utils/logger.js +5 -0
  73. package/lib/Utils/lt-hash.js +45 -0
  74. package/lib/Utils/make-mutex.js +36 -0
  75. package/lib/Utils/message-retry-manager.js +113 -0
  76. package/lib/Utils/messages-media.js +627 -0
  77. package/lib/Utils/messages.js +909 -0
  78. package/lib/Utils/noise-handler.js +144 -0
  79. package/lib/Utils/pre-key-manager.js +85 -0
  80. package/lib/Utils/process-message.js +341 -0
  81. package/lib/Utils/signal.js +161 -0
  82. package/lib/Utils/use-multi-file-auth-state.js +111 -0
  83. package/lib/Utils/validate-connection.js +200 -0
  84. package/lib/WABinary/constants.js +1303 -0
  85. package/lib/WABinary/decode.js +240 -0
  86. package/lib/WABinary/encode.js +218 -0
  87. package/lib/WABinary/generic-utils.js +189 -0
  88. package/lib/WABinary/index.js +7 -0
  89. package/lib/WABinary/jid-utils.js +93 -0
  90. package/lib/WABinary/types.js +3 -0
  91. package/lib/WAM/BinaryInfo.js +11 -0
  92. package/lib/WAM/constants.js +22853 -0
  93. package/lib/WAM/encode.js +154 -0
  94. package/lib/WAM/index.js +5 -0
  95. package/lib/WAUSync/Protocols/USyncContactProtocol.js +30 -0
  96. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  97. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +29 -0
  98. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +39 -0
  99. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  100. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +30 -0
  101. package/lib/WAUSync/Protocols/index.js +6 -0
  102. package/lib/WAUSync/USyncQuery.js +90 -0
  103. package/lib/WAUSync/USyncUser.js +24 -0
  104. package/lib/WAUSync/index.js +5 -0
  105. package/lib/index.js +21 -0
  106. package/package.json +84 -57
  107. package/README.md +0 -1312
  108. package/WAProto/GenerateStatics.sh +0 -3
  109. package/WAProto/fix-imports.js +0 -81
  110. package/WAProto/index.d.ts +0 -14017
  111. package/engine-requirements.js +0 -10
  112. package/src/Defaults/baileys-version.json +0 -1
  113. package/src/Defaults/index.ts +0 -149
  114. package/src/Signal/Group/ciphertext-message.ts +0 -9
  115. package/src/Signal/Group/group-session-builder.ts +0 -56
  116. package/src/Signal/Group/group_cipher.ts +0 -117
  117. package/src/Signal/Group/index.ts +0 -11
  118. package/src/Signal/Group/keyhelper.ts +0 -28
  119. package/src/Signal/Group/sender-chain-key.ts +0 -34
  120. package/src/Signal/Group/sender-key-distribution-message.ts +0 -95
  121. package/src/Signal/Group/sender-key-message.ts +0 -96
  122. package/src/Signal/Group/sender-key-name.ts +0 -66
  123. package/src/Signal/Group/sender-key-record.ts +0 -69
  124. package/src/Signal/Group/sender-key-state.ts +0 -134
  125. package/src/Signal/Group/sender-message-key.ts +0 -36
  126. package/src/Signal/libsignal.ts +0 -521
  127. package/src/Signal/lid-mapping.ts +0 -328
  128. package/src/Socket/Client/index.ts +0 -2
  129. package/src/Socket/Client/types.ts +0 -22
  130. package/src/Socket/Client/websocket.ts +0 -63
  131. package/src/Socket/business.ts +0 -424
  132. package/src/Socket/chats.ts +0 -1272
  133. package/src/Socket/communities.ts +0 -477
  134. package/src/Socket/groups.ts +0 -361
  135. package/src/Socket/index.ts +0 -15
  136. package/src/Socket/messages-recv.ts +0 -1668
  137. package/src/Socket/messages-send.ts +0 -1296
  138. package/src/Socket/mex.ts +0 -58
  139. package/src/Socket/newsletter.ts +0 -229
  140. package/src/Socket/socket.ts +0 -1184
  141. package/src/Types/Auth.ts +0 -116
  142. package/src/Types/Bussines.ts +0 -20
  143. package/src/Types/Call.ts +0 -15
  144. package/src/Types/Chat.ts +0 -138
  145. package/src/Types/Contact.ts +0 -24
  146. package/src/Types/Events.ts +0 -159
  147. package/src/Types/GroupMetadata.ts +0 -70
  148. package/src/Types/Label.ts +0 -48
  149. package/src/Types/LabelAssociation.ts +0 -35
  150. package/src/Types/Message.ts +0 -380
  151. package/src/Types/Newsletter.ts +0 -98
  152. package/src/Types/Product.ts +0 -85
  153. package/src/Types/Signal.ts +0 -76
  154. package/src/Types/Socket.ts +0 -150
  155. package/src/Types/State.ts +0 -43
  156. package/src/Types/USync.ts +0 -27
  157. package/src/Types/globals.d.ts +0 -8
  158. package/src/Types/index.ts +0 -67
  159. package/src/Utils/auth-utils.ts +0 -368
  160. package/src/Utils/browser-utils.ts +0 -31
  161. package/src/Utils/business.ts +0 -286
  162. package/src/Utils/chat-utils.ts +0 -974
  163. package/src/Utils/crypto.ts +0 -147
  164. package/src/Utils/decode-wa-message.ts +0 -355
  165. package/src/Utils/event-buffer.ts +0 -692
  166. package/src/Utils/generics.ts +0 -474
  167. package/src/Utils/history.ts +0 -161
  168. package/src/Utils/identity-change-handler.ts +0 -83
  169. package/src/Utils/index.ts +0 -19
  170. package/src/Utils/link-preview.ts +0 -111
  171. package/src/Utils/logger.ts +0 -13
  172. package/src/Utils/lt-hash.ts +0 -8
  173. package/src/Utils/make-mutex.ts +0 -42
  174. package/src/Utils/message-retry-manager.ts +0 -295
  175. package/src/Utils/messages-media.ts +0 -984
  176. package/src/Utils/messages.ts +0 -1097
  177. package/src/Utils/noise-handler.ts +0 -268
  178. package/src/Utils/pre-key-manager.ts +0 -126
  179. package/src/Utils/process-message.ts +0 -670
  180. package/src/Utils/reporting-utils.ts +0 -344
  181. package/src/Utils/signal.ts +0 -214
  182. package/src/Utils/sync-action-utils.ts +0 -74
  183. package/src/Utils/tc-token-utils.ts +0 -34
  184. package/src/Utils/use-multi-file-auth-state.ts +0 -136
  185. package/src/Utils/validate-connection.ts +0 -253
  186. package/src/WABinary/constants.ts +0 -1305
  187. package/src/WABinary/decode.ts +0 -308
  188. package/src/WABinary/encode.ts +0 -258
  189. package/src/WABinary/generic-utils.ts +0 -141
  190. package/src/WABinary/index.ts +0 -5
  191. package/src/WABinary/jid-utils.ts +0 -128
  192. package/src/WABinary/types.ts +0 -17
  193. package/src/WAM/BinaryInfo.ts +0 -12
  194. package/src/WAM/constants.ts +0 -22889
  195. package/src/WAM/encode.ts +0 -169
  196. package/src/WAM/index.ts +0 -3
  197. package/src/WAUSync/Protocols/USyncContactProtocol.ts +0 -32
  198. package/src/WAUSync/Protocols/USyncDeviceProtocol.ts +0 -78
  199. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.ts +0 -35
  200. package/src/WAUSync/Protocols/USyncStatusProtocol.ts +0 -44
  201. package/src/WAUSync/Protocols/UsyncBotProfileProtocol.ts +0 -76
  202. package/src/WAUSync/Protocols/UsyncLIDProtocol.ts +0 -33
  203. package/src/WAUSync/Protocols/index.ts +0 -4
  204. package/src/WAUSync/USyncQuery.ts +0 -133
  205. package/src/WAUSync/USyncUser.ts +0 -32
  206. package/src/WAUSync/index.ts +0 -3
  207. package/src/__tests__/Signal/Group/sender-key-state-regression.test.ts +0 -22
  208. package/src/__tests__/Signal/lid-mapping.test.ts +0 -47
  209. package/src/__tests__/Socket/identity-change-handling.test.ts +0 -207
  210. package/src/__tests__/TestUtils/session.ts +0 -47
  211. package/src/__tests__/Utils/generics.test.ts +0 -70
  212. package/src/__tests__/Utils/history.test.ts +0 -362
  213. package/src/__tests__/Utils/messages-media.test.ts +0 -405
  214. package/src/__tests__/Utils/noise-handler.test.ts +0 -339
  215. package/src/__tests__/Utils/process-message.test.ts +0 -138
  216. package/src/__tests__/Utils/process-sync-action.test.ts +0 -359
  217. package/src/__tests__/Utils/reporting-utils.test.ts +0 -160
  218. package/src/__tests__/Utils/signal.test.ts +0 -69
  219. package/src/__tests__/Utils/sync-action-utils.test.ts +0 -183
  220. package/src/__tests__/binary/connection-deadlock.test.ts +0 -54
  221. package/src/__tests__/e2e/fetch-wa-web-version.test-e2e.ts +0 -60
  222. package/src/__tests__/e2e/send-receive-message.test-e2e.ts +0 -644
  223. package/src/__tests__/proto-tojson-long.test.ts +0 -31
  224. package/src/index.ts +0 -13
@@ -1,10 +0,0 @@
1
- const major = parseInt(process.versions.node.split('.')[0], 10);
2
-
3
- if (major < 20) {
4
- console.error(
5
- `\n❌ This package requires Node.js 20+ to run reliably.\n` +
6
- ` You are using Node.js ${process.versions.node}.\n` +
7
- ` Please upgrade to Node.js 20+ to proceed.\n`
8
- );
9
- process.exit(1);
10
- }
@@ -1 +0,0 @@
1
- {"version":[2,3000,1033846690]}
@@ -1,149 +0,0 @@
1
- import { proto } from '../../WAProto/index.js'
2
- import { makeLibSignalRepository } from '../Signal/libsignal'
3
- import type { AuthenticationState, SocketConfig, WAVersion } from '../Types'
4
- import { Browsers } from '../Utils/browser-utils'
5
- import logger from '../Utils/logger'
6
-
7
- const version = [2, 3000, 1033846690]
8
-
9
- export const UNAUTHORIZED_CODES = [401, 403, 419]
10
-
11
- export const DEFAULT_ORIGIN = 'https://web.whatsapp.com'
12
- export const CALL_VIDEO_PREFIX = 'https://call.whatsapp.com/video/'
13
- export const CALL_AUDIO_PREFIX = 'https://call.whatsapp.com/voice/'
14
- export const DEF_CALLBACK_PREFIX = 'CB:'
15
- export const DEF_TAG_PREFIX = 'TAG:'
16
- export const PHONE_CONNECTION_CB = 'CB:Pong'
17
-
18
- export const WA_ADV_ACCOUNT_SIG_PREFIX = Buffer.from([6, 0])
19
- export const WA_ADV_DEVICE_SIG_PREFIX = Buffer.from([6, 1])
20
- export const WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX = Buffer.from([6, 5])
21
- export const WA_ADV_HOSTED_DEVICE_SIG_PREFIX = Buffer.from([6, 6])
22
-
23
- export const WA_DEFAULT_EPHEMERAL = 7 * 24 * 60 * 60
24
-
25
- /** Status messages older than 24 hours are considered expired */
26
- export const STATUS_EXPIRY_SECONDS = 24 * 60 * 60
27
-
28
- /** WA Web enforces a 14-day maximum age for placeholder resend requests */
29
- export const PLACEHOLDER_MAX_AGE_SECONDS = 14 * 24 * 60 * 60
30
-
31
- export const NOISE_MODE = 'Noise_XX_25519_AESGCM_SHA256\0\0\0\0'
32
- export const DICT_VERSION = 3
33
- export const KEY_BUNDLE_TYPE = Buffer.from([5])
34
- export const NOISE_WA_HEADER = Buffer.from([87, 65, 6, DICT_VERSION]) // last is "DICT_VERSION"
35
- /** from: https://stackoverflow.com/questions/3809401/what-is-a-good-regular-expression-to-match-a-url */
36
- export const URL_REGEX = /https:\/\/(?![^:@\/\s]+:[^:@\/\s]+@)[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(:\d+)?(\/[^\s]*)?/g
37
-
38
- export const WA_CERT_DETAILS = {
39
- SERIAL: 0,
40
- ISSUER: 'WhatsAppLongTerm1',
41
- PUBLIC_KEY: Buffer.from('142375574d0a587166aae71ebe516437c4a28b73e3695c6ce1f7f9545da8ee6b', 'hex')
42
- }
43
-
44
- export const PROCESSABLE_HISTORY_TYPES = [
45
- proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP,
46
- proto.HistorySync.HistorySyncType.PUSH_NAME,
47
- proto.HistorySync.HistorySyncType.RECENT,
48
- proto.HistorySync.HistorySyncType.FULL,
49
- proto.HistorySync.HistorySyncType.ON_DEMAND,
50
- proto.HistorySync.HistorySyncType.NON_BLOCKING_DATA,
51
- proto.HistorySync.HistorySyncType.INITIAL_STATUS_V3
52
- ]
53
-
54
- export const DEFAULT_CONNECTION_CONFIG: SocketConfig = {
55
- version: version as WAVersion,
56
- browser: Browsers.macOS('Chrome'),
57
- waWebSocketUrl: 'wss://web.whatsapp.com/ws/chat',
58
- connectTimeoutMs: 20_000,
59
- keepAliveIntervalMs: 30_000,
60
- logger: logger.child({ class: 'baileys' }),
61
- emitOwnEvents: true,
62
- defaultQueryTimeoutMs: 60_000,
63
- customUploadHosts: [],
64
- retryRequestDelayMs: 250,
65
- maxMsgRetryCount: 5,
66
- fireInitQueries: true,
67
- auth: undefined as unknown as AuthenticationState,
68
- markOnlineOnConnect: true,
69
- syncFullHistory: true,
70
- patchMessageBeforeSending: msg => msg,
71
- shouldSyncHistoryMessage: ({ syncType }: proto.Message.IHistorySyncNotification) => {
72
- return syncType !== proto.HistorySync.HistorySyncType.FULL
73
- },
74
- shouldIgnoreJid: () => false,
75
- linkPreviewImageThumbnailWidth: 192,
76
- transactionOpts: { maxCommitRetries: 10, delayBetweenTriesMs: 3000 },
77
- generateHighQualityLinkPreview: false,
78
- enableAutoSessionRecreation: true,
79
- enableRecentMessageCache: true,
80
- options: {},
81
- appStateMacVerification: {
82
- patch: false,
83
- snapshot: false
84
- },
85
- countryCode: 'US',
86
- getMessage: async () => undefined,
87
- cachedGroupMetadata: async () => undefined,
88
- makeSignalRepository: makeLibSignalRepository
89
- }
90
-
91
- export const MEDIA_PATH_MAP: { [T in MediaType]?: string } = {
92
- image: '/mms/image',
93
- video: '/mms/video',
94
- document: '/mms/document',
95
- audio: '/mms/audio',
96
- sticker: '/mms/image',
97
- 'thumbnail-link': '/mms/image',
98
- 'product-catalog-image': '/product/image',
99
- 'md-app-state': '',
100
- 'md-msg-hist': '/mms/md-app-state',
101
- 'biz-cover-photo': '/pps/biz-cover-photo'
102
- }
103
-
104
- export const MEDIA_HKDF_KEY_MAPPING = {
105
- audio: 'Audio',
106
- document: 'Document',
107
- gif: 'Video',
108
- image: 'Image',
109
- ppic: '',
110
- product: 'Image',
111
- ptt: 'Audio',
112
- sticker: 'Image',
113
- video: 'Video',
114
- 'thumbnail-document': 'Document Thumbnail',
115
- 'thumbnail-image': 'Image Thumbnail',
116
- 'thumbnail-video': 'Video Thumbnail',
117
- 'thumbnail-link': 'Link Thumbnail',
118
- 'md-msg-hist': 'History',
119
- 'md-app-state': 'App State',
120
- 'product-catalog-image': '',
121
- 'payment-bg-image': 'Payment Background',
122
- ptv: 'Video',
123
- 'biz-cover-photo': 'Image'
124
- }
125
-
126
- export type MediaType = keyof typeof MEDIA_HKDF_KEY_MAPPING
127
-
128
- export const MEDIA_KEYS = Object.keys(MEDIA_PATH_MAP) as MediaType[]
129
-
130
- export const MIN_PREKEY_COUNT = 5
131
-
132
- export const INITIAL_PREKEY_COUNT = 812
133
-
134
- export const UPLOAD_TIMEOUT = 30000 // 30 seconds
135
- export const MIN_UPLOAD_INTERVAL = 5000 // 5 seconds minimum between uploads
136
-
137
- export const DEFAULT_CACHE_TTLS = {
138
- SIGNAL_STORE: 5 * 60, // 5 minutes
139
- MSG_RETRY: 60 * 60, // 1 hour
140
- CALL_OFFER: 5 * 60, // 5 minutes
141
- USER_DEVICES: 5 * 60 // 5 minutes
142
- }
143
-
144
- export const TimeMs = {
145
- Minute: 60 * 1000,
146
- Hour: 60 * 60 * 1000,
147
- Day: 24 * 60 * 60 * 1000,
148
- Week: 7 * 24 * 60 * 60 * 1000
149
- }
@@ -1,9 +0,0 @@
1
- export class CiphertextMessage {
2
- readonly UNSUPPORTED_VERSION: number = 1
3
- readonly CURRENT_VERSION: number = 3
4
- readonly WHISPER_TYPE: number = 2
5
- readonly PREKEY_TYPE: number = 3
6
- readonly SENDERKEY_TYPE: number = 4
7
- readonly SENDERKEY_DISTRIBUTION_TYPE: number = 5
8
- readonly ENCRYPTED_MESSAGE_OVERHEAD: number = 53
9
- }
@@ -1,56 +0,0 @@
1
- import * as keyhelper from './keyhelper'
2
- import { SenderKeyDistributionMessage } from './sender-key-distribution-message'
3
- import { SenderKeyName } from './sender-key-name'
4
- import { SenderKeyRecord } from './sender-key-record'
5
-
6
- interface SenderKeyStore {
7
- loadSenderKey(senderKeyName: SenderKeyName): Promise<SenderKeyRecord>
8
- storeSenderKey(senderKeyName: SenderKeyName, record: SenderKeyRecord): Promise<void>
9
- }
10
-
11
- export class GroupSessionBuilder {
12
- private readonly senderKeyStore: SenderKeyStore
13
-
14
- constructor(senderKeyStore: SenderKeyStore) {
15
- this.senderKeyStore = senderKeyStore
16
- }
17
-
18
- public async process(
19
- senderKeyName: SenderKeyName,
20
- senderKeyDistributionMessage: SenderKeyDistributionMessage
21
- ): Promise<void> {
22
- const senderKeyRecord = await this.senderKeyStore.loadSenderKey(senderKeyName)
23
- senderKeyRecord.addSenderKeyState(
24
- senderKeyDistributionMessage.getId(),
25
- senderKeyDistributionMessage.getIteration(),
26
- senderKeyDistributionMessage.getChainKey(),
27
- senderKeyDistributionMessage.getSignatureKey()
28
- )
29
- await this.senderKeyStore.storeSenderKey(senderKeyName, senderKeyRecord)
30
- }
31
-
32
- public async create(senderKeyName: SenderKeyName): Promise<SenderKeyDistributionMessage> {
33
- const senderKeyRecord = await this.senderKeyStore.loadSenderKey(senderKeyName)
34
-
35
- if (senderKeyRecord.isEmpty()) {
36
- const keyId = keyhelper.generateSenderKeyId()
37
- const senderKey = keyhelper.generateSenderKey()
38
- const signingKey = keyhelper.generateSenderSigningKey()
39
-
40
- senderKeyRecord.setSenderKeyState(keyId, 0, senderKey, signingKey)
41
- await this.senderKeyStore.storeSenderKey(senderKeyName, senderKeyRecord)
42
- }
43
-
44
- const state = senderKeyRecord.getSenderKeyState()
45
- if (!state) {
46
- throw new Error('No session state available')
47
- }
48
-
49
- return new SenderKeyDistributionMessage(
50
- state.getKeyId(),
51
- state.getSenderChainKey().getIteration(),
52
- state.getSenderChainKey().getSeed(),
53
- state.getSigningKeyPublic()
54
- )
55
- }
56
- }
@@ -1,117 +0,0 @@
1
- import { decrypt, encrypt } from 'libsignal/src/crypto'
2
- import { SenderKeyMessage } from './sender-key-message'
3
- import { SenderKeyName } from './sender-key-name'
4
- import { SenderKeyRecord } from './sender-key-record'
5
- import { SenderKeyState } from './sender-key-state'
6
-
7
- export interface SenderKeyStore {
8
- loadSenderKey(senderKeyName: SenderKeyName): Promise<SenderKeyRecord>
9
-
10
- storeSenderKey(senderKeyName: SenderKeyName, record: SenderKeyRecord): Promise<void>
11
- }
12
-
13
- export class GroupCipher {
14
- private readonly senderKeyStore: SenderKeyStore
15
- private readonly senderKeyName: SenderKeyName
16
-
17
- constructor(senderKeyStore: SenderKeyStore, senderKeyName: SenderKeyName) {
18
- this.senderKeyStore = senderKeyStore
19
- this.senderKeyName = senderKeyName
20
- }
21
-
22
- public async encrypt(paddedPlaintext: Uint8Array): Promise<Uint8Array> {
23
- const record = await this.senderKeyStore.loadSenderKey(this.senderKeyName)
24
- if (!record) {
25
- throw new Error('No SenderKeyRecord found for encryption')
26
- }
27
-
28
- const senderKeyState = record.getSenderKeyState()
29
- if (!senderKeyState) {
30
- throw new Error('No session to encrypt message')
31
- }
32
-
33
- const iteration = senderKeyState.getSenderChainKey().getIteration()
34
- const senderKey = this.getSenderKey(senderKeyState, iteration === 0 ? 0 : iteration + 1)
35
-
36
- const ciphertext = await this.getCipherText(senderKey.getIv(), senderKey.getCipherKey(), paddedPlaintext)
37
-
38
- const senderKeyMessage = new SenderKeyMessage(
39
- senderKeyState.getKeyId(),
40
- senderKey.getIteration(),
41
- ciphertext,
42
- senderKeyState.getSigningKeyPrivate()
43
- )
44
-
45
- await this.senderKeyStore.storeSenderKey(this.senderKeyName, record)
46
- return senderKeyMessage.serialize()
47
- }
48
-
49
- public async decrypt(senderKeyMessageBytes: Uint8Array): Promise<Uint8Array> {
50
- const record = await this.senderKeyStore.loadSenderKey(this.senderKeyName)
51
- if (!record) {
52
- throw new Error('No SenderKeyRecord found for decryption')
53
- }
54
-
55
- const senderKeyMessage = new SenderKeyMessage(null, null, null, null, senderKeyMessageBytes)
56
- const senderKeyState = record.getSenderKeyState(senderKeyMessage.getKeyId())
57
- if (!senderKeyState) {
58
- throw new Error('No session found to decrypt message')
59
- }
60
-
61
- senderKeyMessage.verifySignature(senderKeyState.getSigningKeyPublic())
62
- const senderKey = this.getSenderKey(senderKeyState, senderKeyMessage.getIteration())
63
-
64
- const plaintext = await this.getPlainText(
65
- senderKey.getIv(),
66
- senderKey.getCipherKey(),
67
- senderKeyMessage.getCipherText()
68
- )
69
-
70
- await this.senderKeyStore.storeSenderKey(this.senderKeyName, record)
71
- return plaintext
72
- }
73
-
74
- private getSenderKey(senderKeyState: SenderKeyState, iteration: number) {
75
- let senderChainKey = senderKeyState.getSenderChainKey()
76
- if (senderChainKey.getIteration() > iteration) {
77
- if (senderKeyState.hasSenderMessageKey(iteration)) {
78
- const messageKey = senderKeyState.removeSenderMessageKey(iteration)
79
- if (!messageKey) {
80
- throw new Error('No sender message key found for iteration')
81
- }
82
-
83
- return messageKey
84
- }
85
-
86
- throw new Error(`Received message with old counter: ${senderChainKey.getIteration()}, ${iteration}`)
87
- }
88
-
89
- if (iteration - senderChainKey.getIteration() > 2000) {
90
- throw new Error('Over 2000 messages into the future!')
91
- }
92
-
93
- while (senderChainKey.getIteration() < iteration) {
94
- senderKeyState.addSenderMessageKey(senderChainKey.getSenderMessageKey())
95
- senderChainKey = senderChainKey.getNext()
96
- }
97
-
98
- senderKeyState.setSenderChainKey(senderChainKey.getNext())
99
- return senderChainKey.getSenderMessageKey()
100
- }
101
-
102
- private async getPlainText(iv: Uint8Array, key: Uint8Array, ciphertext: Uint8Array): Promise<Uint8Array> {
103
- try {
104
- return decrypt(key, ciphertext, iv)
105
- } catch (e) {
106
- throw new Error('InvalidMessageException')
107
- }
108
- }
109
-
110
- private async getCipherText(iv: Uint8Array, key: Uint8Array, plaintext: Uint8Array): Promise<Buffer> {
111
- try {
112
- return encrypt(key, plaintext, iv)
113
- } catch (e) {
114
- throw new Error('InvalidMessageException')
115
- }
116
- }
117
- }
@@ -1,11 +0,0 @@
1
- export { GroupSessionBuilder } from './group-session-builder'
2
- export { SenderKeyDistributionMessage } from './sender-key-distribution-message'
3
- export { SenderKeyRecord } from './sender-key-record'
4
- export { SenderKeyName } from './sender-key-name'
5
- export { GroupCipher } from './group_cipher'
6
- export { SenderKeyState } from './sender-key-state'
7
- export { SenderKeyMessage } from './sender-key-message'
8
- export { SenderMessageKey } from './sender-message-key'
9
- export { SenderChainKey } from './sender-chain-key'
10
- export { CiphertextMessage } from './ciphertext-message'
11
- export * as keyhelper from './keyhelper'
@@ -1,28 +0,0 @@
1
- import * as nodeCrypto from 'crypto'
2
- import { generateKeyPair } from 'libsignal/src/curve'
3
-
4
- type KeyPairType = ReturnType<typeof generateKeyPair>
5
-
6
- export function generateSenderKey(): Buffer {
7
- return nodeCrypto.randomBytes(32)
8
- }
9
-
10
- export function generateSenderKeyId(): number {
11
- return nodeCrypto.randomInt(2147483647)
12
- }
13
-
14
- export interface SigningKeyPair {
15
- public: Buffer
16
- private: Buffer
17
- }
18
-
19
- export function generateSenderSigningKey(key?: KeyPairType): SigningKeyPair {
20
- if (!key) {
21
- key = generateKeyPair()
22
- }
23
-
24
- return {
25
- public: Buffer.from(key.pubKey),
26
- private: Buffer.from(key.privKey)
27
- }
28
- }
@@ -1,34 +0,0 @@
1
- import { calculateMAC } from 'libsignal/src/crypto'
2
- import { SenderMessageKey } from './sender-message-key'
3
-
4
- export class SenderChainKey {
5
- private readonly MESSAGE_KEY_SEED: Uint8Array = Buffer.from([0x01])
6
- private readonly CHAIN_KEY_SEED: Uint8Array = Buffer.from([0x02])
7
- private readonly iteration: number
8
- private readonly chainKey: Buffer
9
-
10
- constructor(iteration: number, chainKey: Uint8Array | Buffer) {
11
- this.iteration = iteration
12
- this.chainKey = Buffer.from(chainKey)
13
- }
14
-
15
- public getIteration(): number {
16
- return this.iteration
17
- }
18
-
19
- public getSenderMessageKey(): SenderMessageKey {
20
- return new SenderMessageKey(this.iteration, this.getDerivative(this.MESSAGE_KEY_SEED, this.chainKey))
21
- }
22
-
23
- public getNext(): SenderChainKey {
24
- return new SenderChainKey(this.iteration + 1, this.getDerivative(this.CHAIN_KEY_SEED, this.chainKey))
25
- }
26
-
27
- public getSeed(): Uint8Array {
28
- return this.chainKey
29
- }
30
-
31
- private getDerivative(seed: Uint8Array, key: Buffer): Uint8Array {
32
- return calculateMAC(key, seed)
33
- }
34
- }
@@ -1,95 +0,0 @@
1
- import { proto } from '../../../WAProto/index.js'
2
- import { CiphertextMessage } from './ciphertext-message'
3
-
4
- interface SenderKeyDistributionMessageStructure {
5
- id: number
6
- iteration: number
7
- chainKey: string | Uint8Array
8
- signingKey: string | Uint8Array
9
- }
10
-
11
- export class SenderKeyDistributionMessage extends CiphertextMessage {
12
- private readonly id: number
13
- private readonly iteration: number
14
- private readonly chainKey: Uint8Array
15
- private readonly signatureKey: Uint8Array
16
- private readonly serialized: Uint8Array
17
-
18
- constructor(
19
- id?: number | null,
20
- iteration?: number | null,
21
- chainKey?: Uint8Array | null,
22
- signatureKey?: Uint8Array | null,
23
- serialized?: Uint8Array | null
24
- ) {
25
- super()
26
-
27
- if (serialized) {
28
- try {
29
- const message = serialized.slice(1)
30
- const distributionMessage = proto.SenderKeyDistributionMessage.decode(
31
- message
32
- ).toJSON() as SenderKeyDistributionMessageStructure
33
-
34
- this.serialized = serialized
35
- this.id = distributionMessage.id
36
- this.iteration = distributionMessage.iteration
37
- this.chainKey =
38
- typeof distributionMessage.chainKey === 'string'
39
- ? Buffer.from(distributionMessage.chainKey, 'base64')
40
- : distributionMessage.chainKey
41
- this.signatureKey =
42
- typeof distributionMessage.signingKey === 'string'
43
- ? Buffer.from(distributionMessage.signingKey, 'base64')
44
- : distributionMessage.signingKey
45
- } catch (e) {
46
- throw new Error(String(e))
47
- }
48
- } else {
49
- const version = this.intsToByteHighAndLow(this.CURRENT_VERSION, this.CURRENT_VERSION)
50
- this.id = id!
51
- this.iteration = iteration!
52
- this.chainKey = chainKey!
53
- this.signatureKey = signatureKey!
54
-
55
- const message = proto.SenderKeyDistributionMessage.encode(
56
- proto.SenderKeyDistributionMessage.create({
57
- id,
58
- iteration,
59
- chainKey,
60
- signingKey: this.signatureKey
61
- })
62
- ).finish()
63
-
64
- this.serialized = Buffer.concat([Buffer.from([version]), message])
65
- }
66
- }
67
-
68
- private intsToByteHighAndLow(highValue: number, lowValue: number): number {
69
- return (((highValue << 4) | lowValue) & 0xff) % 256
70
- }
71
-
72
- public serialize(): Uint8Array {
73
- return this.serialized
74
- }
75
-
76
- public getType(): number {
77
- return this.SENDERKEY_DISTRIBUTION_TYPE
78
- }
79
-
80
- public getIteration(): number {
81
- return this.iteration
82
- }
83
-
84
- public getChainKey(): Uint8Array {
85
- return this.chainKey
86
- }
87
-
88
- public getSignatureKey(): Uint8Array {
89
- return this.signatureKey
90
- }
91
-
92
- public getId(): number {
93
- return this.id
94
- }
95
- }
@@ -1,96 +0,0 @@
1
- import { calculateSignature, verifySignature } from 'libsignal/src/curve'
2
- import { proto } from '../../../WAProto/index.js'
3
- import { CiphertextMessage } from './ciphertext-message'
4
-
5
- interface SenderKeyMessageStructure {
6
- id: number
7
- iteration: number
8
- ciphertext: string | Buffer
9
- }
10
-
11
- export class SenderKeyMessage extends CiphertextMessage {
12
- private readonly SIGNATURE_LENGTH = 64
13
- private readonly messageVersion: number
14
- private readonly keyId: number
15
- private readonly iteration: number
16
- private readonly ciphertext: Uint8Array
17
- private readonly signature: Uint8Array
18
- private readonly serialized: Uint8Array
19
-
20
- constructor(
21
- keyId?: number | null,
22
- iteration?: number | null,
23
- ciphertext?: Uint8Array | null,
24
- signatureKey?: Uint8Array | null,
25
- serialized?: Uint8Array | null
26
- ) {
27
- super()
28
-
29
- if (serialized) {
30
- const version = serialized[0]!
31
- const message = serialized.slice(1, serialized.length - this.SIGNATURE_LENGTH)
32
- const signature = serialized.slice(-1 * this.SIGNATURE_LENGTH)
33
- const senderKeyMessage = proto.SenderKeyMessage.decode(message).toJSON() as SenderKeyMessageStructure
34
-
35
- this.serialized = serialized
36
- this.messageVersion = (version & 0xff) >> 4
37
- this.keyId = senderKeyMessage.id
38
- this.iteration = senderKeyMessage.iteration
39
- this.ciphertext =
40
- typeof senderKeyMessage.ciphertext === 'string'
41
- ? Buffer.from(senderKeyMessage.ciphertext, 'base64')
42
- : senderKeyMessage.ciphertext
43
- this.signature = signature
44
- } else {
45
- const version = (((this.CURRENT_VERSION << 4) | this.CURRENT_VERSION) & 0xff) % 256
46
- const ciphertextBuffer = Buffer.from(ciphertext!)
47
- const message = proto.SenderKeyMessage.encode(
48
- proto.SenderKeyMessage.create({
49
- id: keyId!,
50
- iteration: iteration!,
51
- ciphertext: ciphertextBuffer
52
- })
53
- ).finish()
54
-
55
- const signature = this.getSignature(signatureKey!, Buffer.concat([Buffer.from([version]), message]))
56
-
57
- this.serialized = Buffer.concat([Buffer.from([version]), message, Buffer.from(signature)])
58
- this.messageVersion = this.CURRENT_VERSION
59
- this.keyId = keyId!
60
- this.iteration = iteration!
61
- this.ciphertext = ciphertextBuffer
62
- this.signature = signature
63
- }
64
- }
65
-
66
- public getKeyId(): number {
67
- return this.keyId
68
- }
69
-
70
- public getIteration(): number {
71
- return this.iteration
72
- }
73
-
74
- public getCipherText(): Uint8Array {
75
- return this.ciphertext
76
- }
77
-
78
- public verifySignature(signatureKey: Uint8Array): void {
79
- const part1 = this.serialized.slice(0, this.serialized.length - this.SIGNATURE_LENGTH)
80
- const part2 = this.serialized.slice(-1 * this.SIGNATURE_LENGTH)
81
- const res = verifySignature(signatureKey, part1, part2)
82
- if (!res) throw new Error('Invalid signature!')
83
- }
84
-
85
- private getSignature(signatureKey: Uint8Array, serialized: Uint8Array): Uint8Array {
86
- return Buffer.from(calculateSignature(signatureKey, serialized))
87
- }
88
-
89
- public serialize(): Uint8Array {
90
- return this.serialized
91
- }
92
-
93
- public getType(): number {
94
- return 4
95
- }
96
- }
@@ -1,66 +0,0 @@
1
- interface Sender {
2
- id: string
3
- deviceId: number
4
- toString(): string
5
- }
6
-
7
- function isNull(str: string | null): boolean {
8
- return str === null || str === ''
9
- }
10
-
11
- function intValue(num: number): number {
12
- const MAX_VALUE = 0x7fffffff
13
- const MIN_VALUE = -0x80000000
14
- if (num > MAX_VALUE || num < MIN_VALUE) {
15
- return num & 0xffffffff
16
- }
17
-
18
- return num
19
- }
20
-
21
- function hashCode(strKey: string): number {
22
- let hash = 0
23
- if (!isNull(strKey)) {
24
- for (let i = 0; i < strKey.length; i++) {
25
- hash = hash * 31 + strKey.charCodeAt(i)
26
- hash = intValue(hash)
27
- }
28
- }
29
-
30
- return hash
31
- }
32
-
33
- export class SenderKeyName {
34
- private readonly groupId: string
35
- private readonly sender: Sender
36
-
37
- constructor(groupId: string, sender: Sender) {
38
- this.groupId = groupId
39
- this.sender = sender
40
- }
41
-
42
- public getGroupId(): string {
43
- return this.groupId
44
- }
45
-
46
- public getSender(): Sender {
47
- return this.sender
48
- }
49
-
50
- public serialize(): string {
51
- return `${this.groupId}::${this.sender.id}::${this.sender.deviceId}`
52
- }
53
-
54
- public toString(): string {
55
- return this.serialize()
56
- }
57
-
58
- public equals(other: SenderKeyName | null): boolean {
59
- if (other === null) return false
60
- return this.groupId === other.groupId && this.sender.toString() === other.sender.toString()
61
- }
62
-
63
- public hashCode(): number {
64
- return hashCode(this.groupId) ^ hashCode(this.sender.toString())
65
- }
66
- }