@gara31/void-baileys 7.0.0-rc.14

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 (95) hide show
  1. package/LICENSE +21 -0
  2. package/WAProto/index.js +117292 -0
  3. package/lib/Defaults/baileys-version.json +3 -0
  4. package/lib/Defaults/index.js +116 -0
  5. package/lib/Signal/Group/ciphertext-message.js +12 -0
  6. package/lib/Signal/Group/group-session-builder.js +42 -0
  7. package/lib/Signal/Group/group_cipher.js +109 -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 +32 -0
  11. package/lib/Signal/Group/sender-key-distribution-message.js +67 -0
  12. package/lib/Signal/Group/sender-key-message.js +80 -0
  13. package/lib/Signal/Group/sender-key-name.js +50 -0
  14. package/lib/Signal/Group/sender-key-record.js +47 -0
  15. package/lib/Signal/Group/sender-key-state.js +105 -0
  16. package/lib/Signal/Group/sender-message-key.js +30 -0
  17. package/lib/Signal/libsignal.js +416 -0
  18. package/lib/Signal/lid-mapping.js +189 -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 +61 -0
  22. package/lib/Socket/business.js +404 -0
  23. package/lib/Socket/chats.js +1146 -0
  24. package/lib/Socket/communities.js +505 -0
  25. package/lib/Socket/groups.js +404 -0
  26. package/lib/Socket/index.js +18 -0
  27. package/lib/Socket/messages-recv.js +1600 -0
  28. package/lib/Socket/messages-send.js +1203 -0
  29. package/lib/Socket/mex.js +56 -0
  30. package/lib/Socket/newsletter.js +240 -0
  31. package/lib/Socket/socket.js +1060 -0
  32. package/lib/Types/Auth.js +2 -0
  33. package/lib/Types/Bussines.js +2 -0
  34. package/lib/Types/Call.js +2 -0
  35. package/lib/Types/Chat.js +8 -0
  36. package/lib/Types/Contact.js +2 -0
  37. package/lib/Types/Events.js +2 -0
  38. package/lib/Types/GroupMetadata.js +2 -0
  39. package/lib/Types/Label.js +25 -0
  40. package/lib/Types/LabelAssociation.js +7 -0
  41. package/lib/Types/Message.js +11 -0
  42. package/lib/Types/Newsletter.js +31 -0
  43. package/lib/Types/Product.js +2 -0
  44. package/lib/Types/Signal.js +2 -0
  45. package/lib/Types/Socket.js +3 -0
  46. package/lib/Types/State.js +13 -0
  47. package/lib/Types/USync.js +2 -0
  48. package/lib/Types/index.js +32 -0
  49. package/lib/Utils/auth-utils.js +276 -0
  50. package/lib/Utils/browser-utils.js +32 -0
  51. package/lib/Utils/business.js +262 -0
  52. package/lib/Utils/chat-utils.js +941 -0
  53. package/lib/Utils/crypto.js +179 -0
  54. package/lib/Utils/decode-wa-message.js +333 -0
  55. package/lib/Utils/event-buffer.js +580 -0
  56. package/lib/Utils/generics.js +436 -0
  57. package/lib/Utils/history.js +103 -0
  58. package/lib/Utils/index.js +19 -0
  59. package/lib/Utils/link-preview.js +99 -0
  60. package/lib/Utils/logger.js +3 -0
  61. package/lib/Utils/lt-hash.js +56 -0
  62. package/lib/Utils/make-mutex.js +38 -0
  63. package/lib/Utils/message-retry-manager.js +181 -0
  64. package/lib/Utils/messages-media.js +727 -0
  65. package/lib/Utils/messages.js +1309 -0
  66. package/lib/Utils/noise-handler.js +162 -0
  67. package/lib/Utils/pre-key-manager.js +125 -0
  68. package/lib/Utils/process-message.js +594 -0
  69. package/lib/Utils/signal.js +194 -0
  70. package/lib/Utils/use-multi-file-auth-state.js +118 -0
  71. package/lib/Utils/validate-connection.js +240 -0
  72. package/lib/WABinary/constants.js +1301 -0
  73. package/lib/WABinary/decode.js +240 -0
  74. package/lib/WABinary/encode.js +216 -0
  75. package/lib/WABinary/generic-utils.js +104 -0
  76. package/lib/WABinary/index.js +6 -0
  77. package/lib/WABinary/jid-utils.js +95 -0
  78. package/lib/WABinary/types.js +2 -0
  79. package/lib/WAM/BinaryInfo.js +10 -0
  80. package/lib/WAM/constants.js +22863 -0
  81. package/lib/WAM/encode.js +152 -0
  82. package/lib/WAM/index.js +4 -0
  83. package/lib/WAUSync/Protocols/USyncContactProtocol.js +29 -0
  84. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +59 -0
  85. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  86. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +36 -0
  87. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +60 -0
  88. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  89. package/lib/WAUSync/Protocols/index.js +5 -0
  90. package/lib/WAUSync/USyncQuery.js +104 -0
  91. package/lib/WAUSync/USyncUser.js +23 -0
  92. package/lib/WAUSync/index.js +4 -0
  93. package/lib/index.js +11 -0
  94. package/package.json +32 -0
  95. package/readme.md +1452 -0
