@nexustechpro/baileys 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/README.md +1573 -0
  2. package/WAProto/fix-imports.js +29 -0
  3. package/WAProto/index.js +169659 -0
  4. package/lib/Defaults/index.js +115 -0
  5. package/lib/Signal/Group/ciphertext-message.js +12 -0
  6. package/lib/Signal/Group/group-session-builder.js +30 -0
  7. package/lib/Signal/Group/group_cipher.js +82 -0
  8. package/lib/Signal/Group/index.js +12 -0
  9. package/lib/Signal/Group/keyhelper.js +18 -0
  10. package/lib/Signal/Group/sender-chain-key.js +26 -0
  11. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  12. package/lib/Signal/Group/sender-key-message.js +66 -0
  13. package/lib/Signal/Group/sender-key-name.js +48 -0
  14. package/lib/Signal/Group/sender-key-record.js +41 -0
  15. package/lib/Signal/Group/sender-key-state.js +84 -0
  16. package/lib/Signal/Group/sender-message-key.js +26 -0
  17. package/lib/Signal/libsignal.js +342 -0
  18. package/lib/Signal/lid-mapping.js +171 -0
  19. package/lib/Socket/Client/index.js +3 -0
  20. package/lib/Socket/Client/types.js +11 -0
  21. package/lib/Socket/Client/websocket.js +91 -0
  22. package/lib/Socket/business.js +376 -0
  23. package/lib/Socket/chats.js +963 -0
  24. package/lib/Socket/communities.js +431 -0
  25. package/lib/Socket/groups.js +328 -0
  26. package/lib/Socket/index.js +19 -0
  27. package/lib/Socket/messages-recv.js +1240 -0
  28. package/lib/Socket/messages-send.js +1370 -0
  29. package/lib/Socket/mex.js +42 -0
  30. package/lib/Socket/newsletter.js +202 -0
  31. package/lib/Socket/nexus-handler.js +667 -0
  32. package/lib/Socket/socket.js +871 -0
  33. package/lib/Store/index.js +4 -0
  34. package/lib/Store/make-cache-manager-store.js +81 -0
  35. package/lib/Store/make-in-memory-store.js +416 -0
  36. package/lib/Store/make-ordered-dictionary.js +82 -0
  37. package/lib/Store/object-repository.js +31 -0
  38. package/lib/Types/Auth.js +2 -0
  39. package/lib/Types/Bussines.js +2 -0
  40. package/lib/Types/Call.js +2 -0
  41. package/lib/Types/Chat.js +8 -0
  42. package/lib/Types/Contact.js +2 -0
  43. package/lib/Types/Events.js +2 -0
  44. package/lib/Types/GroupMetadata.js +2 -0
  45. package/lib/Types/Label.js +25 -0
  46. package/lib/Types/LabelAssociation.js +7 -0
  47. package/lib/Types/Message.js +11 -0
  48. package/lib/Types/Newsletter.js +31 -0
  49. package/lib/Types/Product.js +2 -0
  50. package/lib/Types/Signal.js +2 -0
  51. package/lib/Types/Socket.js +3 -0
  52. package/lib/Types/State.js +13 -0
  53. package/lib/Types/USync.js +2 -0
  54. package/lib/Types/index.js +26 -0
  55. package/lib/Utils/auth-utils.js +257 -0
  56. package/lib/Utils/baileys-event-stream.js +56 -0
  57. package/lib/Utils/browser-utils.js +28 -0
  58. package/lib/Utils/business.js +231 -0
  59. package/lib/Utils/chat-utils.js +763 -0
  60. package/lib/Utils/crypto.js +142 -0
  61. package/lib/Utils/decode-wa-message.js +279 -0
  62. package/lib/Utils/event-buffer.js +548 -0
  63. package/lib/Utils/generics.js +381 -0
  64. package/lib/Utils/history.js +84 -0
  65. package/lib/Utils/index.js +20 -0
  66. package/lib/Utils/link-preview.js +85 -0
  67. package/lib/Utils/logger.js +3 -0
  68. package/lib/Utils/lt-hash.js +48 -0
  69. package/lib/Utils/make-mutex.js +40 -0
  70. package/lib/Utils/message-retry-manager.js +149 -0
  71. package/lib/Utils/messages-media.js +685 -0
  72. package/lib/Utils/messages.js +820 -0
  73. package/lib/Utils/noise-handler.js +147 -0
  74. package/lib/Utils/pre-key-manager.js +106 -0
  75. package/lib/Utils/process-message.js +413 -0
  76. package/lib/Utils/signal.js +159 -0
  77. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  78. package/lib/Utils/validate-connection.js +195 -0
  79. package/lib/WABinary/constants.js +1301 -0
  80. package/lib/WABinary/decode.js +238 -0
  81. package/lib/WABinary/encode.js +216 -0
  82. package/lib/WABinary/generic-utils.js +111 -0
  83. package/lib/WABinary/index.js +6 -0
  84. package/lib/WABinary/jid-utils.js +96 -0
  85. package/lib/WABinary/types.js +2 -0
  86. package/lib/WAM/BinaryInfo.js +10 -0
  87. package/lib/WAM/constants.js +22853 -0
  88. package/lib/WAM/encode.js +150 -0
  89. package/lib/WAM/index.js +4 -0
  90. package/lib/WAUSync/Protocols/USyncContactProtocol.js +29 -0
  91. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  92. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  93. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  94. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  95. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  96. package/lib/WAUSync/Protocols/index.js +5 -0
  97. package/lib/WAUSync/USyncQuery.js +94 -0
  98. package/lib/WAUSync/USyncUser.js +23 -0
  99. package/lib/WAUSync/index.js +4 -0
  100. package/lib/index.js +24 -0
  101. package/package.json +113 -0
