@xz-bails/baileys 0.0.0-stage → 6.0.10

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 (120) hide show
  1. package/LICENSE +49 -0
  2. package/README.md +541 -2
  3. package/WAProto/GenerateStatics.sh +17 -0
  4. package/WAProto/WAProto.proto +8583 -0
  5. package/WAProto/fix-imports.js +85 -0
  6. package/WAProto/index.d.ts +16 -0
  7. package/WAProto/index.js +95 -0
  8. package/WAProto/self-test.js +38 -0
  9. package/engine-requirements.js +10 -0
  10. package/lib/Defaults/index.js +130 -0
  11. package/lib/Signal/Group/ciphertext-message.js +12 -0
  12. package/lib/Signal/Group/group-session-builder.js +30 -0
  13. package/lib/Signal/Group/group_cipher.js +82 -0
  14. package/lib/Signal/Group/index.js +12 -0
  15. package/lib/Signal/Group/keyhelper.js +18 -0
  16. package/lib/Signal/Group/sender-chain-key.js +26 -0
  17. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  18. package/lib/Signal/Group/sender-key-message.js +66 -0
  19. package/lib/Signal/Group/sender-key-name.js +48 -0
  20. package/lib/Signal/Group/sender-key-record.js +41 -0
  21. package/lib/Signal/Group/sender-key-state.js +84 -0
  22. package/lib/Signal/Group/sender-message-key.js +26 -0
  23. package/lib/Signal/libsignal.js +431 -0
  24. package/lib/Signal/lid-mapping.js +277 -0
  25. package/lib/Socket/Client/index.js +3 -0
  26. package/lib/Socket/Client/types.js +11 -0
  27. package/lib/Socket/Client/websocket.js +86 -0
  28. package/lib/Socket/business.js +379 -0
  29. package/lib/Socket/chats.js +1193 -0
  30. package/lib/Socket/communities.js +432 -0
  31. package/lib/Socket/groups.js +374 -0
  32. package/lib/Socket/index.js +15 -0
  33. package/lib/Socket/luxu.js +386 -0
  34. package/lib/Socket/messages-recv.js +1916 -0
  35. package/lib/Socket/messages-send.js +645 -0
  36. package/lib/Socket/mex.js +41 -0
  37. package/lib/Socket/newsletter.js +494 -0
  38. package/lib/Socket/socket.js +992 -0
  39. package/lib/Socket/username.js +234 -0
  40. package/lib/Store/index.js +10 -0
  41. package/lib/Store/keyed-db.js +108 -0
  42. package/lib/Store/make-cache-manager-store.js +85 -0
  43. package/lib/Store/make-in-memory-store.js +198 -0
  44. package/lib/Store/make-ordered-dictionary.js +75 -0
  45. package/lib/Store/object-repository.js +32 -0
  46. package/lib/Types/Auth.js +2 -0
  47. package/lib/Types/Bussines.js +2 -0
  48. package/lib/Types/Call.js +2 -0
  49. package/lib/Types/Chat.js +8 -0
  50. package/lib/Types/Contact.js +2 -0
  51. package/lib/Types/Events.js +2 -0
  52. package/lib/Types/GroupMetadata.js +2 -0
  53. package/lib/Types/Label.js +25 -0
  54. package/lib/Types/LabelAssociation.js +7 -0
  55. package/lib/Types/Message.js +11 -0
  56. package/lib/Types/Mex.js +37 -0
  57. package/lib/Types/Product.js +2 -0
  58. package/lib/Types/Signal.js +2 -0
  59. package/lib/Types/Socket.js +3 -0
  60. package/lib/Types/State.js +56 -0
  61. package/lib/Types/USync.js +2 -0
  62. package/lib/Types/index.js +26 -0
  63. package/lib/Utils/auth-utils.js +302 -0
  64. package/lib/Utils/ban-sentinel.js +128 -0
  65. package/lib/Utils/browser-utils.js +49 -0
  66. package/lib/Utils/business.js +231 -0
  67. package/lib/Utils/chat-utils.js +872 -0
  68. package/lib/Utils/companion-reg-client-utils.js +35 -0
  69. package/lib/Utils/crypto.js +118 -0
  70. package/lib/Utils/decode-wa-message.js +350 -0
  71. package/lib/Utils/event-buffer.js +622 -0
  72. package/lib/Utils/generics.js +403 -0
  73. package/lib/Utils/history.js +134 -0
  74. package/lib/Utils/identity-change-handler.js +50 -0
  75. package/lib/Utils/index.js +23 -0
  76. package/lib/Utils/link-preview.js +85 -0
  77. package/lib/Utils/logger.js +3 -0
  78. package/lib/Utils/lt-hash.js +8 -0
  79. package/lib/Utils/make-mutex.js +33 -0
  80. package/lib/Utils/message-composer.js +273 -0
  81. package/lib/Utils/message-retry-manager.js +265 -0
  82. package/lib/Utils/messages-media.js +788 -0
  83. package/lib/Utils/messages.js +1260 -0
  84. package/lib/Utils/noise-handler.js +201 -0
  85. package/lib/Utils/offline-node-processor.js +40 -0
  86. package/lib/Utils/pre-key-manager.js +106 -0
  87. package/lib/Utils/process-message.js +630 -0
  88. package/lib/Utils/reporting-utils.js +258 -0
  89. package/lib/Utils/signal.js +201 -0
  90. package/lib/Utils/stanza-ack.js +38 -0
  91. package/lib/Utils/sync-action-utils.js +49 -0
  92. package/lib/Utils/tc-token-utils.js +163 -0
  93. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  94. package/lib/Utils/validate-connection.js +203 -0
  95. package/lib/WABinary/constants.js +1301 -0
  96. package/lib/WABinary/decode.js +262 -0
  97. package/lib/WABinary/encode.js +220 -0
  98. package/lib/WABinary/generic-utils.js +204 -0
  99. package/lib/WABinary/index.js +6 -0
  100. package/lib/WABinary/jid-utils.js +98 -0
  101. package/lib/WABinary/types.js +2 -0
  102. package/lib/WAM/BinaryInfo.js +10 -0
  103. package/lib/WAM/constants.js +22853 -0
  104. package/lib/WAM/encode.js +150 -0
  105. package/lib/WAM/index.js +4 -0
  106. package/lib/WAUSync/Protocols/USyncContactProtocol.js +52 -0
  107. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  108. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  109. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  110. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  111. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  112. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  113. package/lib/WAUSync/Protocols/index.js +6 -0
  114. package/lib/WAUSync/USyncQuery.js +98 -0
  115. package/lib/WAUSync/USyncUser.js +31 -0
  116. package/lib/WAUSync/index.js +4 -0
  117. package/lib/index.d.ts +7 -0
  118. package/lib/index.js +78 -0
  119. package/package.json +126 -4
  120. package/scripts/check-syntax.js +24 -0