@@ -0,0 +1,194 @@
1
+ import { KEY_BUNDLE_TYPE } from "../Defaults/index.js";
2
+ import {
3
+ assertNodeErrorFree,
4
+ getBinaryNodeChild,
5
+ getBinaryNodeChildBuffer,
6
+ getBinaryNodeChildren,
7
+ getBinaryNodeChildUInt,
8
+ getServerFromDomainType,
9
+ jidDecode,
10
+ S_WHATSAPP_NET,
11
+ WAJIDDomains,
12
+ } from "../WABinary/index.js";
13
+ import { Curve, generateSignalPubKey } from "./crypto.js";
14
+ import { encodeBigEndian } from "./generics.js";
15
+ function chunk(array, size) {
16
+ const chunks = [];
17
+ for (let i = 0; i < array.length; i += size) {
18
+ chunks.push(array.slice(i, i + size));
19
+ }
20
+ return chunks;
21
+ }
22
+ export const createSignalIdentity = (wid, accountSignatureKey) => {
23
+ return {
24
+ identifier: { name: wid, deviceId: 0 },
25
+ identifierKey: generateSignalPubKey(accountSignatureKey),
26
+ };
27
+ };
28
+ export const getPreKeys = async ({ get }, min, limit) => {
29
+ const idList = [];
30
+ for (let id = min; id < limit; id++) {
31
+ idList.push(id.toString());
32
+ }
33
+ return get("pre-key", idList);
34
+ };
35
+ export const generateOrGetPreKeys = (creds, range) => {
36
+ const avaliable = creds.nextPreKeyId - creds.firstUnuploadedPreKeyId;
37
+ const remaining = range - avaliable;
38
+ const lastPreKeyId = creds.nextPreKeyId + remaining - 1;
39
+ const newPreKeys = {};
40
+ if (remaining > 0) {
41
+ for (let i = creds.nextPreKeyId; i <= lastPreKeyId; i++) {
42
+ newPreKeys[i] = Curve.generateKeyPair();
43
+ }
44
+ }
45
+ return {
46
+ newPreKeys,
47
+ lastPreKeyId,
48
+ preKeysRange: [creds.firstUnuploadedPreKeyId, range],
49
+ };
50
+ };
51
+ export const xmppSignedPreKey = (key) => ({
52
+ tag: "skey",
53
+ attrs: {},
54
+ content: [
55
+ { tag: "id", attrs: {}, content: encodeBigEndian(key.keyId, 3) },
56
+ { tag: "value", attrs: {}, content: key.keyPair.public },
57
+ { tag: "signature", attrs: {}, content: key.signature },
58
+ ],
59
+ });
60
+ export const xmppPreKey = (pair, id) => ({
61
+ tag: "key",
62
+ attrs: {},
63
+ content: [
64
+ { tag: "id", attrs: {}, content: encodeBigEndian(id, 3) },
65
+ { tag: "value", attrs: {}, content: pair.public },
66
+ ],
67
+ });
68
+ export const parseAndInjectE2ESessions = async (node, repository) => {
69
+ const extractKey = (key) =>
70
+ key
71
+ ? {
72
+ keyId: getBinaryNodeChildUInt(key, "id", 3),
73
+ publicKey: generateSignalPubKey(
74
+ getBinaryNodeChildBuffer(key, "value"),
75
+ ),
76
+ signature: getBinaryNodeChildBuffer(key, "signature"),
77
+ }
78
+ : undefined;
79
+ const nodes = getBinaryNodeChildren(getBinaryNodeChild(node, "list"), "user");
80
+ for (const node of nodes) {
81
+ assertNodeErrorFree(node);
82
+ }
83
+ // Most of the work in repository.injectE2ESession is CPU intensive, not IO
84
+ // So Promise.all doesn't really help here,
85
+ // but blocks even loop if we're using it inside keys.transaction, and it makes it "sync" actually
86
+ // This way we chunk it in smaller parts and between those parts we can yield to the event loop
87
+ // It's rare case when you need to E2E sessions for so many users, but it's possible
88
+ const chunkSize = 100;
89
+ const chunks = chunk(nodes, chunkSize);
90
+ for (const nodesChunk of chunks) {
91
+ for (const node of nodesChunk) {
92
+ const signedKey = getBinaryNodeChild(node, "skey");
93
+ const key = getBinaryNodeChild(node, "key");
94
+ const identity = getBinaryNodeChildBuffer(node, "identity");
95
+ const jid = node.attrs.jid;
96
+ const registrationId = getBinaryNodeChildUInt(node, "registration", 4);
97
+ await repository.injectE2ESession({
98
+ jid,
99
+ session: {
100
+ registrationId: registrationId,
101
+ identityKey: generateSignalPubKey(identity),
102
+ signedPreKey: extractKey(signedKey),
103
+ preKey: extractKey(key),
104
+ },
105
+ });
106
+ }
107
+ }
108
+ };
109
+ export const extractDeviceJids = (result, myJid, myLid, excludeZeroDevices) => {
110
+ const { user: myUser, device: myDevice } = jidDecode(myJid);
111
+ const extracted = [];
112
+ for (const userResult of result) {
113
+ const { devices, id } = userResult;
114
+ const decoded = jidDecode(id),
115
+ { user, server } = decoded;
116
+ let { domainType } = decoded;
117
+ const deviceList = devices?.deviceList;
118
+ if (!Array.isArray(deviceList)) continue;
119
+ for (const { id: device, keyIndex, isHosted } of deviceList) {
120
+ if (
121
+ (!excludeZeroDevices || device !== 0) && // if zero devices are not-excluded, or device is non zero
122
+ ((myUser !== user && myLid !== user) || myDevice !== device) && // either different user or if me user, not this device
123
+ (device === 0 || !!keyIndex) // ensure that "key-index" is specified for "non-zero" devices, produces a bad req otherwise
124
+ ) {
125
+ if (isHosted) {
126
+ domainType =
127
+ domainType === WAJIDDomains.LID
128
+ ? WAJIDDomains.HOSTED_LID
129
+ : WAJIDDomains.HOSTED;
130
+ }
131
+ extracted.push({
132
+ user,
133
+ device,
134
+ domainType,
135
+ server: getServerFromDomainType(server, domainType),
136
+ });
137
+ }
138
+ }
139
+ }
140
+ return extracted;
141
+ };
142
+ /**
143
+ * get the next N keys for upload or processing
144
+ * @param count number of pre-keys to get or generate
145
+ */
146
+ export const getNextPreKeys = async ({ creds, keys }, count) => {
147
+ const { newPreKeys, lastPreKeyId, preKeysRange } = generateOrGetPreKeys(
148
+ creds,
149
+ count,
150
+ );
151
+ const update = {
152
+ nextPreKeyId: Math.max(lastPreKeyId + 1, creds.nextPreKeyId),
153
+ firstUnuploadedPreKeyId: Math.max(
154
+ creds.firstUnuploadedPreKeyId,
155
+ lastPreKeyId + 1,
156
+ ),
157
+ };
158
+ await keys.set({ "pre-key": newPreKeys });
159
+ const preKeys = await getPreKeys(
160
+ keys,
161
+ preKeysRange[0],
162
+ preKeysRange[0] + preKeysRange[1],
163
+ );
164
+ return { update, preKeys };
165
+ };
166
+ export const getNextPreKeysNode = async (state, count) => {
167
+ const { creds } = state;
168
+ const { update, preKeys } = await getNextPreKeys(state, count);
169
+ const node = {
170
+ tag: "iq",
171
+ attrs: {
172
+ xmlns: "encrypt",
173
+ type: "set",
174
+ to: S_WHATSAPP_NET,
175
+ },
176
+ content: [
177
+ {
178
+ tag: "registration",
179
+ attrs: {},
180
+ content: encodeBigEndian(creds.registrationId),
181
+ },
182
+ { tag: "type", attrs: {}, content: KEY_BUNDLE_TYPE },
183
+ { tag: "identity", attrs: {}, content: creds.signedIdentityKey.public },
184
+ {
185
+ tag: "list",
186
+ attrs: {},
187
+ content: Object.keys(preKeys).map((k) => xmppPreKey(preKeys[+k], +k)),
188
+ },
189
+ xmppSignedPreKey(creds.signedPreKey),
190
+ ],
191
+ };
192
+ return { update, node };
193
+ };
194
+ //# sourceMappingURL=signal.js.map
@@ -0,0 +1,118 @@
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
+ } finally {
37
+ release();
38
+ }
39
+ });
40
+ };
41
+ const readData = async (file) => {
42
+ try {
43
+ const filePath = join(folder, fixFileName(file));
44
+ const mutex = getFileLock(filePath);
45
+ return await mutex.acquire().then(async (release) => {
46
+ try {
47
+ const data = await readFile(filePath, { encoding: "utf-8" });
48
+ return JSON.parse(data, BufferJSON.reviver);
49
+ } finally {
50
+ release();
51
+ }
52
+ });
53
+ } catch (error) {
54
+ return null;
55
+ }
56
+ };
57
+ const removeData = async (file) => {
58
+ try {
59
+ const filePath = join(folder, fixFileName(file));
60
+ const mutex = getFileLock(filePath);
61
+ return mutex.acquire().then(async (release) => {
62
+ try {
63
+ await unlink(filePath);
64
+ } catch {
65
+ } finally {
66
+ release();
67
+ }
68
+ });
69
+ } catch {}
70
+ };
71
+ const folderInfo = await stat(folder).catch(() => {});
72
+ if (folderInfo) {
73
+ if (!folderInfo.isDirectory()) {
74
+ throw new Error(
75
+ `found something that is not a directory at ${folder}, either delete it or specify a different location`,
76
+ );
77
+ }
78
+ } else {
79
+ await mkdir(folder, { recursive: true });
80
+ }
81
+ const fixFileName = (file) => file?.replace(/\//g, "__")?.replace(/:/g, "-");
82
+ const creds = (await readData("creds.json")) || initAuthCreds();
83
+ return {
84
+ state: {
85
+ creds,
86
+ keys: {
87
+ get: async (type, ids) => {
88
+ const data = {};
89
+ await Promise.all(
90
+ ids.map(async (id) => {
91
+ let value = await readData(`${type}-${id}.json`);
92
+ if (type === "app-state-sync-key" && value) {
93
+ value = proto.Message.AppStateSyncKeyData.fromObject(value);
94
+ }
95
+ data[id] = value;
96
+ }),
97
+ );
98
+ return data;
99
+ },
100
+ set: async (data) => {
101
+ const tasks = [];
102
+ for (const category in data) {
103
+ for (const id in data[category]) {
104
+ const value = data[category][id];
105
+ const file = `${category}-${id}.json`;
106
+ tasks.push(value ? writeData(value, file) : removeData(file));
107
+ }
108
+ }
109
+ await Promise.all(tasks);
110
+ },
111
+ },
112
+ },
113
+ saveCreds: async () => {
114
+ return writeData(creds, "creds.json");
115
+ },
116
+ };
117
+ };
118
+ //# sourceMappingURL=use-multi-file-auth-state.js.map
@@ -0,0 +1,240 @@
1
+ import { Boom } from "@hapi/boom";
2
+ import { createHash } from "crypto";
3
+ import { proto } from "../../WAProto/index.js";
4
+ import {
5
+ KEY_BUNDLE_TYPE,
6
+ WA_ADV_ACCOUNT_SIG_PREFIX,
7
+ WA_ADV_DEVICE_SIG_PREFIX,
8
+ WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX,
9
+ } from "../Defaults/index.js";
10
+ import {
11
+ getBinaryNodeChild,
12
+ jidDecode,
13
+ S_WHATSAPP_NET,
14
+ } from "../WABinary/index.js";
15
+ import { Curve, hmacSign } from "./crypto.js";
16
+ import { encodeBigEndian } from "./generics.js";
17
+ import { createSignalIdentity } from "./signal.js";
18
+ const getUserAgent = (config) => {
19
+ return {
20
+ appVersion: {
21
+ primary: config.version[0],
22
+ secondary: config.version[1],
23
+ tertiary: config.version[2],
24
+ },
25
+ platform: proto.ClientPayload.UserAgent.Platform.WEB,
26
+ releaseChannel: proto.ClientPayload.UserAgent.ReleaseChannel.RELEASE,
27
+ osVersion: "0.1",
28
+ device: "Desktop",
29
+ osBuildNumber: "0.1",
30
+ localeLanguageIso6391: "en",
31
+ mnc: "000",
32
+ mcc: "000",
33
+ localeCountryIso31661Alpha2: config.countryCode,
34
+ };
35
+ };
36
+ const PLATFORM_MAP = {
37
+ "Mac OS": proto.ClientPayload.WebInfo.WebSubPlatform.DARWIN,
38
+ Windows: proto.ClientPayload.WebInfo.WebSubPlatform.WIN32,
39
+ };
40
+ const getWebInfo = (config) => {
41
+ let webSubPlatform = proto.ClientPayload.WebInfo.WebSubPlatform.WEB_BROWSER;
42
+ if (
43
+ config.syncFullHistory &&
44
+ PLATFORM_MAP[config.browser[0]] &&
45
+ config.browser[1] === "Desktop"
46
+ ) {
47
+ webSubPlatform = PLATFORM_MAP[config.browser[0]];
48
+ }
49
+ return { webSubPlatform };
50
+ };
51
+ const getClientPayload = (config) => {
52
+ const payload = {
53
+ connectType: proto.ClientPayload.ConnectType.WIFI_UNKNOWN,
54
+ connectReason: proto.ClientPayload.ConnectReason.USER_ACTIVATED,
55
+ userAgent: getUserAgent(config),
56
+ };
57
+ payload.webInfo = getWebInfo(config);
58
+ return payload;
59
+ };
60
+ export const generateLoginNode = (userJid, config) => {
61
+ const { user, device } = jidDecode(userJid);
62
+ const payload = {
63
+ ...getClientPayload(config),
64
+ passive: true,
65
+ pull: true,
66
+ username: +user,
67
+ device: device,
68
+ // TODO: investigate (hard set as false atm)
69
+ lidDbMigrated: false,
70
+ };
71
+ return proto.ClientPayload.fromObject(payload);
72
+ };
73
+ const getPlatformType = (platform) => {
74
+ const platformType = platform.toUpperCase();
75
+ return (
76
+ proto.DeviceProps.PlatformType[platformType] ||
77
+ proto.DeviceProps.PlatformType.CHROME
78
+ );
79
+ };
80
+ export const generateRegistrationNode = (
81
+ { registrationId, signedPreKey, signedIdentityKey },
82
+ config,
83
+ ) => {
84
+ // the app version needs to be md5 hashed
85
+ // and passed in
86
+ const appVersionBuf = createHash("md5")
87
+ .update(config.version.join(".")) // join as string
88
+ .digest();
89
+ const companion = {
90
+ os: config.browser[0],
91
+ platformType: getPlatformType(config.browser[1]),
92
+ requireFullSync: config.syncFullHistory,
93
+ historySyncConfig: {
94
+ storageQuotaMb: 10240,
95
+ inlineInitialPayloadInE2EeMsg: true,
96
+ recentSyncDaysLimit: undefined,
97
+ supportCallLogHistory: false,
98
+ supportBotUserAgentChatHistory: true,
99
+ supportCagReactionsAndPolls: true,
100
+ supportBizHostedMsg: true,
101
+ supportRecentSyncChunkMessageCountTuning: true,
102
+ supportHostedGroupMsg: true,
103
+ supportFbidBotChatHistory: true,
104
+ supportAddOnHistorySyncMigration: undefined,
105
+ supportMessageAssociation: true,
106
+ supportGroupHistory: false,
107
+ onDemandReady: undefined,
108
+ supportGuestChat: undefined,
109
+ },
110
+ version: {
111
+ primary: 10,
112
+ secondary: 15,
113
+ tertiary: 7,
114
+ },
115
+ };
116
+ const companionProto = proto.DeviceProps.encode(companion).finish();
117
+ const registerPayload = {
118
+ ...getClientPayload(config),
119
+ passive: false,
120
+ pull: false,
121
+ devicePairingData: {
122
+ buildHash: appVersionBuf,
123
+ deviceProps: companionProto,
124
+ eRegid: encodeBigEndian(registrationId),
125
+ eKeytype: KEY_BUNDLE_TYPE,
126
+ eIdent: signedIdentityKey.public,
127
+ eSkeyId: encodeBigEndian(signedPreKey.keyId, 3),
128
+ eSkeyVal: signedPreKey.keyPair.public,
129
+ eSkeySig: signedPreKey.signature,
130
+ },
131
+ };
132
+ return proto.ClientPayload.fromObject(registerPayload);
133
+ };
134
+ export const configureSuccessfulPairing = (
135
+ stanza,
136
+ { advSecretKey, signedIdentityKey, signalIdentities },
137
+ ) => {
138
+ const msgId = stanza.attrs.id;
139
+ const pairSuccessNode = getBinaryNodeChild(stanza, "pair-success");
140
+ const deviceIdentityNode = getBinaryNodeChild(
141
+ pairSuccessNode,
142
+ "device-identity",
143
+ );
144
+ const platformNode = getBinaryNodeChild(pairSuccessNode, "platform");
145
+ const deviceNode = getBinaryNodeChild(pairSuccessNode, "device");
146
+ const businessNode = getBinaryNodeChild(pairSuccessNode, "biz");
147
+ if (!deviceIdentityNode || !deviceNode) {
148
+ throw new Boom("Missing device-identity or device in pair success node", {
149
+ data: stanza,
150
+ });
151
+ }
152
+ const bizName = businessNode?.attrs.name;
153
+ const jid = deviceNode.attrs.jid;
154
+ const lid = deviceNode.attrs.lid;
155
+ const { details, hmac, accountType } =
156
+ proto.ADVSignedDeviceIdentityHMAC.decode(deviceIdentityNode.content);
157
+ let hmacPrefix = Buffer.from([]);
158
+ if (
159
+ accountType !== undefined &&
160
+ accountType === proto.ADVEncryptionType.HOSTED
161
+ ) {
162
+ hmacPrefix = WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX;
163
+ }
164
+ const advSign = hmacSign(
165
+ Buffer.concat([hmacPrefix, details]),
166
+ Buffer.from(advSecretKey, "base64"),
167
+ );
168
+ if (Buffer.compare(hmac, advSign) !== 0) {
169
+ throw new Boom("Invalid account signature");
170
+ }
171
+ const account = proto.ADVSignedDeviceIdentity.decode(details);
172
+ const {
173
+ accountSignatureKey,
174
+ accountSignature,
175
+ details: deviceDetails,
176
+ } = account;
177
+ const deviceIdentity = proto.ADVDeviceIdentity.decode(deviceDetails);
178
+ const accountSignaturePrefix =
179
+ deviceIdentity.deviceType === proto.ADVEncryptionType.HOSTED
180
+ ? WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX
181
+ : WA_ADV_ACCOUNT_SIG_PREFIX;
182
+ const accountMsg = Buffer.concat([
183
+ accountSignaturePrefix,
184
+ deviceDetails,
185
+ signedIdentityKey.public,
186
+ ]);
187
+ if (!Curve.verify(accountSignatureKey, accountMsg, accountSignature)) {
188
+ throw new Boom("Failed to verify account signature");
189
+ }
190
+ const deviceMsg = Buffer.concat([
191
+ WA_ADV_DEVICE_SIG_PREFIX,
192
+ deviceDetails,
193
+ signedIdentityKey.public,
194
+ accountSignatureKey,
195
+ ]);
196
+ account.deviceSignature = Curve.sign(signedIdentityKey.private, deviceMsg);
197
+ const identity = createSignalIdentity(lid, accountSignatureKey);
198
+ const accountEnc = encodeSignedDeviceIdentity(account, false);
199
+ const reply = {
200
+ tag: "iq",
201
+ attrs: {
202
+ to: S_WHATSAPP_NET,
203
+ type: "result",
204
+ id: msgId,
205
+ },
206
+ content: [
207
+ {
208
+ tag: "pair-device-sign",
209
+ attrs: {},
210
+ content: [
211
+ {
212
+ tag: "device-identity",
213
+ attrs: { "key-index": deviceIdentity.keyIndex.toString() },
214
+ content: accountEnc,
215
+ },
216
+ ],
217
+ },
218
+ ],
219
+ };
220
+ const authUpdate = {
221
+ account,
222
+ me: { id: jid, name: bizName, lid },
223
+ signalIdentities: [...(signalIdentities || []), identity],
224
+ platform: platformNode?.attrs.name,
225
+ };
226
+ return {
227
+ creds: authUpdate,
228
+ reply,
229
+ };
230
+ };
231
+ export const encodeSignedDeviceIdentity = (account, includeSignatureKey) => {
232
+ account = { ...account };
233
+ // set to null if we are not to include the signature key
234
+ // or if we are including the signature key but it is empty
235
+ if (!includeSignatureKey || !account.accountSignatureKey?.length) {
236
+ account.accountSignatureKey = null;
237
+ }
238
+ return proto.ADVSignedDeviceIdentity.encode(account).finish();
239
+ };
240
+ //# sourceMappingURL=validate-connection.js.map