lordceaser-baileys 1.0.19 → 1.0.21

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 (126) hide show
  1. package/lib/Defaults/baileys-version.json +1 -1
  2. package/lib/Defaults/index.d.ts +235 -3
  3. package/lib/Defaults/index.js +23 -7
  4. package/lib/Defaults/phonenumber-mcc.json +223 -0
  5. package/lib/Signal/libsignal.js +9 -18
  6. package/lib/Socket/Client/{types.d.ts → abstract-socket-client.d.ts} +2 -0
  7. package/lib/Socket/Client/index.d.ts +3 -2
  8. package/lib/Socket/Client/index.js +3 -2
  9. package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
  10. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  11. package/lib/Socket/Client/{websocket.d.ts → web-socket-client.d.ts} +1 -1
  12. package/lib/Socket/Client/{websocket.js → web-socket-client.js} +2 -2
  13. package/lib/Socket/business.d.ts +40 -38
  14. package/lib/Socket/chats.d.ts +23 -25
  15. package/lib/Socket/chats.js +77 -78
  16. package/lib/Socket/groups.d.ts +29 -30
  17. package/lib/Socket/groups.js +2 -3
  18. package/lib/Socket/index.d.ts +48 -44
  19. package/lib/Socket/index.js +2 -2
  20. package/lib/Socket/messages-recv.d.ts +37 -37
  21. package/lib/Socket/messages-recv.js +43 -97
  22. package/lib/Socket/messages-send.d.ts +31 -33
  23. package/lib/Socket/messages-send.js +69 -81
  24. package/lib/Socket/registration.d.ts +242 -0
  25. package/lib/Socket/registration.js +166 -0
  26. package/lib/Socket/socket.d.ts +10 -9
  27. package/lib/Socket/socket.js +22 -27
  28. package/lib/Store/index.d.ts +3 -0
  29. package/lib/Store/index.js +10 -0
  30. package/lib/Store/make-cache-manager-store.d.ts +14 -0
  31. package/lib/Store/make-cache-manager-store.js +83 -0
  32. package/lib/Store/make-in-memory-store.d.ts +118 -0
  33. package/lib/Store/make-in-memory-store.js +422 -0
  34. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  35. package/lib/Store/make-ordered-dictionary.js +81 -0
  36. package/lib/Store/object-repository.d.ts +10 -0
  37. package/lib/Store/object-repository.js +27 -0
  38. package/lib/Types/Auth.d.ts +7 -0
  39. package/lib/Types/Chat.d.ts +7 -12
  40. package/lib/Types/Contact.d.ts +1 -1
  41. package/lib/Types/GroupMetadata.d.ts +0 -2
  42. package/lib/Types/Label.js +1 -1
  43. package/lib/Types/LabelAssociation.js +1 -1
  44. package/lib/Types/Message.d.ts +10 -9
  45. package/lib/Types/Message.js +2 -0
  46. package/lib/Types/Socket.d.ts +11 -16
  47. package/lib/Types/index.js +1 -1
  48. package/lib/Utils/auth-utils.d.ts +3 -3
  49. package/lib/Utils/auth-utils.js +13 -7
  50. package/lib/Utils/business.js +5 -13
  51. package/lib/Utils/chat-utils.d.ts +14 -13
  52. package/lib/Utils/chat-utils.js +30 -35
  53. package/lib/Utils/crypto.d.ts +15 -14
  54. package/lib/Utils/crypto.js +30 -70
  55. package/lib/Utils/decode-wa-message.d.ts +2 -18
  56. package/lib/Utils/decode-wa-message.js +18 -22
  57. package/lib/Utils/event-buffer.d.ts +2 -2
  58. package/lib/Utils/event-buffer.js +7 -7
  59. package/lib/Utils/generics.d.ts +14 -15
  60. package/lib/Utils/generics.js +28 -32
  61. package/lib/Utils/history.d.ts +2 -2
  62. package/lib/Utils/link-preview.d.ts +2 -2
  63. package/lib/Utils/link-preview.js +1 -34
  64. package/lib/Utils/logger.d.ts +3 -10
  65. package/lib/Utils/lt-hash.d.ts +2 -2
  66. package/lib/Utils/lt-hash.js +6 -6
  67. package/lib/Utils/make-mutex.d.ts +2 -2
  68. package/lib/Utils/make-mutex.js +0 -1
  69. package/lib/Utils/messages-media.d.ts +24 -20
  70. package/lib/Utils/messages-media.js +75 -78
  71. package/lib/Utils/messages.d.ts +9 -7
  72. package/lib/Utils/messages.js +29 -28
  73. package/lib/Utils/noise-handler.d.ts +11 -9
  74. package/lib/Utils/noise-handler.js +21 -16
  75. package/lib/Utils/process-message.d.ts +5 -4
  76. package/lib/Utils/process-message.js +39 -67
  77. package/lib/Utils/signal.d.ts +1 -2
  78. package/lib/Utils/signal.js +19 -11
  79. package/lib/Utils/use-multi-file-auth-state.js +13 -45
  80. package/lib/Utils/validate-connection.d.ts +3 -2
  81. package/lib/Utils/validate-connection.js +45 -15
  82. package/lib/WABinary/constants.js +5 -5
  83. package/lib/WABinary/decode.d.ts +3 -2
  84. package/lib/WABinary/decode.js +9 -20
  85. package/lib/WABinary/encode.d.ts +2 -1
  86. package/lib/WABinary/encode.js +18 -38
  87. package/lib/WABinary/generic-utils.d.ts +2 -1
  88. package/lib/WABinary/generic-utils.js +2 -2
  89. package/lib/WABinary/jid-utils.d.ts +3 -7
  90. package/lib/WABinary/jid-utils.js +2 -9
  91. package/lib/WAM/BinaryInfo.d.ts +11 -2
  92. package/lib/WAM/constants.d.ts +2 -3
  93. package/lib/WAM/encode.d.ts +2 -1
  94. package/lib/WAM/encode.js +2 -2
  95. package/lib/index.d.ts +1 -1
  96. package/lib/index.js +1 -1
  97. package/package.json +3 -3
  98. package/WAProto/index.d.ts +0 -53473
  99. package/WAProto/index.js +0 -165029
  100. package/lib/Socket/usync.d.ts +0 -36
  101. package/lib/Socket/usync.js +0 -70
  102. package/lib/Types/USync.d.ts +0 -25
  103. package/lib/Types/USync.js +0 -2
  104. package/lib/WAProto/index.d.ts +0 -53473
  105. package/lib/WAProto/index.js +0 -165029
  106. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +0 -9
  107. package/lib/WAUSync/Protocols/USyncContactProtocol.js +0 -32
  108. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +0 -22
  109. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +0 -57
  110. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +0 -12
  111. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +0 -30
  112. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +0 -12
  113. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +0 -42
  114. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +0 -25
  115. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +0 -53
  116. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +0 -8
  117. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +0 -24
  118. package/lib/WAUSync/Protocols/index.d.ts +0 -4
  119. package/lib/WAUSync/Protocols/index.js +0 -20
  120. package/lib/WAUSync/USyncQuery.d.ts +0 -28
  121. package/lib/WAUSync/USyncQuery.js +0 -89
  122. package/lib/WAUSync/USyncUser.d.ts +0 -12
  123. package/lib/WAUSync/USyncUser.js +0 -26
  124. package/lib/WAUSync/index.d.ts +0 -3
  125. package/lib/WAUSync/index.js +0 -19
  126. /package/lib/Socket/Client/{types.js → abstract-socket-client.js} +0 -0
