@denzy-official/baileys 1.0.9 → 1.1.2

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 (133) hide show
  1. package/WAProto/index.d.ts +55058 -0
  2. package/WAProto/index.js +169662 -0
  3. package/WAProto/index.ts.ts +53474 -0
  4. package/lib/Defaults/index.d.ts +52 -0
  5. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  6. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  7. package/lib/Signal/Group/group_cipher.d.ts +18 -0
  8. package/lib/Signal/Group/index.d.ts +12 -0
  9. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  10. package/lib/Signal/Group/queue-job.d.ts +2 -0
  11. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  12. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  13. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  14. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  15. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  16. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  17. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  18. package/lib/Signal/libsignal.d.ts +4 -0
  19. package/lib/Socket/Client/abstract-socket-client.d.ts +17 -0
  20. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  21. package/lib/Socket/Client/index.d.ts +3 -0
  22. package/lib/Socket/Client/index.js +3 -3
  23. package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
  24. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  25. package/lib/Socket/Client/types.d.ts +17 -0
  26. package/lib/Socket/Client/web-socket-client.d.ts +12 -0
  27. package/lib/Socket/Client/web-socket-client.js +62 -0
  28. package/lib/Socket/Client/websocket.d.ts +14 -0
  29. package/lib/Socket/business.d.ts +171 -0
  30. package/lib/Socket/business.js +0 -1
  31. package/lib/Socket/chats.d.ts +267 -0
  32. package/lib/Socket/chats.js +238 -140
  33. package/lib/Socket/dugong.d.ts +254 -0
  34. package/lib/Socket/dugong.js +343 -335
  35. package/lib/Socket/groups.d.ts +115 -0
  36. package/lib/Socket/groups.js +23 -39
  37. package/lib/Socket/index.d.ts +173 -0
  38. package/lib/Socket/index.js +3 -3
  39. package/lib/Socket/messages-recv.d.ts +161 -0
  40. package/lib/Socket/messages-recv.js +65 -10
  41. package/lib/Socket/messages-send.d.ts +149 -0
  42. package/lib/Socket/messages-send.js +392 -412
  43. package/lib/Socket/newsletter.d.ts +134 -0
  44. package/lib/Socket/newsletter.js +124 -72
  45. package/lib/Socket/registration.d.ts +267 -0
  46. package/lib/Socket/registration.js +166 -0
  47. package/lib/Socket/socket.d.ts +43 -0
  48. package/lib/Socket/socket.js +38 -63
  49. package/lib/Socket/usync.d.ts +36 -0
  50. package/lib/Socket/usync.js +0 -1
  51. package/lib/Store/index.d.ts +3 -0
  52. package/lib/Store/make-in-memory-store.d.ts +119 -0
  53. package/lib/Store/make-ordered-dictionary.d.ts +14 -0
  54. package/lib/Store/object-repository.d.ts +11 -0
  55. package/lib/Types/Auth.d.ts +104 -0
  56. package/lib/Types/Call.d.ts +14 -0
  57. package/lib/Types/Chat.d.ts +110 -0
  58. package/lib/Types/Contact.d.ts +24 -0
  59. package/lib/Types/Events.d.ts +200 -0
  60. package/lib/Types/GroupMetadata.d.ts +65 -0
  61. package/lib/Types/Label.d.ts +36 -0
  62. package/lib/Types/LabelAssociation.d.ts +30 -0
  63. package/lib/Types/Message.d.ts +401 -0
  64. package/lib/Types/Newsletter.d.ts +80 -0
  65. package/lib/Types/Product.d.ts +78 -0
  66. package/lib/Types/Signal.d.ts +57 -0
  67. package/lib/Types/Socket.d.ts +119 -0
  68. package/lib/Types/State.d.ts +27 -0
  69. package/lib/Types/USync.d.ts +25 -0
  70. package/lib/Types/index.d.ts +65 -0
  71. package/lib/Utils/auth-utils.d.ts +18 -0
  72. package/lib/Utils/auth-utils.js +13 -8
  73. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  74. package/lib/Utils/baileys-event-stream.js +0 -1
  75. package/lib/Utils/business.d.ts +22 -0
  76. package/lib/Utils/business.js +2 -3
  77. package/lib/Utils/chat-utils.d.ts +71 -0
  78. package/lib/Utils/chat-utils.js +35 -37
  79. package/lib/Utils/crypto.d.ts +41 -0
  80. package/lib/Utils/crypto.js +29 -72
  81. package/lib/Utils/decode-wa-message.d.ts +19 -0
  82. package/lib/Utils/decode-wa-message.js +56 -66
  83. package/lib/Utils/event-buffer.d.ts +35 -0
  84. package/lib/Utils/event-buffer.js +7 -12
  85. package/lib/Utils/generics.d.ts +92 -0
  86. package/lib/Utils/generics.js +75 -96
  87. package/lib/Utils/history.d.ts +15 -0
  88. package/lib/Utils/history.js +6 -5
  89. package/lib/Utils/index.d.ts +17 -0
  90. package/lib/Utils/index.js +0 -1
  91. package/lib/Utils/link-preview.d.ts +21 -0
  92. package/lib/Utils/link-preview.js +1 -34
  93. package/lib/Utils/logger.d.ts +4 -0
  94. package/lib/Utils/lt-hash.d.ts +12 -0
  95. package/lib/Utils/lt-hash.js +6 -6
  96. package/lib/Utils/make-mutex.d.ts +7 -0
  97. package/lib/Utils/messages-media.d.ts +116 -0
  98. package/lib/Utils/messages-media.js +235 -296
  99. package/lib/Utils/messages.d.ts +77 -0
  100. package/lib/Utils/messages.js +60 -304
  101. package/lib/Utils/noise-handler.d.ts +21 -0
  102. package/lib/Utils/noise-handler.js +23 -18
  103. package/lib/Utils/process-message.d.ts +41 -0
  104. package/lib/Utils/process-message.js +25 -89
  105. package/lib/Utils/signal.d.ts +32 -0
  106. package/lib/Utils/signal.js +26 -26
  107. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  108. package/lib/Utils/use-multi-file-auth-state.js +6 -51
  109. package/lib/Utils/validate-connection.d.ts +11 -0
  110. package/lib/Utils/validate-connection.js +52 -20
  111. package/lib/WABinary/constants.d.ts +28 -0
  112. package/lib/WABinary/decode.d.ts +7 -0
  113. package/lib/WABinary/encode.d.ts +3 -0
  114. package/lib/WABinary/generic-utils.d.ts +15 -0
  115. package/lib/WABinary/index.d.ts +6 -0
  116. package/lib/WABinary/jid-utils.d.ts +37 -0
  117. package/lib/WABinary/types.d.ts +19 -0
  118. package/lib/WAM/BinaryInfo.d.ts +9 -0
  119. package/lib/WAM/constants.d.ts +39 -0
  120. package/lib/WAM/encode.d.ts +3 -0
  121. package/lib/WAM/index.d.ts +4 -0
  122. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  123. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  124. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  125. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  126. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +25 -0
  127. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +8 -0
  128. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  129. package/lib/WAUSync/USyncQuery.d.ts +28 -0
  130. package/lib/WAUSync/USyncUser.d.ts +12 -0
  131. package/lib/WAUSync/index.d.ts +3 -0
  132. package/lib/index.d.ts +17 -0
  133. package/package.json +1 -1
