@aseppxyzz12/baileys 1.1.8

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 (185) hide show
  1. package/LICENSE +25 -0
  2. package/README.md +2579 -0
  3. package/WAProto/AICommon/AICommon.js +19396 -0
  4. package/WAProto/AICommon/AICommon.proto +820 -0
  5. package/WAProto/Adv/Adv.js +1137 -0
  6. package/WAProto/Adv/Adv.proto +42 -0
  7. package/WAProto/BotMetadata/BotMetadata.js +8975 -0
  8. package/WAProto/BotMetadata/BotMetadata.proto +484 -0
  9. package/WAProto/Cert/Cert.js +893 -0
  10. package/WAProto/Cert/Cert.proto +30 -0
  11. package/WAProto/ChatLockSettings/ChatLockSettings.js +673 -0
  12. package/WAProto/ChatLockSettings/ChatLockSettings.proto +9 -0
  13. package/WAProto/CompanionReg/CompanionReg.js +2457 -0
  14. package/WAProto/CompanionReg/CompanionReg.proto +103 -0
  15. package/WAProto/DeviceCapabilities/DeviceCapabilities.js +846 -0
  16. package/WAProto/DeviceCapabilities/DeviceCapabilities.proto +38 -0
  17. package/WAProto/E2E/E2E.js +78728 -0
  18. package/WAProto/E2E/E2E.proto +1970 -0
  19. package/WAProto/Ephemeral/Ephemeral.js +143 -0
  20. package/WAProto/Ephemeral/Ephemeral.proto +7 -0
  21. package/WAProto/HistorySync/HistorySync.js +95931 -0
  22. package/WAProto/HistorySync/HistorySync.proto +229 -0
  23. package/WAProto/LidMigrationSyncPayload/LidMigrationSyncPayload.js +414 -0
  24. package/WAProto/LidMigrationSyncPayload/LidMigrationSyncPayload.proto +13 -0
  25. package/WAProto/MdStorageChatRowOpaqueData/MdStorageChatRowOpaqueData.js +980 -0
  26. package/WAProto/MdStorageChatRowOpaqueData/MdStorageChatRowOpaqueData.proto +38 -0
  27. package/WAProto/MdStorageMsgRowOpaqueData/MdStorageMsgRowOpaqueData.js +81185 -0
  28. package/WAProto/MdStorageMsgRowOpaqueData/MdStorageMsgRowOpaqueData.proto +88 -0
  29. package/WAProto/MmsRetry/MmsRetry.js +310 -0
  30. package/WAProto/MmsRetry/MmsRetry.proto +19 -0
  31. package/WAProto/Protocol/Protocol.js +399 -0
  32. package/WAProto/Protocol/Protocol.proto +22 -0
  33. package/WAProto/Reporting/Reporting.js +535 -0
  34. package/WAProto/Reporting/Reporting.proto +22 -0
  35. package/WAProto/ServerSync/ServerSync.js +1830 -0
  36. package/WAProto/ServerSync/ServerSync.proto +70 -0
  37. package/WAProto/SignalLocalStorageProtocol/SignalLocalStorageProtocol.js +3267 -0
  38. package/WAProto/SignalLocalStorageProtocol/SignalLocalStorageProtocol.proto +95 -0
  39. package/WAProto/SignalWhisperTextProtocol/SignalWhisperTextProtocol.js +1140 -0
  40. package/WAProto/SignalWhisperTextProtocol/SignalWhisperTextProtocol.proto +44 -0
  41. package/WAProto/StatusAttributions/StatusAttributions.js +1604 -0
  42. package/WAProto/StatusAttributions/StatusAttributions.proto +89 -0
  43. package/WAProto/SyncAction/SyncAction.js +17424 -0
  44. package/WAProto/SyncAction/SyncAction.proto +663 -0
  45. package/WAProto/UserPassword/UserPassword.js +544 -0
  46. package/WAProto/UserPassword/UserPassword.proto +28 -0
  47. package/WAProto/VnameCert/VnameCert.js +1466 -0
  48. package/WAProto/VnameCert/VnameCert.proto +65 -0
  49. package/WAProto/Wa6/Wa6.js +4601 -0
  50. package/WAProto/Wa6/Wa6.proto +241 -0
  51. package/WAProto/Web/Web.js +90819 -0
  52. package/WAProto/Web/Web.proto +605 -0
  53. package/WAProto/index.js +30 -0
  54. package/engine-requirements.js +9 -0
  55. package/lib/Defaults/baileys-version.json +3 -0
  56. package/lib/Defaults/connection.js +39 -0
  57. package/lib/Defaults/constants.js +50 -0
  58. package/lib/Defaults/history.js +13 -0
  59. package/lib/Defaults/index.js +36 -0
  60. package/lib/Defaults/media.js +43 -0
  61. package/lib/Defaults/phonenumber-mcc.json +223 -0
  62. package/lib/Defaults/prefix.js +12 -0
  63. package/lib/Function/Download/tiktok.js +19 -0
  64. package/lib/Function/Tools/bypass.js +19 -0
  65. package/lib/Function/index.js +13 -0
  66. package/lib/Signal/Group/ciphertext-message.js +14 -0
  67. package/lib/Signal/Group/group-session-builder.js +46 -0
  68. package/lib/Signal/Group/group_cipher.js +104 -0
  69. package/lib/Signal/Group/index.js +42 -0
  70. package/lib/Signal/Group/keyhelper.js +21 -0
  71. package/lib/Signal/Group/queue-job.js +57 -0
  72. package/lib/Signal/Group/sender-chain-key.js +34 -0
  73. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  74. package/lib/Signal/Group/sender-key-message.js +78 -0
  75. package/lib/Signal/Group/sender-key-name.js +49 -0
  76. package/lib/Signal/Group/sender-key-record.js +45 -0
  77. package/lib/Signal/Group/sender-key-state.js +100 -0
  78. package/lib/Signal/Group/sender-message-key.js +28 -0
  79. package/lib/Signal/libsignal.js +364 -0
  80. package/lib/Signal/lid-mapping.js +164 -0
  81. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  82. package/lib/Socket/Client/index.js +31 -0
  83. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  84. package/lib/Socket/Client/types.js +12 -0
  85. package/lib/Socket/Client/web-socket-client.js +62 -0
  86. package/lib/Socket/Client/websocket.js +67 -0
  87. package/lib/Socket/business.js +291 -0
  88. package/lib/Socket/chats.js +874 -0
  89. package/lib/Socket/community.js +454 -0
  90. package/lib/Socket/dugong.js +658 -0
  91. package/lib/Socket/groups.js +357 -0
  92. package/lib/Socket/index.js +13 -0
  93. package/lib/Socket/messages-recv.js +1509 -0
  94. package/lib/Socket/messages-send.js +1505 -0
  95. package/lib/Socket/mex.js +54 -0
  96. package/lib/Socket/newsletter.js +171 -0
  97. package/lib/Socket/registration.js +167 -0
  98. package/lib/Socket/rich-content.js +279 -0
  99. package/lib/Socket/socket.js +905 -0
  100. package/lib/Socket/username.js +157 -0
  101. package/lib/Socket/usync.js +70 -0
  102. package/lib/Store/index.js +37 -0
  103. package/lib/Store/keyed-db.js +114 -0
  104. package/lib/Store/make-cache-manager-store.js +77 -0
  105. package/lib/Store/make-in-memory-store.js +423 -0
  106. package/lib/Store/make-ordered-dictionary.js +78 -0
  107. package/lib/Store/object-repository.js +26 -0
  108. package/lib/Types/Auth.js +2 -0
  109. package/lib/Types/Bussines.js +2 -0
  110. package/lib/Types/Call.js +2 -0
  111. package/lib/Types/Chat.js +10 -0
  112. package/lib/Types/Contact.js +2 -0
  113. package/lib/Types/Events.js +2 -0
  114. package/lib/Types/GroupMetadata.js +2 -0
  115. package/lib/Types/Label.js +25 -0
  116. package/lib/Types/LabelAssociation.js +4 -0
  117. package/lib/Types/Message.js +11 -0
  118. package/lib/Types/Mex.js +40 -0
  119. package/lib/Types/MexUpdates.js +15 -0
  120. package/lib/Types/Newsletter.js +32 -0
  121. package/lib/Types/Product.js +2 -0
  122. package/lib/Types/Signal.js +2 -0
  123. package/lib/Types/Socket.js +2 -0
  124. package/lib/Types/State.js +9 -0
  125. package/lib/Types/USync.js +2 -0
  126. package/lib/Types/index.js +60 -0
  127. package/lib/Utils/auth-utils.js +256 -0
  128. package/lib/Utils/baileys-event-stream.js +63 -0
  129. package/lib/Utils/bot-toolkit.js +455 -0
  130. package/lib/Utils/browser-utils.js +29 -0
  131. package/lib/Utils/business.js +233 -0
  132. package/lib/Utils/chat-utils.js +904 -0
  133. package/lib/Utils/companion-reg-client-utils.js +41 -0
  134. package/lib/Utils/crypto.js +144 -0
  135. package/lib/Utils/decode-wa-message.js +305 -0
  136. package/lib/Utils/event-buffer.js +555 -0
  137. package/lib/Utils/generics.js +411 -0
  138. package/lib/Utils/history.js +100 -0
  139. package/lib/Utils/identity-change-handler.js +53 -0
  140. package/lib/Utils/index.js +57 -0
  141. package/lib/Utils/link-preview.js +76 -0
  142. package/lib/Utils/logger.js +4 -0
  143. package/lib/Utils/lt-hash.js +45 -0
  144. package/lib/Utils/make-mutex.js +33 -0
  145. package/lib/Utils/message-composer.js +289 -0
  146. package/lib/Utils/message-retry-manager.js +134 -0
  147. package/lib/Utils/messages-media.js +806 -0
  148. package/lib/Utils/messages.js +1908 -0
  149. package/lib/Utils/noise-handler.js +157 -0
  150. package/lib/Utils/offline-node-processor.js +42 -0
  151. package/lib/Utils/pre-key-manager.js +86 -0
  152. package/lib/Utils/process-message.js +814 -0
  153. package/lib/Utils/reporting-utils.js +264 -0
  154. package/lib/Utils/signal.js +183 -0
  155. package/lib/Utils/stanza-ack.js +36 -0
  156. package/lib/Utils/sync-action-utils.js +52 -0
  157. package/lib/Utils/tc-token-utils.js +167 -0
  158. package/lib/Utils/use-multi-file-auth-state.js +104 -0
  159. package/lib/Utils/validate-connection.js +229 -0
  160. package/lib/Utils/vialeys-event-stream.js +41 -0
  161. package/lib/WABinary/constants.js +1308 -0
  162. package/lib/WABinary/decode.js +233 -0
  163. package/lib/WABinary/encode.js +212 -0
  164. package/lib/WABinary/generic-utils.js +124 -0
  165. package/lib/WABinary/index.js +36 -0
  166. package/lib/WABinary/jid-utils.js +101 -0
  167. package/lib/WABinary/types.js +2 -0
  168. package/lib/WAM/BinaryInfo.js +12 -0
  169. package/lib/WAM/constants.js +20491 -0
  170. package/lib/WAM/encode.js +148 -0
  171. package/lib/WAM/index.js +34 -0
  172. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +62 -0
  173. package/lib/WAUSync/Protocols/USyncContactProtocol.js +38 -0
  174. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +50 -0
  175. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +25 -0
  176. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +24 -0
  177. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +32 -0
  178. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  179. package/lib/WAUSync/Protocols/index.js +38 -0
  180. package/lib/WAUSync/USyncQuery.js +97 -0
  181. package/lib/WAUSync/USyncUser.js +33 -0
  182. package/lib/WAUSync/index.js +34 -0
  183. package/lib/index.js +113 -0
  184. package/lib/messages-send.js +1496 -0
  185. package/package.json +100 -0
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const { Boom: Boom } = require("@hapi/boom");
4
+ const {
5
+ getBinaryNodeChild: getBinaryNodeChild,
6
+ S_WHATSAPP_NET: S_WHATSAPP_NET,
7
+ } = require("../WABinary");
8
+ const wMexQuery = (variables, queryId, query, generateMessageTag) =>
9
+ query({
10
+ tag: "iq",
11
+ attrs: {
12
+ id: generateMessageTag(),
13
+ type: "get",
14
+ to: S_WHATSAPP_NET,
15
+ xmlns: "w:mex",
16
+ },
17
+ content: [
18
+ {
19
+ tag: "query",
20
+ attrs: { query_id: queryId },
21
+ content: Buffer.from(JSON.stringify({ variables: variables }), "utf-8"),
22
+ },
23
+ ],
24
+ });
25
+ const executeWMexQuery = async (variables, queryId, dataPath, query, generateMessageTag) => {
26
+ const result = await wMexQuery(variables, queryId, query, generateMessageTag);
27
+ const child = getBinaryNodeChild(result, "result");
28
+ if (child?.content) {
29
+ const data = JSON.parse(child.content.toString());
30
+ if (data.errors && data.errors.length > 0) {
31
+ const errorMessages = data.errors
32
+ .map((err) => err.message || "Unknown error")
33
+ .join(", ");
34
+ const firstError = data.errors[0];
35
+ const errorCode = firstError.extensions?.error_code || 400;
36
+ throw new Boom(`GraphQL server error: ${errorMessages}`, {
37
+ statusCode: errorCode,
38
+ data: firstError,
39
+ });
40
+ }
41
+ const response = dataPath ? data?.data?.[dataPath] : data?.data;
42
+ if (typeof response !== "undefined") {
43
+ return response;
44
+ }
45
+ }
46
+ const action = (dataPath || "").startsWith("xwa2_")
47
+ ? dataPath.substring(5).replace(/_/g, " ")
48
+ : dataPath?.replace(/_/g, " ");
49
+ throw new Boom(`Failed to ${action}, unexpected response structure.`, {
50
+ statusCode: 400,
51
+ data: result,
52
+ });
53
+ };
54
+ module.exports = { executeWMexQuery: executeWMexQuery };
@@ -0,0 +1,171 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const { QueryIds: QueryIds, XWAPaths: XWAPaths } = require("../Types");
4
+ const { generateProfilePicture: generateProfilePicture } = require("../Utils");
5
+ const { getBinaryNodeChild: getBinaryNodeChild } = require("../WABinary");
6
+ const { makeGroupsSocket: makeGroupsSocket } = require("./groups");
7
+ const { executeWMexQuery: genericExecuteWMexQuery } = require("./mex");
8
+ const parseNewsletterCreateResponse = (response) => {
9
+ const { id: id, thread_metadata: thread, viewer_metadata: viewer } = response;
10
+ return {
11
+ id: id,
12
+ owner: undefined,
13
+ name: thread.name.text,
14
+ creation_time: parseInt(thread.creation_time, 10),
15
+ description: thread.description.text,
16
+ invite: thread.invite,
17
+ subscribers: parseInt(thread.subscribers_count, 10),
18
+ verification: thread.verification,
19
+ picture: { id: thread.picture.id, directPath: thread.picture.direct_path },
20
+ mute_state: viewer.mute,
21
+ };
22
+ };
23
+ const parseNewsletterMetadata = (result) => {
24
+ if (typeof result !== "object" || result === null) {
25
+ return null;
26
+ }
27
+ if ("id" in result && typeof result.id === "string") {
28
+ return result;
29
+ }
30
+ if (
31
+ "result" in result &&
32
+ typeof result.result === "object" &&
33
+ result.result !== null &&
34
+ "id" in result.result
35
+ ) {
36
+ return result.result;
37
+ }
38
+ return null;
39
+ };
40
+ const makeNewsletterSocket = (config) => {
41
+ const conn = makeGroupsSocket(config);
42
+ const { query: query, generateMessageTag: generateMessageTag } = conn;
43
+ const executeWMexQuery = (variables, queryId, dataPath) =>
44
+ genericExecuteWMexQuery(variables, queryId, dataPath, query, generateMessageTag);
45
+
46
+
47
+ const newsletterUpdate = async (jid, updates) => {
48
+ const variables = {
49
+ newsletter_id: jid,
50
+ updates: { ...updates, settings: null },
51
+ };
52
+ return executeWMexQuery(variables, QueryIds.UPDATE_METADATA, XWAPaths.UPDATE);
53
+ };
54
+ return {
55
+ ...conn,
56
+ executeWMexQuery: executeWMexQuery,
57
+ newsletterCreate: async (name, description) => {
58
+ const variables = {
59
+ input: { name: name, description: description ?? null },
60
+ };
61
+ const rawResponse = await executeWMexQuery(variables, QueryIds.CREATE, XWAPaths.CREATE);
62
+ return parseNewsletterCreateResponse(rawResponse);
63
+ },
64
+ newsletterUpdate: newsletterUpdate,
65
+ newsletterSubscribers: async (jid) =>
66
+ executeWMexQuery({ newsletter_id: jid }, QueryIds.SUBSCRIBERS, XWAPaths.SUBSCRIBERS),
67
+ newsletterMetadata: async (type, key) => {
68
+ const variables = {
69
+ fetch_creation_time: true,
70
+ fetch_full_image: true,
71
+ fetch_viewer_metadata: true,
72
+ input: { key: key, type: type.toUpperCase() },
73
+ };
74
+ const result = await executeWMexQuery(variables, QueryIds.METADATA, XWAPaths.METADATA);
75
+ return parseNewsletterMetadata(result);
76
+ },
77
+ newsletterFollow: (jid) =>
78
+ executeWMexQuery({ newsletter_id: jid }, QueryIds.FOLLOW, XWAPaths.FOLLOW),
79
+ newsletterUnfollow: (jid) =>
80
+ executeWMexQuery({ newsletter_id: jid }, QueryIds.UNFOLLOW, XWAPaths.UNFOLLOW),
81
+ newsletterMute: (jid) =>
82
+ executeWMexQuery({ newsletter_id: jid }, QueryIds.MUTE, XWAPaths.MUTE_V2),
83
+ newsletterUnmute: (jid) =>
84
+ executeWMexQuery({ newsletter_id: jid }, QueryIds.UNMUTE, XWAPaths.UNMUTE_V2),
85
+ newsletterUpdateName: async (jid, name) => await newsletterUpdate(jid, { name: name }),
86
+ newsletterUpdateDescription: async (jid, description) =>
87
+ await newsletterUpdate(jid, { description: description }),
88
+ newsletterUpdatePicture: async (jid, content) => {
89
+ const { img: img } = await generateProfilePicture(content);
90
+ return await newsletterUpdate(jid, { picture: img.toString("base64") });
91
+ },
92
+ newsletterRemovePicture: async (jid) => await newsletterUpdate(jid, { picture: "" }),
93
+ newsletterReactMessage: async (jid, serverId, reaction) => {
94
+ await query({
95
+ tag: "message",
96
+ attrs: {
97
+ to: jid,
98
+ ...(reaction ? {} : { edit: "7" }),
99
+ type: "reaction",
100
+ server_id: serverId,
101
+ id: generateMessageTag(),
102
+ },
103
+ content: [{ tag: "reaction", attrs: reaction ? { code: reaction } : {} }],
104
+ });
105
+ },
106
+ newsletterFetchMessages: async (jid, count, since, after) => {
107
+ const messageUpdateAttrs = { count: count.toString() };
108
+ if (typeof since === "number") {
109
+ messageUpdateAttrs.since = since.toString();
110
+ }
111
+ if (after) {
112
+ messageUpdateAttrs.after = after.toString();
113
+ }
114
+ const result = await query({
115
+ tag: "iq",
116
+ attrs: {
117
+ id: generateMessageTag(),
118
+ type: "get",
119
+ xmlns: "newsletter",
120
+ to: jid,
121
+ },
122
+ content: [{ tag: "message_updates", attrs: messageUpdateAttrs }],
123
+ });
124
+ return result;
125
+ },
126
+ subscribeNewsletterUpdates: async (jid) => {
127
+ const result = await query({
128
+ tag: "iq",
129
+ attrs: {
130
+ id: generateMessageTag(),
131
+ type: "set",
132
+ xmlns: "newsletter",
133
+ to: jid,
134
+ },
135
+ content: [{ tag: "live_updates", attrs: {}, content: [] }],
136
+ });
137
+ const liveUpdatesNode = getBinaryNodeChild(result, "live_updates");
138
+ const duration = liveUpdatesNode?.attrs?.duration;
139
+ return duration ? { duration: duration } : null;
140
+ },
141
+ newsletterAdminCount: async (jid) => {
142
+ const response = await executeWMexQuery(
143
+ { newsletter_id: jid },
144
+ QueryIds.ADMIN_COUNT,
145
+ XWAPaths.ADMIN_COUNT
146
+ );
147
+ return response.admin_count;
148
+ },
149
+ newsletterChangeOwner: async (jid, newOwnerJid) => {
150
+ await executeWMexQuery(
151
+ { newsletter_id: jid, user_id: newOwnerJid },
152
+ QueryIds.CHANGE_OWNER,
153
+ XWAPaths.CHANGE_OWNER
154
+ );
155
+ },
156
+ newsletterDemote: async (jid, userJid) => {
157
+ await executeWMexQuery(
158
+ { newsletter_id: jid, user_id: userJid },
159
+ QueryIds.DEMOTE,
160
+ XWAPaths.DEMOTE
161
+ );
162
+ },
163
+ newsletterDelete: async (jid) => {
164
+ await executeWMexQuery({ newsletter_id: jid }, QueryIds.DELETE, XWAPaths.DELETE_V2);
165
+ },
166
+ };
167
+ };
168
+ module.exports = {
169
+ makeNewsletterSocket: makeNewsletterSocket,
170
+ parseNewsletterMetadata: parseNewsletterMetadata,
171
+ };
@@ -0,0 +1,167 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.mobileRegisterFetch = exports.mobileRegisterEncrypt = exports.mobileRegister = exports.mobileRegisterExists = exports.mobileRegisterCode = exports.registrationParams = exports.makeRegistrationSocket = void 0;
7
+ /* eslint-disable camelcase */
8
+ const axios_1 = __importDefault(require("axios"));
9
+ const Defaults_1 = require("../Defaults");
10
+ const crypto_1 = require("../Utils/crypto");
11
+ const WABinary_1 = require("../WABinary");
12
+ const business_1 = require("./business");
13
+ const community_1 = require("./community");
14
+ function urlencode(str) {
15
+ return str.replace(/-/g, '%2d').replace(/_/g, '%5f').replace(/~/g, '%7e');
16
+ }
17
+ const validRegistrationOptions = (config) => (config === null || config === void 0 ? void 0 : config.phoneNumberCountryCode) &&
18
+ config.phoneNumberNationalNumber &&
19
+ config.phoneNumberMobileCountryCode;
20
+ const makeRegistrationSocket = (config) => {
21
+ const sock = (0, community_1.makeCommunitiesSocket)(config);
22
+ const register = async (code) => {
23
+ if (!validRegistrationOptions(config.auth.creds.registration)) {
24
+ throw new Error('please specify the registration options');
25
+ }
26
+ const result = await mobileRegister({ ...sock.authState.creds, ...sock.authState.creds.registration, code }, config.options);
27
+ sock.authState.creds.me = {
28
+ id: (0, WABinary_1.jidEncode)(result.login, 's.whatsapp.net'),
29
+ name: '~'
30
+ };
31
+ sock.authState.creds.registered = true;
32
+ sock.ev.emit('creds.update', sock.authState.creds);
33
+ return result;
34
+ };
35
+ const requestRegistrationCode = async (registrationOptions) => {
36
+ registrationOptions = registrationOptions || config.auth.creds.registration;
37
+ if (!validRegistrationOptions(registrationOptions)) {
38
+ throw new Error('Invalid registration options');
39
+ }
40
+ sock.authState.creds.registration = registrationOptions;
41
+ sock.ev.emit('creds.update', sock.authState.creds);
42
+ return mobileRegisterCode({ ...config.auth.creds, ...registrationOptions }, config.options);
43
+ };
44
+ return {
45
+ ...sock,
46
+ register,
47
+ requestRegistrationCode,
48
+ };
49
+ };
50
+ exports.makeRegistrationSocket = makeRegistrationSocket;
51
+ function convertBufferToUrlHex(buffer) {
52
+ var id = '';
53
+ buffer.forEach((x) => {
54
+ // encode random identity_id buffer as percentage url encoding
55
+ id += `%${x.toString(16).padStart(2, '0').toLowerCase()}`;
56
+ });
57
+ return id;
58
+ }
59
+ function registrationParams(params) {
60
+ const e_regid = Buffer.alloc(4);
61
+ e_regid.writeInt32BE(params.registrationId);
62
+ const e_skey_id = Buffer.alloc(3);
63
+ e_skey_id.writeInt16BE(params.signedPreKey.keyId);
64
+ params.phoneNumberCountryCode = params.phoneNumberCountryCode.replace('+', '').trim();
65
+ params.phoneNumberNationalNumber = params.phoneNumberNationalNumber.replace(/[/-\s)(]/g, '').trim();
66
+ return {
67
+ cc: params.phoneNumberCountryCode,
68
+ in: params.phoneNumberNationalNumber,
69
+ Rc: '0',
70
+ lg: 'en',
71
+ lc: 'GB',
72
+ mistyped: '6',
73
+ authkey: Buffer.from(params.noiseKey.public).toString('base64url'),
74
+ e_regid: e_regid.toString('base64url'),
75
+ e_keytype: 'BQ',
76
+ e_ident: Buffer.from(params.signedIdentityKey.public).toString('base64url'),
77
+ // e_skey_id: e_skey_id.toString('base64url'),
78
+ e_skey_id: 'AAAA',
79
+ e_skey_val: Buffer.from(params.signedPreKey.keyPair.public).toString('base64url'),
80
+ e_skey_sig: Buffer.from(params.signedPreKey.signature).toString('base64url'),
81
+ fdid: params.phoneId,
82
+ network_ratio_type: '1',
83
+ expid: params.deviceId,
84
+ simnum: '1',
85
+ hasinrc: '1',
86
+ pid: Math.floor(Math.random() * 1000).toString(),
87
+ id: convertBufferToUrlHex(params.identityId),
88
+ backup_token: convertBufferToUrlHex(params.backupToken),
89
+ token: (0, crypto_1.md5)(Buffer.concat([Defaults_1.MOBILE_TOKEN, Buffer.from(params.phoneNumberNationalNumber)])).toString('hex'),
90
+ fraud_checkpoint_code: params.captcha,
91
+ };
92
+ }
93
+ exports.registrationParams = registrationParams;
94
+ /**
95
+ * Requests a registration code for the given phone number.
96
+ */
97
+ function mobileRegisterCode(params, fetchOptions) {
98
+ return mobileRegisterFetch('/code', {
99
+ params: {
100
+ ...registrationParams(params),
101
+ mcc: `${params.phoneNumberMobileCountryCode}`.padStart(3, '0'),
102
+ mnc: `${params.phoneNumberMobileNetworkCode || '001'}`.padStart(3, '0'),
103
+ sim_mcc: '000',
104
+ sim_mnc: '000',
105
+ method: (params === null || params === void 0 ? void 0 : params.method) || 'sms',
106
+ reason: '',
107
+ hasav: '1'
108
+ },
109
+ ...fetchOptions,
110
+ });
111
+ }
112
+ exports.mobileRegisterCode = mobileRegisterCode;
113
+ function mobileRegisterExists(params, fetchOptions) {
114
+ return mobileRegisterFetch('/exist', {
115
+ params: registrationParams(params),
116
+ ...fetchOptions
117
+ });
118
+ }
119
+ exports.mobileRegisterExists = mobileRegisterExists;
120
+ /**
121
+ * Registers the phone number on whatsapp with the received OTP code.
122
+ */
123
+ async function mobileRegister(params, fetchOptions) {
124
+ //const result = await mobileRegisterFetch(`/reg_onboard_abprop?cc=${params.phoneNumberCountryCode}&in=${params.phoneNumberNationalNumber}&rc=0`)
125
+ return mobileRegisterFetch('/register', {
126
+ params: { ...registrationParams(params), code: params.code.replace('-', '') },
127
+ ...fetchOptions,
128
+ });
129
+ }
130
+ exports.mobileRegister = mobileRegister;
131
+ /**
132
+ * Encrypts the given string as AEAD aes-256-gcm with the public whatsapp key and a random keypair.
133
+ */
134
+ function mobileRegisterEncrypt(data) {
135
+ const keypair = crypto_1.Curve.generateKeyPair();
136
+ const key = crypto_1.Curve.sharedKey(keypair.private, Defaults_1.REGISTRATION_PUBLIC_KEY);
137
+ const buffer = (0, crypto_1.aesEncryptGCM)(Buffer.from(data), new Uint8Array(key), Buffer.alloc(12), Buffer.alloc(0));
138
+ return Buffer.concat([Buffer.from(keypair.public), buffer]).toString('base64url');
139
+ }
140
+ exports.mobileRegisterEncrypt = mobileRegisterEncrypt;
141
+ async function mobileRegisterFetch(path, opts = {}) {
142
+ let url = `${Defaults_1.MOBILE_REGISTRATION_ENDPOINT}${path}`;
143
+ if (opts.params) {
144
+ const parameter = [];
145
+ for (const param in opts.params) {
146
+ if (opts.params[param] !== null && opts.params[param] !== undefined) {
147
+ parameter.push(param + '=' + urlencode(opts.params[param]));
148
+ }
149
+ }
150
+ url += `?${parameter.join('&')}`;
151
+ delete opts.params;
152
+ }
153
+ if (!opts.headers) {
154
+ opts.headers = {};
155
+ }
156
+ opts.headers['User-Agent'] = Defaults_1.MOBILE_USERAGENT;
157
+ const response = await (0, axios_1.default)(url, opts);
158
+ var json = response.data;
159
+ if (response.status > 300 || json.reason) {
160
+ throw json;
161
+ }
162
+ if (json.status && !['ok', 'sent'].includes(json.status)) {
163
+ throw json;
164
+ }
165
+ return json;
166
+ }
167
+ exports.mobileRegisterFetch = mobileRegisterFetch;
@@ -0,0 +1,279 @@
1
+ "use strict";
2
+ // Ported & adapted from PouCode fork for AsepXyz Baileys.
3
+ // Handles special sendMessage() content shapes: payment requests, product
4
+ // cards, albums, events, poll results, orders, group status & labels.
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const { proto } = require("../../WAProto");
7
+ const crypto = require("crypto");
8
+
9
+ class AsepXyzRichContent {
10
+ constructor(utils, waUploadToServer, relayMessageFn) {
11
+ this.utils = utils;
12
+ this.relayMessage = relayMessageFn;
13
+ this.waUploadToServer = waUploadToServer;
14
+ }
15
+
16
+ detectType(content) {
17
+ if (content.requestPaymentMessage) return 'PAYMENT';
18
+ if (content.productMessage) return 'PRODUCT';
19
+ if (content.eventMessage) return 'EVENT';
20
+ if (content.pollResultMessage) return 'POLL_RESULT';
21
+ if (content.orderMessage) return 'ORDER';
22
+ if (content.groupStatus) return 'GROUP_STATUS';
23
+ if (content.groupLabel) return 'GROUP_LABEL';
24
+ return null;
25
+ }
26
+
27
+ async handlePayment(content, quoted) {
28
+ const data = content.requestPaymentMessage;
29
+ let notes = {};
30
+
31
+ if (data.sticker?.stickerMessage) {
32
+ notes = {
33
+ stickerMessage: {
34
+ ...data.sticker.stickerMessage,
35
+ contextInfo: {
36
+ stanzaId: quoted?.key?.id,
37
+ participant: quoted?.key?.participant || content.sender,
38
+ quotedMessage: quoted?.message
39
+ }
40
+ }
41
+ };
42
+ } else if (data.note) {
43
+ notes = {
44
+ extendedTextMessage: {
45
+ text: data.note,
46
+ contextInfo: {
47
+ stanzaId: quoted?.key?.id,
48
+ participant: quoted?.key?.participant || content.sender,
49
+ quotedMessage: quoted?.message
50
+ }
51
+ }
52
+ };
53
+ }
54
+
55
+ return {
56
+ requestPaymentMessage: proto.Message.RequestPaymentMessage.fromObject({
57
+ expiryTimestamp: data.expiry || 0,
58
+ amount1000: data.amount || 0,
59
+ currencyCodeIso4217: data.currency || "IDR",
60
+ requestFrom: data.from || "0@s.whatsapp.net",
61
+ noteMessage: notes,
62
+ background: data.background ?? {
63
+ id: "DEFAULT",
64
+ placeholderArgb: 0xFFF0F0F0
65
+ }
66
+ })
67
+ };
68
+ }
69
+
70
+ async handleProduct(content, jid, quoted) {
71
+ const {
72
+ title,
73
+ description,
74
+ thumbnail,
75
+ productId,
76
+ retailerId,
77
+ url,
78
+ body = "",
79
+ footer = "",
80
+ buttons = [],
81
+ priceAmount1000 = null,
82
+ currencyCode = "IDR"
83
+ } = content.productMessage;
84
+
85
+ let productImage;
86
+
87
+ if (Buffer.isBuffer(thumbnail)) {
88
+ const { imageMessage } = await this.utils.generateWAMessageContent({ image: thumbnail }, { upload: this.waUploadToServer });
89
+ productImage = imageMessage;
90
+ } else if (typeof thumbnail === 'object' && thumbnail?.url) {
91
+ const { imageMessage } = await this.utils.generateWAMessageContent({ image: { url: thumbnail.url } }, { upload: this.waUploadToServer });
92
+ productImage = imageMessage;
93
+ }
94
+
95
+ return {
96
+ viewOnceMessage: {
97
+ message: {
98
+ interactiveMessage: {
99
+ body: { text: body },
100
+ footer: { text: footer },
101
+ header: {
102
+ title,
103
+ hasMediaAttachment: true,
104
+ productMessage: {
105
+ product: {
106
+ productImage,
107
+ productId,
108
+ title,
109
+ description,
110
+ currencyCode,
111
+ priceAmount1000,
112
+ retailerId,
113
+ url,
114
+ productImageCount: 1
115
+ },
116
+ businessOwnerJid: "0@s.whatsapp.net"
117
+ }
118
+ },
119
+ nativeFlowMessage: { buttons }
120
+ }
121
+ }
122
+ }
123
+ };
124
+ }
125
+
126
+ async handleEvent(content, jid, quoted) {
127
+ const eventData = content.eventMessage;
128
+
129
+ const msg = await this.utils.generateWAMessageFromContent(jid, {
130
+ viewOnceMessage: {
131
+ message: {
132
+ messageContextInfo: {
133
+ deviceListMetadata: {},
134
+ deviceListMetadataVersion: 2,
135
+ messageSecret: crypto.randomBytes(32),
136
+ supportPayload: JSON.stringify({
137
+ version: 2,
138
+ is_ai_message: true,
139
+ should_show_system_message: true,
140
+ ticket_id: crypto.randomBytes(16).toString('hex')
141
+ })
142
+ },
143
+ eventMessage: {
144
+ contextInfo: {
145
+ mentionedJid: [jid],
146
+ participant: jid,
147
+ remoteJid: "status@broadcast",
148
+ forwardedNewsletterMessageInfo: {
149
+ newsletterName: "AsepXyz",
150
+ newsletterJid: eventData.newsletterJid || "0@newsletter",
151
+ serverMessageId: 1
152
+ }
153
+ },
154
+ isCanceled: eventData.isCanceled || false,
155
+ name: eventData.name,
156
+ description: eventData.description,
157
+ location: eventData.location || {
158
+ degreesLatitude: 0,
159
+ degreesLongitude: 0,
160
+ name: "Location"
161
+ },
162
+ joinLink: eventData.joinLink || '',
163
+ startTime: typeof eventData.startTime === 'string' ? parseInt(eventData.startTime) : eventData.startTime || Date.now(),
164
+ endTime: typeof eventData.endTime === 'string' ? parseInt(eventData.endTime) : eventData.endTime || Date.now() + 3600000,
165
+ extraGuestsAllowed: eventData.extraGuestsAllowed !== false
166
+ }
167
+ }
168
+ }
169
+ }, { quoted });
170
+
171
+ await this.relayMessage(jid, msg.message, { messageId: msg.key.id });
172
+ return msg;
173
+ }
174
+
175
+ async handlePollResult(content, jid, quoted) {
176
+ const pollData = content.pollResultMessage;
177
+ const msg = await this.utils.generateWAMessageFromContent(jid, {
178
+ pollResultSnapshotMessage: {
179
+ name: pollData.name,
180
+ pollVotes: pollData.pollVotes.map(vote => ({
181
+ optionName: vote.optionName,
182
+ optionVoteCount: typeof vote.optionVoteCount === 'number' ? vote.optionVoteCount.toString() : vote.optionVoteCount
183
+ })),
184
+ contextInfo: {
185
+ isForwarded: true,
186
+ forwardingScore: 1,
187
+ forwardedNewsletterMessageInfo: {
188
+ newsletterName: pollData.newsletter?.newsletterName || "AsepXyz",
189
+ newsletterJid: pollData.newsletter?.newsletterJid || "0@newsletter",
190
+ serverMessageId: 1000,
191
+ contentType: "UPDATE"
192
+ }
193
+ }
194
+ }
195
+ }, {
196
+ userJid: this.utils.generateMessageID().split('@')[0] + '@s.whatsapp.net',
197
+ quoted
198
+ });
199
+
200
+ await this.relayMessage(jid, msg.message, { messageId: msg.key.id });
201
+ return msg;
202
+ }
203
+
204
+ async handleOrderMessage(content, jid, quoted) {
205
+ const orderData = content.orderMessage;
206
+
207
+ const orderMsg = await this.utils.generateWAMessageFromContent(jid, {
208
+ orderMessage: {
209
+ orderId: orderData.orderId || ("ASEPXYZ" + Date.now()),
210
+ thumbnail: orderData.thumbnail || null,
211
+ itemCount: orderData.itemCount || 0,
212
+ status: "ACCEPTED",
213
+ surface: "CATALOG",
214
+ message: orderData.message,
215
+ orderTitle: orderData.orderTitle,
216
+ sellerJid: "0@whatsapp.net",
217
+ token: orderData.token || "ASEPXYZ_EXAMPLE_TOKEN",
218
+ totalAmount1000: orderData.totalAmount1000 || 0,
219
+ totalCurrencyCode: orderData.totalCurrencyCode || "IDR",
220
+ messageVersion: 2
221
+ }
222
+ }, { quoted });
223
+
224
+ await this.relayMessage(jid, orderMsg.message, {});
225
+ return orderMsg;
226
+ }
227
+
228
+ async handleGroupStory(content, jid, quoted) {
229
+ const storyData = content.groupStatus;
230
+ let messageContent;
231
+
232
+ if (storyData.message) {
233
+ messageContent = storyData;
234
+ } else {
235
+ messageContent = await this.utils.generateWAMessageContent(storyData, { upload: this.waUploadToServer });
236
+ }
237
+
238
+ const msg = {
239
+ message: {
240
+ groupStatusMessageV2: {
241
+ message: messageContent.message || messageContent
242
+ }
243
+ }
244
+ };
245
+
246
+ return await this.relayMessage(jid, msg.message, { messageId: this.utils.generateMessageID() });
247
+ }
248
+
249
+ async handleGbLabel(content, jid) {
250
+ const x = content.groupLabel;
251
+ if (!jid.endsWith('@g.us')) {
252
+ throw new Error('group required!');
253
+ }
254
+
255
+ const msg = await this.utils.generateWAMessageFromContent(jid, {
256
+ protocolMessage: {
257
+ type: "GROUP_MEMBER_LABEL_CHANGE",
258
+ memberLabel: {
259
+ label: x.labelText.slice(0, 30)
260
+ }
261
+ }
262
+ }, {});
263
+
264
+ await this.relayMessage(jid, msg.message, {
265
+ additionalNodes: [
266
+ {
267
+ tag: 'meta',
268
+ attrs: {
269
+ tag_reason: 'user_update',
270
+ appdata: 'member_tag'
271
+ },
272
+ content: undefined
273
+ }
274
+ ]
275
+ });
276
+ }
277
+ }
278
+ module.exports = AsepXyzRichContent;
279
+ module.exports.default = AsepXyzRichContent;