angularsockets 1.0.2 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/LICENSE +21 -0
  2. package/README.MD +170 -0
  3. package/README.md +1 -1900
  4. package/WAProto/GenerateStatics.sh +4 -0
  5. package/WAProto/WAProto.proto +4775 -0
  6. package/WAProto/index.d.ts +4798 -124
  7. package/WAProto/index.js +14270 -302
  8. package/WAProto/index.ts.ts +53473 -0
  9. package/engine-requirements.js +10 -0
  10. package/lib/Defaults/baileys-version.json +1 -1
  11. package/lib/Defaults/index.d.ts +4 -6
  12. package/lib/Defaults/index.js +4 -6
  13. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  14. package/lib/Signal/Group/ciphertext-message.js +15 -0
  15. package/lib/Signal/Group/group-session-builder.d.ts +14 -0
  16. package/lib/Signal/Group/group-session-builder.js +64 -0
  17. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  18. package/lib/Signal/Group/group_cipher.js +96 -0
  19. package/lib/Signal/Group/index.d.ts +11 -0
  20. package/lib/Signal/Group/index.js +57 -0
  21. package/lib/Signal/Group/keyhelper.d.ts +10 -0
  22. package/lib/Signal/Group/keyhelper.js +55 -0
  23. package/lib/Signal/Group/queue-job.d.ts +1 -0
  24. package/lib/Signal/Group/queue-job.js +57 -0
  25. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  26. package/lib/Signal/Group/sender-chain-key.js +34 -0
  27. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  28. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  29. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  30. package/lib/Signal/Group/sender-key-message.js +69 -0
  31. package/lib/Signal/Group/sender-key-name.d.ts +17 -0
  32. package/lib/Signal/Group/sender-key-name.js +51 -0
  33. package/lib/Signal/Group/sender-key-record.d.ts +30 -0
  34. package/lib/Signal/Group/sender-key-record.js +53 -0
  35. package/lib/Signal/Group/sender-key-state.d.ts +38 -0
  36. package/lib/Signal/Group/sender-key-state.js +99 -0
  37. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  38. package/{WASignalGroup/sender_message_key.js → lib/Signal/Group/sender-message-key.js} +6 -16
  39. package/lib/Signal/libsignal.js +51 -29
  40. package/lib/Socket/Client/index.d.ts +2 -3
  41. package/lib/Socket/Client/index.js +2 -3
  42. package/lib/Socket/Client/{abstract-socket-client.d.ts → types.d.ts} +1 -2
  43. package/lib/Socket/Client/{web-socket-client.d.ts → websocket.d.ts} +2 -1
  44. package/lib/Socket/Client/{web-socket-client.js → websocket.js} +54 -5
  45. package/lib/Socket/RHandler.d.ts +416 -0
  46. package/lib/Socket/RHandler.js +530 -0
  47. package/lib/Socket/business.d.ts +39 -37
  48. package/lib/Socket/chats.d.ts +36 -23
  49. package/lib/Socket/chats.js +74 -116
  50. package/lib/Socket/groups.d.ts +42 -33
  51. package/lib/Socket/groups.js +26 -9
  52. package/lib/Socket/index.d.ts +39 -39
  53. package/lib/Socket/index.js +2 -2
  54. package/lib/Socket/messages-recv.d.ts +37 -34
  55. package/lib/Socket/messages-recv.js +111 -29
  56. package/lib/Socket/messages-send.d.ts +50 -53
  57. package/lib/Socket/messages-send.js +213 -397
  58. package/lib/Socket/newsletter.d.ts +25 -21
  59. package/lib/Socket/newsletter.js +92 -25
  60. package/lib/Socket/socket.d.ts +10 -11
  61. package/lib/Socket/socket.js +34 -23
  62. package/lib/Socket/usync.d.ts +11 -12
  63. package/lib/Store/index.d.ts +1 -2
  64. package/lib/Store/index.js +1 -3
  65. package/lib/Store/make-in-memory-store.d.ts +22 -22
  66. package/lib/Store/make-in-memory-store.js +21 -13
  67. package/lib/Store/make-ordered-dictionary.d.ts +1 -1
  68. package/lib/Types/Auth.d.ts +0 -6
  69. package/lib/Types/Chat.d.ts +6 -4
  70. package/lib/Types/Contact.d.ts +5 -1
  71. package/lib/Types/Events.d.ts +27 -0
  72. package/lib/Types/GroupMetadata.d.ts +8 -0
  73. package/lib/Types/Label.d.ts +0 -11
  74. package/lib/Types/Message.d.ts +59 -90
  75. package/lib/Types/Message.js +0 -2
  76. package/lib/Types/Newsletter.d.ts +97 -86
  77. package/lib/Types/Newsletter.js +38 -32
  78. package/lib/Types/Socket.d.ts +10 -7
  79. package/lib/Types/index.d.ts +1 -3
  80. package/lib/Types/index.js +1 -1
  81. package/lib/Utils/audioToBuffer.js +29 -0
  82. package/lib/Utils/auth-utils.d.ts +3 -3
  83. package/lib/Utils/auth-utils.js +13 -41
  84. package/lib/Utils/business.d.ts +1 -1
  85. package/lib/Utils/chat-utils.d.ts +12 -12
  86. package/lib/Utils/chat-utils.js +4 -19
  87. package/lib/Utils/crypto.d.ts +15 -15
  88. package/lib/Utils/crypto.js +6 -12
  89. package/lib/Utils/decode-wa-message.d.ts +5 -6
  90. package/lib/Utils/decode-wa-message.js +28 -55
  91. package/lib/Utils/event-buffer.d.ts +2 -2
  92. package/lib/Utils/event-buffer.js +2 -1
  93. package/lib/Utils/generics.d.ts +12 -11
  94. package/lib/Utils/generics.js +64 -38
  95. package/lib/Utils/history.d.ts +2 -2
  96. package/lib/Utils/history.js +1 -1
  97. package/lib/Utils/index.d.ts +2 -0
  98. package/lib/Utils/index.js +3 -0
  99. package/lib/Utils/link-preview.d.ts +2 -2
  100. package/lib/Utils/link-preview.js +34 -1
  101. package/lib/Utils/logger.d.ts +10 -1
  102. package/lib/Utils/lt-hash.d.ts +2 -2
  103. package/lib/Utils/lt-hash.js +6 -6
  104. package/lib/Utils/messages-media.d.ts +40 -29
  105. package/lib/Utils/messages-media.js +276 -110
  106. package/lib/Utils/messages.d.ts +8 -10
  107. package/lib/Utils/messages.js +126 -317
  108. package/lib/Utils/noise-handler.d.ts +10 -11
  109. package/lib/Utils/noise-handler.js +3 -13
  110. package/lib/Utils/process-message.d.ts +3 -2
  111. package/lib/Utils/process-message.js +17 -5
  112. package/lib/Utils/signal.js +2 -8
  113. package/lib/Utils/streamToBuffer.js +15 -0
  114. package/lib/Utils/use-multi-file-auth-state.js +72 -242
  115. package/lib/Utils/validate-connection.d.ts +2 -3
  116. package/lib/Utils/validate-connection.js +19 -51
  117. package/lib/WABinary/constants.d.ts +4 -4
  118. package/lib/WABinary/constants.js +1276 -13
  119. package/lib/WABinary/decode.d.ts +2 -2
  120. package/lib/WABinary/decode.js +3 -2
  121. package/lib/WABinary/encode.js +5 -7
  122. package/lib/WABinary/generic-utils.d.ts +2 -2
  123. package/lib/WABinary/jid-utils.d.ts +9 -4
  124. package/lib/WABinary/jid-utils.js +26 -5
  125. package/lib/WABinary/jid-utils.js.bak +83 -0
  126. package/lib/WAM/encode.d.ts +1 -1
  127. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +1 -1
  128. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +3 -3
  129. package/lib/WAUSync/USyncUser.d.ts +2 -0
  130. package/lib/index.d.ts +16 -0
  131. package/lib/index.js +48 -4
  132. package/lib/index.js.bak +56 -0
  133. package/package.json +43 -35
  134. package/WASignalGroup/GroupProtocol.js +0 -1697
  135. package/WASignalGroup/ciphertext_message.js +0 -16
  136. package/WASignalGroup/group_cipher.js +0 -120
  137. package/WASignalGroup/group_session_builder.js +0 -46
  138. package/WASignalGroup/index.js +0 -5
  139. package/WASignalGroup/keyhelper.js +0 -21
  140. package/WASignalGroup/protobufs.js +0 -3
  141. package/WASignalGroup/queue_job.js +0 -69
  142. package/WASignalGroup/sender_chain_key.js +0 -50
  143. package/WASignalGroup/sender_key_distribution_message.js +0 -78
  144. package/WASignalGroup/sender_key_message.js +0 -92
  145. package/WASignalGroup/sender_key_name.js +0 -70
  146. package/WASignalGroup/sender_key_record.js +0 -56
  147. package/WASignalGroup/sender_key_state.js +0 -129
  148. package/lib/Socket/Client/mobile-socket-client.d.ts +0 -13
  149. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  150. package/lib/Socket/registration.d.ts +0 -264
  151. package/lib/Socket/registration.js +0 -166
  152. package/lib/Store/make-cache-manager-store.d.ts +0 -14
  153. package/lib/Store/make-cache-manager-store.js +0 -83
  154. package/lib/Utils/use-single-file-auth-state.d.ts +0 -12
  155. package/lib/Utils/use-single-file-auth-state.js +0 -75
  156. /package/lib/Socket/Client/{abstract-socket-client.js → types.js} +0 -0