@@ -0,0 +1,119 @@
1
+ import { AxiosRequestConfig } from 'axios';
2
+ import type { Agent } from 'https';
3
+ import type { URL } from 'url';
4
+ import { proto } from '../../WAProto';
5
+ import { AuthenticationState, SignalAuthState, TransactionCapabilityOptions } from './Auth';
6
+ import { GroupMetadata } from './GroupMetadata';
7
+ import { MediaConnInfo } from './Message';
8
+ import { SignalRepository } from './Signal';
9
+ import { ILogger } from '../Utils/logger';
10
+ export type WAVersion = [number, number, number];
11
+ export type WABrowserDescription = [string, string, string];
12
+ export type CacheStore = {
13
+ /** get a cached key and change the stats */
14
+ get<T>(key: string): T | undefined;
15
+ /** set a key in the cache */
16
+ set<T>(key: string, value: T): void;
17
+ /** delete a key from the cache */
18
+ del(key: string): void;
19
+ /** flush all data */
20
+ flushAll(): void;
21
+ };
22
+ export type PatchedMessageWithRecipientJID = proto.IMessage & {
23
+ recipientJid?: string;
24
+ };
25
+ export type SocketConfig = {
26
+ /** the WS url to connect to WA */
27
+ waWebSocketUrl: string | URL;
28
+ /** Fails the connection if the socket times out in this interval */
29
+ connectTimeoutMs: number;
30
+ /** Default timeout for queries, undefined for no timeout */
31
+ defaultQueryTimeoutMs: number | undefined;
32
+ /** ping-pong interval for WS connection */
33
+ keepAliveIntervalMs: number;
34
+ /** should baileys use the mobile api instead of the multi device api
35
+ * @deprecated This feature has been removed
36
+ */
37
+ mobile?: boolean;
38
+ /** proxy agent */
39
+ agent?: Agent;
40
+ /** logger */
41
+ logger: ILogger;
42
+ /** version to connect with */
43
+ version: WAVersion;
44
+ /** override browser config */
45
+ browser: WABrowserDescription;
46
+ /** agent used for fetch requests -- uploading/downloading media */
47
+ fetchAgent?: Agent;
48
+ /** should the QR be printed in the terminal */
49
+ printQRInTerminal: boolean;
50
+ /** should events be emitted for actions done by this socket connection */
51
+ emitOwnEvents: boolean;
52
+ /** custom upload hosts to upload media to */
53
+ customUploadHosts: MediaConnInfo['hosts'];
54
+ /** time to wait between sending new retry requests */
55
+ retryRequestDelayMs: number;
56
+ /** max retry count */
57
+ maxMsgRetryCount: number;
58
+ /** time to wait for the generation of the next QR in ms */
59
+ qrTimeout?: number;
60
+ /** provide an auth state object to maintain the auth state */
61
+ auth: AuthenticationState;
62
+ /** manage history processing with this control; by default will sync up everything */
63
+ shouldSyncHistoryMessage: (msg: proto.Message.IHistorySyncNotification) => boolean;
64
+ /** transaction capability options for SignalKeyStore */
65
+ transactionOpts: TransactionCapabilityOptions;
66
+ /** marks the client as online whenever the socket successfully connects */
67
+ markOnlineOnConnect: boolean;
68
+ /** alphanumeric country code (USA -> US) for the number used */
69
+ countryCode: string;
70
+ /** provide a cache to store media, so does not have to be re-uploaded */
71
+ mediaCache?: CacheStore;
72
+ /**
73
+ * map to store the retry counts for failed messages;
74
+ * used to determine whether to retry a message or not */
75
+ msgRetryCounterCache?: CacheStore;
76
+ /** provide a cache to store a user's device list */
77
+ userDevicesCache?: CacheStore;
78
+ /** cache to store call offers */
79
+ callOfferCache?: CacheStore;
80
+ /** cache to track placeholder resends */
81
+ placeholderResendCache?: CacheStore;
82
+ /** width for link preview images */
83
+ linkPreviewImageThumbnailWidth: number;
84
+ /** Should Baileys ask the phone for full history, will be received async */
85
+ syncFullHistory: boolean;
86
+ /** Should baileys fire init queries automatically, default true */
87
+ fireInitQueries: boolean;
88
+ /**
89
+ * generate a high quality link preview,
90
+ * entails uploading the jpegThumbnail to WA
91
+ * */
92
+ generateHighQualityLinkPreview: boolean;
93
+ /**
94
+ * Returns if a jid should be ignored,
95
+ * no event for that jid will be triggered.
96
+ * Messages from that jid will also not be decrypted
97
+ * */
98
+ shouldIgnoreJid: (jid: string) => boolean | undefined;
99
+ /**
100
+ * Optionally patch the message before sending out
101
+ * */
102
+ patchMessageBeforeSending: (msg: proto.IMessage, recipientJids?: string[]) => Promise<PatchedMessageWithRecipientJID[] | PatchedMessageWithRecipientJID> | PatchedMessageWithRecipientJID[] | PatchedMessageWithRecipientJID;
103
+ /** verify app state MACs */
104
+ appStateMacVerification: {
105
+ patch: boolean;
106
+ snapshot: boolean;
107
+ };
108
+ /** options for axios */
109
+ options: AxiosRequestConfig<{}>;
110
+ /**
111
+ * fetch a message from your store
112
+ * implement this so that messages failed to send
113
+ * (solves the "this message can take a while" issue) can be retried
114
+ * */
115
+ getMessage: (key: proto.IMessageKey) => Promise<proto.IMessage | undefined>;
116
+ /** cached group metadata, use to prevent redundant requests to WA & speed up msg sending */
117
+ cachedGroupMetadata: (jid: string) => Promise<GroupMetadata | undefined>;
118
+ makeSignalRepository: (auth: SignalAuthState) => SignalRepository;
119
+ };
@@ -0,0 +1,27 @@
1
+ import { Contact } from './Contact';
2
+ export type WAConnectionState = 'open' | 'connecting' | 'close';
3
+ export type ConnectionState = {
4
+ /** connection is now open, connecting or closed */
5
+ connection: WAConnectionState;
6
+ /** the error that caused the connection to close */
7
+ lastDisconnect?: {
8
+ error: Error | undefined;
9
+ date: Date;
10
+ };
11
+ /** is this a new login */
12
+ isNewLogin?: boolean;
13
+ /** the current QR code */
14
+ qr?: string;
15
+ /** has the device received all pending notifications while it was offline */
16
+ receivedPendingNotifications?: boolean;
17
+ /** legacy connection options */
18
+ legacy?: {
19
+ phoneConnected: boolean;
20
+ user?: Contact;
21
+ };
22
+ /**
23
+ * if the client is shown as an active, online client.
24
+ * If this is false, the primary phone and other devices will receive notifs
25
+ * */
26
+ isOnline?: boolean;
27
+ };
@@ -0,0 +1,25 @@
1
+ import { BinaryNode } from '../WABinary';
2
+ import { USyncUser } from '../WAUSync';
3
+ /**
4
+ * Defines the interface for a USyncQuery protocol
5
+ */
6
+ export interface USyncQueryProtocol {
7
+ /**
8
+ * The name of the protocol
9
+ */
10
+ name: string;
11
+ /**
12
+ * Defines what goes inside the query part of a USyncQuery
13
+ */
14
+ getQueryElement: () => BinaryNode;
15
+ /**
16
+ * Defines what goes inside the user part of a USyncQuery
17
+ */
18
+ getUserElement: (user: USyncUser) => BinaryNode | null;
19
+ /**
20
+ * Parse the result of the query
21
+ * @param data Data from the result
22
+ * @returns Whatever the protocol is supposed to return
23
+ */
24
+ parser: (data: BinaryNode) => unknown;
25
+ }
@@ -0,0 +1,65 @@
1
+ // baileys by denzy
2
+ export * from './Auth';
3
+ export * from './GroupMetadata';
4
+ export * from './Newsletter';
5
+ export * from './Chat';
6
+ export * from './Contact';
7
+ export * from './State';
8
+ export * from './Message';
9
+ export * from './Socket';
10
+ export * from './Events';
11
+ export * from './Product';
12
+ export * from './Call';
13
+ export * from './Signal';
14
+ import { AuthenticationState } from './Auth';
15
+ import { SocketConfig } from './Socket';
16
+ export type UserFacingSocketConfig = Partial<SocketConfig> & {
17
+ auth: AuthenticationState;
18
+ };
19
+ export type BrowsersMap = {
20
+ ubuntu(browser: string): [string, string, string];
21
+ macOS(browser: string): [string, string, string];
22
+ baileys(browser: string): [string, string, string];
23
+ windows(browser: string): [string, string, string];
24
+ appropriate(browser: string): [string, string, string];
25
+ };
26
+ export declare enum DisconnectReason {
27
+ connectionClosed = 428,
28
+ connectionLost = 408,
29
+ connectionReplaced = 440,
30
+ timedOut = 408,
31
+ loggedOut = 401,
32
+ badSession = 500,
33
+ restartRequired = 515,
34
+ multideviceMismatch = 411,
35
+ forbidden = 403,
36
+ unavailableService = 503
37
+ }
38
+ export type WAInitResponse = {
39
+ ref: string;
40
+ ttl: number;
41
+ status: 200;
42
+ };
43
+ export type WABusinessHoursConfig = {
44
+ day_of_week: string;
45
+ mode: string;
46
+ open_time?: number;
47
+ close_time?: number;
48
+ };
49
+ export type WABusinessProfile = {
50
+ description: string;
51
+ email: string | undefined;
52
+ business_hours: {
53
+ timezone?: string;
54
+ config?: WABusinessHoursConfig[];
55
+ business_config?: WABusinessHoursConfig[];
56
+ };
57
+ website: string[];
58
+ category?: string;
59
+ wid?: string;
60
+ address?: string;
61
+ };
62
+ export type CurveKeyPair = {
63
+ private: Uint8Array;
64
+ public: Uint8Array;
65
+ };
@@ -0,0 +1,18 @@
1
+ import type { Logger } from 'pino';
2
+ import type { AuthenticationCreds, CacheStore, SignalKeyStore, SignalKeyStoreWithTransaction, TransactionCapabilityOptions } from '../Types';
3
+ /**
4
+ * Adds caching capability to a SignalKeyStore
5
+ * @param store the store to add caching to
6
+ * @param logger to log trace events
7
+ * @param _cache cache store to use
8
+ */
9
+ export declare function makeCacheableSignalKeyStore(store: SignalKeyStore, logger: Logger, _cache?: CacheStore): SignalKeyStore;
10
+ /**
11
+ * Adds DB like transaction capability (https://en.wikipedia.org/wiki/Database_transaction) to the SignalKeyStore,
12
+ * this allows batch read & write operations & improves the performance of the lib
13
+ * @param state the key store to apply this capability to
14
+ * @param logger logger to log events
15
+ * @returns SignalKeyStore with transaction capability
16
+ */
17
+ export declare const addTransactionCapability: (state: SignalKeyStore, logger: Logger, { maxCommitRetries, delayBetweenTriesMs }: TransactionCapabilityOptions) => SignalKeyStoreWithTransaction;
18
+ export declare const initAuthCreds: () => AuthenticationCreds;
@@ -1,13 +1,12 @@
1
- // baileys by denzy
2
1
  "use strict";
