mybotthisoneis 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 (106) hide show
  1. package/LICENSE +27 -0
  2. package/README.md +275 -0
  3. package/WAProto/GenerateStatics.sh +4 -0
  4. package/WAProto/WAProto.proto +5479 -0
  5. package/WAProto/fix-imports.js +85 -0
  6. package/WAProto/index.js +97691 -0
  7. package/engine-requirements.js +11 -0
  8. package/lib/Defaults/index.js +129 -0
  9. package/lib/Signal/Group/ciphertext-message.js +12 -0
  10. package/lib/Signal/Group/group-session-builder.js +30 -0
  11. package/lib/Signal/Group/group_cipher.js +82 -0
  12. package/lib/Signal/Group/index.js +12 -0
  13. package/lib/Signal/Group/keyhelper.js +18 -0
  14. package/lib/Signal/Group/sender-chain-key.js +26 -0
  15. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  16. package/lib/Signal/Group/sender-key-message.js +66 -0
  17. package/lib/Signal/Group/sender-key-name.js +48 -0
  18. package/lib/Signal/Group/sender-key-record.js +41 -0
  19. package/lib/Signal/Group/sender-key-state.js +84 -0
  20. package/lib/Signal/Group/sender-message-key.js +26 -0
  21. package/lib/Signal/libsignal.js +437 -0
  22. package/lib/Signal/lid-mapping.js +277 -0
  23. package/lib/Socket/Client/index.js +3 -0
  24. package/lib/Socket/Client/types.js +11 -0
  25. package/lib/Socket/Client/websocket.js +54 -0
  26. package/lib/Socket/business.js +379 -0
  27. package/lib/Socket/chats.js +1198 -0
  28. package/lib/Socket/communities.js +431 -0
  29. package/lib/Socket/groups.js +347 -0
  30. package/lib/Socket/index.js +12 -0
  31. package/lib/Socket/messages-recv.js +1772 -0
  32. package/lib/Socket/messages-send.js +1472 -0
  33. package/lib/Socket/mex.js +42 -0
  34. package/lib/Socket/newsletter.js +413 -0
  35. package/lib/Socket/socket.js +967 -0
  36. package/lib/Types/Auth.js +2 -0
  37. package/lib/Types/Bussines.js +2 -0
  38. package/lib/Types/Call.js +2 -0
  39. package/lib/Types/Chat.js +8 -0
  40. package/lib/Types/Contact.js +2 -0
  41. package/lib/Types/Events.js +2 -0
  42. package/lib/Types/GroupMetadata.js +2 -0
  43. package/lib/Types/Label.js +25 -0
  44. package/lib/Types/LabelAssociation.js +7 -0
  45. package/lib/Types/Message.js +11 -0
  46. package/lib/Types/Mex.js +37 -0
  47. package/lib/Types/Product.js +2 -0
  48. package/lib/Types/Signal.js +2 -0
  49. package/lib/Types/Socket.js +3 -0
  50. package/lib/Types/State.js +56 -0
  51. package/lib/Types/USync.js +2 -0
  52. package/lib/Types/index.js +26 -0
  53. package/lib/Utils/auth-utils.js +302 -0
  54. package/lib/Utils/browser-utils.js +28 -0
  55. package/lib/Utils/business.js +231 -0
  56. package/lib/Utils/chat-utils.js +872 -0
  57. package/lib/Utils/companion-reg-client-utils.js +35 -0
  58. package/lib/Utils/crypto.js +118 -0
  59. package/lib/Utils/decode-wa-message.js +317 -0
  60. package/lib/Utils/event-buffer.js +622 -0
  61. package/lib/Utils/generics.js +393 -0
  62. package/lib/Utils/history.js +134 -0
  63. package/lib/Utils/identity-change-handler.js +50 -0
  64. package/lib/Utils/index.js +22 -0
  65. package/lib/Utils/link-preview.js +85 -0
  66. package/lib/Utils/logger.js +3 -0
  67. package/lib/Utils/lt-hash.js +8 -0
  68. package/lib/Utils/make-mutex.js +33 -0
  69. package/lib/Utils/message-retry-manager.js +265 -0
  70. package/lib/Utils/messages-media.js +718 -0
  71. package/lib/Utils/messages.js +1134 -0
  72. package/lib/Utils/noise-handler.js +201 -0
  73. package/lib/Utils/offline-node-processor.js +40 -0
  74. package/lib/Utils/pre-key-manager.js +106 -0
  75. package/lib/Utils/process-message.js +630 -0
  76. package/lib/Utils/reporting-utils.js +258 -0
  77. package/lib/Utils/signal.js +201 -0
  78. package/lib/Utils/stanza-ack.js +38 -0
  79. package/lib/Utils/sync-action-utils.js +49 -0
  80. package/lib/Utils/tc-token-utils.js +156 -0
  81. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  82. package/lib/Utils/validate-connection.js +240 -0
  83. package/lib/WABinary/constants.js +1301 -0
  84. package/lib/WABinary/decode.js +262 -0
  85. package/lib/WABinary/encode.js +220 -0
  86. package/lib/WABinary/generic-utils.js +113 -0
  87. package/lib/WABinary/index.js +6 -0
  88. package/lib/WABinary/jid-utils.js +96 -0
  89. package/lib/WABinary/types.js +2 -0
  90. package/lib/WAM/BinaryInfo.js +10 -0
  91. package/lib/WAM/constants.js +22853 -0
  92. package/lib/WAM/encode.js +150 -0
  93. package/lib/WAM/index.js +4 -0
  94. package/lib/WAUSync/Protocols/USyncContactProtocol.js +52 -0
  95. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  96. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  97. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  98. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  99. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  100. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  101. package/lib/WAUSync/Protocols/index.js +6 -0
  102. package/lib/WAUSync/USyncQuery.js +98 -0
  103. package/lib/WAUSync/USyncUser.js +31 -0
  104. package/lib/WAUSync/index.js +4 -0
  105. package/lib/index.js +60 -0
  106. package/package.json +116 -0
