@boruto_vk7/baileys 1.0.0

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 (110) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +1388 -0
  3. package/WAProto/index.js +104236 -0
  4. package/engine-requirements.js +13 -0
  5. package/lib/Defaults/index.js +148 -0
  6. package/lib/Signal/Group/ciphertext-message.js +11 -0
  7. package/lib/Signal/Group/group-session-builder.js +29 -0
  8. package/lib/Signal/Group/group_cipher.js +81 -0
  9. package/lib/Signal/Group/index.js +11 -0
  10. package/lib/Signal/Group/keyhelper.js +17 -0
  11. package/lib/Signal/Group/sender-chain-key.js +25 -0
  12. package/lib/Signal/Group/sender-key-distribution-message.js +62 -0
  13. package/lib/Signal/Group/sender-key-message.js +65 -0
  14. package/lib/Signal/Group/sender-key-name.js +47 -0
  15. package/lib/Signal/Group/sender-key-record.js +40 -0
  16. package/lib/Signal/Group/sender-key-state.js +83 -0
  17. package/lib/Signal/Group/sender-message-key.js +25 -0
  18. package/lib/Signal/libsignal.js +406 -0
  19. package/lib/Signal/lid-mapping.js +276 -0
  20. package/lib/Socket/Client/index.js +2 -0
  21. package/lib/Socket/Client/types.js +10 -0
  22. package/lib/Socket/Client/websocket.js +53 -0
  23. package/lib/Socket/business.js +378 -0
  24. package/lib/Socket/chats.js +1059 -0
  25. package/lib/Socket/communities.js +430 -0
  26. package/lib/Socket/groups.js +329 -0
  27. package/lib/Socket/index.js +11 -0
  28. package/lib/Socket/messages-recv.js +1476 -0
  29. package/lib/Socket/messages-send.js +1268 -0
  30. package/lib/Socket/mex.js +41 -0
  31. package/lib/Socket/newsletter.js +227 -0
  32. package/lib/Socket/socket.js +949 -0
  33. package/lib/Store/index.js +3 -0
  34. package/lib/Store/make-in-memory-store.js +420 -0
  35. package/lib/Store/make-ordered-dictionary.js +78 -0
  36. package/lib/Store/object-repository.js +23 -0
  37. package/lib/Types/Auth.js +1 -0
  38. package/lib/Types/Bussines.js +1 -0
  39. package/lib/Types/Call.js +1 -0
  40. package/lib/Types/Chat.js +7 -0
  41. package/lib/Types/Contact.js +1 -0
  42. package/lib/Types/Events.js +1 -0
  43. package/lib/Types/GroupMetadata.js +1 -0
  44. package/lib/Types/Label.js +24 -0
  45. package/lib/Types/LabelAssociation.js +6 -0
  46. package/lib/Types/Message.js +17 -0
  47. package/lib/Types/Newsletter.js +33 -0
  48. package/lib/Types/Product.js +1 -0
  49. package/lib/Types/RichType.js +22 -0
  50. package/lib/Types/Signal.js +1 -0
  51. package/lib/Types/Socket.js +2 -0
  52. package/lib/Types/State.js +12 -0
  53. package/lib/Types/USync.js +1 -0
  54. package/lib/Types/index.js +25 -0
  55. package/lib/Utils/auth-utils.js +289 -0
  56. package/lib/Utils/browser-utils.js +28 -0
  57. package/lib/Utils/business.js +230 -0
  58. package/lib/Utils/chat-utils.js +811 -0
  59. package/lib/Utils/companion-reg-client-utils.js +32 -0
  60. package/lib/Utils/crypto.js +117 -0
  61. package/lib/Utils/decode-wa-message.js +282 -0
  62. package/lib/Utils/event-buffer.js +589 -0
  63. package/lib/Utils/generics.js +385 -0
  64. package/lib/Utils/history.js +130 -0
  65. package/lib/Utils/identity-change-handler.js +48 -0
  66. package/lib/Utils/index.js +23 -0
  67. package/lib/Utils/link-preview.js +84 -0
  68. package/lib/Utils/logger.js +2 -0
  69. package/lib/Utils/lt-hash.js +7 -0
  70. package/lib/Utils/make-mutex.js +32 -0
  71. package/lib/Utils/message-retry-manager.js +241 -0
  72. package/lib/Utils/messages-media.js +830 -0
  73. package/lib/Utils/messages.js +1879 -0
  74. package/lib/Utils/noise-handler.js +200 -0
  75. package/lib/Utils/offline-node-processor.js +39 -0
  76. package/lib/Utils/pre-key-manager.js +105 -0
  77. package/lib/Utils/process-message.js +527 -0
  78. package/lib/Utils/reporting-utils.js +257 -0
  79. package/lib/Utils/rich-message-utils.js +387 -0
  80. package/lib/Utils/signal.js +158 -0
  81. package/lib/Utils/stanza-ack.js +37 -0
  82. package/lib/Utils/sync-action-utils.js +47 -0
  83. package/lib/Utils/tc-token-utils.js +17 -0
  84. package/lib/Utils/use-multi-file-auth-state.js +120 -0
  85. package/lib/Utils/use-single-file-auth-state.js +96 -0
  86. package/lib/Utils/validate-connection.js +206 -0
  87. package/lib/WABinary/constants.js +1372 -0
  88. package/lib/WABinary/decode.js +261 -0
  89. package/lib/WABinary/encode.js +219 -0
  90. package/lib/WABinary/generic-utils.js +227 -0
  91. package/lib/WABinary/index.js +5 -0
  92. package/lib/WABinary/jid-utils.js +95 -0
  93. package/lib/WABinary/types.js +1 -0
  94. package/lib/WAM/BinaryInfo.js +9 -0
  95. package/lib/WAM/constants.js +22852 -0
  96. package/lib/WAM/encode.js +149 -0
  97. package/lib/WAM/index.js +3 -0
  98. package/lib/WAUSync/Protocols/USyncContactProtocol.js +28 -0
  99. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  100. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  101. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  102. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -0
  103. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  104. package/lib/WAUSync/Protocols/index.js +4 -0
  105. package/lib/WAUSync/USyncQuery.js +93 -0
  106. package/lib/WAUSync/USyncUser.js +22 -0
  107. package/lib/WAUSync/index.js +3 -0
  108. package/lib/index.js +14 -0
  109. package/lib/logger.js +87 -0
  110. package/package.json +80 -0