3
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
4
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
5
4
  };
6
5
  Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.initAuthCreds = exports.addTransactionCapability = void 0;
8
- exports.makeCacheableSignalKeyStore = makeCacheableSignalKeyStore;
6
+ exports.initAuthCreds = exports.addTransactionCapability = exports.makeCacheableSignalKeyStore = void 0;
9
7
  const crypto_1 = require("crypto");
10
- const node_cache_1 = __importDefault(require("@cacheable/node-cache"));
8
+ const node_cache_1 = __importDefault(require("node-cache"));
9
+ const uuid_1 = require("uuid");
11
10
  const Defaults_1 = require("../Defaults");
12
11
  const crypto_2 = require("./crypto");
13
12
  const generics_1 = require("./generics");
@@ -19,7 +18,7 @@ const generics_1 = require("./generics");
19
18
  */
20
19
  function makeCacheableSignalKeyStore(store, logger, _cache) {
21
20
  const cache = _cache || new node_cache_1.default({
22
- stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.SIGNAL_STORE, // 5 minutes
21
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.SIGNAL_STORE,
23
22
  useClones: false,
24
23
  deleteOnExpire: true,
25
24
  });
@@ -40,7 +39,7 @@ function makeCacheableSignalKeyStore(store, logger, _cache) {
40
39
  }
41
40
  }
