keith-baileys 1.0.26

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 (109) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -0
  3. package/WAProto/GenerateStatics.sh +2 -0
  4. package/WAProto/WAProto.proto +4633 -0
  5. package/WAProto/index.js +165029 -0
  6. package/WAProto/keith +1 -0
  7. package/engine-requirements.js +10 -0
  8. package/lib/Defaults/Keith +1 -0
  9. package/lib/Defaults/baileys-version.json +3 -0
  10. package/lib/Defaults/index.js +105 -0
  11. package/lib/Signal/Group/Keith +1 -0
  12. package/lib/Signal/Group/ciphertext-message.js +15 -0
  13. package/lib/Signal/Group/group-session-builder.js +64 -0
  14. package/lib/Signal/Group/group_cipher.js +96 -0
  15. package/lib/Signal/Group/index.js +57 -0
  16. package/lib/Signal/Group/keyhelper.js +55 -0
  17. package/lib/Signal/Group/queue-job.js +57 -0
  18. package/lib/Signal/Group/sender-chain-key.js +34 -0
  19. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  20. package/lib/Signal/Group/sender-key-message.js +69 -0
  21. package/lib/Signal/Group/sender-key-name.js +51 -0
  22. package/lib/Signal/Group/sender-key-record.js +53 -0
  23. package/lib/Signal/Group/sender-key-state.js +99 -0
  24. package/lib/Signal/Group/sender-message-key.js +29 -0
  25. package/lib/Signal/Keith +1 -0
  26. package/lib/Signal/libsignal.js +174 -0
  27. package/lib/Socket/Client/Keith +1 -0
  28. package/lib/Socket/Client/index.js +18 -0
  29. package/lib/Socket/Client/types.js +13 -0
  30. package/lib/Socket/Client/websocket.js +62 -0
  31. package/lib/Socket/Keith +1 -0
  32. package/lib/Socket/business.js +260 -0
  33. package/lib/Socket/chats.js +880 -0
  34. package/lib/Socket/groups.js +340 -0
  35. package/lib/Socket/groupstatus.js +237 -0
  36. package/lib/Socket/index.js +10 -0
  37. package/lib/Socket/messages-recv.js +1077 -0
  38. package/lib/Socket/messages-send.js +988 -0
  39. package/lib/Socket/mex.js +46 -0
  40. package/lib/Socket/newsletter.js +233 -0
  41. package/lib/Socket/socket.js +617 -0
  42. package/lib/Socket/usync.js +65 -0
  43. package/lib/Types/Auth.js +2 -0
  44. package/lib/Types/Call.js +2 -0
  45. package/lib/Types/Chat.js +10 -0
  46. package/lib/Types/Contact.js +2 -0
  47. package/lib/Types/Events.js +2 -0
  48. package/lib/Types/GroupMetadata.js +2 -0
  49. package/lib/Types/Keith +1 -0
  50. package/lib/Types/Label.js +27 -0
  51. package/lib/Types/LabelAssociation.js +9 -0
  52. package/lib/Types/Message.js +7 -0
  53. package/lib/Types/Newsletter.js +33 -0
  54. package/lib/Types/Product.js +2 -0
  55. package/lib/Types/Signal.js +2 -0
  56. package/lib/Types/Socket.js +2 -0
  57. package/lib/Types/State.js +2 -0
  58. package/lib/Types/USync.js +2 -0
  59. package/lib/Types/index.js +42 -0
  60. package/lib/Utils/Keith +1 -0
  61. package/lib/Utils/auth-utils.js +199 -0
  62. package/lib/Utils/baileys-event-stream.js +63 -0
  63. package/lib/Utils/business.js +240 -0
  64. package/lib/Utils/chat-utils.js +741 -0
  65. package/lib/Utils/crypto.js +187 -0
  66. package/lib/Utils/decode-wa-message.js +283 -0
  67. package/lib/Utils/event-buffer.js +516 -0
  68. package/lib/Utils/generics.js +400 -0
  69. package/lib/Utils/history.js +100 -0
  70. package/lib/Utils/index.js +34 -0
  71. package/lib/Utils/lid-mapping.js +88 -0
  72. package/lib/Utils/link-preview.js +122 -0
  73. package/lib/Utils/logger.js +7 -0
  74. package/lib/Utils/lt-hash.js +51 -0
  75. package/lib/Utils/make-mutex.js +44 -0
  76. package/lib/Utils/messages-media.js +706 -0
  77. package/lib/Utils/messages.js +797 -0
  78. package/lib/Utils/noise-handler.js +150 -0
  79. package/lib/Utils/process-message.js +381 -0
  80. package/lib/Utils/signal.js +155 -0
  81. package/lib/Utils/use-multi-file-auth-state.js +124 -0
  82. package/lib/Utils/validate-connection.js +170 -0
  83. package/lib/WABinary/Keith +1 -0
  84. package/lib/WABinary/constants.js +1303 -0
  85. package/lib/WABinary/decode.js +266 -0
  86. package/lib/WABinary/encode.js +252 -0
  87. package/lib/WABinary/generic-utils.js +110 -0
  88. package/lib/WABinary/index.js +21 -0
  89. package/lib/WABinary/jid-utils.js +66 -0
  90. package/lib/WABinary/types.js +2 -0
  91. package/lib/WAM/BinaryInfo.js +13 -0
  92. package/lib/WAM/constants.js +15243 -0
  93. package/lib/WAM/encode.js +153 -0
  94. package/lib/WAM/index.js +19 -0
  95. package/lib/WAM/keith +1 -0
  96. package/lib/WAUSync/Keith +1 -0
  97. package/lib/WAUSync/Protocols/Keith +1 -0
  98. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  99. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  100. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  101. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  102. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  103. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  104. package/lib/WAUSync/Protocols/index.js +20 -0
  105. package/lib/WAUSync/USyncQuery.js +93 -0
  106. package/lib/WAUSync/USyncUser.js +26 -0
  107. package/lib/WAUSync/index.js +19 -0
  108. package/lib/index.js +30 -0
  109. package/package.json +32 -0