@@ -1,20 +1,19 @@
1
- import { Logger } from 'pino';
1
+ import { ILogger } from './logger';
2
2
  import { proto } from '../../WAProto';
3
3
  import { KeyPair } from '../Types';
4
4
  import { BinaryNode } from '../WABinary';
5
- export declare const makeNoiseHandler: ({ keyPair: { private: privateKey, public: publicKey }, NOISE_HEADER, mobile, logger, routingInfo }: {
5
+ export declare const makeNoiseHandler: ({ keyPair: { private: privateKey, public: publicKey }, NOISE_HEADER, logger, routingInfo }: {
6
6
  keyPair: KeyPair;
7
7
  NOISE_HEADER: Uint8Array;
8
- mobile: boolean;
9
- logger: Logger;
8
+ logger: ILogger;
10
9
  routingInfo?: Buffer | undefined;
11
10
  }) => {
12
- encrypt: (plaintext: Uint8Array) => any;
13
- decrypt: (ciphertext: Uint8Array) => any;
11
+ encrypt: (plaintext: Uint8Array) => Buffer<ArrayBuffer>;
12
+ decrypt: (ciphertext: Uint8Array) => Buffer<ArrayBuffer>;
14
13
  authenticate: (data: Uint8Array) => void;
15
- mixIntoKey: (data: Uint8Array) => void;
16
- finishInit: () => void;
17
- processHandshake: ({ serverHello }: proto.HandshakeMessage, noiseKey: KeyPair) => any;
18
- encodeFrame: (data: Buffer | Uint8Array) => any;
19
- decodeFrame: (newData: Buffer | Uint8Array, onFrame: (buff: Uint8Array | BinaryNode) => void) => void;
14
+ mixIntoKey: (data: Uint8Array) => Promise<void>;
15
+ finishInit: () => Promise<void>;
16
+ processHandshake: ({ serverHello }: proto.HandshakeMessage, noiseKey: KeyPair) => Promise<Buffer<ArrayBuffer>>;
17
+ encodeFrame: (data: Buffer | Uint8Array) => Buffer<ArrayBuffer>;
18
+ decodeFrame: (newData: Buffer | Uint8Array, onFrame: (buff: Uint8Array | BinaryNode) => void) => Promise<void>;
20
19
  };
@@ -11,7 +11,7 @@ const generateIV = (counter) => {
11
11
  new DataView(iv).setUint32(8, counter);
12
12
  return new Uint8Array(iv);
13
13
  };
14
- const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publicKey }, NOISE_HEADER, mobile, logger, routingInfo }) => {
14
+ const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publicKey }, NOISE_HEADER, logger, routingInfo }) => {
15
15
  logger = logger.child({ class: 'ns' });
16
16
  const authenticate = (data) => {
17
17
  if (!isFinished) {
@@ -60,7 +60,7 @@ const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publicKey },
60
60
  isFinished = true;
61
61
  };
62
62
  const data = Buffer.from(Defaults_1.NOISE_MODE);
63
- let hash = Buffer.from(data.byteLength === 32 ? data : (0, crypto_1.sha256)(data));
63
+ let hash = data.byteLength === 32 ? data : (0, crypto_1.sha256)(data);
64
64
  let salt = hash;
65
65
  let encKey = hash;
66
66
  let decKey = hash;
@@ -87,17 +87,7 @@ const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publicKey },
87
87
  const { issuerSerial } = WAProto_1.proto.CertChain.NoiseCertificate.Details.decode(certIntermediate.details);