42
41
  if (idsToFetch.length) {
43
- logger === null || logger === void 0 ? void 0 : logger.trace({ items: idsToFetch.length }, 'loading from store');
42
+ logger.trace({ items: idsToFetch.length }, 'loading from store');
44
43
  const fetched = await store.get(type, idsToFetch);
45
44
  for (const id of idsToFetch) {
46
45
  const item = fetched[id];
@@ -60,7 +59,7 @@ function makeCacheableSignalKeyStore(store, logger, _cache) {
60
59
  keys += 1;
61
60
  }
62
61
  }
63
- logger === null || logger === void 0 ? void 0 : logger.trace({ keys }, 'updated cache');
62
+ logger.trace({ keys }, 'updated cache');
64
63
  await store.set(data);
65
64
  },
66
65
  async clear() {
@@ -70,6 +69,7 @@ function makeCacheableSignalKeyStore(store, logger, _cache) {
70
69
  }
71
70
  };
72
71
  }
72
+ exports.makeCacheableSignalKeyStore = makeCacheableSignalKeyStore;
73
73
  /**
74
74
  * Adds DB like transaction capability (https://en.wikipedia.org/wiki/Database_transaction) to the SignalKeyStore,
75
75
  * this allows batch read & write operations & improves the performance of the lib
@@ -191,11 +191,16 @@ const initAuthCreds = () => {
191
191
  accountSettings: {
192
192
  unarchiveChats: false
193
193
  },
194
+ // mobile creds
195
+ deviceId: Buffer.from((0, uuid_1.v4)().replace(/-/g, ''), 'hex').toString('base64url'),
196
+ phoneId: (0, uuid_1.v4)(),
197
+ identityId: (0, crypto_1.randomBytes)(20),
194
198
  registered: false,
199
+ backupToken: (0, crypto_1.randomBytes)(20),
200
+ registration: {},
195
201
  pairingCode: undefined,
196
202
  lastPropHash: undefined,
197
203
  routingInfo: undefined,
198
204
  };
199
205
  };
200
206
  exports.initAuthCreds = initAuthCreds;
201
- // baileys by denzy
@@ -0,0 +1,16 @@
1
+ import type { BaileysEventEmitter } from '../Types';
2
+ /**
3
+ * Captures events from a baileys event emitter & stores them in a file
4
+ * @param ev The event emitter to read events from
5
+ * @param filename File to save to
6
+ */
7
+ export declare const captureEventStream: (ev: BaileysEventEmitter, filename: string) => void;
8
+ /**
9
+ * Read event file and emit events from there
10
+ * @param filename filename containing event data
11
+ * @param delayIntervalMs delay between each event emit
12
+ */
13
+ export declare const readAndEmitEventStream: (filename: string, delayIntervalMs?: number) => {
14
+ ev: BaileysEventEmitter;
15
+ task: Promise<void>;
16
+ };
@@ -1,4 +1,3 @@
1
- // baileys by denzy
2
1
  "use strict";