@@ -0,0 +1,155 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getNextPreKeysNode = exports.getNextPreKeys = exports.extractDeviceJids = exports.parseAndInjectE2ESessions = exports.xmppPreKey = exports.xmppSignedPreKey = exports.generateOrGetPreKeys = exports.getPreKeys = exports.createSignalIdentity = void 0;
4
+ const lodash_1 = require("lodash");
5
+ const Defaults_1 = require("../Defaults");
6
+ const WABinary_1 = require("../WABinary");
7
+ const crypto_1 = require("./crypto");
8
+ const generics_1 = require("./generics");
9
+ const createSignalIdentity = (wid, accountSignatureKey) => {
10
+ return {
11
+ identifier: { name: wid, deviceId: 0 },
12
+ identifierKey: (0, crypto_1.generateSignalPubKey)(accountSignatureKey)
13
+ };
14
+ };
15
+ exports.createSignalIdentity = createSignalIdentity;
16
+ const getPreKeys = async ({ get }, min, limit) => {
17
+ const idList = [];
18
+ for (let id = min; id < limit; id++) {
19
+ idList.push(id.toString());
20
+ }
21
+ return get('pre-key', idList);
22
+ };
23
+ exports.getPreKeys = getPreKeys;
24
+ const generateOrGetPreKeys = (creds, range) => {
25
+ const avaliable = creds.nextPreKeyId - creds.firstUnuploadedPreKeyId;
26
+ const remaining = range - avaliable;
27
+ const lastPreKeyId = creds.nextPreKeyId + remaining - 1;
28
+ const newPreKeys = {};
29
+ if (remaining > 0) {
30
+ for (let i = creds.nextPreKeyId; i <= lastPreKeyId; i++) {
31
+ newPreKeys[i] = crypto_1.Curve.generateKeyPair();
32
+ }
33
+ }
34
+ return {
35
+ newPreKeys,
36
+ lastPreKeyId,
37
+ preKeysRange: [creds.firstUnuploadedPreKeyId, range]
38
+ };
39
+ };
40
+ exports.generateOrGetPreKeys = generateOrGetPreKeys;
41
+ const xmppSignedPreKey = (key) => ({
42
+ tag: 'skey',
43
+ attrs: {},
44
+ content: [
45
+ { tag: 'id', attrs: {}, content: (0, generics_1.encodeBigEndian)(key.keyId, 3) },
46
+ { tag: 'value', attrs: {}, content: key.keyPair.public },
47
+ { tag: 'signature', attrs: {}, content: key.signature }
48
+ ]
49
+ });
50
+ exports.xmppSignedPreKey = xmppSignedPreKey;
51
+ const xmppPreKey = (pair, id) => ({
52
+ tag: 'key',
53
+ attrs: {},
54
+ content: [
55
+ { tag: 'id', attrs: {}, content: (0, generics_1.encodeBigEndian)(id, 3) },
56
+ { tag: 'value', attrs: {}, content: pair.public }
57
+ ]
58
+ });
59
+ exports.xmppPreKey = xmppPreKey;
60
+ const parseAndInjectE2ESessions = async (node, repository) => {
61
+ const extractKey = (key) => key
62
+ ? {
63
+ keyId: (0, WABinary_1.getBinaryNodeChildUInt)(key, 'id', 3),
64
+ publicKey: (0, crypto_1.generateSignalPubKey)((0, WABinary_1.getBinaryNodeChildBuffer)(key, 'value')),
65
+ signature: (0, WABinary_1.getBinaryNodeChildBuffer)(key, 'signature')
66
+ }
67
+ : undefined;
68
+ const nodes = (0, WABinary_1.getBinaryNodeChildren)((0, WABinary_1.getBinaryNodeChild)(node, 'list'), 'user');
69
+ for (const node of nodes) {
70
+ (0, WABinary_1.assertNodeErrorFree)(node);
71
+ }
72
+ // Most of the work in repository.injectE2ESession is CPU intensive, not IO
73
+ // So Promise.all doesn't really help here,
74
+ // but blocks even loop if we're using it inside keys.transaction, and it makes it "sync" actually
75
+ // This way we chunk it in smaller parts and between those parts we can yield to the event loop
76
+ // It's rare case when you need to E2E sessions for so many users, but it's possible
77
+ const chunkSize = 100;
78
+ const chunks = (0, lodash_1.chunk)(nodes, chunkSize);
79
+ for (const nodesChunk of chunks) {
80
+ await Promise.all(nodesChunk.map(async (node) => {
81
+ const signedKey = (0, WABinary_1.getBinaryNodeChild)(node, 'skey');
82
+ const key = (0, WABinary_1.getBinaryNodeChild)(node, 'key');
83
+ const identity = (0, WABinary_1.getBinaryNodeChildBuffer)(node, 'identity');
84
+ const jid = node.attrs.jid;
85
+ const registrationId = (0, WABinary_1.getBinaryNodeChildUInt)(node, 'registration', 4);
86
+ await repository.injectE2ESession({
87
+ jid,
88
+ session: {
89
+ registrationId: registrationId,
90
+ identityKey: (0, crypto_1.generateSignalPubKey)(identity),
91
+ signedPreKey: extractKey(signedKey),
92
+ preKey: extractKey(key)
93
+ }
94
+ });
95
+ }));
96
+ }
97
+ };
98
+ exports.parseAndInjectE2ESessions = parseAndInjectE2ESessions;
99
+ const extractDeviceJids = (result, myJid, excludeZeroDevices) => {
100
+ const { user: myUser, device: myDevice } = (0, WABinary_1.jidDecode)(myJid);
101
+ const extracted = [];
102
+ for (const userResult of result) {
103
+ const { devices, id } = userResult;
104
+ const { user } = (0, WABinary_1.jidDecode)(id);
105
+ const deviceList = devices === null || devices === void 0 ? void 0 : devices.deviceList;
106
+ if (Array.isArray(deviceList)) {
107
+ for (const { id: device, keyIndex } of deviceList) {
108
+ if ((!excludeZeroDevices || device !== 0) && // if zero devices are not-excluded, or device is non zero
109
+ (myUser !== user || myDevice !== device) && // either different user or if me user, not this device
110
+ (device === 0 || !!keyIndex) // ensure that "key-index" is specified for "non-zero" devices, produces a bad req otherwise
111
+ ) {
112
+ extracted.push({ user, device });
113
+ }
114
+ }
115
+ }
116
+ }
117
+ return extracted;
118
+ };
119
+ exports.extractDeviceJids = extractDeviceJids;
120
+ /**
121
+ * get the next N keys for upload or processing
122
+ * @param count number of pre-keys to get or generate
123
+ */
124
+ const getNextPreKeys = async ({ creds, keys }, count) => {
125
+ const { newPreKeys, lastPreKeyId, preKeysRange } = (0, exports.generateOrGetPreKeys)(creds, count);
126
+ const update = {
127
+ nextPreKeyId: Math.max(lastPreKeyId + 1, creds.nextPreKeyId),
128
+ firstUnuploadedPreKeyId: Math.max(creds.firstUnuploadedPreKeyId, lastPreKeyId + 1)
129
+ };
130
+ await keys.set({ 'pre-key': newPreKeys });
131
+ const preKeys = await (0, exports.getPreKeys)(keys, preKeysRange[0], preKeysRange[0] + preKeysRange[1]);
132
+ return { update, preKeys };
133
+ };
134
+ exports.getNextPreKeys = getNextPreKeys;
135
+ const getNextPreKeysNode = async (state, count) => {
136
+ const { creds } = state;
137
+ const { update, preKeys } = await (0, exports.getNextPreKeys)(state, count);
138
+ const node = {
139
+ tag: 'iq',
140
+ attrs: {
141
+ xmlns: 'encrypt',
142
+ type: 'set',
143
+ to: WABinary_1.S_WHATSAPP_NET
144
+ },
145
+ content: [
146
+ { tag: 'registration', attrs: {}, content: (0, generics_1.encodeBigEndian)(creds.registrationId) },
147
+ { tag: 'type', attrs: {}, content: Defaults_1.KEY_BUNDLE_TYPE },
148
+ { tag: 'identity', attrs: {}, content: creds.signedIdentityKey.public },
149
+ { tag: 'list', attrs: {}, content: Object.keys(preKeys).map(k => (0, exports.xmppPreKey)(preKeys[+k], +k)) },
150
+ (0, exports.xmppSignedPreKey)(creds.signedPreKey)
151
+ ]
152
+ };
153
+ return { update, node };
154
+ };
155
+ exports.getNextPreKeysNode = getNextPreKeysNode;
@@ -0,0 +1,124 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useMultiFileAuthState = void 0;
4
+ const async_mutex_1 = require("async-mutex");
5
+ const promises_1 = require("fs/promises");
6
+ const path_1 = require("path");
7
+ const WAProto_1 = require("../../WAProto");
8
+ const auth_utils_1 = require("./auth-utils");
9
+ const generics_1 = require("./generics");
10
+ // We need to lock files due to the fact that we are using async functions to read and write files
11
+ // https://github.com/WhiskeySockets/Baileys/issues/794
12
+ // https://github.com/nodejs/node/issues/26338
13
+ // Use a Map to store mutexes for each file path
14
+ const fileLocks = new Map();
15
+ // Get or create a mutex for a specific file path
16
+ const getFileLock = (path) => {
17
+ let mutex = fileLocks.get(path);
18
+ if (!mutex) {
19
+ mutex = new async_mutex_1.Mutex();
20
+ fileLocks.set(path, mutex);
21
+ }
22
+ return mutex;
23
+ };
24
+ /**
25
+ * stores the full authentication state in a single folder.
26
+ * Far more efficient than singlefileauthstate
27
+ *
28
+ * Again, I wouldn't endorse this for any production level use other than perhaps a bot.
29
+ * Would recommend writing an auth state for use with a proper SQL or No-SQL DB
30
+ * */
31
+ const useMultiFileAuthState = async (folder) => {
32
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
33
+ const writeData = async (data, file) => {
34
+ const filePath = (0, path_1.join)(folder, fixFileName(file));
35
+ const mutex = getFileLock(filePath);
36
+ return mutex.acquire().then(async (release) => {
37
+ try {
38
+ await (0, promises_1.writeFile)(filePath, JSON.stringify(data, generics_1.BufferJSON.replacer));
39
+ }
40
+ finally {
41
+ release();
42
+ }
43
+ });
44
+ };
45
+ const readData = async (file) => {
46
+ try {
47
+ const filePath = (0, path_1.join)(folder, fixFileName(file));
48
+ const mutex = getFileLock(filePath);
49
+ return await mutex.acquire().then(async (release) => {
50
+ try {
51
+ const data = await (0, promises_1.readFile)(filePath, { encoding: 'utf-8' });
52
+ return JSON.parse(data, generics_1.BufferJSON.reviver);
53
+ }
54
+ finally {
55
+ release();
56
+ }
57
+ });
58
+ }
59
+ catch (error) {
60
+ return null;
61
+ }
62
+ };
63
+ const removeData = async (file) => {
64
+ try {
65
+ const filePath = (0, path_1.join)(folder, fixFileName(file));
66
+ const mutex = getFileLock(filePath);
67
+ return mutex.acquire().then(async (release) => {
68
+ try {
69
+ await (0, promises_1.unlink)(filePath);
70
+ }
71
+ catch (_a) {
72
+ }
73
+ finally {
74
+ release();
75
+ }
76
+ });
77
+ }
78
+ catch (_a) { }
79
+ };
80
+ const folderInfo = await (0, promises_1.stat)(folder).catch(() => { });
81
+ if (folderInfo) {
82
+ if (!folderInfo.isDirectory()) {
83
+ throw new Error(`found something that is not a directory at ${folder}, either delete it or specify a different location`);
84
+ }
85
+ }
86
+ else {
87
+ await (0, promises_1.mkdir)(folder, { recursive: true });
88
+ }
89
+ const fixFileName = (file) => { var _a; return (_a = file === null || file === void 0 ? void 0 : file.replace(/\//g, '__')) === null || _a === void 0 ? void 0 : _a.replace(/:/g, '-'); };
90
+ const creds = (await readData('creds.json')) || (0, auth_utils_1.initAuthCreds)();
91
+ return {
92
+ state: {
93
+ creds,
94
+ keys: {
95
+ get: async (type, ids) => {
96
+ const data = {};
97
+ await Promise.all(ids.map(async (id) => {
98
+ let value = await readData(`${type}-${id}.json`);
99
+ if (type === 'app-state-sync-key' && value) {
100
+ value = WAProto_1.proto.Message.AppStateSyncKeyData.fromObject(value);
101
+ }
102
+ data[id] = value;
103
+ }));
104
+ return data;
105
+ },
106
+ set: async (data) => {
107
+ const tasks = [];
108
+ for (const category in data) {
109
+ for (const id in data[category]) {
110
+ const value = data[category][id];
111
+ const file = `${category}-${id}.json`;
112
+ tasks.push(value ? writeData(value, file) : removeData(file));
113
+ }
114
+ }
115
+ await Promise.all(tasks);
116
+ }
117
+ }
118
+ },
119
+ saveCreds: async () => {
120
+ return writeData(creds, 'creds.json');
121
+ }
122
+ };
123
+ };
124
+ exports.useMultiFileAuthState = useMultiFileAuthState;
@@ -0,0 +1,170 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.encodeSignedDeviceIdentity = exports.configureSuccessfulPairing = exports.generateRegistrationNode = exports.generateLoginNode = void 0;
4
+ const boom_1 = require("@hapi/boom");
5
+ const crypto_1 = require("crypto");
6
+ const WAProto_1 = require("../../WAProto");
7
+ const Defaults_1 = require("../Defaults");
8
+ const WABinary_1 = require("../WABinary");
9
+ const crypto_2 = require("./crypto");
10
+ const generics_1 = require("./generics");
11
+ const signal_1 = require("./signal");
12
+ const getUserAgent = (config) => {
13
+ return {
14
+ appVersion: {
15
+ primary: config.version[0],
16
+ secondary: config.version[1],
17
+ tertiary: config.version[2]
18
+ },
19
+ platform: WAProto_1.proto.ClientPayload.UserAgent.Platform.WEB,
20
+ releaseChannel: WAProto_1.proto.ClientPayload.UserAgent.ReleaseChannel.RELEASE,
21
+ osVersion: '0.1',
22
+ device: 'Desktop',
23
+ osBuildNumber: '0.1',
24
+ localeLanguageIso6391: 'en',
25
+ mnc: '000',
26
+ mcc: '000',
27
+ localeCountryIso31661Alpha2: config.countryCode
28
+ };
29
+ };
30
+ const PLATFORM_MAP = {
31
+ 'Mac OS': WAProto_1.proto.ClientPayload.WebInfo.WebSubPlatform.DARWIN,
32
+ Windows: WAProto_1.proto.ClientPayload.WebInfo.WebSubPlatform.WIN32
33
+ };
34
+ const getWebInfo = (config) => {
35
+ let webSubPlatform = WAProto_1.proto.ClientPayload.WebInfo.WebSubPlatform.WEB_BROWSER;
36
+ if (config.syncFullHistory && PLATFORM_MAP[config.browser[0]]) {
37
+ webSubPlatform = PLATFORM_MAP[config.browser[0]];
38
+ }
39
+ return { webSubPlatform };
40
+ };
41
+ const getClientPayload = (config) => {
42
+ const payload = {
43
+ connectType: WAProto_1.proto.ClientPayload.ConnectType.WIFI_UNKNOWN,
44
+ connectReason: WAProto_1.proto.ClientPayload.ConnectReason.USER_ACTIVATED,
45
+ userAgent: getUserAgent(config)
46
+ };
47
+ payload.webInfo = getWebInfo(config);
48
+ return payload;
49
+ };
50
+ const generateLoginNode = (userJid, config) => {
51
+ const { user, device } = (0, WABinary_1.jidDecode)(userJid);
52
+ const payload = {
53
+ ...getClientPayload(config),
54
+ passive: false,
55
+ pull: true,
56
+ username: +user,
57
+ device: device
58
+ };
59
+ return WAProto_1.proto.ClientPayload.fromObject(payload);
60
+ };
61
+ exports.generateLoginNode = generateLoginNode;
62
+ const getPlatformType = (platform) => {
63
+ const platformType = platform.toUpperCase();
64
+ return WAProto_1.proto.DeviceProps.PlatformType[platformType] || WAProto_1.proto.DeviceProps.PlatformType.DESKTOP;
65
+ };
66
+ const generateRegistrationNode = ({ registrationId, signedPreKey, signedIdentityKey }, config) => {
67
+ // the app version needs to be md5 hashed
68
+ // and passed in
69
+ const appVersionBuf = (0, crypto_1.createHash)('md5')
70
+ .update(config.version.join('.')) // join as string
71
+ .digest();
72
+ const companion = {
73
+ os: config.browser[0],
74
+ platformType: getPlatformType(config.browser[1]),
75
+ requireFullSync: config.syncFullHistory
76
+ };
77
+ const companionProto = WAProto_1.proto.DeviceProps.encode(companion).finish();
78
+ const registerPayload = {
79
+ ...getClientPayload(config),
80
+ passive: false,
81
+ pull: false,
82
+ devicePairingData: {
83
+ buildHash: appVersionBuf,
84
+ deviceProps: companionProto,
85
+ eRegid: (0, generics_1.encodeBigEndian)(registrationId),
86
+ eKeytype: Defaults_1.KEY_BUNDLE_TYPE,
87
+ eIdent: signedIdentityKey.public,
88
+ eSkeyId: (0, generics_1.encodeBigEndian)(signedPreKey.keyId, 3),
89
+ eSkeyVal: signedPreKey.keyPair.public,
90
+ eSkeySig: signedPreKey.signature
91
+ }
92
+ };
93
+ return WAProto_1.proto.ClientPayload.fromObject(registerPayload);
94
+ };
95
+ exports.generateRegistrationNode = generateRegistrationNode;
96
+ const configureSuccessfulPairing = (stanza, { advSecretKey, signedIdentityKey, signalIdentities }) => {
97
+ const msgId = stanza.attrs.id;
98
+ const pairSuccessNode = (0, WABinary_1.getBinaryNodeChild)(stanza, 'pair-success');
99
+ const deviceIdentityNode = (0, WABinary_1.getBinaryNodeChild)(pairSuccessNode, 'device-identity');
100
+ const platformNode = (0, WABinary_1.getBinaryNodeChild)(pairSuccessNode, 'platform');
101
+ const deviceNode = (0, WABinary_1.getBinaryNodeChild)(pairSuccessNode, 'device');
102
+ const businessNode = (0, WABinary_1.getBinaryNodeChild)(pairSuccessNode, 'biz');
103
+ if (!deviceIdentityNode || !deviceNode) {
104
+ throw new boom_1.Boom('Missing device-identity or device in pair success node', { data: stanza });
105
+ }
106
+ const bizName = businessNode === null || businessNode === void 0 ? void 0 : businessNode.attrs.name;
107
+ const jid = deviceNode.attrs.jid;
108
+ const { details, hmac, accountType } = WAProto_1.proto.ADVSignedDeviceIdentityHMAC.decode(deviceIdentityNode.content);
109
+ const isHostedAccount = accountType !== undefined && accountType === WAProto_1.proto.ADVEncryptionType.HOSTED;
110
+ const hmacPrefix = isHostedAccount ? Buffer.from([6, 5]) : Buffer.alloc(0);
111
+ const advSign = (0, crypto_2.hmacSign)(Buffer.concat([hmacPrefix, details]), Buffer.from(advSecretKey, 'base64'));
112
+ if (Buffer.compare(hmac, advSign) !== 0) {
113
+ throw new boom_1.Boom('Invalid account signature');
114
+ }
115
+ const account = WAProto_1.proto.ADVSignedDeviceIdentity.decode(details);
116
+ const { accountSignatureKey, accountSignature, details: deviceDetails } = account;
117
+ const accountMsg = Buffer.concat([Buffer.from([6, 0]), deviceDetails, signedIdentityKey.public]);
118
+ if (!crypto_2.Curve.verify(accountSignatureKey, accountMsg, accountSignature)) {
119
+ throw new boom_1.Boom('Failed to verify account signature');
120
+ }
121
+ const devicePrefix = isHostedAccount ? Buffer.from([6, 6]) : Buffer.from([6, 1]);
122
+ const deviceMsg = Buffer.concat([devicePrefix, deviceDetails, signedIdentityKey.public, accountSignatureKey]);
123
+ account.deviceSignature = crypto_2.Curve.sign(signedIdentityKey.private, deviceMsg);
124
+ const identity = (0, signal_1.createSignalIdentity)(jid, accountSignatureKey);
125
+ const accountEnc = (0, exports.encodeSignedDeviceIdentity)(account, false);
126
+ const deviceIdentity = WAProto_1.proto.ADVDeviceIdentity.decode(account.details);
127
+ const reply = {
128
+ tag: 'iq',
129
+ attrs: {
130
+ to: WABinary_1.S_WHATSAPP_NET,
131
+ type: 'result',
132
+ id: msgId
133
+ },
134
+ content: [
135
+ {
136
+ tag: 'pair-device-sign',
137
+ attrs: {},
138
+ content: [
139
+ {
140
+ tag: 'device-identity',
141
+ attrs: { 'key-index': deviceIdentity.keyIndex.toString() },
142
+ content: accountEnc
143
+ }
144
+ ]
145
+ }
146
+ ]
147
+ };
148
+ const authUpdate = {
149
+ account,
150
+ me: { id: jid, name: bizName },
151
+ signalIdentities: [...(signalIdentities || []), identity],
152
+ platform: platformNode === null || platformNode === void 0 ? void 0 : platformNode.attrs.name
153
+ };
154
+ return {
155
+ creds: authUpdate,
156
+ reply
157
+ };
158
+ };
159
+ exports.configureSuccessfulPairing = configureSuccessfulPairing;
160
+ const encodeSignedDeviceIdentity = (account, includeSignatureKey) => {
161
+ var _a;
162
+ account = { ...account };
163
+ // set to null if we are not to include the signature key
164
+ // or if we are including the signature key but it is empty
165
+ if (!includeSignatureKey || !((_a = account.accountSignatureKey) === null || _a === void 0 ? void 0 : _a.length)) {
166
+ account.accountSignatureKey = null;
167
+ }
168
+ return WAProto_1.proto.ADVSignedDeviceIdentity.encode(account).finish();
169
+ };
170
+ exports.encodeSignedDeviceIdentity = encodeSignedDeviceIdentity;
@@ -0,0 +1 @@
1
+