@@ -0,0 +1,158 @@
1
+ import { KEY_BUNDLE_TYPE } from '../Defaults/index.js';
2
+ import { assertNodeErrorFree, getBinaryNodeChild, getBinaryNodeChildBuffer, getBinaryNodeChildren, getBinaryNodeChildUInt, getServerFromDomainType, jidDecode, S_WHATSAPP_NET, WAJIDDomains } from '../WABinary/index.js';
3
+ import { Curve, generateSignalPubKey } from './crypto.js';
4
+ import { encodeBigEndian } from './generics.js';
5
+ function chunk(array, size) {
6
+ const chunks = [];
7
+ for (let i = 0; i < array.length; i += size) {
8
+ chunks.push(array.slice(i, i + size));
9
+ }
10
+ return chunks;
11
+ }
12
+ export const createSignalIdentity = (wid, accountSignatureKey) => {
13
+ return {
14
+ identifier: { name: wid, deviceId: 0 },
15
+ identifierKey: generateSignalPubKey(accountSignatureKey)
16
+ };
17
+ };
18
+ export const getPreKeys = async ({ get }, min, limit) => {
19
+ const idList = [];
20
+ for (let id = min; id < limit; id++) {
21
+ idList.push(id.toString());
22
+ }
23
+ return get('pre-key', idList);
24
+ };
25
+ export const generateOrGetPreKeys = (creds, range) => {
26
+ const avaliable = creds.nextPreKeyId - creds.firstUnuploadedPreKeyId;
27
+ const remaining = range - avaliable;
28
+ const lastPreKeyId = creds.nextPreKeyId + remaining - 1;
29
+ const newPreKeys = {};
30
+ if (remaining > 0) {
31
+ for (let i = creds.nextPreKeyId; i <= lastPreKeyId; i++) {
32
+ newPreKeys[i] = Curve.generateKeyPair();
33
+ }
34
+ }
35
+ return {
36
+ newPreKeys,
37
+ lastPreKeyId,
38
+ preKeysRange: [creds.firstUnuploadedPreKeyId, range]
39
+ };
40
+ };
41
+ export const xmppSignedPreKey = (key) => ({
42
+ tag: 'skey',
43
+ attrs: {},
44
+ content: [
45
+ { tag: 'id', attrs: {}, content: encodeBigEndian(key.keyId, 3) },
46
+ { tag: 'value', attrs: {}, content: key.keyPair.public },
47
+ { tag: 'signature', attrs: {}, content: key.signature }
48
+ ]
49
+ });
50
+ export const xmppPreKey = (pair, id) => ({
51
+ tag: 'key',
52
+ attrs: {},
53
+ content: [
54
+ { tag: 'id', attrs: {}, content: encodeBigEndian(id, 3) },
55
+ { tag: 'value', attrs: {}, content: pair.public }
56
+ ]
57
+ });
58
+ export const parseAndInjectE2ESessions = async (node, repository) => {
59
+ const extractKey = (key) => key
60
+ ? {
61
+ keyId: getBinaryNodeChildUInt(key, 'id', 3),
62
+ publicKey: generateSignalPubKey(getBinaryNodeChildBuffer(key, 'value')),
63
+ signature: getBinaryNodeChildBuffer(key, 'signature')
64
+ }
65
+ : undefined;
66
+ const nodes = getBinaryNodeChildren(getBinaryNodeChild(node, 'list'), 'user');
67
+ for (const node of nodes) {
68
+ assertNodeErrorFree(node);
69
+ }
70
+ // Most of the work in repository.injectE2ESession is CPU intensive, not IO
71
+ // So Promise.all doesn't really help here,
72
+ // but blocks even loop if we're using it inside keys.transaction, and it makes it "sync" actually
73
+ // This way we chunk it in smaller parts and between those parts we can yield to the event loop
74
+ // It's rare case when you need to E2E sessions for so many users, but it's possible
75
+ const chunkSize = 100;
76
+ const chunks = chunk(nodes, chunkSize);
77
+ for (const nodesChunk of chunks) {
78
+ for (const node of nodesChunk) {
79
+ const signedKey = getBinaryNodeChild(node, 'skey');
80
+ const key = getBinaryNodeChild(node, 'key');
81
+ const identity = getBinaryNodeChildBuffer(node, 'identity');
82
+ const jid = node.attrs.jid;
83
+ const registrationId = getBinaryNodeChildUInt(node, 'registration', 4);
84
+ await repository.injectE2ESession({
85
+ jid,
86
+ session: {
87
+ registrationId: registrationId,
88
+ identityKey: generateSignalPubKey(identity),
89
+ signedPreKey: extractKey(signedKey),
90
+ preKey: extractKey(key)
91
+ }
92
+ });
93
+ }
94
+ }
95
+ };
96
+ export const extractDeviceJids = (result, myJid, myLid, excludeZeroDevices) => {
97
+ const { user: myUser, device: myDevice } = jidDecode(myJid);
98
+ const extracted = [];
99
+ for (const userResult of result) {
100
+ const { devices, id } = userResult;
101
+ const decoded = jidDecode(id), { user, server } = decoded;
102
+ let { domainType } = decoded;
103
+ const deviceList = devices?.deviceList;
104
+ if (!Array.isArray(deviceList))
105
+ continue;
106
+ for (const { id: device, keyIndex, isHosted } of deviceList) {
107
+ if ((!excludeZeroDevices || device !== 0) && // if zero devices are not-excluded, or device is non zero
108
+ ((myUser !== user && myLid !== user) || myDevice !== device) && // either different user or if me user, not this device
109
+ (device === 0 || !!keyIndex) // ensure that "key-index" is specified for "non-zero" devices, produces a bad req otherwise
110
+ ) {
111
+ if (isHosted) {
112
+ domainType = domainType === WAJIDDomains.LID ? WAJIDDomains.HOSTED_LID : WAJIDDomains.HOSTED;
113
+ }
114
+ extracted.push({
115
+ user,
116
+ device,
117
+ domainType,
118
+ server: getServerFromDomainType(server, domainType)
119
+ });
120
+ }
121
+ }
122
+ }
123
+ return extracted;
124
+ };
125
+ /**
126
+ * get the next N keys for upload or processing
127
+ * @param count number of pre-keys to get or generate
128
+ */
129
+ export const getNextPreKeys = async ({ creds, keys }, count) => {
130
+ const { newPreKeys, lastPreKeyId, preKeysRange } = generateOrGetPreKeys(creds, count);
131
+ const update = {
132
+ nextPreKeyId: Math.max(lastPreKeyId + 1, creds.nextPreKeyId),
133
+ firstUnuploadedPreKeyId: Math.max(creds.firstUnuploadedPreKeyId, lastPreKeyId + 1)
134
+ };
135
+ await keys.set({ 'pre-key': newPreKeys });
136
+ const preKeys = await getPreKeys(keys, preKeysRange[0], preKeysRange[0] + preKeysRange[1]);
137
+ return { update, preKeys };
138
+ };
139
+ export const getNextPreKeysNode = async (state, count) => {
140
+ const { creds } = state;
141
+ const { update, preKeys } = await getNextPreKeys(state, count);
142
+ const node = {
143
+ tag: 'iq',
144
+ attrs: {
145
+ xmlns: 'encrypt',
146
+ type: 'set',
147
+ to: S_WHATSAPP_NET
148
+ },
149
+ content: [
150
+ { tag: 'registration', attrs: {}, content: encodeBigEndian(creds.registrationId) },
151
+ { tag: 'type', attrs: {}, content: KEY_BUNDLE_TYPE },
152
+ { tag: 'identity', attrs: {}, content: creds.signedIdentityKey.public },
153
+ { tag: 'list', attrs: {}, content: Object.keys(preKeys).map(k => xmppPreKey(preKeys[+k], +k)) },
154
+ xmppSignedPreKey(creds.signedPreKey)
155
+ ]
156
+ };
157
+ return { update, node };
158
+ };
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Builds an ACK stanza for a received node.
3
+ * Pure function -- no I/O, no side effects.
4
+ *
5
+ * Mirrors WhatsApp Web's ACK construction:
6
+ * - WAWebHandleMsgSendAck.sendAck / sendNack
7
+ * - WAWebCreateNackFromStanza.createNackFromStanza
8
+ */
9
+ export function buildAckStanza(node, errorCode, meId) {
10
+ const { tag, attrs } = node;
11
+ const stanza = {
12
+ tag: 'ack',
13
+ attrs: {
14
+ id: attrs.id,
15
+ to: attrs.from,
16
+ class: tag
17
+ }
18
+ };
19
+ if (errorCode) {
20
+ stanza.attrs.error = errorCode.toString();
21
+ }
22
+ if (attrs.participant) {
23
+ stanza.attrs.participant = attrs.participant;
24
+ }
25
+ if (attrs.recipient) {
26
+ stanza.attrs.recipient = attrs.recipient;
27
+ }
28
+ // WA Web always includes type when present: `n.type || DROP_ATTR`
29
+ if (attrs.type) {
30
+ stanza.attrs.type = attrs.type;
31
+ }
32
+ // WA Web WAWebHandleMsgSendAck.sendAck/sendNack always include `from` for message-class ACKs
33
+ if (tag === 'message' && meId) {
34
+ stanza.attrs.from = meId;
35
+ }
36
+ return stanza;
37
+ }
@@ -0,0 +1,47 @@
1
+ import { proto } from '../../WAProto/index.js';
2
+ import { isLidUser, isPnUser } from '../WABinary/index.js';
3
+ /**
4
+ * Process contactAction and return events to emit.
5
+ * Pure function - no side effects.
6
+ */
7
+ export const processContactAction = (action, id, logger) => {
8
+ const results = [];
9
+ if (!id) {
10
+ logger?.warn({ hasFullName: !!action.fullName, hasLidJid: !!action.lidJid, hasPnJid: !!action.pnJid }, 'contactAction sync: missing id in index');
11
+ return results;
12
+ }
13
+ const lidJid = action.lidJid;
14
+ const idIsPn = isPnUser(id);
15
+ // PN is in index[1], not in contactAction.pnJid which is usually null
16
+ const phoneNumber = idIsPn ? id : action.pnJid || undefined;
17
+ // Always emit contacts.upsert
18
+ results.push({
19
+ event: 'contacts.upsert',
20
+ data: [
21
+ {
22
+ id,
23
+ name: action.fullName || action.firstName || action.username || undefined,
24
+ lid: lidJid || undefined,
25
+ phoneNumber
26
+ }
27
+ ]
28
+ });
29
+ // Emit lid-mapping.update if we have valid LID-PN pair
30
+ if (lidJid && isLidUser(lidJid) && idIsPn) {
31
+ results.push({
32
+ event: 'lid-mapping.update',
33
+ data: { lid: lidJid, pn: id }
34
+ });
35
+ }
36
+ return results;
37
+ };
38
+ export const emitSyncActionResults = (ev, results) => {
39
+ for (const result of results) {
40
+ if (result.event === 'contacts.upsert') {
41
+ ev.emit('contacts.upsert', result.data);
42
+ }
43
+ else {
44
+ ev.emit('lid-mapping.update', result.data);
45
+ }
46
+ }
47
+ };
@@ -0,0 +1,17 @@
1
+ export async function buildTcTokenFromJid({ authState, jid, baseContent = [] }) {
2
+ try {
3
+ const tcTokenData = await authState.keys.get('tctoken', [jid]);
4
+ const tcTokenBuffer = tcTokenData?.[jid]?.token;
5
+ if (!tcTokenBuffer)
6
+ return baseContent.length > 0 ? baseContent : undefined;
7
+ baseContent.push({
8
+ tag: 'tctoken',
9
+ attrs: {},
10
+ content: tcTokenBuffer
11
+ });
12
+ return baseContent;
13
+ }
14
+ catch (error) {
15
+ return baseContent.length > 0 ? baseContent : undefined;
16
+ }
17
+ }
@@ -0,0 +1,120 @@
1
+ import { Mutex } from 'async-mutex';
2
+ import { mkdir, readFile, stat, unlink, writeFile } from 'fs/promises';
3
+ import { join } from 'path';
4
+ import { proto } from '../../WAProto/index.js';
5
+ import { initAuthCreds } from './auth-utils.js';
6
+ import { BufferJSON } from './generics.js';
7
+ // We need to lock files due to the fact that we are using async functions to read and write files
8
+ // https://github.com/WhiskeySockets/Baileys/issues/794
9
+ // https://github.com/nodejs/node/issues/26338
10
+ // Use a Map to store mutexes for each file path
11
+ const fileLocks = new Map();
12
+ // Get or create a mutex for a specific file path
13
+ const getFileLock = (path) => {
14
+ let mutex = fileLocks.get(path);
15
+ if (!mutex) {
16
+ mutex = new Mutex();
17
+ fileLocks.set(path, mutex);
18
+ }
19
+ return mutex;
20
+ };
21
+ /**
22
+ * stores the full authentication state in a single folder.
23
+ * Far more efficient than singlefileauthstate
24
+ *
25
+ * Again, I wouldn't endorse this for any production level use other than perhaps a bot.
26
+ * Would recommend writing an auth state for use with a proper SQL or No-SQL DB
27
+ * */
28
+ export const useMultiFileAuthState = async (folder) => {
29
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
30
+ const writeData = async (data, file) => {
31
+ const filePath = join(folder, fixFileName(file));
32
+ const mutex = getFileLock(filePath);
33
+ return mutex.acquire().then(async (release) => {
34
+ try {
35
+ await writeFile(filePath, JSON.stringify(data, BufferJSON.replacer));
36
+ }
37
+ finally {
38
+ release();
39
+ }
40
+ });
41
+ };
42
+ const readData = async (file) => {
43
+ try {
44
+ const filePath = join(folder, fixFileName(file));
45
+ const mutex = getFileLock(filePath);
46
+ return await mutex.acquire().then(async (release) => {
47
+ try {
48
+ const data = await readFile(filePath, { encoding: 'utf-8' });
49
+ return JSON.parse(data, BufferJSON.reviver);
50
+ }
51
+ finally {
52
+ release();
53
+ }
54
+ });
55
+ }
56
+ catch (error) {
57
+ return null;
58
+ }
59
+ };
60
+ const removeData = async (file) => {
61
+ try {
62
+ const filePath = join(folder, fixFileName(file));
63
+ const mutex = getFileLock(filePath);
64
+ return mutex.acquire().then(async (release) => {
65
+ try {
66
+ await unlink(filePath);
67
+ }
68
+ catch {
69
+ }
70
+ finally {
71
+ release();
72
+ }
73
+ });
74
+ }
75
+ catch { }
76
+ };
77
+ const folderInfo = await stat(folder).catch(() => { });
78
+ if (folderInfo) {
79
+ if (!folderInfo.isDirectory()) {
80
+ throw new Error(`found something that is not a directory at ${folder}, either delete it or specify a different location`);
81
+ }
82
+ }
83
+ else {
84
+ await mkdir(folder, { recursive: true });
85
+ }
86
+ const fixFileName = (file) => file?.replace(/\//g, '__')?.replace(/:/g, '-');
87
+ const creds = (await readData('creds.json')) || initAuthCreds();
88
+ return {
89
+ state: {
90
+ creds,
91
+ keys: {
92
+ get: async (type, ids) => {
93
+ const data = {};
94
+ await Promise.all(ids.map(async (id) => {
95
+ let value = await readData(`${type}-${id}.json`);
96
+ if (type === 'app-state-sync-key' && value) {
97
+ value = proto.Message.AppStateSyncKeyData.fromObject(value);
98
+ }
99
+ data[id] = value;
100
+ }));
101
+ return data;
102
+ },
103
+ set: async (data) => {
104
+ const tasks = [];
105
+ for (const category in data) {
106
+ for (const id in data[category]) {
107
+ const value = data[category][id];
108
+ const file = `${category}-${id}.json`;
109
+ tasks.push(value ? writeData(value, file) : removeData(file));
110
+ }
111
+ }
112
+ await Promise.all(tasks);
113
+ }
114
+ }
115
+ },
116
+ saveCreds: async () => {
117
+ return writeData(creds, 'creds.json');
118
+ }
119
+ };
120
+ };
@@ -0,0 +1,96 @@
1
+ import { readFile, rename, stat, writeFile } from 'fs/promises';
2
+ import { DEFAULT_CACHE_TTLS } from '../Defaults/index.js';
3
+ import { proto } from '../../WAProto/index.js';
4
+ import { initAuthCreds } from './auth-utils.js';
5
+ import { BufferJSON } from './generics.js';
6
+ // Lia@Changes 25-03-26 --- Add useSingleFileAuthState with integrated cache
7
+ const FLUSH_TIMEOUT_MS = 3000;
8
+ export const useSingleFileAuthState = async (fileName) => {
9
+ const cache = new Map();
10
+ let isLoaded,
11
+ isWriting,
12
+ isNeedWrite,
13
+ flushTimeout,
14
+ loadPromise;
15
+ const loadKey = () => {
16
+ if (isLoaded) return;
17
+ if (loadPromise) return loadPromise;
18
+ loadPromise = (async () => {
19
+ try {
20
+ const data = JSON.parse(await readFile(fileName, 'utf-8'), BufferJSON.reviver);
21
+ for (const [keyName, value] of Object.entries(data)) {
22
+ cache.set(keyName, value);
23
+ }
24
+ }
25
+ catch { }
26
+ isLoaded = true;
27
+ loadPromise = null;
28
+ })();
29
+ return loadPromise;
30
+ };
31
+ const flushKey = () => {
32
+ if (flushTimeout) return;
33
+ flushTimeout = setTimeout(async () => {
34
+ flushTimeout = null;
35
+ if (isWriting) {
36
+ isNeedWrite = true;
37
+ return;
38
+ }
39
+ isWriting = true;
40
+ do {
41
+ isNeedWrite = false;
42
+ const tempFile = fileName + '.temp';
43
+ const value = Object.fromEntries(cache);
44
+ await writeFile(tempFile, JSON.stringify(value, BufferJSON.replacer));
45
+ await rename(tempFile, fileName);
46
+ }
47
+ while (isNeedWrite);
48
+ isWriting = false;
49
+ }, FLUSH_TIMEOUT_MS);
50
+ };
51
+ const writeKey = (keyName, value) => {
52
+ cache.set(keyName, value);
53
+ flushKey();
54
+ };
55
+ const removeKey = (keyName) => {
56
+ cache.delete(keyName);
57
+ flushKey();
58
+ };
59
+ const fileInfo = await stat(fileName).catch(() => null);
60
+ if (!fileInfo) {
61
+ await writeFile(fileName, '{}');
62
+ }
63
+ else if (!fileInfo.isFile()) {
64
+ throw new Error(`found something that is not a file at ${fileName}, either delete it or specify a different location`);
65
+ }
66
+ await loadKey();
67
+ const creds = cache.get('creds') || initAuthCreds();
68
+ return {
69
+ state: {
70
+ creds,
71
+ keys: {
72
+ get: (type, ids) => {
73
+ const data = {};
74
+ for (const id of ids) {
75
+ let value = cache.get(type + id);
76
+ if (type === 'app-state-sync-key' && value) {
77
+ value = proto.Message.AppStateSyncKeyData.fromObject(value);
78
+ }
79
+ data[id] = value;
80
+ }
81
+ return data;
82
+ },
83
+ set: (data) => {
84
+ for (const category in data) {
85
+ for (const id in data[category]) {
86
+ const keyName = category + id;
87
+ const value = data[category][id];
88
+ value ? writeKey(keyName, value) : removeKey(keyName);
89
+ }
90
+ }
91
+ }
92
+ }
93
+ },
94
+ saveCreds: () => writeKey('creds', creds)
95
+ };
96
+ };
@@ -0,0 +1,206 @@
1
+ import { Boom } from '@hapi/boom';
2
+ import { createHash } from 'crypto';
3
+ import { proto } from '../../WAProto/index.js';
4
+ import { KEY_BUNDLE_TYPE, WA_ADV_ACCOUNT_SIG_PREFIX, WA_ADV_DEVICE_SIG_PREFIX, WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX } from '../Defaults/index.js';
5
+ import { getBinaryNodeChild, jidDecode, S_WHATSAPP_NET } from '../WABinary/index.js';
6
+ import { Curve, hmacSign } from './crypto.js';
7
+ import { encodeBigEndian } from './generics.js';
8
+ import { createSignalIdentity } from './signal.js';
9
+ const getUserAgent = (config) => {
10
+ return {
11
+ appVersion: {
12
+ primary: config.version[0],
13
+ secondary: config.version[1],
14
+ tertiary: config.version[2]
15
+ },
16
+ platform: config.browser[1].toLocaleLowerCase().includes('android')
17
+ ? proto.ClientPayload.UserAgent.Platform.ANDROID
18
+ : proto.ClientPayload.UserAgent.Platform.WEB,
19
+ releaseChannel: proto.ClientPayload.UserAgent.ReleaseChannel.RELEASE,
20
+ osVersion: '0.1',
21
+ device: 'Desktop',
22
+ osBuildNumber: '0.1',
23
+ localeLanguageIso6391: 'en',
24
+ mnc: '000',
25
+ mcc: '000',
26
+ localeCountryIso31661Alpha2: config.countryCode
27
+ };
28
+ };
29
+ const PLATFORM_MAP = {
30
+ 'Mac OS': proto.ClientPayload.WebInfo.WebSubPlatform.DARWIN,
31
+ Windows: proto.ClientPayload.WebInfo.WebSubPlatform.WIN32
32
+ };
33
+ const getWebInfo = (config) => {
34
+ let webSubPlatform = proto.ClientPayload.WebInfo.WebSubPlatform.WEB_BROWSER;
35
+ if (config.syncFullHistory &&
36
+ PLATFORM_MAP[config.browser[0]] &&
37
+ config.browser[1] === 'Desktop') {
38
+ webSubPlatform = PLATFORM_MAP[config.browser[0]];
39
+ }
40
+ return { webSubPlatform };
41
+ };
42
+ const getClientPayload = (config) => {
43
+ const payload = {
44
+ connectType: proto.ClientPayload.ConnectType.WIFI_UNKNOWN,
45
+ connectReason: proto.ClientPayload.ConnectReason.USER_ACTIVATED,
46
+ userAgent: getUserAgent(config)
47
+ };
48
+ if (!config.browser[1].toLocaleLowerCase().includes('android')) {
49
+ payload.webInfo = getWebInfo(config);
50
+ }
51
+ return payload;
52
+ };
53
+ export const generateLoginNode = (userJid, config) => {
54
+ const { user, device } = jidDecode(userJid);
55
+ const payload = {
56
+ ...getClientPayload(config),
57
+ passive: true,
58
+ pull: true,
59
+ username: +user,
60
+ device: device,
61
+ // TODO: investigate (hard set as false atm)
62
+ lidDbMigrated: false
63
+ };
64
+ return proto.ClientPayload.fromObject(payload);
65
+ };
66
+ const getPlatformType = (platform) => {
67
+ const platformType = platform.toUpperCase();
68
+ if (platformType === 'ANDROID') {
69
+ return proto.DeviceProps.PlatformType.ANDROID_PHONE;
70
+ }
71
+ return (proto.DeviceProps.PlatformType[platformType] ||
72
+ proto.DeviceProps.PlatformType.CHROME);
73
+ };
74
+ export const generateRegistrationNode = ({ registrationId, signedPreKey, signedIdentityKey }, config) => {
75
+ // the app version needs to be md5 hashed
76
+ // and passed in
77
+ const appVersionBuf = createHash('md5')
78
+ .update(config.version.join('.')) // join as string
79
+ .digest();
80
+ const companion = {
81
+ os: config.browser[0],
82
+ platformType: getPlatformType(config.browser[1]),
83
+ requireFullSync: config.syncFullHistory,
84
+ historySyncConfig: {
85
+ storageQuotaMb: 10240,
86
+ inlineInitialPayloadInE2EeMsg: true,
87
+ recentSyncDaysLimit: undefined,
88
+ supportCallLogHistory: false,
89
+ supportBotUserAgentChatHistory: true,
90
+ supportCagReactionsAndPolls: true,
91
+ supportBizHostedMsg: true,
92
+ supportRecentSyncChunkMessageCountTuning: true,
93
+ supportHostedGroupMsg: true,
94
+ supportFbidBotChatHistory: true,
95
+ supportAddOnHistorySyncMigration: undefined,
96
+ supportMessageAssociation: true,
97
+ supportGroupHistory: false,
98
+ onDemandReady: undefined,
99
+ supportGuestChat: undefined
100
+ },
101
+ version: {
102
+ primary: 10,
103
+ secondary: 15,
104
+ tertiary: 7
105
+ }
106
+ };
107
+ const companionProto = proto.DeviceProps.encode(companion).finish();
108
+ const registerPayload = {
109
+ ...getClientPayload(config),
110
+ passive: false,
111
+ pull: false,
112
+ devicePairingData: {
113
+ buildHash: appVersionBuf,
114
+ deviceProps: companionProto,
115
+ eRegid: encodeBigEndian(registrationId),
116
+ eKeytype: KEY_BUNDLE_TYPE,
117
+ eIdent: signedIdentityKey.public,
118
+ eSkeyId: encodeBigEndian(signedPreKey.keyId, 3),
119
+ eSkeyVal: signedPreKey.keyPair.public,
120
+ eSkeySig: signedPreKey.signature
121
+ }
122
+ };
123
+ return proto.ClientPayload.fromObject(registerPayload);
124
+ };
125
+ export const configureSuccessfulPairing = (stanza, { advSecretKey, signedIdentityKey, signalIdentities }) => {
126
+ const msgId = stanza.attrs.id;
127
+ const pairSuccessNode = getBinaryNodeChild(stanza, 'pair-success');
128
+ const deviceIdentityNode = getBinaryNodeChild(pairSuccessNode, 'device-identity');
129
+ const platformNode = getBinaryNodeChild(pairSuccessNode, 'platform');
130
+ const deviceNode = getBinaryNodeChild(pairSuccessNode, 'device');
131
+ const businessNode = getBinaryNodeChild(pairSuccessNode, 'biz');
132
+ if (!deviceIdentityNode || !deviceNode) {
133
+ throw new Boom('Missing device-identity or device in pair success node', { data: stanza });
134
+ }
135
+ const bizName = businessNode?.attrs.name;
136
+ const jid = deviceNode.attrs.jid;
137
+ const lid = deviceNode.attrs.lid;
138
+ const { details, hmac, accountType } = proto.ADVSignedDeviceIdentityHMAC.decode(deviceIdentityNode.content);
139
+ let hmacPrefix = Buffer.from([]);
140
+ if (accountType !== undefined && accountType === proto.ADVEncryptionType.HOSTED) {
141
+ hmacPrefix = WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX;
142
+ }
143
+ const advSign = hmacSign(Buffer.concat([hmacPrefix, details]), Buffer.from(advSecretKey, 'base64'));
144
+ if (Buffer.compare(hmac, advSign) !== 0) {
145
+ throw new Boom('Invalid account signature');
146
+ }
147
+ const account = proto.ADVSignedDeviceIdentity.decode(details);
148
+ const { accountSignatureKey, accountSignature, details: deviceDetails } = account;
149
+ const deviceIdentity = proto.ADVDeviceIdentity.decode(deviceDetails);
150
+ const accountSignaturePrefix = deviceIdentity.deviceType === proto.ADVEncryptionType.HOSTED
151
+ ? WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX
152
+ : WA_ADV_ACCOUNT_SIG_PREFIX;
153
+ const accountMsg = Buffer.concat([accountSignaturePrefix, deviceDetails, signedIdentityKey.public]);
154
+ if (!Curve.verify(accountSignatureKey, accountMsg, accountSignature)) {
155
+ throw new Boom('Failed to verify account signature');
156
+ }
157
+ const deviceMsg = Buffer.concat([
158
+ WA_ADV_DEVICE_SIG_PREFIX,
159
+ deviceDetails,
160
+ signedIdentityKey.public,
161
+ accountSignatureKey
162
+ ]);
163
+ account.deviceSignature = Curve.sign(signedIdentityKey.private, deviceMsg);
164
+ const identity = createSignalIdentity(lid, accountSignatureKey);
165
+ const accountEnc = encodeSignedDeviceIdentity(account, false);
166
+ const reply = {
167
+ tag: 'iq',
168
+ attrs: {
169
+ to: S_WHATSAPP_NET,
170
+ type: 'result',
171
+ id: msgId
172
+ },
173
+ content: [
174
+ {
175
+ tag: 'pair-device-sign',
176
+ attrs: {},
177
+ content: [
178
+ {
179
+ tag: 'device-identity',
180
+ attrs: { 'key-index': deviceIdentity.keyIndex.toString() },
181
+ content: accountEnc
182
+ }
183
+ ]
184
+ }
185
+ ]
186
+ };
187
+ const authUpdate = {
188
+ account,
189
+ me: { id: jid, name: bizName, lid },
190
+ signalIdentities: [...(signalIdentities || []), identity],
191
+ platform: platformNode?.attrs.name
192
+ };
193
+ return {
194
+ creds: authUpdate,
195
+ reply
196
+ };
197
+ };
198
+ export const encodeSignedDeviceIdentity = (account, includeSignatureKey) => {
199
+ account = { ...account };
200
+ // set to null if we are not to include the signature key
201
+ // or if we are including the signature key but it is empty
202
+ if (!includeSignatureKey || !account.accountSignatureKey?.length) {
203
+ account.accountSignatureKey = null;
204
+ }
205
+ return proto.ADVSignedDeviceIdentity.encode(account).finish();
206
+ };