3
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
4
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
@@ -0,0 +1,22 @@
1
+ import { CatalogCollection, OrderDetails, Product, ProductCreate, ProductUpdate, WAMediaUpload, WAMediaUploadFunction } from '../Types';
2
+ import { BinaryNode } from '../WABinary';
3
+ export declare const parseCatalogNode: (node: BinaryNode) => {
4
+ products: Product[];
5
+ nextPageCursor: string | undefined;
6
+ };
7
+ export declare const parseCollectionsNode: (node: BinaryNode) => {
8
+ collections: CatalogCollection[];
9
+ };
10
+ export declare const parseOrderDetailsNode: (node: BinaryNode) => OrderDetails;
11
+ export declare const toProductNode: (productId: string | undefined, product: ProductCreate | ProductUpdate) => BinaryNode;
12
+ export declare const parseProductNode: (productNode: BinaryNode) => Product;
13
+ /**
14
+ * Uploads images not already uploaded to WA's servers
15
+ */
16
+ export declare function uploadingNecessaryImagesOfProduct<T extends ProductUpdate | ProductCreate>(product: T, waUploadToServer: WAMediaUploadFunction, timeoutMs?: number): Promise<T>;
17
+ /**
18
+ * Uploads images not already uploaded to WA's servers
19
+ */
20
+ export declare const uploadingNecessaryImages: (images: WAMediaUpload[], waUploadToServer: WAMediaUploadFunction, timeoutMs?: number) => Promise<{
21
+ url: string;
22
+ }[]>;
@@ -1,8 +1,6 @@
1
- // baileys by denzy
2
1
  "use strict";
3
2
  Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.uploadingNecessaryImages = exports.parseProductNode = exports.toProductNode = exports.parseOrderDetailsNode = exports.parseCollectionsNode = exports.parseCatalogNode = void 0;
5
- exports.uploadingNecessaryImagesOfProduct = uploadingNecessaryImagesOfProduct;
3
+ exports.uploadingNecessaryImages = exports.uploadingNecessaryImagesOfProduct = exports.parseProductNode = exports.toProductNode = exports.parseOrderDetailsNode = exports.parseCollectionsNode = exports.parseCatalogNode = void 0;
6
4
  const boom_1 = require("@hapi/boom");
7
5
  const crypto_1 = require("crypto");
8
6
  const WABinary_1 = require("../WABinary");
@@ -190,6 +188,7 @@ async function uploadingNecessaryImagesOfProduct(product, waUploadToServer, time
190
188
  };
191
189
  return product;
192
190
  }
191
+ exports.uploadingNecessaryImagesOfProduct = uploadingNecessaryImagesOfProduct;
193
192
  /**
194
193
  * Uploads images not already uploaded to WA's servers
195
194
  */