88
88
  if (issuerSerial !== Defaults_1.WA_CERT_DETAILS.SERIAL) {
89
89
  throw new boom_1.Boom('certification match failed', { statusCode: 400 });
90
- }/*
91
- if (mobile) {
92
- WAProto_1.proto.CertChain.NoiseCertificate.decode(certDecoded);
93
90
  }
94
- else {
95
- const { intermediate: certIntermediate } = WAProto_1.proto.CertChain.decode(certDecoded);
96
- const { issuerSerial } = WAProto_1.proto.CertChain.NoiseCertificate.Details.decode(certIntermediate.details);
97
- if (issuerSerial !== Defaults_1.WA_CERT_DETAILS.SERIAL) {
98
- throw new boom_1.Boom('certification match failed', { statusCode: 400 });
99
- }
100
- }*/
101
91
  const keyEnc = encrypt(noiseKey.public);
102
92
  await mixIntoKey(crypto_1.Curve.sharedKey(noiseKey.private, serverHello.ephemeral));
103
93
  return keyEnc;
@@ -157,4 +147,4 @@ const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publicKey },
157
147
  }
158
148
  };
159
149
  };
160
- exports.makeNoiseHandler = makeNoiseHandler;
150
+ exports.makeNoiseHandler = makeNoiseHandler;
@@ -1,6 +1,6 @@
1
1
  import { AxiosRequestConfig } from 'axios';