@@ -0,0 +1,156 @@
1
+ import { getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isJidMetaAI, isLidUser, isPnUser, jidNormalizedUser } from '../WABinary/index.js';
2
+
3
+ const BOT_PHONE_REGEX = /^1313555\d{4}$|^131655500\d{2}$/;
4
+ function isRegularUser(jid) {
5
+ if (!jid)
6
+ return false;
7
+ const user = jid.split('@')[0] ?? '';
8
+ if (user === '0')
9
+ return false; // PSA
10
+ if (BOT_PHONE_REGEX.test(user))
11
+ return false; // Bot by phone pattern
12
+ if (isJidMetaAI(jid))
13
+ return false; // MetaAI (@bot server)
14
+ return !!(isPnUser(jid) || isLidUser(jid) || isHostedPnUser(jid) || isHostedLidUser(jid) || jid.endsWith('@c.us'));
15
+ }
16
+ const TC_TOKEN_BUCKET_DURATION = 604800; // 7 days
17
+ const TC_TOKEN_NUM_BUCKETS = 4; // ~28-day rolling window
18
+ /** Sentinel key under `tctoken` store holding a JSON array of tracked storage JIDs for cross-session pruning. */
19
+ export const TC_TOKEN_INDEX_KEY = '__index';
20
+ /** Read the persisted tctoken JID index and return its entries (never contains the sentinel key itself). */
21
+ export async function readTcTokenIndex(keys) {
22
+ const data = await keys.get('tctoken', [TC_TOKEN_INDEX_KEY]);
23
+ const entry = data[TC_TOKEN_INDEX_KEY];
24
+ if (!entry?.token?.length)
25
+ return [];
26
+ try {
27
+ const parsed = JSON.parse(Buffer.from(entry.token).toString());
28
+ if (!Array.isArray(parsed))
29
+ return [];
30
+ return parsed.filter((j) => typeof j === 'string' && j.length > 0 && j !== TC_TOKEN_INDEX_KEY);
31
+ }
32
+ catch {
33
+ return [];
34
+ }
35
+ }
36
+ /** Build a SignalDataSet fragment that writes the merged index (persisted ∪ added) under the sentinel key. */
37
+ export async function buildMergedTcTokenIndexWrite(keys, addedJids) {
38
+ const persisted = await readTcTokenIndex(keys);
39
+ const merged = new Set(persisted);
40
+ for (const jid of addedJids) {
41
+ if (jid && jid !== TC_TOKEN_INDEX_KEY)
42
+ merged.add(jid);
43
+ }
44
+ return {
45
+ [TC_TOKEN_INDEX_KEY]: { token: Buffer.from(JSON.stringify([...merged])) }
46
+ };
47
+ }
48
+ // WA Web has separate sender/receiver AB props for these but they're identical today
49
+ export function isTcTokenExpired(timestamp) {
50
+ if (timestamp === null || timestamp === undefined)
51
+ return true;
52
+ const ts = typeof timestamp === 'string' ? parseInt(timestamp) : timestamp;
53
+ if (isNaN(ts))
54
+ return true;
55
+ const now = Math.floor(Date.now() / 1000);
56
+ const currentBucket = Math.floor(now / TC_TOKEN_BUCKET_DURATION);
57
+ const cutoffBucket = currentBucket - (TC_TOKEN_NUM_BUCKETS - 1);
58
+ const cutoffTimestamp = cutoffBucket * TC_TOKEN_BUCKET_DURATION;
59
+ return ts < cutoffTimestamp;
60
+ }
61
+ export function shouldSendNewTcToken(senderTimestamp) {
62
+ if (senderTimestamp === undefined)
63
+ return true;
64
+ const now = Math.floor(Date.now() / 1000);
65
+ const currentBucket = Math.floor(now / TC_TOKEN_BUCKET_DURATION);
66
+ const senderBucket = Math.floor(senderTimestamp / TC_TOKEN_BUCKET_DURATION);
67
+ return currentBucket > senderBucket;
68
+ }
69
+ /** Resolve JID to LID for tctoken storage (WA Web stores under LID) */
70
+ export async function resolveTcTokenJid(jid, getLIDForPN) {
71
+ if (isLidUser(jid))
72
+ return jid;
73
+ const lid = await getLIDForPN(jid);
74
+ return lid ?? jid;
75
+ }
76
+ /** Resolve target JID for issuing privacy token based on AB prop 14303 */
77
+ export async function resolveIssuanceJid(jid, issueToLid, getLIDForPN, getPNForLID) {
78
+ if (issueToLid) {
79
+ if (isLidUser(jid))
80
+ return jid;
81
+ const lid = await getLIDForPN(jid);
82
+ return lid ?? jid;
83
+ }
84
+ if (!isLidUser(jid))
85
+ return jid;
86
+ if (getPNForLID) {
87
+ const pn = await getPNForLID(jid);
88
+ return pn ?? jid;
89
+ }
90
+ return jid;
91
+ }
92
+ export async function buildTcTokenFromJid({ authState, jid, baseContent = [], getLIDForPN }) {
93
+ try {
94
+ const storageJid = await resolveTcTokenJid(jid, getLIDForPN);
95
+ const tcTokenData = await authState.keys.get('tctoken', [storageJid]);
96
+ const entry = tcTokenData?.[storageJid];
97
+ const tcTokenBuffer = entry?.token;
98
+ const timestamp = entry?.timestamp;
99
+ if (!tcTokenBuffer?.length || timestamp === undefined || isTcTokenExpired(timestamp)) {
100
+ if (tcTokenBuffer) {
101
+ // Preserve senderTimestamp so shouldSendNewTcToken() keeps its dedupe state
102
+ // after we drop the unusable peer token. Only wipe the record entirely when
103
+ // there's nothing worth keeping.
104
+ const cleared = entry?.senderTimestamp !== undefined
105
+ ? { token: Buffer.alloc(0), senderTimestamp: entry.senderTimestamp }
106
+ : null;
107
+ await authState.keys.set({ tctoken: { [storageJid]: cleared } });
108
+ }
109
+ return baseContent.length > 0 ? baseContent : undefined;
110
+ }
111
+ baseContent.push({
112
+ tag: 'tctoken',
113
+ attrs: { t: String(timestamp) },
114
+ content: tcTokenBuffer
115
+ });
116
+ return baseContent;
117
+ }
118
+ catch (error) {
119
+ return baseContent.length > 0 ? baseContent : undefined;
120
+ }
121
+ }
122
+ export async function storeTcTokensFromIqResult({ result, fallbackJid, keys, getLIDForPN, onNewJidStored }) {
123
+ const tokensNode = getBinaryNodeChild(result, 'tokens');
124
+ if (!tokensNode)
125
+ return;
126
+ const tokenNodes = getBinaryNodeChildren(tokensNode, 'token');
127
+ for (const tokenNode of tokenNodes) {
128
+ if (tokenNode.attrs.type !== 'trusted_contact' || !(tokenNode.content instanceof Uint8Array)) {
129
+ continue;
130
+ }
131
+ // In notifications tokenNode.attrs.jid is your own device JID, not the sender's
132
+ const rawJid = jidNormalizedUser(fallbackJid || tokenNode.attrs.jid);
133
+ if (!isRegularUser(rawJid))
134
+ continue;
135
+ const storageJid = await resolveTcTokenJid(rawJid, getLIDForPN);
136
+ const existingTcData = await keys.get('tctoken', [storageJid]);
137
+ const existingEntry = existingTcData[storageJid];
138
+ const existingTs = existingEntry?.timestamp ? Number(existingEntry.timestamp) : 0;
139
+ const incomingTs = tokenNode.attrs.t ? Number(tokenNode.attrs.t) : 0;
140
+ // timestamp-less tokens would be immediately expired
141
+ if (!incomingTs)
142
+ continue;
143
+ if (existingTs > 0 && existingTs > incomingTs)
144
+ continue;
145
+ await keys.set({
146
+ tctoken: {
147
+ [storageJid]: {
148
+ ...existingEntry,
149
+ token: Buffer.from(tokenNode.content),
150
+ timestamp: tokenNode.attrs.t
151
+ }
152
+ }
153
+ });
154
+ onNewJidStored?.(storageJid);
155
+ }
156
+ }
@@ -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,240 @@
1
+ import { Boom } from '@hapi/boom';
2
+ import { createHash } from 'crypto';
3
+ import { proto } from '../../WAProto/index.js';
4
+ import { KEY_BUNDLE_TYPE } 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
+
10
+ const getUserAgent = (config) => {
11
+ return {
12
+ appVersion: {
13
+ primary: config.version[0],
14
+ secondary: config.version[1],
15
+ tertiary: config.version[2],
16
+ },
17
+ platform: config.browser[1].toLocaleLowerCase().includes('android')
18
+ ? proto.ClientPayload.UserAgent.Platform.ANDROID
19
+ : proto.ClientPayload.UserAgent.Platform.WEB,
20
+ releaseChannel: 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
+
31
+ const PLATFORM_MAP = {
32
+ 'Mac OS': proto.ClientPayload.WebInfo.WebSubPlatform.DARWIN,
33
+ 'Windows': proto.ClientPayload.WebInfo.WebSubPlatform.WIN32
34
+ };
35
+
36
+ const getWebInfo = (config) => {
37
+ let webSubPlatform = proto.ClientPayload.WebInfo.WebSubPlatform.WEB_BROWSER;
38
+ if (config.syncFullHistory &&
39
+ PLATFORM_MAP[config.browser[0]] &&
40
+ config.browser[1] === 'Desktop') {
41
+ webSubPlatform = PLATFORM_MAP[config.browser[0]];
42
+ }
43
+ return { webSubPlatform };
44
+ };
45
+
46
+ const getClientPayload = (config) => {
47
+ const payload = {
48
+ connectType: proto.ClientPayload.ConnectType.WIFI_UNKNOWN,
49
+ connectReason: proto.ClientPayload.ConnectReason.USER_ACTIVATED,
50
+ userAgent: getUserAgent(config),
51
+ };
52
+
53
+ // Only add webInfo for non-Android connections
54
+ if (!config.browser[1].toLocaleLowerCase().includes('android')) {
55
+ payload.webInfo = getWebInfo(config);
56
+ }
57
+
58
+ if (config.pushName) {
59
+ payload.pushName = config.pushName;
60
+ }
61
+ return payload;
62
+ };
63
+
64
+ export const generateLoginNode = (userJid, config) => {
65
+ const { user, device } = jidDecode(userJid);
66
+ const payload = {
67
+ ...getClientPayload(config),
68
+ passive: false,
69
+ pull: true,
70
+ username: +user,
71
+ device: device,
72
+ lidDbMigrated: false
73
+ };
74
+ return proto.ClientPayload.fromObject(payload);
75
+ };
76
+
77
+ const getPlatformType = (platform) => {
78
+ const platformType = platform.toUpperCase();
79
+ // 'ANDROID' is not in PlatformType enum — map to ANDROID_PHONE
80
+ if (platformType === 'ANDROID') {
81
+ return proto.DeviceProps.PlatformType.ANDROID_PHONE;
82
+ }
83
+ return (proto.DeviceProps.PlatformType[platformType] ||
84
+ proto.DeviceProps.PlatformType.CHROME);
85
+ };
86
+
87
+ export const generateRegistrationNode = ({ registrationId, signedPreKey, signedIdentityKey }, config) => {
88
+
89
+ const appVersionBuf = createHash('md5')
90
+ .update(config.version.join('.'))
91
+ .digest();
92
+
93
+ const companion = {
94
+ os: config.browser[0],
95
+ platformType: getPlatformType(config.browser[1]),
96
+ requireFullSync: config.syncFullHistory,
97
+ historySyncConfig: {
98
+ storageQuotaMb: 10240,
99
+ inlineInitialPayloadInE2EeMsg: true,
100
+ recentSyncDaysLimit: undefined,
101
+ supportCallLogHistory: false,
102
+ supportBotUserAgentChatHistory: true,
103
+ supportCagReactionsAndPolls: true,
104
+ supportBizHostedMsg: true,
105
+ supportRecentSyncChunkMessageCountTuning: true,
106
+ supportHostedGroupMsg: true,
107
+ supportFbidBotChatHistory: true,
108
+ supportAddOnHistorySyncMigration: undefined,
109
+ supportMessageAssociation: true,
110
+ supportGroupHistory: false,
111
+ onDemandReady: undefined,
112
+ supportGuestChat: undefined
113
+ },
114
+ version: {
115
+ primary: 10,
116
+ secondary: 15,
117
+ tertiary: 7
118
+ }
119
+ };
120
+
121
+ const companionProto = proto.DeviceProps.encode(companion).finish();
122
+
123
+ const registerPayload = {
124
+ ...getClientPayload(config),
125
+ passive: false,
126
+ pull: false,
127
+ devicePairingData: {
128
+ buildHash: appVersionBuf,
129
+ deviceProps: companionProto,
130
+ eRegid: encodeBigEndian(registrationId),
131
+ eKeytype: KEY_BUNDLE_TYPE,
132
+ eIdent: signedIdentityKey.public,
133
+ eSkeyId: encodeBigEndian(signedPreKey.keyId, 3),
134
+ eSkeyVal: signedPreKey.keyPair.public,
135
+ eSkeySig: signedPreKey.signature,
136
+ }
137
+ };
138
+
139
+ return proto.ClientPayload.fromObject(registerPayload);
140
+ };
141
+
142
+ export const configureSuccessfulPairing = (stanza, { advSecretKey, signedIdentityKey, signalIdentities }) => {
143
+ const msgId = stanza.attrs.id;
144
+ const pairSuccessNode = getBinaryNodeChild(stanza, 'pair-success');
145
+ const deviceIdentityNode = getBinaryNodeChild(pairSuccessNode, 'device-identity');
146
+ const platformNode = getBinaryNodeChild(pairSuccessNode, 'platform');
147
+ const deviceNode = getBinaryNodeChild(pairSuccessNode, 'device');
148
+ const businessNode = getBinaryNodeChild(pairSuccessNode, 'biz');
149
+
150
+ if (!deviceIdentityNode || !deviceNode) {
151
+ throw new Boom('Missing device-identity or device in pair success node', { data: stanza });
152
+ }
153
+
154
+ const bizName = businessNode?.attrs?.name;
155
+ const jid = deviceNode.attrs.jid;
156
+ const lid = deviceNode.attrs.lid;
157
+ const { details, hmac, accountType } = proto.ADVSignedDeviceIdentityHMAC.decode(deviceIdentityNode.content);
158
+
159
+ let hmacPrefix = Buffer.from([]);
160
+ if (accountType !== undefined && accountType === proto.ADVEncryptionType.HOSTED) {
161
+ hmacPrefix = Buffer.from([6, 5]);
162
+ }
163
+
164
+ const advSign = hmacSign(Buffer.concat([hmacPrefix, details]), Buffer.from(advSecretKey, 'base64'));
165
+ if (Buffer.compare(hmac, advSign) !== 0) {
166
+ throw new Boom('Invalid account signature');
167
+ }
168
+
169
+ const account = proto.ADVSignedDeviceIdentity.decode(details);
170
+ const { accountSignatureKey, accountSignature, details: deviceDetails } = account;
171
+
172
+ const decodedDeviceIdentity = proto.ADVDeviceIdentity.decode(deviceDetails);
173
+
174
+ const accountSignaturePrefix =
175
+ decodedDeviceIdentity.deviceType === proto.ADVEncryptionType.HOSTED
176
+ ? Buffer.from([6, 5])
177
+ : Buffer.from([6, 0]);
178
+
179
+ const accountMsg = Buffer.concat([accountSignaturePrefix, deviceDetails, signedIdentityKey.public]);
180
+ if (!Curve.verify(accountSignatureKey, accountMsg, accountSignature)) {
181
+ throw new Boom('Failed to verify account signature');
182
+ }
183
+
184
+ const deviceMsg = Buffer.concat([
185
+ Buffer.from([6, 1]),
186
+ deviceDetails,
187
+ signedIdentityKey.public,
188
+ accountSignatureKey
189
+ ]);
190
+
191
+ account.deviceSignature = Curve.sign(signedIdentityKey.private, deviceMsg);
192
+ const identity = createSignalIdentity(lid, accountSignatureKey);
193
+ const accountEnc = encodeSignedDeviceIdentity(account, false);
194
+ const deviceIdentityData = proto.ADVDeviceIdentity.decode(account.details);
195
+
196
+ const reply = {
197
+ tag: 'iq',
198
+ attrs: {
199
+ to: S_WHATSAPP_NET,
200
+ type: 'result',
201
+ id: msgId,
202
+ },
203
+ content: [
204
+ {
205
+ tag: 'pair-device-sign',
206
+ attrs: {},
207
+ content: [
208
+ {
209
+ tag: 'device-identity',
210
+ attrs: { 'key-index': deviceIdentityData.keyIndex.toString() },
211
+ content: accountEnc
212
+ }
213
+ ]
214
+ }
215
+ ]
216
+ };
217
+
218
+ const authUpdate = {
219
+ account,
220
+ me: { id: jid, name: bizName, lid },
221
+ signalIdentities: [
222
+ ...(signalIdentities || []),
223
+ identity
224
+ ],
225
+ platform: platformNode?.attrs?.name
226
+ };
227
+
228
+ return {
229
+ creds: authUpdate,
230
+ reply
231
+ };
232
+ };
233
+
234
+ export const encodeSignedDeviceIdentity = (account, includeSignatureKey) => {
235
+ account = { ...account };
236
+ if (!includeSignatureKey || !account.accountSignatureKey?.length) {
237
+ account.accountSignatureKey = null;
238
+ }
239
+ return proto.ADVSignedDeviceIdentity.encode(account).finish();
240
+ };