@@ -0,0 +1,159 @@
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
+ };
159
+ //# sourceMappingURL=signal.js.map
@@ -0,0 +1,121 @@
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
+ };
121
+ //# sourceMappingURL=use-multi-file-auth-state.js.map
@@ -0,0 +1,195 @@
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: proto.ClientPayload.UserAgent.Platform.WEB,
17
+ releaseChannel: proto.ClientPayload.UserAgent.ReleaseChannel.RELEASE,
18
+ osVersion: '0.1',
19
+ device: 'Desktop',
20
+ osBuildNumber: '0.1',
21
+ localeLanguageIso6391: 'en',
22
+ mnc: '000',
23
+ mcc: '000',
24
+ localeCountryIso31661Alpha2: config.countryCode
25
+ };
26
+ };
27
+ const PLATFORM_MAP = {
28
+ 'Mac OS': proto.ClientPayload.WebInfo.WebSubPlatform.DARWIN,
29
+ Windows: proto.ClientPayload.WebInfo.WebSubPlatform.WIN32
30
+ };
31
+ const getWebInfo = (config) => {
32
+ let webSubPlatform = proto.ClientPayload.WebInfo.WebSubPlatform.WEB_BROWSER;
33
+ if (config.syncFullHistory &&
34
+ PLATFORM_MAP[config.browser[0]] &&
35
+ config.browser[1] === 'Desktop') {
36
+ webSubPlatform = PLATFORM_MAP[config.browser[0]];
37
+ }
38
+ return { webSubPlatform };
39
+ };
40
+ const getClientPayload = (config) => {
41
+ const payload = {
42
+ connectType: proto.ClientPayload.ConnectType.WIFI_UNKNOWN,
43
+ connectReason: proto.ClientPayload.ConnectReason.USER_ACTIVATED,
44
+ userAgent: getUserAgent(config)
45
+ };
46
+ payload.webInfo = getWebInfo(config);
47
+ return payload;
48
+ };
49
+ export const generateLoginNode = (userJid, config) => {
50
+ const { user, device } = jidDecode(userJid);
51
+ const payload = {
52
+ ...getClientPayload(config),
53
+ passive: true,
54
+ pull: true,
55
+ username: +user,
56
+ device: device,
57
+ // TODO: investigate (hard set as false atm)
58
+ lidDbMigrated: false
59
+ };
60
+ return proto.ClientPayload.fromObject(payload);
61
+ };
62
+ const getPlatformType = (platform) => {
63
+ const platformType = platform.toUpperCase();
64
+ return (proto.DeviceProps.PlatformType[platformType] ||
65
+ proto.DeviceProps.PlatformType.CHROME);
66
+ };
67
+ export const generateRegistrationNode = ({ registrationId, signedPreKey, signedIdentityKey }, config) => {
68
+ // the app version needs to be md5 hashed
69
+ // and passed in
70
+ const appVersionBuf = createHash('md5')
71
+ .update(config.version.join('.')) // join as string
72
+ .digest();
73
+ const companion = {
74
+ os: config.browser[0],
75
+ platformType: getPlatformType(config.browser[1]),
76
+ requireFullSync: config.syncFullHistory,
77
+ historySyncConfig: {
78
+ storageQuotaMb: 569150,
79
+ inlineInitialPayloadInE2EeMsg: true,
80
+ supportCallLogHistory: false,
81
+ supportBotUserAgentChatHistory: true,
82
+ supportCagReactionsAndPolls: true,
83
+ supportBizHostedMsg: true,
84
+ supportRecentSyncChunkMessageCountTuning: true,
85
+ supportHostedGroupMsg: true,
86
+ supportFbidBotChatHistory: true,
87
+ supportMessageAssociation: true
88
+ },
89
+ version: {
90
+ primary: 10,
91
+ secondary: 15,
92
+ tertiary: 7
93
+ }
94
+ };
95
+ const companionProto = proto.DeviceProps.encode(companion).finish();
96
+ const registerPayload = {
97
+ ...getClientPayload(config),
98
+ passive: false,
99
+ pull: false,
100
+ devicePairingData: {
101
+ buildHash: appVersionBuf,
102
+ deviceProps: companionProto,
103
+ eRegid: encodeBigEndian(registrationId),
104
+ eKeytype: KEY_BUNDLE_TYPE,
105
+ eIdent: signedIdentityKey.public,
106
+ eSkeyId: encodeBigEndian(signedPreKey.keyId, 3),
107
+ eSkeyVal: signedPreKey.keyPair.public,
108
+ eSkeySig: signedPreKey.signature
109
+ }
110
+ };
111
+ return proto.ClientPayload.fromObject(registerPayload);
112
+ };
113
+ export const configureSuccessfulPairing = (stanza, { advSecretKey, signedIdentityKey, signalIdentities }) => {
114
+ const msgId = stanza.attrs.id;
115
+ const pairSuccessNode = getBinaryNodeChild(stanza, 'pair-success');
116
+ const deviceIdentityNode = getBinaryNodeChild(pairSuccessNode, 'device-identity');
117
+ const platformNode = getBinaryNodeChild(pairSuccessNode, 'platform');
118
+ const deviceNode = getBinaryNodeChild(pairSuccessNode, 'device');
119
+ const businessNode = getBinaryNodeChild(pairSuccessNode, 'biz');
120
+ if (!deviceIdentityNode || !deviceNode) {
121
+ throw new Boom('Missing device-identity or device in pair success node', { data: stanza });
122
+ }
123
+ const bizName = businessNode?.attrs.name;
124
+ const jid = deviceNode.attrs.jid;
125
+ const lid = deviceNode.attrs.lid;
126
+ const { details, hmac, accountType } = proto.ADVSignedDeviceIdentityHMAC.decode(deviceIdentityNode.content);
127
+ let hmacPrefix = Buffer.from([]);
128
+ if (accountType !== undefined && accountType === proto.ADVEncryptionType.HOSTED) {
129
+ hmacPrefix = WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX;
130
+ }
131
+ const advSign = hmacSign(Buffer.concat([hmacPrefix, details]), Buffer.from(advSecretKey, 'base64'));
132
+ if (Buffer.compare(hmac, advSign) !== 0) {
133
+ throw new Boom('Invalid account signature');
134
+ }
135
+ const account = proto.ADVSignedDeviceIdentity.decode(details);
136
+ const { accountSignatureKey, accountSignature, details: deviceDetails } = account;
137
+ const deviceIdentity = proto.ADVDeviceIdentity.decode(deviceDetails);
138
+ const accountSignaturePrefix = deviceIdentity.deviceType === proto.ADVEncryptionType.HOSTED
139
+ ? WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX
140
+ : WA_ADV_ACCOUNT_SIG_PREFIX;
141
+ const accountMsg = Buffer.concat([accountSignaturePrefix, deviceDetails, signedIdentityKey.public]);
142
+ if (!Curve.verify(accountSignatureKey, accountMsg, accountSignature)) {
143
+ throw new Boom('Failed to verify account signature');
144
+ }
145
+ const deviceMsg = Buffer.concat([
146
+ WA_ADV_DEVICE_SIG_PREFIX,
147
+ deviceDetails,
148
+ signedIdentityKey.public,
149
+ accountSignatureKey
150
+ ]);
151
+ account.deviceSignature = Curve.sign(signedIdentityKey.private, deviceMsg);
152
+ const identity = createSignalIdentity(lid, accountSignatureKey);
153
+ const accountEnc = encodeSignedDeviceIdentity(account, false);
154
+ const reply = {
155
+ tag: 'iq',
156
+ attrs: {
157
+ to: S_WHATSAPP_NET,
158
+ type: 'result',
159
+ id: msgId
160
+ },
161
+ content: [
162
+ {
163
+ tag: 'pair-device-sign',
164
+ attrs: {},
165
+ content: [
166
+ {
167
+ tag: 'device-identity',
168
+ attrs: { 'key-index': deviceIdentity.keyIndex.toString() },
169
+ content: accountEnc
170
+ }
171
+ ]
172
+ }
173
+ ]
174
+ };
175
+ const authUpdate = {
176
+ account,
177
+ me: { id: jid, name: bizName, lid },
178
+ signalIdentities: [...(signalIdentities || []), identity],
179
+ platform: platformNode?.attrs.name
180
+ };
181
+ return {
182
+ creds: authUpdate,
183
+ reply
184
+ };
185
+ };
186
+ export const encodeSignedDeviceIdentity = (account, includeSignatureKey) => {
187
+ account = { ...account };
188
+ // set to null if we are not to include the signature key
189
+ // or if we are including the signature key but it is empty
190
+ if (!includeSignatureKey || !account.accountSignatureKey?.length) {
191
+ account.accountSignatureKey = null;
192
+ }
193
+ return proto.ADVSignedDeviceIdentity.encode(account).finish();
194
+ };
195
+ //# sourceMappingURL=validate-connection.js.map