@@ -0,0 +1,71 @@
1
+ /// <reference types="node" />
2
+ import { AxiosRequestConfig } from 'axios';
3
+ import type { Logger } from 'pino';
4
+ import { proto } from '../../WAProto';
5
+ import { BaileysEventEmitter, ChatModification, ChatMutation, Contact, InitialAppStateSyncOptions, LTHashState, WAPatchCreate, WAPatchName } from '../Types';
6
+ import { BinaryNode } from '../WABinary';
7
+ type FetchAppStateSyncKey = (keyId: string) => Promise<proto.Message.IAppStateSyncKeyData | null | undefined>;
8
+ export type ChatMutationMap = {
9
+ [index: string]: ChatMutation;
10
+ };
11
+ export declare const newLTHashState: () => LTHashState;
12
+ export declare const encodeSyncdPatch: ({ type, index, syncAction, apiVersion, operation }: WAPatchCreate, myAppStateKeyId: string, state: LTHashState, getAppStateSyncKey: FetchAppStateSyncKey) => Promise<{
13
+ patch: proto.ISyncdPatch;
14
+ state: LTHashState;
15
+ }>;
16
+ export declare const decodeSyncdMutations: (msgMutations: (proto.ISyncdMutation | proto.ISyncdRecord)[], initialState: LTHashState, getAppStateSyncKey: FetchAppStateSyncKey, onMutation: (mutation: ChatMutation) => void, validateMacs: boolean) => Promise<{
17
+ hash: Buffer;
18
+ indexValueMap: {
19
+ [indexMacBase64: string]: {
20
+ valueMac: Uint8Array | Buffer;
21
+ };
22
+ };
23
+ }>;
24
+ export declare const decodeSyncdPatch: (msg: proto.ISyncdPatch, name: WAPatchName, initialState: LTHashState, getAppStateSyncKey: FetchAppStateSyncKey, onMutation: (mutation: ChatMutation) => void, validateMacs: boolean) => Promise<{
25
+ hash: Buffer;
26
+ indexValueMap: {
27
+ [indexMacBase64: string]: {
28
+ valueMac: Uint8Array | Buffer;
29
+ };
30
+ };
31
+ }>;
32
+ export declare const extractSyncdPatches: (result: BinaryNode, options: AxiosRequestConfig<any>) => Promise<{
33
+ critical_block: {
34
+ patches: proto.ISyncdPatch[];
35
+ hasMorePatches: boolean;
36
+ snapshot?: proto.ISyncdSnapshot | undefined;
37
+ };
38
+ critical_unblock_low: {
39
+ patches: proto.ISyncdPatch[];
40
+ hasMorePatches: boolean;
41
+ snapshot?: proto.ISyncdSnapshot | undefined;
42
+ };
43
+ regular_high: {
44
+ patches: proto.ISyncdPatch[];
45
+ hasMorePatches: boolean;
46
+ snapshot?: proto.ISyncdSnapshot | undefined;
47
+ };
48
+ regular_low: {
49
+ patches: proto.ISyncdPatch[];
50
+ hasMorePatches: boolean;
51
+ snapshot?: proto.ISyncdSnapshot | undefined;
52
+ };
53
+ regular: {
54
+ patches: proto.ISyncdPatch[];
55
+ hasMorePatches: boolean;
56
+ snapshot?: proto.ISyncdSnapshot | undefined;
57
+ };
58
+ }>;
59
+ export declare const downloadExternalBlob: (blob: proto.IExternalBlobReference, options: AxiosRequestConfig<any>) => Promise<Buffer>;
60
+ export declare const downloadExternalPatch: (blob: proto.IExternalBlobReference, options: AxiosRequestConfig<any>) => Promise<proto.SyncdMutations>;
61
+ export declare const decodeSyncdSnapshot: (name: WAPatchName, snapshot: proto.ISyncdSnapshot, getAppStateSyncKey: FetchAppStateSyncKey, minimumVersionNumber: number | undefined, validateMacs?: boolean) => Promise<{
62
+ state: LTHashState;
63
+ mutationMap: ChatMutationMap;
64
+ }>;
65
+ export declare const decodePatches: (name: WAPatchName, syncds: proto.ISyncdPatch[], initial: LTHashState, getAppStateSyncKey: FetchAppStateSyncKey, options: AxiosRequestConfig<any>, minimumVersionNumber?: number, logger?: Logger, validateMacs?: boolean) => Promise<{
66
+ state: LTHashState;
67
+ mutationMap: ChatMutationMap;
68
+ }>;
69
+ export declare const chatModificationToAppPatch: (mod: ChatModification, jid: string) => WAPatchCreate;
70
+ export declare const processSyncAction: (syncAction: ChatMutation, ev: BaileysEventEmitter, me: Contact, initialSyncOpts?: InitialAppStateSyncOptions, logger?: Logger) => void;
71
+ export {};
@@ -1,17 +1,16 @@
1
- // baileys by denzy
2
1
  "use strict";
3
2
  Object.defineProperty(exports, "__esModule", { value: true });
4
3
  exports.processSyncAction = exports.chatModificationToAppPatch = exports.decodePatches = exports.decodeSyncdSnapshot = exports.downloadExternalPatch = exports.downloadExternalBlob = exports.extractSyncdPatches = exports.decodeSyncdPatch = exports.decodeSyncdMutations = exports.encodeSyncdPatch = exports.newLTHashState = void 0;
5
4
  const boom_1 = require("@hapi/boom");
6
5
  const WAProto_1 = require("../../WAProto");
7
- const WABinary_1 = require("../WABinary");
8
6
  const LabelAssociation_1 = require("../Types/LabelAssociation");
7
+ const WABinary_1 = require("../WABinary");
9
8
  const crypto_1 = require("./crypto");
10
9
  const generics_1 = require("./generics");
11
10
  const lt_hash_1 = require("./lt-hash");
12
11
  const messages_media_1 = require("./messages-media");
