Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
jajbshjahavahh
GitHub Repository: jajbshjahavahh/Gojo-Satoru
Path: blob/master/node_modules/@adiwajshing/baileys/lib/LegacySocket/auth.js
2593 views
1
"use strict";
2
var __importDefault = (this && this.__importDefault) || function (mod) {
3
return (mod && mod.__esModule) ? mod : { "default": mod };
4
};
5
Object.defineProperty(exports, "__esModule", { value: true });
6
const boom_1 = require("@hapi/boom");
7
const events_1 = __importDefault(require("events"));
8
const Types_1 = require("../Types");
9
const Utils_1 = require("../Utils");
10
const socket_1 = require("./socket");
11
const makeAuthSocket = (config) => {
12
const { logger, version, browser, connectTimeoutMs, printQRInTerminal, auth: initialAuthInfo } = config;
13
const ev = new events_1.default();
14
const authInfo = initialAuthInfo || Utils_1.newLegacyAuthCreds();
15
const state = {
16
legacy: {
17
phoneConnected: false,
18
},
19
connection: 'connecting',
20
};
21
const socket = socket_1.makeSocket(config);
22
const { ws } = socket;
23
let curveKeys;
24
let initTimeout;
25
ws.on('phone-connection', ({ value: phoneConnected }) => {
26
updateState({ legacy: { ...state.legacy, phoneConnected } });
27
});
28
// add close listener
29
ws.on('ws-close', (error) => {
30
logger.info({ error }, 'closed connection to WhatsApp');
31
initTimeout && clearTimeout(initTimeout);
32
// if no reconnects occur
33
// send close event
34
updateState({
35
connection: 'close',
36
qr: undefined,
37
lastDisconnect: {
38
error,
39
date: new Date()
40
}
41
});
42
});
43
/** Can you login to WA without scanning the QR */
44
const canLogin = () => !!(authInfo === null || authInfo === void 0 ? void 0 : authInfo.encKey) && !!(authInfo === null || authInfo === void 0 ? void 0 : authInfo.macKey);
45
const updateState = (update) => {
46
Object.assign(state, update);
47
ev.emit('connection.update', update);
48
};
49
/**
50
* Logs you out from WA
51
* If connected, invalidates the credentials with the server
52
*/
53
const logout = async () => {
54
if (state.connection === 'open') {
55
await socket.sendNode({
56
json: ['admin', 'Conn', 'disconnect'],
57
tag: 'goodbye'
58
});
59
}
60
// will call state update to close connection
61
socket === null || socket === void 0 ? void 0 : socket.end(new boom_1.Boom('Logged Out', { statusCode: Types_1.DisconnectReason.loggedOut }));
62
};
63
const updateEncKeys = () => {
64
// update the keys so we can decrypt traffic
65
socket.updateKeys({ encKey: authInfo.encKey, macKey: authInfo.macKey });
66
};
67
const generateKeysForAuth = async (ref, ttl) => {
68
curveKeys = Utils_1.Curve.generateKeyPair();
69
const publicKey = Buffer.from(curveKeys.public).toString('base64');
70
let qrGens = 0;
71
const qrLoop = ttl => {
72
const qr = [ref, publicKey, authInfo.clientID].join(',');
73
updateState({ qr });
74
initTimeout = setTimeout(async () => {
75
var _a;
76
if (state.connection !== 'connecting') {
77
return;
78
}
79
logger.debug('regenerating QR');
80
try {
81
// request new QR
82
const { ref: newRef, ttl: newTTL } = await socket.query({
83
json: ['admin', 'Conn', 'reref'],
84
expect200: true,
85
longTag: true,
86
requiresPhoneConnection: false
87
});
88
ttl = newTTL;
89
ref = newRef;
90
}
91
catch (error) {
92
logger.error({ error }, 'error in QR gen');
93
if (((_a = error.output) === null || _a === void 0 ? void 0 : _a.statusCode) === 429) { // too many QR requests
94
socket.end(error);
95
return;
96
}
97
}
98
qrGens += 1;
99
qrLoop(ttl);
100
}, ttl || 20000); // default is 20s, on the off-chance ttl is not present
101
};
102
qrLoop(ttl);
103
};
104
const onOpen = async () => {
105
var _a, _b;
106
const canDoLogin = canLogin();
107
const initQuery = (async () => {
108
const { ref, ttl } = await socket.query({
109
json: ['admin', 'init', version, browser, authInfo.clientID, true],
110
expect200: true,
111
longTag: true,
112
requiresPhoneConnection: false
113
});
114
if (!canDoLogin) {
115
generateKeysForAuth(ref, ttl);
116
}
117
})();
118
let loginTag;
119
if (canDoLogin) {
120
updateEncKeys();
121
// if we have the info to restore a closed session
122
const json = [
123
'admin',
124
'login',
125
authInfo.clientToken,
126
authInfo.serverToken,
127
authInfo.clientID,
128
'takeover'
129
];
130
loginTag = socket.generateMessageTag(true);
131
// send login every 10s
132
const sendLoginReq = () => {
133
if (state.connection === 'open') {
134
logger.warn('Received login timeout req when state=open, ignoring...');
135
return;
136
}
137
logger.info('sending login request');
138
socket.sendNode({
139
json,
140
tag: loginTag
141
});
142
initTimeout = setTimeout(sendLoginReq, 10000);
143
};
144
sendLoginReq();
145
}
146
await initQuery;
147
// wait for response with tag "s1"
148
let response = await Promise.race([
149
socket.waitForMessage('s1', false, undefined).promise,
150
...(loginTag ? [socket.waitForMessage(loginTag, false, connectTimeoutMs).promise] : [])
151
]);
152
initTimeout && clearTimeout(initTimeout);
153
initTimeout = undefined;
154
if (response.status && response.status !== 200) {
155
throw new boom_1.Boom('Unexpected error in login', { data: response, statusCode: response.status });
156
}
157
// if its a challenge request (we get it when logging in)
158
if ((_a = response[1]) === null || _a === void 0 ? void 0 : _a.challenge) {
159
const json = Utils_1.computeChallengeResponse(response[1].challenge, authInfo);
160
logger.info('resolving login challenge');
161
await socket.query({ json, expect200: true, timeoutMs: connectTimeoutMs });
162
response = await socket.waitForMessage('s2', true).promise;
163
}
164
if (!response || !response[1]) {
165
throw new boom_1.Boom('Received unexpected login response', { data: response });
166
}
167
if (response[1].type === 'upgrade_md_prod') {
168
throw new boom_1.Boom('Require multi-device edition', { statusCode: Types_1.DisconnectReason.multideviceMismatch });
169
}
170
// validate the new connection
171
const { user, auth } = Utils_1.validateNewConnection(response[1], authInfo, curveKeys); // validate the connection
172
const isNewLogin = user.id !== ((_b = state.legacy.user) === null || _b === void 0 ? void 0 : _b.id);
173
Object.assign(authInfo, auth);
174
updateEncKeys();
175
logger.info({ user }, 'logged in');
176
ev.emit('creds.update', auth);
177
updateState({
178
connection: 'open',
179
legacy: {
180
phoneConnected: true,
181
user,
182
},
183
isNewLogin,
184
qr: undefined
185
});
186
};
187
ws.once('open', async () => {
188
try {
189
await onOpen();
190
}
191
catch (error) {
192
socket.end(error);
193
}
194
});
195
if (printQRInTerminal) {
196
Utils_1.printQRIfNecessaryListener(ev, logger);
197
}
198
process.nextTick(() => {
199
ev.emit('connection.update', {
200
...state
201
});
202
});
203
return {
204
...socket,
205
state,
206
authInfo,
207
ev,
208
canLogin,
209
logout,
210
/** Waits for the connection to WA to reach a state */
211
waitForConnectionUpdate: Utils_1.bindWaitForConnectionUpdate(ev)
212
};
213
};
214
exports.default = makeAuthSocket;
215
216