Path: blob/master/node_modules/@adiwajshing/baileys/lib/Utils/auth-utils.js
1129 views
"use strict";1Object.defineProperty(exports, "__esModule", { value: true });2exports.initAuthCreds = exports.addTransactionCapability = void 0;3const boom_1 = require("@hapi/boom");4const crypto_1 = require("crypto");5const crypto_2 = require("./crypto");6const generics_1 = require("./generics");7/**8* Adds DB like transaction capability (https://en.wikipedia.org/wiki/Database_transaction) to the SignalKeyStore,9* this allows batch read & write operations & improves the performance of the lib10* @param state the key store to apply this capability to11* @param logger logger to log events12* @returns SignalKeyStore with transaction capability13*/14const addTransactionCapability = (state, logger, { maxCommitRetries, delayBetweenTriesMs }) => {15let inTransaction = false;16// number of queries made to the DB during the transaction17// only there for logging purposes18let dbQueriesInTransaction = 0;19let transactionCache = {};20let mutations = {};21/**22* prefetches some data and stores in memory,23* useful if these data points will be used together often24* */25const prefetch = async (type, ids) => {26if (!inTransaction) {27throw new boom_1.Boom('Cannot prefetch without transaction');28}29const dict = transactionCache[type];30const idsRequiringFetch = dict ? ids.filter(item => !(item in dict)) : ids;31// only fetch if there are any items to fetch32if (idsRequiringFetch.length) {33dbQueriesInTransaction += 1;34const result = await state.get(type, idsRequiringFetch);35transactionCache[type] = Object.assign(transactionCache[type] || {}, result);36}37};38return {39get: async (type, ids) => {40if (inTransaction) {41await prefetch(type, ids);42return ids.reduce((dict, id) => {43var _a;44const value = (_a = transactionCache[type]) === null || _a === void 0 ? void 0 : _a[id];45if (value) {46dict[id] = value;47}48return dict;49}, {});50}51else {52return state.get(type, ids);53}54},55set: data => {56if (inTransaction) {57logger.trace({ types: Object.keys(data) }, 'caching in transaction');58for (const key in data) {59transactionCache[key] = transactionCache[key] || {};60Object.assign(transactionCache[key], data[key]);61mutations[key] = mutations[key] || {};62Object.assign(mutations[key], data[key]);63}64}65else {66return state.set(data);67}68},69isInTransaction: () => inTransaction,70prefetch: (type, ids) => {71logger.trace({ type, ids }, 'prefetching');72return prefetch(type, ids);73},74transaction: async (work) => {75// if we're already in a transaction,76// just execute what needs to be executed -- no commit required77if (inTransaction) {78await work();79}80else {81logger.trace('entering transaction');82inTransaction = true;83try {84await work();85if (Object.keys(mutations).length) {86logger.trace('committing transaction');87// retry mechanism to ensure we've some recovery88// in case a transaction fails in the first attempt89let tries = maxCommitRetries;90while (tries) {91tries -= 1;92try {93await state.set(mutations);94logger.trace({ dbQueriesInTransaction }, 'committed transaction');95break;96}97catch (error) {98logger.warn(`failed to commit ${Object.keys(mutations).length} mutations, tries left=${tries}`);99await (0, generics_1.delay)(delayBetweenTriesMs);100}101}102}103else {104logger.trace('no mutations in transaction');105}106}107finally {108inTransaction = false;109transactionCache = {};110mutations = {};111dbQueriesInTransaction = 0;112}113}114}115};116};117exports.addTransactionCapability = addTransactionCapability;118const initAuthCreds = () => {119const identityKey = crypto_2.Curve.generateKeyPair();120return {121noiseKey: crypto_2.Curve.generateKeyPair(),122signedIdentityKey: identityKey,123signedPreKey: (0, crypto_2.signedKeyPair)(identityKey, 1),124registrationId: (0, generics_1.generateRegistrationId)(),125advSecretKey: (0, crypto_1.randomBytes)(32).toString('base64'),126processedHistoryMessages: [],127nextPreKeyId: 1,128firstUnuploadedPreKeyId: 1,129accountSettings: {130unarchiveChats: false131}132};133};134exports.initAuthCreds = initAuthCreds;135136137