13
- const mutationKeys = async (keydata) => {
14
- const expanded = await (0, crypto_1.hkdf)(keydata, 160, { info: 'WhatsApp Mutation Keys' });
12
+ const mutationKeys = (keydata) => {
13
+ const expanded = (0, crypto_1.hkdf)(keydata, 160, { info: 'WhatsApp Mutation Keys' });
15
14
  return {
16
15
  indexKey: expanded.slice(0, 32),
17
16
  valueEncryptionKey: expanded.slice(32, 64),
@@ -70,9 +69,9 @@ const makeLtHashGenerator = ({ indexValueMap, hash }) => {
70
69
  subBuffs.push(new Uint8Array(prevOp.valueMac).buffer);
71
70
  }
72
71
  },
73
- finish: async () => {
72
+ finish: () => {
74
73
  const hashArrayBuffer = new Uint8Array(hash).buffer;
75
- const result = await lt_hash_1.LT_HASH_ANTI_TAMPERING.subtractThenAdd(hashArrayBuffer, addBuffs, subBuffs);
74
+ const result = lt_hash_1.LT_HASH_ANTI_TAMPERING.subtractThenAdd(hashArrayBuffer, addBuffs, subBuffs);
76
75
  const buffer = Buffer.from(result);
77
76
  return {
78
77
  hash: buffer,
@@ -115,14 +114,14 @@ const encodeSyncdPatch = async ({ type, index, syncAction, apiVersion, operation
115
114
  version: apiVersion
116
115
  });
117
116
  const encoded = WAProto_1.proto.SyncActionData.encode(dataProto).finish();
118
- const keyValue = await mutationKeys(key.keyData);
117
+ const keyValue = mutationKeys(key.keyData);
119
118
  const encValue = (0, crypto_1.aesEncrypt)(encoded, keyValue.valueEncryptionKey);
120
119
  const valueMac = generateMac(operation, encValue, encKeyId, keyValue.valueMacKey);
121
120
  const indexMac = (0, crypto_1.hmacSign)(indexBuffer, keyValue.indexKey);
122
121
  // update LT hash
123
122
  const generator = makeLtHashGenerator(state);
124
123
  generator.mix({ indexMac, valueMac, operation });
125
- Object.assign(state, await generator.finish());
124
+ Object.assign(state, generator.finish());
126
125
  state.version += 1;
127
126
  const snapshotMac = generateSnapshotMac(state.hash, state.version, type, keyValue.snapshotMacKey);
128
127
  const patch = {
@@ -185,7 +184,7 @@ const decodeSyncdMutations = async (msgMutations, initialState, getAppStateSyncK
185
184
  operation: operation
186
185
  });
187
186
  }
188
- return await ltGenerator.finish();
187
+ return ltGenerator.finish();
189
188
  async function getKey(keyId) {
190
189
  const base64Key = Buffer.from(keyId).toString('base64');
191
190
  const keyEnc = await getAppStateSyncKey(base64Key);
@@ -203,7 +202,7 @@ const decodeSyncdPatch = async (msg, name, initialState, getAppStateSyncKey, onM
203
202
  if (!mainKeyObj) {
204
203
  throw new boom_1.Boom(`failed to find key "${base64Key}" to decode patch`, { statusCode: 404, data: { msg } });
205
204
  }
206
- const mainKey = await mutationKeys(mainKeyObj.keyData);
205
+ const mainKey = mutationKeys(mainKeyObj.keyData);
207
206
  const mutationmacs = msg.mutations.map(mutation => mutation.record.value.blob.slice(-32));
208
207
  const patchMac = generatePatchMac(msg.snapshotMac, mutationmacs, (0, generics_1.toNumber)(msg.version.version), name, mainKey.patchMacKey);
209
208
  if (Buffer.compare(patchMac, msg.patchMac) !== 0) {
@@ -287,7 +286,7 @@ const decodeSyncdSnapshot = async (name, snapshot, getAppStateSyncKey, minimumVe
287
286
  if (!keyEnc) {
288
287
  throw new boom_1.Boom(`failed to find key "${base64Key}" to decode mutation`);
289
288
  }
290
- const result = await mutationKeys(keyEnc.keyData);
289
+ const result = mutationKeys(keyEnc.keyData);
291
290
  const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey);
292
291
  if (Buffer.compare(snapshot.mac, computedSnapshotMac) !== 0) {
293
292
  throw new boom_1.Boom(`failed to verify LTHash at ${newState.version} of ${name} from snapshot`);
@@ -333,7 +332,7 @@ const decodePatches = async (name, syncds, initial, getAppStateSyncKey, options,
333
332
  if (!keyEnc) {
334
333
  throw new boom_1.Boom(`failed to find key "${base64Key}" to decode mutation`);
335
334
  }
336
- const result = await mutationKeys(keyEnc.keyData);
335
+ const result = mutationKeys(keyEnc.keyData);
337
336
  const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey);
338
337
  if (Buffer.compare(snapshotMac, computedSnapshotMac) !== 0) {
339
338
  throw new boom_1.Boom(`failed to verify LTHash at ${newState.version} of ${name}`);
@@ -419,31 +418,25 @@ const chatModificationToAppPatch = (mod, jid) => {
419
418
  operation: OP.SET
420
419
  };
421
420
  }
422
- else if ('deleteForMe' in mod) {
423
- const { timestamp, key, deleteMedia } = mod.deleteForMe;
424
- patch = {
425
- syncAction: {
426
- deleteMessageForMeAction: {
427
- deleteMedia,
428
- messageTimestamp: timestamp
429
- }
430
- },
431
- index: ['deleteMessageForMe', jid, key.id, key.fromMe ? '1' : '0', '0'],
432
- type: 'regular_high',
433
- apiVersion: 3,
434
- operation: OP.SET
435
- };
436
- }
437
421
  else if ('clear' in mod) {
438
- patch = {
439
- syncAction: {
440
- clearChatAction: {} // add message range later
441
- },
442
- index: ['clearChat', jid, '1' /*the option here is 0 when keep starred messages is enabled*/, '0'],
443
- type: 'regular_high',
444
- apiVersion: 6,
445
- operation: OP.SET
446
- };
422
+ if (mod.clear === 'all') {
423
+ throw new boom_1.Boom('not supported');
424
+ }
425
+ else {
426
+ const key = mod.clear.messages[0];
427
+ patch = {
428
+ syncAction: {
429
+ deleteMessageForMeAction: {
430
+ deleteMedia: false,
431
+ messageTimestamp: key.timestamp
432
+ }
433
+ },
434
+ index: ['deleteMessageForMe', jid, key.id, key.fromMe ? '1' : '0', '0'],
435
+ type: 'regular_high',
436
+ apiVersion: 3,
437
+ operation: OP.SET
438
+ };
439
+ }
447
440
  }
448
441
  else if ('pin' in mod) {
449
442
  patch = {
@@ -640,7 +633,12 @@ const processSyncAction = (syncAction, ev, me, initialSyncOpts, logger) => {
640
633
  });
641
634
  }
642
635
  else if (action === null || action === void 0 ? void 0 : action.contactAction) {
643
- ev.emit('contacts.upsert', [{ id, name: action.contactAction.fullName, lid: action.contactAction.lidJid || undefined, jid: (0, WABinary_1.isJidUser)(id) ? id : action.contactAction.pnJid }]);
636
+ ev.emit('contacts.upsert', [{
637
+ id: id,
638
+ name: action.contactAction.fullName,
639
+ lid: action.contactAction.lidJid || undefined,
640
+ jid: (0, WABinary_1.isJidUser)(id) ? id : undefined
641
+ }]);
644
642
  }
645
643
  else if (action === null || action === void 0 ? void 0 : action.pushNameSetting) {
646
644
  const name = (_b = action === null || action === void 0 ? void 0 : action.pushNameSetting) === null || _b === void 0 ? void 0 : _b.name;
@@ -0,0 +1,41 @@
1
+ /// <reference types="node" />
2
+ import { KeyPair } from '../Types';
3
+ /** prefix version byte to the pub keys, required for some curve crypto functions */
4
+ export declare const generateSignalPubKey: (pubKey: Uint8Array | Buffer) => Uint8Array | Buffer;
5
+ export declare const Curve: {
6
+ generateKeyPair: () => KeyPair;
7
+ sharedKey: (privateKey: Uint8Array, publicKey: Uint8Array) => Buffer;
8
+ sign: (privateKey: Uint8Array, buf: Uint8Array) => any;
9
+ verify: (pubKey: Uint8Array, message: Uint8Array, signature: Uint8Array) => boolean;
10
+ };
11
+ export declare const signedKeyPair: (identityKeyPair: KeyPair, keyId: number) => {
12
+ keyPair: KeyPair;
13
+ signature: any;
14
+ keyId: number;
15
+ };
16
+ /**
17
+ * encrypt AES 256 GCM;
18
+ * where the tag tag is suffixed to the ciphertext
19
+ * */
20
+ export declare function aesEncryptGCM(plaintext: Uint8Array, key: Uint8Array, iv: Uint8Array, additionalData: Uint8Array): Buffer;
21
+ /**
22
+ * decrypt AES 256 GCM;
23
+ * where the auth tag is suffixed to the ciphertext
24
+ * */
25
+ export declare function aesDecryptGCM(ciphertext: Uint8Array, key: Uint8Array, iv: Uint8Array, additionalData: Uint8Array): Buffer;
26
+ export declare function aesEncryptCTR(plaintext: Uint8Array, key: Uint8Array, iv: Uint8Array): Buffer;
27
+ export declare function aesDecryptCTR(ciphertext: Uint8Array, key: Uint8Array, iv: Uint8Array): Buffer;
28
+ /** decrypt AES 256 CBC; where the IV is prefixed to the buffer */
29
+ export declare function aesDecrypt(buffer: Buffer, key: Buffer): Buffer;
30
+ /** decrypt AES 256 CBC */
31
+ export declare function aesDecryptWithIV(buffer: Buffer, key: Buffer, IV: Buffer): Buffer;
32
+ export declare function aesEncrypt(buffer: Buffer | Uint8Array, key: Buffer): Buffer;
33
+ export declare function aesEncrypWithIV(buffer: Buffer, key: Buffer, IV: Buffer): Buffer;
34
+ export declare function hmacSign(buffer: Buffer | Uint8Array, key: Buffer | Uint8Array, variant?: 'sha256' | 'sha512'): Buffer;
35
+ export declare function sha256(buffer: Buffer): Buffer;
36
+ export declare function md5(buffer: Buffer): Buffer;
37
+ export declare function hkdf(buffer: Uint8Array | Buffer, expandedLength: number, info: {
38
+ salt?: Buffer;
39
+ info?: string;
40
+ }): Buffer;
41
+ export declare function derivePairingCodeKey(pairingCode: string, salt: Buffer): Buffer;