2
2
  import { proto } from '../../WAProto';
3
- import { AuthenticationCreds, BaileysEventEmitter, CacheStore, SignalKeyStoreWithTransaction } from '../Types';
3
+ import { AuthenticationCreds, BaileysEventEmitter, CacheStore, SignalKeyStoreWithTransaction, SocketConfig } from '../Types';
4
4
  import { ILogger } from './logger';
5
5
  type ProcessMessageContext = {
6
6
  shouldProcessHistoryMsg: boolean;
@@ -8,6 +8,7 @@ type ProcessMessageContext = {
8
8
  creds: AuthenticationCreds;
9
9
  keyStore: SignalKeyStoreWithTransaction;
10
10
  ev: BaileysEventEmitter;
11
+ getMessage: SocketConfig['getMessage'];
11
12
  logger?: ILogger;
12
13
  options: AxiosRequestConfig<{}>;
13
14
  };
@@ -37,5 +38,5 @@ type PollContext = {
37
38
  * @returns list of SHA256 options
38
39
  */
39
40
  export declare function decryptPollVote({ encPayload, encIv }: proto.Message.IPollEncValue, { pollCreatorJid, pollMsgId, pollEncKey, voterJid, }: PollContext): proto.Message.PollVoteMessage;
40
- declare const processMessage: (message: proto.IWebMessageInfo, { shouldProcessHistoryMsg, placeholderResendCache, ev, creds, keyStore, logger, options }: ProcessMessageContext) => Promise<void>;
41
+ declare const processMessage: (message: proto.IWebMessageInfo, { shouldProcessHistoryMsg, placeholderResendCache, ev, creds, keyStore, logger, options, getMessage }: ProcessMessageContext) => Promise<void>;
41
42
  export default processMessage;
@@ -21,8 +21,21 @@ const REAL_MSG_REQ_ME_STUB_TYPES = new Set([
21
21
  /** Cleans a received message to further processing */
22
22
  const cleanMessage = (message, meId) => {
23
23
  // ensure remoteJid and participant doesn't have device or agent in it
24
- message.key.remoteJid = (0, WABinary_1.jidNormalizedUser)(message.key.remoteJid);
25
- message.key.participant = message.key.participant ? (0, WABinary_1.jidNormalizedUser)(message.key.participant) : undefined;
24
+ // normalize JIDs but catch errors to avoid throwing on invalid LIDs/JIDs
25
+ try {
26
+ message.key.remoteJid = (0, WABinary_1.jidNormalizedUser)(message.key.remoteJid);
27
+ }
28
+ catch (_e) {
29
+ // if normalization fails, retain original remoteJid
30
+ }
31
+ if (message.key.participant) {
32
+ try {
33
+ message.key.participant = (0, WABinary_1.jidNormalizedUser)(message.key.participant);
34
+ }
35
+ catch (_e) {
36
+ // ignore if can't normalize participant
37
+ }
38
+ }
26
39
  const content = (0, messages_1.normalizeMessageContent)(message.message);
27
40
  // if the message has a reaction, ensure fromMe & remoteJid are from our perspective
28
41
  if (content === null || content === void 0 ? void 0 : content.reactionMessage) {
@@ -102,8 +115,8 @@ function decryptPollVote({ encPayload, encIv }, { pollCreatorJid, pollMsgId, pol
102
115
  return Buffer.from(txt);
103
116
  }
104
117
  }
105
- const processMessage = async (message, { shouldProcessHistoryMsg, placeholderResendCache, ev, creds, keyStore, logger, options }) => {
106
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
118
+ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderResendCache, ev, creds, keyStore, logger, options, getMessage }) => {
119
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s;
107
120
  const meId = creds.me.id;
108
121
  const { accountSettings } = creds;
109
122
  const chat = { id: (0, WABinary_1.jidNormalizedUser)((0, exports.getChatId)(message.key)) };
@@ -201,7 +214,6 @@ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderRes
201
214
  const { peerDataOperationResult } = response;
202
215
  for (const result of peerDataOperationResult) {
203
216
  const { placeholderMessageResendResponse: retryResponse } = result;
204
- //eslint-disable-next-line max-depth
205
217
  if (retryResponse) {
206
218
  const webMessageInfo = WAProto_1.proto.WebMessageInfo.decode(retryResponse.webMessageInfoBytes);
207
219
  // wait till another upsert event is available, don't want it to be part of the PDO response message
@@ -1,17 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getNextPreKeysNode = exports.getNextPreKeys = exports.extractDeviceJids = exports.parseAndInjectE2ESessions = exports.xmppPreKey = exports.xmppSignedPreKey = exports.generateOrGetPreKeys = exports.getPreKeys = exports.createSignalIdentity = void 0;
4
+ const lodash_1 = require("lodash");
4
5
  const Defaults_1 = require("../Defaults");
5
6
  const WABinary_1 = require("../WABinary");
6
7
  const crypto_1 = require("./crypto");
7
8
  const generics_1 = require("./generics");
8
- function chunk(array, size) {
9
- const result = [];
10
- for (let i = 0; i < array.length; i += size) {
11
- result.push(array.slice(i, i + size));
12
- }
13
- return result;
14
- }
15
9
  const createSignalIdentity = (wid, accountSignatureKey) => {
16
10
  return {
17
11
  identifier: { name: wid, deviceId: 0 },
@@ -79,7 +73,7 @@ const parseAndInjectE2ESessions = async (node, repository) => {
79
73
  // This way we chunk it in smaller parts and between those parts we can yield to the event loop
80
74
  // It's rare case when you need to E2E sessions for so many users, but it's possible
81
75
  const chunkSize = 100;
82
- const chunks = chunk(nodes, chunkSize);
76
+ const chunks = (0, lodash_1.chunk)(nodes, chunkSize);
83
77
  for (const nodesChunk of chunks) {
84
78
  await Promise.all(nodesChunk.map(async (node) => {
85
79
  const signedKey = (0, WABinary_1.getBinaryNodeChild)(node, 'skey');
@@ -0,0 +1,15 @@
1
+ const { Readable } = require("stream");
2
+
3
+ /**
4
+ * Mengonversi Node.js Readable Stream menjadi Buffer.
5
+ * * @param {Readable} stream Aliran data yang dapat dibaca.
6
+ * @returns {Promise<Buffer>} Promise yang diselesaikan dengan Buffer berisi semua data dari aliran.
7
+ */
8
+ async function streamToBuffer(stream) {
9
+ const chunks = [];
10
+ return new Promise((resolve, reject) => {
11
+ stream.on('data', chunk => chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)));
12
+ stream.on('end', () => resolve(Buffer.concat(chunks)));
13
+ stream.on('error', reject);
14
+ });
15
+ }
@@ -1,295 +1,125 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
3
  exports.useMultiFileAuthState = void 0;
7
- const async_lock_1 = __importDefault(require("async-lock"));
4
+ const async_mutex_1 = require("async-mutex");
8
5
  const promises_1 = require("fs/promises");
9
6
  const path_1 = require("path");
10
7
  const WAProto_1 = require("../../WAProto");
11
8
  const auth_utils_1 = require("./auth-utils");
12
9
  const generics_1 = require("./generics");
13
- const node_cache_1 = __importDefault(require("node-cache"));
14
- const Defaults_1 = require("../Defaults");
15
-
16
- // Enhanced locking mechanism
17
- const fileLock = new async_lock_1.default({
18
- maxPending: Infinity,
19
- timeout: 5000 // 5s timeout to prevent deadlocks
20
- });
21
- const globalAuthLock = new async_lock_1.default(); // Additional global lock
22
-
23
- // Debugging utilities
24
- let AUTH_DEBUG = false;
25
- function authDebug(...args) {
26
- if (AUTH_DEBUG) {
27
- console.log('[AUTH DEBUG]', new Date().toISOString(), ...args);
10
+ // We need to lock files due to the fact that we are using async functions to read and write files
11
+ // https://github.com/WhiskeySockets/Baileys/issues/794
12
+ // https://github.com/nodejs/node/issues/26338
13
+ // Use a Map to store mutexes for each file path
14
+ const fileLocks = new Map();
15
+ // Get or create a mutex for a specific file path
16
+ const getFileLock = (path) => {
17
+ let mutex = fileLocks.get(path);
18
+ if (!mutex) {
19
+ mutex = new async_mutex_1.Mutex();
20
+ fileLocks.set(path, mutex);
28
21
  }
29
- }
30
-
22
+ return mutex;
23
+ };
31
24
  /**
32
- * Enhanced multi-file auth state storage with:
33
- * - Better error handling
34
- * - Additional locking
35
- * - Data validation
36
- * - Auto-repair mechanisms
37
- */
38
- const useMultiFileAuthState = async (folder, options = {}) => {
39
- AUTH_DEBUG = options.authDebug ?? false;
40
- const cache = options.syncCache ? new node_cache_1.default({
41
- stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.SIGNAL_STORE,
42
- useClones: false,
43
- deleteOnExpire: true,
44
- checkperiod: 120
45
- }) : null;
46
- // Validate and prepare folder
47
- const prepareFolder = async () => {
48
- try {
49
- const folderInfo = await (0, promises_1.stat)(folder).catch(() => null);
50
-
51
- if (folderInfo) {
52
- if (!folderInfo.isDirectory()) {
53
- throw new Error(`Path exists but is not a directory: ${folder}`);
54
- }
55
- } else {
56
- authDebug('Creating auth folder:', folder);
57
- await (0, promises_1.mkdir)(folder, { recursive: true });
58
- }
59
-
60
- // Verify folder is writable
61
- await testFolderAccess();
62
- } catch (error) {
63
- authDebug('Folder preparation failed:', error);
64
- throw new Error(`Auth folder initialization failed: ${error.message}`);
65
- }
66
- };
67
-
68
- const testFolderAccess = async () => {
69
- const testFile = (0, path_1.join)(folder, '.temp_test');
70
- try {
71
- await (0, promises_1.writeFile)(testFile, 'test');
72
- await (0, promises_1.unlink)(testFile);
73
- } catch (error) {
74
- throw new Error(`Folder not writable: ${error.message}`);
75
- }
76
- };
77
-
78
- const fixFileName = (file) => {
79
- if (!file) return file;
80
- return file.replace(/\//g, '__').replace(/:/g, '-');
81
- };
82
-
83
- function getUniqueId(type, id) {
84
- return `${type}.${id}`;
85
- }
86
-
87
- // Enhanced write with retries
25
+ * stores the full authentication state in a single folder.
26
+ * Far more efficient than singlefileauthstate
27
+ *
28
+ * Again, I wouldn't endorse this for any production level use other than perhaps a bot.
29
+ * Would recommend writing an auth state for use with a proper SQL or No-SQL DB
30
+ * */
31
+ const useMultiFileAuthState = async (folder) => {
32
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
88
33
  const writeData = async (data, file) => {
89
- return globalAuthLock.acquire('write', async () => {
90
- const filePath = (0, path_1.join)(folder, fixFileName(file));
91
- let attempts = 0;
92
- const maxAttempts = 3;
93
-
94
- while (attempts < maxAttempts) {
95
- attempts++;
96
- try {
97
- await fileLock.acquire(filePath, async () => {
98
- const serialized = JSON.stringify(data, generics_1.BufferJSON.replacer);
99
- await (0, promises_1.writeFile)(filePath, serialized);
100
- authDebug('Write successful:', file);
101
- });
102
- return;
103
- } catch (error) {
104
- authDebug(`Write attempt ${attempts} failed for ${file}:`, error);
105
- if (attempts >= maxAttempts) {
106
- throw new Error(`Failed to write after ${maxAttempts} attempts: ${error.message}`);
107
- }
108
- await new Promise(resolve => setTimeout(resolve, 100 * attempts));
109
- }
34
+ const filePath = (0, path_1.join)(folder, fixFileName(file));
35
+ const mutex = getFileLock(filePath);
36
+ return mutex.acquire().then(async (release) => {
37
+ try {
38
+ await (0, promises_1.writeFile)(filePath, JSON.stringify(data, generics_1.BufferJSON.replacer));
39
+ }
40
+ finally {
41
+ release();
110
42
  }
111
43
  });
112
44
  };
113
-
114
- // Enhanced read with validation
115
45
  const readData = async (file) => {
116
- return globalAuthLock.acquire('read', async () => {
46
+ try {
117
47
  const filePath = (0, path_1.join)(folder, fixFileName(file));
118
-
119
- try {
120
- const data = await fileLock.acquire(filePath, async () => {
121
- const content = await (0, promises_1.readFile)(filePath, { encoding: 'utf-8' });
122
- authDebug('Read successful:', file);
123
- return content;
124
- });
125
-
126
- const parsed = JSON.parse(data, generics_1.BufferJSON.reviver);
127
-
128
- // Basic data validation
129
- if (file === 'creds.json' && !parsed.me) {
130
- authDebug('Invalid creds data detected');
131
- return null;
48
+ const mutex = getFileLock(filePath);
49
+ return await mutex.acquire().then(async (release) => {
50
+ try {
51
+ const data = await (0, promises_1.readFile)(filePath, { encoding: 'utf-8' });
52
+ return JSON.parse(data, generics_1.BufferJSON.reviver);
132
53
  }
133
-
134
- return parsed;
135
- } catch (error) {
136
- if (error.code !== 'ENOENT') { // Ignore "file not found" errors
137
- authDebug('Read error:', file, error);
54
+ finally {
55
+ release();
138
56
  }
139
- return null;
140
- }
141
- });
57
+ });
58
+ }
59
+ catch (error) {
60
+ return null;
61
+ }
142
62
  };
143
-
144
- // Safe removal
145
63
  const removeData = async (file) => {
146
- return globalAuthLock.acquire('remove', async () => {
64
+ try {
147
65
  const filePath = (0, path_1.join)(folder, fixFileName(file));
148
-
149
- try {
150
- await fileLock.acquire(filePath, async () => {
66
+ const mutex = getFileLock(filePath);
67
+ return mutex.acquire().then(async (release) => {
68
+ try {
151
69
  await (0, promises_1.unlink)(filePath);
152
- authDebug('Removed:', file);
153
- });
154
- } catch (error) {
155
- if (error.code !== 'ENOENT') { // Ignore "file not found" errors
156
- authDebug('Remove error:', file, error);
157
70
  }
158
- }
159
- });
160
- };
161
-
162
- // Initialize
163
- await prepareFolder();
164
-
165
- // Load or initialize credentials
166
- let creds = await readData('creds.json');
167
- if (!creds) {
168
- authDebug('No existing creds found, initializing new ones');
169
- creds = (0, auth_utils_1.initAuthCreds)();
170
- await writeData(creds, 'creds.json');
171
- }
172
-
173
- async function warmUpCache() {
174
- try {
175
- const files = await promises_1.readdir(folder);
176
- for (const file of files) {
177
- if (file.endsWith('.json') && file !== 'creds.json') {
178
- const parts = file.split('-');
179
- if (parts.length === 2) {
180
- const type = parts[0];
181
- const id = parts[1].replace('.json', '');
182
- const data = await readData(file);
183
- if (data) {
184
- cache.set(getUniqueId(type, id), data);
185
- authDebug(`Cache warmed: ${type}-${id}`);
186
- }
187
- }
188
- }
71
+ catch (_a) {
72
+ }
73
+ finally {
74
+ release();
75
+ }
76
+ });
189
77
  }
190
- } catch (error) {
191
- authDebug('Cache warm-up failed:', error);
192
- }
193
- }
194
-
195
- if (cache) warmUpCache();
196
-
197
- // Auto-save mechanism
198
- let saveTimeout;
199
- const scheduleSave = () => {
200
- if (saveTimeout) clearTimeout(saveTimeout);
201
- saveTimeout = setTimeout(() => {
202
- saveCreds().catch(error => {
203
- authDebug('Auto-save failed, retrying sooner:', error);
204
- setTimeout(scheduleSave, 60000);
205
- });
206
- }, 180000);
207
- };
208
- // Enhanced save function
209
- const saveCreds = async () => {
210
- try {
211
- await writeData(creds, 'creds.json');
212
- scheduleSave();
213
- } catch (error) {
214
- authDebug('Critical: Creds save failed:', error);
215
- throw error;
78
+ catch (_a) {
216
79
  }
217
80
  };
218
-
219
- process.on('beforeExit', async () => {
220
- if (saveTimeout) clearTimeout(saveTimeout);
221
- await saveCreds().catch(error => {
222
- authDebug('Emergency save failed:', error);
223
- });
224
- });
225
-
226
- process.on('uncaughtException', async (error) => {
227
- authDebug('Uncaught exception, attempting emergency save:', error);
228
- if (saveTimeout) clearTimeout(saveTimeout);
229
- await saveCreds().catch(e => {
230
- authDebug('Emergency save failed:', e);
231
- });
232
- process.exit(1);
233
- });
234
- // Start auto-save loop
235
- scheduleSave();
236
-
81
+ const folderInfo = await (0, promises_1.stat)(folder).catch(() => { });
82
+ if (folderInfo) {
83
+ if (!folderInfo.isDirectory()) {
84
+ throw new Error(`found something that is not a directory at ${folder}, either delete it or specify a different location`);
85
+ }
86
+ }
87
+ else {
88
+ await (0, promises_1.mkdir)(folder, { recursive: true });
89
+ }
90
+ const fixFileName = (file) => { var _a; return (_a = file === null || file === void 0 ? void 0 : file.replace(/\//g, '__')) === null || _a === void 0 ? void 0 : _a.replace(/:/g, '-'); };
91
+ const creds = await readData('creds.json') || (0, auth_utils_1.initAuthCreds)();
237
92
  return {
238
93
  state: {
239
94
  creds,
240
95
  keys: {
241
96
  get: async (type, ids) => {
242
97
  const data = {};
243
-
244
98
  await Promise.all(ids.map(async (id) => {
245
99
  let value = await readData(`${type}-${id}.json`);
246
-
247
100
  if (type === 'app-state-sync-key' && value) {
248
- try {
249
- value = WAProto_1.proto.Message.AppStateSyncKeyData.fromObject(value);
250
- } catch (error) {
251
- authDebug('Key conversion failed:', type, id, error);
252
- value = null;
253
- }
101
+ value = WAProto_1.proto.Message.AppStateSyncKeyData.fromObject(value);
254
102
  }
255
-
256
103
  data[id] = value;
257
104
  }));
258
-
259
105
  return data;
260
106
  },
261
107
  set: async (data) => {
262
108
  const tasks = [];
263
-
264
109
  for (const category in data) {
265
110
  for (const id in data[category]) {
266
111
  const value = data[category][id];
267
112
  const file = `${category}-${id}.json`;
268
-
269
- if (value) {
270
- tasks.push(writeData(value, file));
271
- } else {
272
- tasks.push(removeData(file));
273
- }
113
+ tasks.push(value ? writeData(value, file) : removeData(file));
274
114
  }
275
115
  }
276
-
277
- try {
278
- await Promise.all(tasks);
279
- } catch (error) {
280
- authDebug('Bulk key update failed:', error);
281
- throw error;
282
- }
116
+ await Promise.all(tasks);
283
117
  }
284
118
  }
285
119
  },
286
- saveCreds,
287
- // Additional maintenance API
288
- cleanup: async () => {
289
- if (saveTimeout) clearTimeout(saveTimeout);
290
- await saveCreds();
291
- },
292
- cache
120
+ saveCreds: async () => {
121
+ return writeData(creds, 'creds.json');
122
+ }
293
123
  };
294
124
  };
295
- exports.useMultiFileAuthState = useMultiFileAuthState;
125
+ exports.useMultiFileAuthState = useMultiFileAuthState;
@@ -1,11 +1,10 @@
1
1
  import { proto } from '../../WAProto';
2
2
  import type { AuthenticationCreds, SignalCreds, SocketConfig } from '../Types';
3
3
  import { BinaryNode } from '../WABinary';
4
- export declare const generateMobileNode: (config: SocketConfig) => proto.IClientPayload;
5
4
  export declare const generateLoginNode: (userJid: string, config: SocketConfig) => proto.IClientPayload;
6
5
  export declare const generateRegistrationNode: ({ registrationId, signedPreKey, signedIdentityKey }: SignalCreds, config: SocketConfig) => proto.ClientPayload;
7
- export declare const configureSuccessfulPairing: (stanza: BinaryNode, { advSecretKey, signedIdentityKey, signalIdentities }: Pick<AuthenticationCreds, 'advSecretKey' | 'signedIdentityKey' | 'signalIdentities'>) => {
6
+ export declare const configureSuccessfulPairing: (stanza: BinaryNode, { advSecretKey, signedIdentityKey, signalIdentities }: Pick<AuthenticationCreds, "advSecretKey" | "signedIdentityKey" | "signalIdentities">) => {
8
7
  creds: Partial<AuthenticationCreds>;
9
8
  reply: BinaryNode;
10
9
  };
11
- export declare const encodeSignedDeviceIdentity: (account: proto.IADVSignedDeviceIdentity, includeSignatureKey: boolean) => Uint8Array;
10
+ export declare const encodeSignedDeviceIdentity: (account: proto.IADVSignedDeviceIdentity, includeSignatureKey: boolean) => Uint8Array<ArrayBufferLike>;