@@ -0,0 +1,85 @@
1
+ import { readFileSync, writeFileSync } from 'fs';
2
+ import { exit } from 'process';
3
+
4
+ const filePath = './index.js'
5
+
6
+ try {
7
+ let content = readFileSync(filePath, 'utf8')
8
+
9
+ content = content.replace(/import \* as (\$protobuf) from/g, 'import $1 from')
10
+ content = content.replace(/(['"])protobufjs\/minimal(['"])/g, '$1protobufjs/minimal.js$2')
11
+
12
+ const marker = 'const $root = $protobuf.roots["default"] || ($protobuf.roots["default"] = {});\n\n'
13
+ const longToStringHelper =
14
+ 'function longToString(value, unsigned) {\n' +
15
+ '\tif (typeof value === "string") {\n' +
16
+ '\t\treturn value;\n' +
17
+ '\t}\n' +
18
+ '\tif (typeof value === "number") {\n' +
19
+ '\t\treturn String(value);\n' +
20
+ '\t}\n' +
21
+ '\t// Fast path: convert Long {low, high} directly via native BigInt\n' +
22
+ '\t// BigInt.toString() is a native C++ operation, much faster than Long\'s pure JS division loops\n' +
23
+ '\tif (value && typeof value.low === "number" && typeof value.high === "number") {\n' +
24
+ '\t\tconst lo = BigInt(value.low >>> 0);\n' +
25
+ '\t\tconst hi = BigInt(value.high >>> 0);\n' +
26
+ '\t\tconst combined = (hi << 32n) | lo;\n' +
27
+ '\t\tif (!unsigned && value.high < 0) {\n' +
28
+ '\t\t\treturn (combined - (1n << 64n)).toString();\n' +
29
+ '\t\t}\n' +
30
+ '\t\treturn combined.toString();\n' +
31
+ '\t}\n' +
32
+ '\treturn String(value);\n' +
33
+ '}\n\n'
34
+ const longToNumberHelper =
35
+ 'function longToNumber(value, unsigned) {\n' +
36
+ '\tif (typeof value === "number") {\n' +
37
+ '\t\treturn value;\n' +
38
+ '\t}\n' +
39
+ '\tif (typeof value === "string") {\n' +
40
+ '\t\treturn Number(value);\n' +
41
+ '\t}\n' +
42
+ '\t// Fast path: convert Long {low, high} directly via native BigInt\n' +
43
+ '\tif (value && typeof value.low === "number" && typeof value.high === "number") {\n' +
44
+ '\t\tconst lo = BigInt(value.low >>> 0);\n' +
45
+ '\t\tconst hi = BigInt(value.high >>> 0);\n' +
46
+ '\t\tconst combined = (hi << 32n) | lo;\n' +
47
+ '\t\tif (!unsigned && value.high < 0) {\n' +
48
+ '\t\t\treturn Number(combined - (1n << 64n));\n' +
49
+ '\t\t}\n' +
50
+ '\t\treturn Number(combined);\n' +
51
+ '\t}\n' +
52
+ '\treturn Number(value);\n' +
53
+ '}\n\n'
54
+
55
+ if (!content.includes('function longToString(')) {
56
+ const markerIndex = content.indexOf(marker)
57
+ if (markerIndex === -1) {
58
+ throw new Error('Unable to inject Long helpers: marker not found in WAProto index output')
59
+ }
60
+
61
+ content = content.replace(marker, `${marker}${longToStringHelper}${longToNumberHelper}`)
62
+ } else {
63
+ const longToStringRegex = /function longToString\(value, unsigned\) {\n[\s\S]*?\n}\n\n/
64
+ const longToNumberRegex = /function longToNumber\(value, unsigned\) {\n[\s\S]*?\n}\n\n/
65
+
66
+ if (!longToStringRegex.test(content) || !longToNumberRegex.test(content)) {
67
+ throw new Error('Unable to update Long helpers: existing definitions not found')
68
+ }
69
+
70
+ content = content.replace(longToStringRegex, longToStringHelper)
71
+ content = content.replace(longToNumberRegex, longToNumberHelper)
72
+ }
73
+
74
+ const longPattern = /([ \t]+d\.(\w+) = )o\.longs === String \? \$util\.Long\.prototype\.toString\.call\(m\.\2\) : o\.longs === Number \? new \$util\.LongBits\(m\.\2\.low >>> 0, m\.\2\.high >>> 0\)\.toNumber\((true)?\) : m\.\2;/g
75
+ content = content.replace(longPattern, (_match, prefix, field, unsignedFlag) => {
76
+ const unsignedArg = unsignedFlag ? ', true' : ''
77
+ return `${prefix}o.longs === String ? longToString(m.${field}${unsignedArg}) : o.longs === Number ? longToNumber(m.${field}${unsignedArg}) : m.${field};`
78
+ })
79
+
80
+ writeFileSync(filePath, content, 'utf8')
81
+ console.log(`✅ Fixed imports in ${filePath}`)
82
+ } catch (error) {
83
+ console.error(`❌ Error fixing imports: ${error.message}`)
84
+ exit(1)
85
+ }
@@ -0,0 +1,16 @@
1
+ import * as $protobuf from 'protobufjs';
2
+
3
+ /**
4
+ * Dynamically loaded WAProto namespace.
5
+ *
6
+ * Message entries are protobufjs Type objects (create/fromObject/encode/
7
+ * decode/toObject); enum entries expose both symbolic and numeric keys.
8
+ * The concrete members are defined by the adjacent WAProto.proto file.
9
+ */
10
+ export type ProtoNamespace = Record<string, any>;
11
+
12
+ export const proto: ProtoNamespace;
13
+ export const root: $protobuf.Root;
14
+
15
+ declare const $root: $protobuf.Root;
16
+ export default $root;
@@ -0,0 +1,95 @@
1
+ /**
2
+ * WAProto runtime loader.
3
+ *
4
+ * Loads the supplied WhatsApp protobuf schema and exposes it using the same
5
+ * namespace shape as protobufjs static-module output:
6
+ * proto.Message.encode(...)
7
+ * proto.Message.ImageMessage
8
+ * proto.WebMessageInfo.StubType
9
+ *
10
+ * Keep this adapter in sync with the schema shipped in WAProto.proto.
11
+ */
12
+ import $protobuf from 'protobufjs';
13
+ import { readFileSync } from 'node:fs';
14
+ import { fileURLToPath } from 'node:url';
15
+
16
+ const schemaPath = fileURLToPath(new URL('./WAProto.proto', import.meta.url));
17
+ const schema = readFileSync(schemaPath, 'utf8');
18
+
19
+ const parsed = $protobuf.parse(schema, { keepCase: false });
20
+ const $root = parsed.root;
21
+
22
+ // Resolve cross-message and nested-enum references before exposing the API.
23
+ $root.resolveAll();
24
+
25
+ function isMessageType(value) {
26
+ return Boolean(
27
+ value &&
28
+ value.fields &&
29
+ typeof value.encode === 'function' &&
30
+ typeof value.decode === 'function'
31
+ );
32
+ }
33
+
34
+ function isEnumType(value) {
35
+ return Boolean(
36
+ value &&
37
+ value.values &&
38
+ value.valuesById
39
+ );
40
+ }
41
+
42
+ /**
43
+ * Convert protobufjs reflection namespaces to the direct property access
44
+ * expected by the rest of Baileys. Message Type objects are kept intact so
45
+ * their create/fromObject/encode/decode methods remain available.
46
+ */
47
+ function exposeNamespace(namespace) {
48
+ const exposed = {};
49
+
50
+ for (const [name, child] of Object.entries(namespace.nested || {})) {
51
+ if (isMessageType(child)) {
52
+ exposed[name] = exposeMessage(child);
53
+ } else if (isEnumType(child)) {
54
+ // Match protobufjs static output: enum names and reverse numeric
55
+ // lookups are both available (e.g. Type[0] === 'UNKNOWN').
56
+ exposed[name] = Object.assign(
57
+ Object.create(null),
58
+ child.valuesById,
59
+ child.values
60
+ );
61
+ } else if (child && child.nested) {
62
+ exposed[name] = exposeNamespace(child);
63
+ }
64
+ }
65
+
66
+ return exposed;
67
+ }
68
+
69
+ function exposeMessage(messageType) {
70
+ // Preserve the real protobufjs Type instance and its codec methods.
71
+ for (const [name, child] of Object.entries(messageType.nested || {})) {
72
+ if (isMessageType(child)) {
73
+ messageType[name] = exposeMessage(child);
74
+ } else if (isEnumType(child)) {
75
+ messageType[name] = Object.assign(
76
+ Object.create(null),
77
+ child.valuesById,
78
+ child.values
79
+ );
80
+ } else if (child && child.nested) {
81
+ messageType[name] = exposeNamespace(child);
82
+ }
83
+ }
84
+
85
+ return messageType;
86
+ }
87
+
88
+ const protoNamespace = $root.lookup('proto');
89
+ if (!protoNamespace || !protoNamespace.nested) {
90
+ throw new Error('WAProto schema does not contain the expected `proto` namespace');
91
+ }
92
+
93
+ export const proto = exposeNamespace(protoNamespace);
94
+ export { $root as root };
95
+ export default $root;
@@ -0,0 +1,38 @@
1
+ import assert from 'node:assert/strict';
2
+ import { proto, root } from './index.js';
3
+
4
+ assert.ok(root, 'protobuf root should be exported');
5
+ assert.ok(proto, 'proto namespace should be exported');
6
+
7
+ const requiredMessages = [
8
+ 'Message',
9
+ 'WebMessageInfo',
10
+ 'ClientPayload',
11
+ 'HandshakeMessage',
12
+ 'HistorySync',
13
+ 'SyncdPatch',
14
+ 'DeviceProps',
15
+ 'CertChain',
16
+ 'MediaRetryNotification'
17
+ ];
18
+
19
+ for (const name of requiredMessages) {
20
+ assert.ok(proto[name], `missing proto.${name}`);
21
+ }
22
+
23
+ assert.equal(typeof proto.Message.encode, 'function');
24
+ assert.equal(typeof proto.Message.decode, 'function');
25
+ assert.equal(typeof proto.Message.fromObject, 'function');
26
+ assert.equal(typeof proto.WebMessageInfo.fromObject, 'function');
27
+ assert.equal(typeof proto.HistorySync.HistorySyncType.RECENT, 'number');
28
+ assert.equal(typeof proto.Message.ProtocolMessage.Type.REVOKE, 'number');
29
+
30
+ const message = proto.Message.fromObject({
31
+ conversation: 'WAProto smoke test'
32
+ });
33
+ const encoded = proto.Message.encode(message).finish();
34
+ const decoded = proto.Message.decode(encoded);
35
+
36
+ assert.equal(decoded.conversation, 'WAProto smoke test');
37
+
38
+ console.log('WAProto smoke test passed.');
@@ -0,0 +1,10 @@
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
+ }
@@ -0,0 +1,130 @@
1
+ import { proto } from '../../WAProto/index.js';
2
+ import { makeLibSignalRepository } from '../Signal/libsignal.js';
3
+ import { Browsers } from '../Utils/browser-utils.js';
4
+ import logger from '../Utils/logger.js';
5
+ const version = [2, 3000, 1035194821];
6
+ export const UNAUTHORIZED_CODES = [401, 403, 419];
7
+ export const DEFAULT_ORIGIN = 'https://web.whatsapp.com';
8
+ export const CALL_VIDEO_PREFIX = 'https://call.whatsapp.com/video/';
9
+ export const CALL_AUDIO_PREFIX = 'https://call.whatsapp.com/voice/';
10
+ export const DEF_CALLBACK_PREFIX = 'CB:';
11
+ export const DEF_TAG_PREFIX = 'TAG:';
12
+ export const PHONE_CONNECTION_CB = 'CB:Pong';
13
+ export const WA_ADV_ACCOUNT_SIG_PREFIX = Buffer.from([6, 0]);
14
+ export const WA_ADV_DEVICE_SIG_PREFIX = Buffer.from([6, 1]);
15
+ export const WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX = Buffer.from([6, 5]);
16
+ export const WA_ADV_HOSTED_DEVICE_SIG_PREFIX = Buffer.from([6, 6]);
17
+ export const WA_DEFAULT_EPHEMERAL = 7 * 24 * 60 * 60;
18
+ /** Status messages older than 24 hours are considered expired */
19
+ export const STATUS_EXPIRY_SECONDS = 24 * 60 * 60;
20
+ /** WA Web enforces a 14-day maximum age for placeholder resend requests */
21
+ export const PLACEHOLDER_MAX_AGE_SECONDS = 14 * 24 * 60 * 60;
22
+ export const NOISE_MODE = 'Noise_XX_25519_AESGCM_SHA256\0\0\0\0';
23
+ export const DICT_VERSION = 3;
24
+ export const KEY_BUNDLE_TYPE = Buffer.from([5]);
25
+ export const NOISE_WA_HEADER = Buffer.from([87, 65, 6, DICT_VERSION]); // last is "DICT_VERSION"
26
+ /** from: https://stackoverflow.com/questions/3809401/what-is-a-good-regular-expression-to-match-a-url */
27
+ export const URL_REGEX = /https:\/\/(?![^:@\/\s]+:[^:@\/\s]+@)[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(:\d+)?(\/[^\s]*)?/g;
28
+ export const WA_CERT_DETAILS = {
29
+ SERIAL: 0,
30
+ ISSUER: 'WhatsAppLongTerm1',
31
+ PUBLIC_KEY: Buffer.from('142375574d0a587166aae71ebe516437c4a28b73e3695c6ce1f7f9545da8ee6b', 'hex')
32
+ };
33
+ export const PROCESSABLE_HISTORY_TYPES = [
34
+ proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP,
35
+ proto.HistorySync.HistorySyncType.PUSH_NAME,
36
+ proto.HistorySync.HistorySyncType.RECENT,
37
+ proto.HistorySync.HistorySyncType.FULL,
38
+ proto.HistorySync.HistorySyncType.ON_DEMAND,
39
+ proto.HistorySync.HistorySyncType.NON_BLOCKING_DATA,
40
+ proto.HistorySync.HistorySyncType.INITIAL_STATUS_V3
41
+ ];
42
+ export const DEFAULT_CACHE_TTLS = {
43
+ SIGNAL_STORE: 5 * 60, // 5 minutes
44
+ MSG_RETRY: 60 * 60, // 1 hour
45
+ CALL_OFFER: 5 * 60, // 5 minutes
46
+ USER_DEVICES: 5 * 60 // 5 minutes
47
+ };
48
+ export const DEFAULT_CONNECTION_CONFIG = {
49
+ version: version,
50
+ browser: Browsers.macOS('Chrome'),
51
+ waWebSocketUrl: 'wss://web.whatsapp.com/ws/chat',
52
+ connectTimeoutMs: 20000,
53
+ keepAliveIntervalMs: 30000,
54
+ logger: logger.child({ class: 'LiniusNv' }),
55
+ emitOwnEvents: true,
56
+ defaultQueryTimeoutMs: 60000,
57
+ customUploadHosts: [],
58
+ retryRequestDelayMs: 250,
59
+ maxMsgRetryCount: 5,
60
+ fireInitQueries: true,
61
+ auth: undefined,
62
+ markOnlineOnConnect: true,
63
+ aiLabel: false,
64
+ syncFullHistory: true,
65
+ patchMessageBeforeSending: msg => msg,
66
+ shouldSyncHistoryMessage: ({ syncType }) => {
67
+ return syncType !== proto.HistorySync.HistorySyncType.FULL;
68
+ },
69
+ shouldIgnoreJid: () => false,
70
+ linkPreviewImageThumbnailWidth: 192,
71
+ transactionOpts: { maxCommitRetries: 10, delayBetweenTriesMs: 3000 },
72
+ generateHighQualityLinkPreview: false,
73
+ enableAutoSessionRecreation: true,
74
+ enableRecentMessageCache: true,
75
+ options: {},
76
+ appStateMacVerification: {
77
+ patch: false,
78
+ snapshot: false
79
+ },
80
+ countryCode: 'US',
81
+ getMessage: async () => undefined,
82
+ cachedGroupMetadata: async () => undefined,
83
+ makeSignalRepository: makeLibSignalRepository
84
+ };
85
+ export const MEDIA_PATH_MAP = {
86
+ image: '/mms/image',
87
+ video: '/mms/video',
88
+ document: '/mms/document',
89
+ audio: '/mms/audio',
90
+ sticker: '/mms/image',
91
+ 'thumbnail-link': '/mms/image',
92
+ 'product-catalog-image': '/product/image',
93
+ 'md-app-state': '',
94
+ 'md-msg-hist': '/mms/md-app-state',
95
+ 'biz-cover-photo': '/pps/biz-cover-photo'
96
+ };
97
+ export const MEDIA_HKDF_KEY_MAPPING = {
98
+ audio: 'Audio',
99
+ document: 'Document',
100
+ gif: 'Video',
101
+ image: 'Image',
102
+ ppic: '',
103
+ product: 'Image',
104
+ ptt: 'Audio',
105
+ sticker: 'Image',
106
+ video: 'Video',
107
+ 'thumbnail-document': 'Document Thumbnail',
108
+ 'thumbnail-image': 'Image Thumbnail',
109
+ 'thumbnail-video': 'Video Thumbnail',
110
+ 'thumbnail-link': 'Link Thumbnail',
111
+ 'md-msg-hist': 'History',
112
+ 'md-app-state': 'App State',
113
+ 'product-catalog-image': '',
114
+ 'payment-bg-image': 'Payment Background',
115
+ ptv: 'Video',
116
+ 'biz-cover-photo': 'Image'
117
+ };
118
+ export const MEDIA_KEYS = Object.keys(MEDIA_PATH_MAP);
119
+ /** 120s timeout for history sync stall detection, same as WA Web's handleChunkProgress / restartPausedTimer (g = 120) */
120
+ export const HISTORY_SYNC_PAUSED_TIMEOUT_MS = 120000;
121
+ export const MIN_PREKEY_COUNT = 5;
122
+ export const INITIAL_PREKEY_COUNT = 812;
123
+ export const UPLOAD_TIMEOUT = 30000; // 30 seconds
124
+ export const TimeMs = {
125
+ Minute: 60 * 1000,
126
+ Hour: 60 * 60 * 1000,
127
+ Day: 24 * 60 * 60 * 1000,
128
+ Week: 7 * 24 * 60 * 60 * 1000
129
+ };
130
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,12 @@
1
+ export class CiphertextMessage {
2
+ constructor() {
3
+ this.UNSUPPORTED_VERSION = 1;
4
+ this.CURRENT_VERSION = 3;
5
+ this.WHISPER_TYPE = 2;
6
+ this.PREKEY_TYPE = 3;
7
+ this.SENDERKEY_TYPE = 4;
8
+ this.SENDERKEY_DISTRIBUTION_TYPE = 5;
9
+ this.ENCRYPTED_MESSAGE_OVERHEAD = 53;
10
+ }
11
+ }
12
+ //# sourceMappingURL=ciphertext-message.js.map
@@ -0,0 +1,30 @@
1
+ import * as keyhelper from './keyhelper.js';
2
+ import { SenderKeyDistributionMessage } from './sender-key-distribution-message.js';
3
+ import { SenderKeyName } from './sender-key-name.js';
4
+ import { SenderKeyRecord } from './sender-key-record.js';
5
+ export class GroupSessionBuilder {
6
+ constructor(senderKeyStore) {
7
+ this.senderKeyStore = senderKeyStore;
8
+ }
9
+ async process(senderKeyName, senderKeyDistributionMessage) {
10
+ const senderKeyRecord = await this.senderKeyStore.loadSenderKey(senderKeyName);
11
+ senderKeyRecord.addSenderKeyState(senderKeyDistributionMessage.getId(), senderKeyDistributionMessage.getIteration(), senderKeyDistributionMessage.getChainKey(), senderKeyDistributionMessage.getSignatureKey());
12
+ await this.senderKeyStore.storeSenderKey(senderKeyName, senderKeyRecord);
13
+ }
14
+ async create(senderKeyName) {
15
+ const senderKeyRecord = await this.senderKeyStore.loadSenderKey(senderKeyName);
16
+ if (senderKeyRecord.isEmpty()) {
17
+ const keyId = keyhelper.generateSenderKeyId();
18
+ const senderKey = keyhelper.generateSenderKey();
19
+ const signingKey = keyhelper.generateSenderSigningKey();
20
+ senderKeyRecord.setSenderKeyState(keyId, 0, senderKey, signingKey);
21
+ await this.senderKeyStore.storeSenderKey(senderKeyName, senderKeyRecord);
22
+ }
23
+ const state = senderKeyRecord.getSenderKeyState();
24
+ if (!state) {
25
+ throw new Error('No session state available');
26
+ }
27
+ return new SenderKeyDistributionMessage(state.getKeyId(), state.getSenderChainKey().getIteration(), state.getSenderChainKey().getSeed(), state.getSigningKeyPublic());
28
+ }
29
+ }
30
+ //# sourceMappingURL=group-session-builder.js.map
@@ -0,0 +1,82 @@
1
+ import { decrypt, encrypt } from 'libsignal/src/crypto.js';
2
+ import { SenderKeyMessage } from './sender-key-message.js';
3
+ import { SenderKeyName } from './sender-key-name.js';
4
+ import { SenderKeyRecord } from './sender-key-record.js';
5
+ import { SenderKeyState } from './sender-key-state.js';
6
+ export class GroupCipher {
7
+ constructor(senderKeyStore, senderKeyName) {
8
+ this.senderKeyStore = senderKeyStore;
9
+ this.senderKeyName = senderKeyName;
10
+ }
11
+ async encrypt(paddedPlaintext) {
12
+ const record = await this.senderKeyStore.loadSenderKey(this.senderKeyName);
13
+ if (!record) {
14
+ throw new Error('No SenderKeyRecord found for encryption');
15
+ }
16
+ const senderKeyState = record.getSenderKeyState();
17
+ if (!senderKeyState) {
18
+ throw new Error('No session to encrypt message');
19
+ }
20
+ const iteration = senderKeyState.getSenderChainKey().getIteration();
21
+ const senderKey = this.getSenderKey(senderKeyState, iteration === 0 ? 0 : iteration + 1);
22
+ const ciphertext = await this.getCipherText(senderKey.getIv(), senderKey.getCipherKey(), paddedPlaintext);
23
+ const senderKeyMessage = new SenderKeyMessage(senderKeyState.getKeyId(), senderKey.getIteration(), ciphertext, senderKeyState.getSigningKeyPrivate());
24
+ await this.senderKeyStore.storeSenderKey(this.senderKeyName, record);
25
+ return senderKeyMessage.serialize();
26
+ }
27
+ async decrypt(senderKeyMessageBytes) {
28
+ const record = await this.senderKeyStore.loadSenderKey(this.senderKeyName);
29
+ if (!record) {
30
+ throw new Error('No SenderKeyRecord found for decryption');
31
+ }
32
+ const senderKeyMessage = new SenderKeyMessage(null, null, null, null, senderKeyMessageBytes);
33
+ const senderKeyState = record.getSenderKeyState(senderKeyMessage.getKeyId());
34
+ if (!senderKeyState) {
35
+ throw new Error('No session found to decrypt message');
36
+ }
37
+ senderKeyMessage.verifySignature(senderKeyState.getSigningKeyPublic());
38
+ const senderKey = this.getSenderKey(senderKeyState, senderKeyMessage.getIteration());
39
+ const plaintext = await this.getPlainText(senderKey.getIv(), senderKey.getCipherKey(), senderKeyMessage.getCipherText());
40
+ await this.senderKeyStore.storeSenderKey(this.senderKeyName, record);
41
+ return plaintext;
42
+ }
43
+ getSenderKey(senderKeyState, iteration) {
44
+ let senderChainKey = senderKeyState.getSenderChainKey();
45
+ if (senderChainKey.getIteration() > iteration) {
46
+ if (senderKeyState.hasSenderMessageKey(iteration)) {
47
+ const messageKey = senderKeyState.removeSenderMessageKey(iteration);
48
+ if (!messageKey) {
49
+ throw new Error('No sender message key found for iteration');
50
+ }
51
+ return messageKey;
52
+ }
53
+ throw new Error(`Received message with old counter: ${senderChainKey.getIteration()}, ${iteration}`);
54
+ }
55
+ if (iteration - senderChainKey.getIteration() > 2000) {
56
+ throw new Error('Over 2000 messages into the future!');
57
+ }
58
+ while (senderChainKey.getIteration() < iteration) {
59
+ senderKeyState.addSenderMessageKey(senderChainKey.getSenderMessageKey());
60
+ senderChainKey = senderChainKey.getNext();
61
+ }
62
+ senderKeyState.setSenderChainKey(senderChainKey.getNext());
63
+ return senderChainKey.getSenderMessageKey();
64
+ }
65
+ async getPlainText(iv, key, ciphertext) {
66
+ try {
67
+ return decrypt(key, ciphertext, iv);
68
+ }
69
+ catch (e) {
70
+ throw new Error('InvalidMessageException');
71
+ }
72
+ }
73
+ async getCipherText(iv, key, plaintext) {
74
+ try {
75
+ return encrypt(key, plaintext, iv);
76
+ }
77
+ catch (e) {
78
+ throw new Error('InvalidMessageException');
79
+ }
80
+ }
81
+ }
82
+ //# sourceMappingURL=group_cipher.js.map
@@ -0,0 +1,12 @@
1
+ export { GroupSessionBuilder } from './group-session-builder.js';
2
+ export { SenderKeyDistributionMessage } from './sender-key-distribution-message.js';
3
+ export { SenderKeyRecord } from './sender-key-record.js';
4
+ export { SenderKeyName } from './sender-key-name.js';
5
+ export { GroupCipher } from './group_cipher.js';
6
+ export { SenderKeyState } from './sender-key-state.js';
7
+ export { SenderKeyMessage } from './sender-key-message.js';
8
+ export { SenderMessageKey } from './sender-message-key.js';
9
+ export { SenderChainKey } from './sender-chain-key.js';
10
+ export { CiphertextMessage } from './ciphertext-message.js';
11
+ export * as keyhelper from './keyhelper.js';
12
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,18 @@
1
+ import * as nodeCrypto from 'crypto';
2
+ import { generateKeyPair } from 'libsignal/src/curve.js';
3
+ export function generateSenderKey() {
4
+ return nodeCrypto.randomBytes(32);
5
+ }
6
+ export function generateSenderKeyId() {
7
+ return nodeCrypto.randomInt(2147483647);
8
+ }
9
+ export function generateSenderSigningKey(key) {
10
+ if (!key) {
11
+ key = generateKeyPair();
12
+ }
13
+ return {
14
+ public: Buffer.from(key.pubKey),
15
+ private: Buffer.from(key.privKey)
16
+ };
17
+ }
18
+ //# sourceMappingURL=keyhelper.js.map
@@ -0,0 +1,26 @@
1
+ import { calculateMAC } from 'libsignal/src/crypto.js';
2
+ import { SenderMessageKey } from './sender-message-key.js';
3
+ export class SenderChainKey {
4
+ constructor(iteration, chainKey) {
5
+ this.MESSAGE_KEY_SEED = Buffer.from([0x01]);
6
+ this.CHAIN_KEY_SEED = Buffer.from([0x02]);
7
+ this.iteration = iteration;
8
+ this.chainKey = Buffer.from(chainKey);
9
+ }
10
+ getIteration() {
11
+ return this.iteration;
12
+ }
13
+ getSenderMessageKey() {
14
+ return new SenderMessageKey(this.iteration, this.getDerivative(this.MESSAGE_KEY_SEED, this.chainKey));
15
+ }
16
+ getNext() {
17
+ return new SenderChainKey(this.iteration + 1, this.getDerivative(this.CHAIN_KEY_SEED, this.chainKey));
18
+ }
19
+ getSeed() {
20
+ return this.chainKey;
21
+ }
22
+ getDerivative(seed, key) {
23
+ return calculateMAC(key, seed);
24
+ }
25
+ }
26
+ //# sourceMappingURL=sender-chain-key.js.map
@@ -0,0 +1,63 @@
1
+ import { proto } from '../../../WAProto/index.js';
2
+ import { CiphertextMessage } from './ciphertext-message.js';
3
+ export class SenderKeyDistributionMessage extends CiphertextMessage {
4
+ constructor(id, iteration, chainKey, signatureKey, serialized) {
5
+ super();
6
+ if (serialized) {
7
+ try {
8
+ const message = serialized.slice(1);
9
+ const distributionMessage = proto.SenderKeyDistributionMessage.decode(message).toJSON();
10
+ this.serialized = serialized;
11
+ this.id = distributionMessage.id;
12
+ this.iteration = distributionMessage.iteration;
13
+ this.chainKey =
14
+ typeof distributionMessage.chainKey === 'string'
15
+ ? Buffer.from(distributionMessage.chainKey, 'base64')
16
+ : distributionMessage.chainKey;
17
+ this.signatureKey =
18
+ typeof distributionMessage.signingKey === 'string'
19
+ ? Buffer.from(distributionMessage.signingKey, 'base64')
20
+ : distributionMessage.signingKey;
21
+ }
22
+ catch (e) {
23
+ throw new Error(String(e));
24
+ }
25
+ }
26
+ else {
27
+ const version = this.intsToByteHighAndLow(this.CURRENT_VERSION, this.CURRENT_VERSION);
28
+ this.id = id;
29
+ this.iteration = iteration;
30
+ this.chainKey = chainKey;
31
+ this.signatureKey = signatureKey;
32
+ const message = proto.SenderKeyDistributionMessage.encode(proto.SenderKeyDistributionMessage.create({
33
+ id,
34
+ iteration,
35
+ chainKey,
36
+ signingKey: this.signatureKey
37
+ })).finish();
38
+ this.serialized = Buffer.concat([Buffer.from([version]), message]);
39
+ }
40
+ }
41
+ intsToByteHighAndLow(highValue, lowValue) {
42
+ return (((highValue << 4) | lowValue) & 0xff) % 256;
43
+ }
44
+ serialize() {
45
+ return this.serialized;
46
+ }
47
+ getType() {
48
+ return this.SENDERKEY_DISTRIBUTION_TYPE;
49
+ }
50
+ getIteration() {
51
+ return this.iteration;
52
+ }
53
+ getChainKey() {
54
+ return this.chainKey;
55
+ }
56
+ getSignatureKey() {
57
+ return this.signatureKey;
58
+ }
59
+ getId() {
60
+ return this.id;
61
+ }
62
+ }
63
+ //# sourceMappingURL=sender-key-distribution-message.js.map