@@ -1,4 +1,8 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
3
+ /// <reference types="node" />
1
4
  import { AxiosRequestConfig } from 'axios';
5
+ import type { Logger } from 'pino';
2
6
  import type { Readable } from 'stream';
3
7
  import type { URL } from 'url';
4
8
  import { proto } from '../../WAProto';
@@ -16,16 +20,13 @@ export type WATextMessage = proto.Message.IExtendedTextMessage;
16
20
  export type WAContextInfo = proto.IContextInfo;
17
21
  export type WALocationMessage = proto.Message.ILocationMessage;
18
22
  export type WAGenericMediaMessage = proto.Message.IVideoMessage | proto.Message.IImageMessage | proto.Message.IAudioMessage | proto.Message.IDocumentMessage | proto.Message.IStickerMessage;
19
- export declare const WAMessageStubType: typeof proto.WebMessageInfo.StubType;
20
- export declare const WAMessageStatus: typeof proto.WebMessageInfo.Status;
21
- import { ILogger } from '../Utils/logger';
22
- export type WAMediaPayloadURL = {
23
+ export import WAMessageStubType = proto.WebMessageInfo.StubType;
24
+ export import WAMessageStatus = proto.WebMessageInfo.Status;
25
+ export type WAMediaUpload = Buffer | {
23
26
  url: URL | string;
24
- };
25
- export type WAMediaPayloadStream = {
27
+ } | {
26
28
  stream: Readable;
27
29
  };
28
- export type WAMediaUpload = Buffer | WAMediaPayloadStream | WAMediaPayloadURL;
29
30
  /** Set of message types that are supported by the library */
30
31
  export type MessageType = keyof proto.Message;
31
32
  export type DownloadableMessage = {
@@ -215,7 +216,7 @@ export type MiscMessageGenerationOptions = MinimalRelayOptions & {
215
216
  export type MessageGenerationOptionsFromContent = MiscMessageGenerationOptions & {
216
217
  userJid: string;
217
218
  };
218
- export type WAMediaUploadFunction = (encFilePath: string, opts: {
219
+ export type WAMediaUploadFunction = (readStream: Readable, opts: {
219
220
  fileEncSha256B64: string;
220
221
  mediaType: MediaType;
221
222
  timeoutMs?: number;
@@ -224,7 +225,7 @@ export type WAMediaUploadFunction = (encFilePath: string, opts: {
224
225
  directPath: string;
225
226
  }>;
226
227
  export type MediaGenerationOptions = {
227
- logger?: ILogger;
228
+ logger?: Logger;
228
229
  mediaTypeOverride?: MediaType;
229
230
  upload: WAMediaUploadFunction;
230
231
  /** cache media so it does not have to be uploaded again */
@@ -3,5 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.WAMessageStatus = exports.WAMessageStubType = exports.WAProto = void 0;
4
4
  const WAProto_1 = require("../../WAProto");
5
5
  Object.defineProperty(exports, "WAProto", { enumerable: true, get: function () { return WAProto_1.proto; } });
6
+ // eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars
6
7
  exports.WAMessageStubType = WAProto_1.proto.WebMessageInfo.StubType;
8
+ // eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars
7
9
  exports.WAMessageStatus = WAProto_1.proto.WebMessageInfo.Status;
@@ -1,8 +1,10 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
1
3
  import { AxiosRequestConfig } from 'axios';
2
4
  import type { Agent } from 'https';
5
+ import type { Logger } from 'pino';
3
6
  import type { URL } from 'url';
4
7
  import { proto } from '../../WAProto';
5
- import { ILogger } from '../Utils/logger';
6
8
  import { AuthenticationState, SignalAuthState, TransactionCapabilityOptions } from './Auth';
7
9
  import { GroupMetadata } from './GroupMetadata';
8
10
  import { MediaConnInfo } from './Message';
@@ -19,9 +21,6 @@ export type CacheStore = {
19
21
  /** flush all data */
20
22
  flushAll(): void;
21
23
  };
22
- export type PatchedMessageWithRecipientJID = proto.IMessage & {
23
- recipientJid?: string;
24
- };
25
24
  export type SocketConfig = {
26
25
  /** the WS url to connect to WA */
27
26
  waWebSocketUrl: string | URL;
@@ -31,24 +30,20 @@ export type SocketConfig = {
31
30
  defaultQueryTimeoutMs: number | undefined;
32
31
  /** ping-pong interval for WS connection */
33
32
  keepAliveIntervalMs: number;
34
- /** should baileys use the mobile api instead of the multi device api
35
- * @deprecated This feature has been removed
36
- */
33
+ /** should baileys use the mobile api instead of the multi device api */
37
34
  mobile?: boolean;
38
35
  /** proxy agent */
39
36
  agent?: Agent;
40
- /** logger */
41
- logger: ILogger;
37
+ /** pino logger */
38
+ logger: Logger;
42
39
  /** version to connect with */
43
40
  version: WAVersion;
44
41
  /** override browser config */
45
42
  browser: WABrowserDescription;
46
43
  /** agent used for fetch requests -- uploading/downloading media */
47
44
  fetchAgent?: Agent;
48
- /** should the QR be printed in the terminal
49
- * @deprecated This feature has been removed
50
- */
51
- printQRInTerminal?: boolean;
45
+ /** should the QR be printed in the terminal */
46
+ printQRInTerminal: boolean;
52
47
  /** should events be emitted for actions done by this socket connection */
53
48
  emitOwnEvents: boolean;
54
49
  /** custom upload hosts to upload media to */
@@ -67,8 +62,6 @@ export type SocketConfig = {
67
62
  transactionOpts: TransactionCapabilityOptions;
68
63
  /** marks the client as online whenever the socket successfully connects */
69
64
  markOnlineOnConnect: boolean;
70
- /** alphanumeric country code (USA -> US) for the number used */
71
- countryCode: string;
72
65
  /** provide a cache to store media, so does not have to be re-uploaded */
73
66
  mediaCache?: CacheStore;
74
67
  /**
@@ -101,7 +94,7 @@ export type SocketConfig = {
101
94
  /**
102
95
  * Optionally patch the message before sending out
103
96
  * */
104
- patchMessageBeforeSending: (msg: proto.IMessage, recipientJids?: string[]) => Promise<PatchedMessageWithRecipientJID[] | PatchedMessageWithRecipientJID> | PatchedMessageWithRecipientJID[] | PatchedMessageWithRecipientJID;
97
+ patchMessageBeforeSending: (msg: proto.IMessage, recipientJids: string[]) => Promise<proto.IMessage> | proto.IMessage;
105
98
  /** verify app state MACs */
106
99
  appStateMacVerification: {
107
100
  patch: boolean;
@@ -118,4 +111,6 @@ export type SocketConfig = {
118
111
  /** cached group metadata, use to prevent redundant requests to WA & speed up msg sending */
119
112
  cachedGroupMetadata: (jid: string) => Promise<GroupMetadata | undefined>;
120
113
  makeSignalRepository: (auth: SignalAuthState) => SignalRepository;
114
+ /** Socket passthrough */
115
+ socket?: any;
121
116
  };
@@ -38,4 +38,4 @@ var DisconnectReason;
38
38
  DisconnectReason[DisconnectReason["multideviceMismatch"] = 411] = "multideviceMismatch";
39
39
  DisconnectReason[DisconnectReason["forbidden"] = 403] = "forbidden";
40
40
  DisconnectReason[DisconnectReason["unavailableService"] = 503] = "unavailableService";
41
- })(DisconnectReason || (exports.DisconnectReason = DisconnectReason = {}));
41
+ })(DisconnectReason = exports.DisconnectReason || (exports.DisconnectReason = {}));
@@ -1,12 +1,12 @@
1
+ import type { Logger } from 'pino';
1
2
  import type { AuthenticationCreds, CacheStore, SignalKeyStore, SignalKeyStoreWithTransaction, TransactionCapabilityOptions } from '../Types';
2
- import { ILogger } from './logger';
3
3
  /**
4
4
  * Adds caching capability to a SignalKeyStore
5
5
  * @param store the store to add caching to
6
6
  * @param logger to log trace events
7
7
  * @param _cache cache store to use
8
8
  */
9
- export declare function makeCacheableSignalKeyStore(store: SignalKeyStore, logger?: ILogger, _cache?: CacheStore): SignalKeyStore;
9
+ export declare function makeCacheableSignalKeyStore(store: SignalKeyStore, logger: Logger, _cache?: CacheStore): SignalKeyStore;
10
10
  /**
11
11
  * Adds DB like transaction capability (https://en.wikipedia.org/wiki/Database_transaction) to the SignalKeyStore,
12
12
  * this allows batch read & write operations & improves the performance of the lib
@@ -14,5 +14,5 @@ export declare function makeCacheableSignalKeyStore(store: SignalKeyStore, logge
14
14
  * @param logger logger to log events
15
15
  * @returns SignalKeyStore with transaction capability
16
16
  */
17
- export declare const addTransactionCapability: (state: SignalKeyStore, logger: ILogger, { maxCommitRetries, delayBetweenTriesMs }: TransactionCapabilityOptions) => SignalKeyStoreWithTransaction;
17
+ export declare const addTransactionCapability: (state: SignalKeyStore, logger: Logger, { maxCommitRetries, delayBetweenTriesMs }: TransactionCapabilityOptions) => SignalKeyStoreWithTransaction;
18
18
  export declare const initAuthCreds: () => AuthenticationCreds;
@@ -3,10 +3,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.initAuthCreds = exports.addTransactionCapability = void 0;
7
- exports.makeCacheableSignalKeyStore = makeCacheableSignalKeyStore;
8
- const node_cache_1 = __importDefault(require("@cacheable/node-cache"));
6
+ exports.initAuthCreds = exports.addTransactionCapability = exports.makeCacheableSignalKeyStore = void 0;
9
7
  const crypto_1 = require("crypto");
8
+ const node_cache_1 = __importDefault(require("node-cache"));
9
+ const uuid_1 = require("uuid");
10
10
  const Defaults_1 = require("../Defaults");
11
11
  const crypto_2 = require("./crypto");
12
12
  const generics_1 = require("./generics");
@@ -18,7 +18,7 @@ const generics_1 = require("./generics");
18
18
  */
19
19
  function makeCacheableSignalKeyStore(store, logger, _cache) {
20
20
  const cache = _cache || new node_cache_1.default({
21
- stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.SIGNAL_STORE, // 5 minutes
21
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.SIGNAL_STORE,
22
22
  useClones: false,
23
23
  deleteOnExpire: true,
24
24
  });
@@ -39,7 +39,7 @@ function makeCacheableSignalKeyStore(store, logger, _cache) {
39
39
  }
40
40
  }
41
41
  if (idsToFetch.length) {
42
- logger === null || logger === void 0 ? void 0 : logger.trace({ items: idsToFetch.length }, 'loading from store');
42
+ logger.trace({ items: idsToFetch.length }, 'loading from store');
43
43
  const fetched = await store.get(type, idsToFetch);
44
44
  for (const id of idsToFetch) {
45
45
  const item = fetched[id];
@@ -59,7 +59,7 @@ function makeCacheableSignalKeyStore(store, logger, _cache) {
59
59
  keys += 1;
60
60
  }
61
61
  }
62
- logger === null || logger === void 0 ? void 0 : logger.trace({ keys }, 'updated cache');
62
+ logger.trace({ keys }, 'updated cache');
63
63
  await store.set(data);
64
64
  },
65
65
  async clear() {
@@ -69,6 +69,7 @@ function makeCacheableSignalKeyStore(store, logger, _cache) {
69
69
  }
70
70
  };
71
71
  }
72
+ exports.makeCacheableSignalKeyStore = makeCacheableSignalKeyStore;
72
73
  /**
73
74
  * Adds DB like transaction capability (https://en.wikipedia.org/wiki/Database_transaction) to the SignalKeyStore,
74
75
  * this allows batch read & write operations & improves the performance of the lib
@@ -142,7 +143,6 @@ const addTransactionCapability = (state, logger, { maxCommitRetries, delayBetwee
142
143
  let tries = maxCommitRetries;
143
144
  while (tries) {
144
145
  tries -= 1;
145
- //eslint-disable-next-line max-depth
146
146
  try {
147
147
  await state.set(mutations);
148
148
  logger.trace({ dbQueriesInTransaction }, 'committed transaction');
@@ -191,7 +191,13 @@ 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,
@@ -1,14 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.uploadingNecessaryImages = exports.parseProductNode = exports.toProductNode = exports.parseOrderDetailsNode = exports.parseCollectionsNode = exports.parseCatalogNode = void 0;
4
- exports.uploadingNecessaryImagesOfProduct = uploadingNecessaryImagesOfProduct;
3
+ exports.uploadingNecessaryImages = exports.uploadingNecessaryImagesOfProduct = exports.parseProductNode = exports.toProductNode = exports.parseOrderDetailsNode = exports.parseCollectionsNode = exports.parseCatalogNode = void 0;
5
4
  const boom_1 = require("@hapi/boom");
6
5
  const crypto_1 = require("crypto");
7
- const fs_1 = require("fs");
8
- const os_1 = require("os");
9
- const path_1 = require("path");
10
6
  const WABinary_1 = require("../WABinary");
11
- const generics_1 = require("./generics");
12
7
  const messages_media_1 = require("./messages-media");
13
8
  const parseCatalogNode = (node) => {
14
9
  const catalogNode = (0, WABinary_1.getBinaryNodeChild)(node, 'product_catalog');
@@ -193,6 +188,7 @@ async function uploadingNecessaryImagesOfProduct(product, waUploadToServer, time
193
188
  };
194
189
  return product;
195
190
  }
191
+ exports.uploadingNecessaryImagesOfProduct = uploadingNecessaryImagesOfProduct;
196
192
  /**
197
193
  * Uploads images not already uploaded to WA's servers
198
194
  */
@@ -206,21 +202,17 @@ const uploadingNecessaryImages = async (images, waUploadToServer, timeoutMs = 30
206
202
  }
207
203
  const { stream } = await (0, messages_media_1.getStream)(img);
208
204
  const hasher = (0, crypto_1.createHash)('sha256');
209
- const filePath = (0, path_1.join)((0, os_1.tmpdir)(), 'img' + (0, generics_1.generateMessageIDV2)());
210
- const encFileWriteStream = (0, fs_1.createWriteStream)(filePath);
205
+ const contentBlocks = [];
211
206
  for await (const block of stream) {
212
207
  hasher.update(block);
213
- encFileWriteStream.write(block);
208
+ contentBlocks.push(block);
214
209
  }
215
210
  const sha = hasher.digest('base64');
216
- const { directPath } = await waUploadToServer(filePath, {
211
+ const { directPath } = await waUploadToServer((0, messages_media_1.toReadable)(Buffer.concat(contentBlocks)), {
217
212
  mediaType: 'product-catalog-image',
218
213
  fileEncSha256B64: sha,
219
214
  timeoutMs
220
215
  });
221
- await fs_1.promises
222
- .unlink(filePath)
223
- .catch(err => console.log('Error deleting temp file ', err));
224
216
  return { url: (0, messages_media_1.getUrlFromDirectPath)(directPath) };
225
217
  }));
226
218
  return results;
@@ -1,8 +1,9 @@
1
+ /// <reference types="node" />
1
2
  import { AxiosRequestConfig } from 'axios';
3
+ import type { Logger } from 'pino';
2
4
  import { proto } from '../../WAProto';
3
5
  import { BaileysEventEmitter, ChatModification, ChatMutation, Contact, InitialAppStateSyncOptions, LTHashState, WAPatchCreate, WAPatchName } from '../Types';
4
6
  import { BinaryNode } from '../WABinary';
5
- import { ILogger } from './logger';
6
7
  type FetchAppStateSyncKey = (keyId: string) => Promise<proto.Message.IAppStateSyncKeyData | null | undefined>;
7
8
  export type ChatMutationMap = {
8
9
  [index: string]: ChatMutation;
@@ -13,7 +14,7 @@ export declare const encodeSyncdPatch: ({ type, index, syncAction, apiVersion, o
13
14
  state: LTHashState;
14
15
  }>;
15
16
  export declare const decodeSyncdMutations: (msgMutations: (proto.ISyncdMutation | proto.ISyncdRecord)[], initialState: LTHashState, getAppStateSyncKey: FetchAppStateSyncKey, onMutation: (mutation: ChatMutation) => void, validateMacs: boolean) => Promise<{
16
- hash: Buffer<any>;
17
+ hash: Buffer;
17
18
  indexValueMap: {
18
19
  [indexMacBase64: string]: {
19
20
  valueMac: Uint8Array | Buffer;
@@ -21,50 +22,50 @@ export declare const decodeSyncdMutations: (msgMutations: (proto.ISyncdMutation
21
22
  };
22
23
  }>;
23
24
  export declare const decodeSyncdPatch: (msg: proto.ISyncdPatch, name: WAPatchName, initialState: LTHashState, getAppStateSyncKey: FetchAppStateSyncKey, onMutation: (mutation: ChatMutation) => void, validateMacs: boolean) => Promise<{
24
- hash: Buffer<any>;
25
+ hash: Buffer;
25
26
  indexValueMap: {
26
27
  [indexMacBase64: string]: {
27
28
  valueMac: Uint8Array | Buffer;
28
29
  };
29
30
  };
30
31
  }>;
31
- export declare const extractSyncdPatches: (result: BinaryNode, options: AxiosRequestConfig<{}>) => Promise<{
32
+ export declare const extractSyncdPatches: (result: BinaryNode, options: AxiosRequestConfig<any>) => Promise<{
32
33
  critical_block: {
33
34
  patches: proto.ISyncdPatch[];
34
35
  hasMorePatches: boolean;
35
- snapshot?: proto.ISyncdSnapshot;
36
+ snapshot?: proto.ISyncdSnapshot | undefined;
36
37
  };
37
38
  critical_unblock_low: {
38
39
  patches: proto.ISyncdPatch[];
39
40
  hasMorePatches: boolean;
40
- snapshot?: proto.ISyncdSnapshot;
41
+ snapshot?: proto.ISyncdSnapshot | undefined;
41
42
  };
42
43
  regular_high: {
43
44
  patches: proto.ISyncdPatch[];
44
45
  hasMorePatches: boolean;
45
- snapshot?: proto.ISyncdSnapshot;
46
+ snapshot?: proto.ISyncdSnapshot | undefined;
46
47
  };
47
48
  regular_low: {
48
49
  patches: proto.ISyncdPatch[];
49
50
  hasMorePatches: boolean;
50
- snapshot?: proto.ISyncdSnapshot;
51
+ snapshot?: proto.ISyncdSnapshot | undefined;
51
52
  };
52
53
  regular: {
53
54
  patches: proto.ISyncdPatch[];
54
55
  hasMorePatches: boolean;
55
- snapshot?: proto.ISyncdSnapshot;
56
+ snapshot?: proto.ISyncdSnapshot | undefined;
56
57
  };
57
58
  }>;
58
- export declare const downloadExternalBlob: (blob: proto.IExternalBlobReference, options: AxiosRequestConfig<{}>) => Promise<Buffer<ArrayBuffer>>;
59
- export declare const downloadExternalPatch: (blob: proto.IExternalBlobReference, options: AxiosRequestConfig<{}>) => Promise<proto.SyncdMutations>;
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>;
60
61
  export declare const decodeSyncdSnapshot: (name: WAPatchName, snapshot: proto.ISyncdSnapshot, getAppStateSyncKey: FetchAppStateSyncKey, minimumVersionNumber: number | undefined, validateMacs?: boolean) => Promise<{
61
62
  state: LTHashState;
62
63
  mutationMap: ChatMutationMap;
63
64
  }>;
64
- export declare const decodePatches: (name: WAPatchName, syncds: proto.ISyncdPatch[], initial: LTHashState, getAppStateSyncKey: FetchAppStateSyncKey, options: AxiosRequestConfig<{}>, minimumVersionNumber?: number, logger?: ILogger, validateMacs?: boolean) => Promise<{
65
+ export declare const decodePatches: (name: WAPatchName, syncds: proto.ISyncdPatch[], initial: LTHashState, getAppStateSyncKey: FetchAppStateSyncKey, options: AxiosRequestConfig<any>, minimumVersionNumber?: number, logger?: Logger, validateMacs?: boolean) => Promise<{
65
66
  state: LTHashState;
66
67
  mutationMap: ChatMutationMap;
67
68
  }>;
68
69
  export declare const chatModificationToAppPatch: (mod: ChatModification, jid: string) => WAPatchCreate;
69
- export declare const processSyncAction: (syncAction: ChatMutation, ev: BaileysEventEmitter, me: Contact, initialSyncOpts?: InitialAppStateSyncOptions, logger?: ILogger) => void;
70
+ export declare const processSyncAction: (syncAction: ChatMutation, ev: BaileysEventEmitter, me: Contact, initialSyncOpts?: InitialAppStateSyncOptions, logger?: Logger) => void;
70
71
  export {};
@@ -9,8 +9,8 @@ const crypto_1 = require("./crypto");
9
9
  const generics_1 = require("./generics");
10
10
  const lt_hash_1 = require("./lt-hash");
11
11
  const messages_media_1 = require("./messages-media");
12
- const mutationKeys = async (keydata) => {
13
- 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' });
14
14
  return {
15
15
  indexKey: expanded.slice(0, 32),
16
16
  valueEncryptionKey: expanded.slice(32, 64),
@@ -69,9 +69,9 @@ const makeLtHashGenerator = ({ indexValueMap, hash }) => {
69
69
  subBuffs.push(new Uint8Array(prevOp.valueMac).buffer);
70
70
  }
71
71
  },
72
- finish: async () => {
72
+ finish: () => {
73
73
  const hashArrayBuffer = new Uint8Array(hash).buffer;
74
- 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);
75
75
  const buffer = Buffer.from(result);
76
76
  return {
77
77
  hash: buffer,
@@ -114,14 +114,14 @@ const encodeSyncdPatch = async ({ type, index, syncAction, apiVersion, operation
114
114
  version: apiVersion
115
115
  });
116
116
  const encoded = WAProto_1.proto.SyncActionData.encode(dataProto).finish();
117
- const keyValue = await mutationKeys(key.keyData);
117
+ const keyValue = mutationKeys(key.keyData);
118
118
  const encValue = (0, crypto_1.aesEncrypt)(encoded, keyValue.valueEncryptionKey);
119
119
  const valueMac = generateMac(operation, encValue, encKeyId, keyValue.valueMacKey);
120
120
  const indexMac = (0, crypto_1.hmacSign)(indexBuffer, keyValue.indexKey);
121
121
  // update LT hash
122
122
  const generator = makeLtHashGenerator(state);
123
123
  generator.mix({ indexMac, valueMac, operation });
124
- Object.assign(state, await generator.finish());
124
+ Object.assign(state, generator.finish());
125
125
  state.version += 1;
126
126
  const snapshotMac = generateSnapshotMac(state.hash, state.version, type, keyValue.snapshotMacKey);
127
127
  const patch = {
@@ -184,7 +184,7 @@ const decodeSyncdMutations = async (msgMutations, initialState, getAppStateSyncK
184
184
  operation: operation
185
185
  });
186
186
  }
187
- return await ltGenerator.finish();
187
+ return ltGenerator.finish();
188
188
  async function getKey(keyId) {
189
189
  const base64Key = Buffer.from(keyId).toString('base64');
190
190
  const keyEnc = await getAppStateSyncKey(base64Key);
@@ -202,7 +202,7 @@ const decodeSyncdPatch = async (msg, name, initialState, getAppStateSyncKey, onM
202
202
  if (!mainKeyObj) {
203
203
  throw new boom_1.Boom(`failed to find key "${base64Key}" to decode patch`, { statusCode: 404, data: { msg } });
204
204
  }
205
- const mainKey = await mutationKeys(mainKeyObj.keyData);
205
+ const mainKey = mutationKeys(mainKeyObj.keyData);
206
206
  const mutationmacs = msg.mutations.map(mutation => mutation.record.value.blob.slice(-32));
207
207
  const patchMac = generatePatchMac(msg.snapshotMac, mutationmacs, (0, generics_1.toNumber)(msg.version.version), name, mainKey.patchMacKey);
208
208
  if (Buffer.compare(patchMac, msg.patchMac) !== 0) {
@@ -286,7 +286,7 @@ const decodeSyncdSnapshot = async (name, snapshot, getAppStateSyncKey, minimumVe
286
286
  if (!keyEnc) {
287
287
  throw new boom_1.Boom(`failed to find key "${base64Key}" to decode mutation`);
288
288
  }
289
- const result = await mutationKeys(keyEnc.keyData);
289
+ const result = mutationKeys(keyEnc.keyData);
290
290
  const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey);
291
291
  if (Buffer.compare(snapshot.mac, computedSnapshotMac) !== 0) {
292
292
  throw new boom_1.Boom(`failed to verify LTHash at ${newState.version} of ${name} from snapshot`);
@@ -305,7 +305,8 @@ const decodePatches = async (name, syncds, initial, getAppStateSyncKey, options,
305
305
  indexValueMap: { ...initial.indexValueMap }
306
306
  };
307
307
  const mutationMap = {};
308
- for (const syncd of syncds) {
308
+ for (let i = 0; i < syncds.length; i++) {
309
+ const syncd = syncds[i];
309
310
  const { version, keyId, snapshotMac } = syncd;
310
311
  if (syncd.externalMutations) {
311
312
  logger === null || logger === void 0 ? void 0 : logger.trace({ name, version }, 'downloading external patch');
@@ -331,7 +332,7 @@ const decodePatches = async (name, syncds, initial, getAppStateSyncKey, options,
331
332
  if (!keyEnc) {
332
333
  throw new boom_1.Boom(`failed to find key "${base64Key}" to decode mutation`);
333
334
  }
334
- const result = await mutationKeys(keyEnc.keyData);
335
+ const result = mutationKeys(keyEnc.keyData);
335
336
  const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey);
336
337
  if (Buffer.compare(snapshotMac, computedSnapshotMac) !== 0) {
337
338
  throw new boom_1.Boom(`failed to verify LTHash at ${newState.version} of ${name}`);
@@ -417,31 +418,25 @@ const chatModificationToAppPatch = (mod, jid) => {
417
418
  operation: OP.SET
418
419
  };
419
420
  }
420
- else if ('deleteForMe' in mod) {
421
- const { timestamp, key, deleteMedia } = mod.deleteForMe;
422
- patch = {
423
- syncAction: {
424
- deleteMessageForMeAction: {
425
- deleteMedia,
426
- messageTimestamp: timestamp
427
- }
428
- },
429
- index: ['deleteMessageForMe', jid, key.id, key.fromMe ? '1' : '0', '0'],
430
- type: 'regular_high',
431
- apiVersion: 3,
432
- operation: OP.SET
433
- };
434
- }
435
421
  else if ('clear' in mod) {
436
- patch = {
437
- syncAction: {
438
- clearChatAction: {} // add message range later
439
- },
440
- index: ['clearChat', jid, '1' /*the option here is 0 when keep starred messages is enabled*/, '0'],
441
- type: 'regular_high',
442
- apiVersion: 6,
443
- operation: OP.SET
444
- };
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
+ }
445
440
  }
446
441
  else if ('pin' in mod) {
447
442
  patch = {
@@ -1,9 +1,10 @@
1
+ /// <reference types="node" />
1
2
  import { KeyPair } from '../Types';
2
3
  /** prefix version byte to the pub keys, required for some curve crypto functions */
3
- export declare const generateSignalPubKey: (pubKey: Uint8Array | Buffer) => Uint8Array<ArrayBufferLike> | Buffer<ArrayBufferLike>;
4
+ export declare const generateSignalPubKey: (pubKey: Uint8Array | Buffer) => Uint8Array | Buffer;
4
5
  export declare const Curve: {
5
6
  generateKeyPair: () => KeyPair;
6
- sharedKey: (privateKey: Uint8Array, publicKey: Uint8Array) => Buffer<any>;
7
+ sharedKey: (privateKey: Uint8Array, publicKey: Uint8Array) => Buffer;
7
8
  sign: (privateKey: Uint8Array, buf: Uint8Array) => any;
8
9
  verify: (pubKey: Uint8Array, message: Uint8Array, signature: Uint8Array) => boolean;
9
10
  };
@@ -16,25 +17,25 @@ export declare const signedKeyPair: (identityKeyPair: KeyPair, keyId: number) =>
16
17
  * encrypt AES 256 GCM;
17
18
  * where the tag tag is suffixed to the ciphertext
18
19
  * */
19
- export declare function aesEncryptGCM(plaintext: Uint8Array, key: Uint8Array, iv: Uint8Array, additionalData: Uint8Array): Buffer<ArrayBuffer>;
20
+ export declare function aesEncryptGCM(plaintext: Uint8Array, key: Uint8Array, iv: Uint8Array, additionalData: Uint8Array): Buffer;
20
21
  /**
21
22
  * decrypt AES 256 GCM;
22
23
  * where the auth tag is suffixed to the ciphertext
23
24
  * */
24
- export declare function aesDecryptGCM(ciphertext: Uint8Array, key: Uint8Array, iv: Uint8Array, additionalData: Uint8Array): Buffer<ArrayBuffer>;
25
- export declare function aesEncryptCTR(plaintext: Uint8Array, key: Uint8Array, iv: Uint8Array): Buffer<ArrayBuffer>;
26
- export declare function aesDecryptCTR(ciphertext: Uint8Array, key: Uint8Array, iv: Uint8Array): Buffer<ArrayBuffer>;
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;
27
28
  /** decrypt AES 256 CBC; where the IV is prefixed to the buffer */
28
- export declare function aesDecrypt(buffer: Buffer, key: Buffer): Buffer<ArrayBuffer>;
29
+ export declare function aesDecrypt(buffer: Buffer, key: Buffer): Buffer;
29
30
  /** decrypt AES 256 CBC */
30
- export declare function aesDecryptWithIV(buffer: Buffer, key: Buffer, IV: Buffer): Buffer<ArrayBuffer>;
31
- export declare function aesEncrypt(buffer: Buffer | Uint8Array, key: Buffer): Buffer<ArrayBuffer>;
32
- export declare function aesEncrypWithIV(buffer: Buffer, key: Buffer, IV: Buffer): Buffer<ArrayBuffer>;
33
- export declare function hmacSign(buffer: Buffer | Uint8Array, key: Buffer | Uint8Array, variant?: 'sha256' | 'sha512'): Buffer<ArrayBufferLike>;
34
- export declare function sha256(buffer: Buffer): Buffer<ArrayBufferLike>;
35
- export declare function md5(buffer: Buffer): Buffer<ArrayBufferLike>;
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;
36
37
  export declare function hkdf(buffer: Uint8Array | Buffer, expandedLength: number, info: {
37
38
  salt?: Buffer;
38
39
  info?: string;
39
- }): Promise<Buffer>;
40
+ }): Buffer;
40
41
  export declare function derivePairingCodeKey(pairingCode: string, salt: Buffer): Promise<Buffer>;