forked from makara-filip/ts-messenger-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
367 lines (331 loc) · 13.3 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
import { ApiCtx, ApiOptions, LoginCredentials, Dfs } from './lib/types';
import * as utils from './lib/utils';
import log, { LogLevels } from 'npmlog';
import Jar from './lib/jar';
import cheerio from 'cheerio';
import Api from './lib/api';
import { Response } from 'got';
const defaultLogRecordSize = 100;
/** Logs you into Facebook using given credentials and returns an `Api` instance.
*
* Login using email & password:
* ```typescript
* import facebookLogin from 'ts-messenger-api';
* const api = await facebookLogin({ email: '[email protected]', password: 'your_fb_password' }, {});
* ```
* Login using an `AppState` given from last login:
* ```typescript
* import facebookLogin from 'ts-messenger-api';
* import fs from 'fs';
* const api = await facebookLogin({ appState: JSON.parse(fs.readFileSync('path_to_file')) }, {});
* ```
*/
export default async function login(loginData: LoginCredentials, options: ApiOptions = {}): Promise<Api | undefined> {
const globalOptions: ApiOptions = {
selfListen: false,
listenEvents: false,
updatePresence: false,
forceLogin: false,
autoMarkDelivery: true,
autoMarkRead: false,
logRecordSize: defaultLogRecordSize,
userAgent:
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/600.3.18 (KHTML, like Gecko) Version/8.0.3 Safari/600.3.18'
};
setOptions(globalOptions, options);
//TODO: Add support for appState
return await loginHelper(loginData, globalOptions);
}
/** Sets `globalOptions` and npmlog based on the `options` attribute */
function setOptions(globalOptions: ApiOptions, options: ApiOptions): void {
Object.keys(options).map(function (key) {
switch (key) {
case 'logLevel':
log.level = options.logLevel as LogLevels;
globalOptions.logLevel = options.logLevel;
break;
case 'logRecordSize':
log.maxRecordSize = options.logRecordSize as number;
globalOptions.logRecordSize = options.logRecordSize;
break;
case 'selfListen':
globalOptions.selfListen = options.selfListen;
break;
case 'listenEvents':
globalOptions.listenEvents = options.listenEvents;
break;
case 'pageID':
globalOptions.pageID = options.pageID?.toString();
break;
case 'updatePresence':
globalOptions.updatePresence = options.updatePresence;
break;
case 'forceLogin':
globalOptions.forceLogin = options.forceLogin;
break;
case 'userAgent':
globalOptions.userAgent = options.userAgent;
break;
case 'autoMarkDelivery':
globalOptions.autoMarkDelivery = options.autoMarkDelivery;
break;
case 'autoMarkRead':
globalOptions.autoMarkRead = options.autoMarkRead;
break;
default:
log.warn('setOptions', 'Unrecognized option given to setOptions: ' + key);
break;
}
});
}
async function loginHelper(credentials: LoginCredentials, globalOptions: ApiOptions) {
let mainPromise: Promise<any>;
const jar = new Jar();
let ctx: ApiCtx;
let defaultFuncs: Dfs;
let api: Api | undefined;
// If we're given an appState we loop through it and save each cookie into the jar.
if (credentials.appState) {
credentials.appState.map(c =>
jar.setCookie(
`${c.key}=${c.value}; expires=${c.expires}; domain=${c.domain}; path=${c.path};`,
'http://' + c.domain
)
);
// Load the main page.
mainPromise = utils.get('https://www.facebook.com/', jar, null, globalOptions).then(utils.saveCookies(jar));
} else if (credentials.email && credentials.password) {
// Open the main page, then we login with the given credentials and finally
// load the main page again (it'll give us some IDs that we need)
mainPromise = utils
.get('https://m.facebook.com/', null, null, globalOptions)
.then(utils.saveCookies(jar))
.then(makeLogin(jar, credentials.email, credentials.password, globalOptions));
} else throw new Error('Argument error: you must specify AppState or email-password credentials');
mainPromise = mainPromise.then(async (res: Response<string>) => {
// Hacky check for the redirection that happens on some ISPs, which doesn't return statusCode 3xx
const reg = /<meta http-equiv="refresh" content="0;url=([^"]+)[^>]+>/;
const redirect = reg.exec(res.body);
if (redirect && redirect[1])
res = await utils.get(redirect[1], jar, null, globalOptions).then(utils.saveCookies(jar));
// Define global state
const stuff = buildAPI(globalOptions, res.body, jar);
ctx = stuff.ctx;
defaultFuncs = stuff.defaultFuncs; // TODO: remove the defaultFuncs, because they are already in the api
api = stuff.api;
const form = {
reason: 6
};
log.info('login', 'Request to reconnect');
await defaultFuncs
.get('https://www.facebook.com/ajax/presence/reconnect.php', ctx.jar, form)
.then(utils.saveCookies(ctx.jar));
const presence = utils.generatePresence(ctx.userID);
ctx.jar.setCookie('presence=' + presence + '; path=/; domain=.facebook.com; secure', 'https://www.facebook.com');
ctx.jar.setCookie('presence=' + presence + '; path=/; domain=.messenger.com; secure', 'https://www.messenger.com');
ctx.jar.setCookie('locale=en_US; path=/; domain=.facebook.com; secure', 'https://www.facebook.com');
ctx.jar.setCookie('locale=en_US; path=/; domain=.messenger.com; secure', 'https://www.messenger.com');
ctx.jar.setCookie(
'a11y=' + utils.generateAccessibilityCookie() + '; path=/; domain=.facebook.com; secure',
'https://www.facebook.com'
);
});
// given a pageID we log in as a page
if (globalOptions.pageID) {
mainPromise = mainPromise
.then(async () => {
return await utils.get(
'https://www.facebook.com/' + ctx.globalOptions.pageID + '/messages/?section=messages&subsection=inbox',
ctx.jar,
null,
globalOptions
);
})
.then(async (resData: Response<string>) => {
let url = utils
.getFrom(resData.body, 'window.location.replace("https:\\/\\/www.facebook.com\\', '");')
.split('\\')
.join('');
url = url.substring(0, url.length - 1);
return await utils.get('https://www.facebook.com' + url, ctx.jar, null, globalOptions);
});
}
await mainPromise;
log.info('login', 'Done logging in.');
return api;
}
function buildAPI(globalOptions: ApiOptions, html: string, jar: Jar) {
const userIdCookies = jar.getCookies('https://www.facebook.com').filter(cookie => cookie.key === 'c_user');
if (userIdCookies.length === 0) {
throw new Error(
'Error retrieving userID. This can be caused by a lot of things, including having wrong AppState credentials or getting blocked by Facebook for logging in from an unknown location. Try logging in with a browser to verify.'
);
}
const userID = userIdCookies[0].value;
log.info('login', 'Logged in');
const clientID = ((Math.random() * 2147483648) | 0).toString(16);
const $ = cheerio.load(html);
const fb_dtsg = $('input[name=fb_dtsg]')?.attr('value');
const jazoest = $('input[name=jazoest]')?.attr('value');
// All data available to api functions
const ctx: ApiCtx = {
userID: userID,
jar: jar,
clientID: clientID,
globalOptions: globalOptions,
loggedIn: true,
access_token: 'NONE',
clientMutationId: 0,
mqttClient: undefined,
lastSeqId: 0,
syncToken: undefined,
fb_dtsg,
jazoest
};
const defaultFuncs: Dfs = utils.makeDefaults(html, userID, ctx);
const api = new Api(defaultFuncs, ctx);
return { ctx, defaultFuncs, api };
}
/** Magic function */
function makeLogin(jar: Jar, email: string, password: string, loginOptions: ApiOptions) {
return async (res: Response<string>) => {
const html: string = res.body;
const $ = cheerio.load(html);
const jazoest = $('input[name=jazoest]').attr('value');
const lsd = $('input[name=lsd]').attr('value');
const publicKeyDataString = utils.getFrom(html, 'pubKeyData:', '}') + '}';
const publicKeyData = {
publicKey: utils.getFrom(publicKeyDataString, 'publicKey:"', '"'),
keyId: utils.getFrom(publicKeyDataString, 'keyId:', '}')
};
// in newer versions of Facebook, encrypted password is being used
// (even Instagram uses the same technique to send password during login)
const currentTime = Math.floor(Date.now() / 1000).toString();
const form = {
jazoest,
lsd,
email,
login_source: 'comet_headerless_login',
next: '',
// eslint-disable-next-line @typescript-eslint/no-var-requires
encpass: `#PWD_BROWSER:5:${currentTime}:${await require('./lib/passwordHasher.js')(
publicKeyData,
currentTime,
password
)}`
};
const loginUrl = `https://www.facebook.com/login/?privacy_mutation_token=${Buffer.from(
`{"type":0,"creation_time":${currentTime},"callsite_id":381229079575946}`
).toString('base64')}`;
// Getting cookies from the HTML page... (kill me now plz)
// we used to get a bunch of cookies in the headers of the response of the
// request, but FB changed and they now send those cookies inside the JS.
// They run the JS which then injects the cookies in the page.
// The "solution" is to parse through the html and find those cookies
// which happen to be conveniently indicated with a _js_ in front of their
// variable name.
//
// ---------- Very Hacky Part Starts -----------------
const willBeCookies: string[] = html.split('"_js_');
willBeCookies.slice(1).map(function (val) {
const cookieData = JSON.parse('["' + utils.getFrom(val, '', ']') + ']');
jar.setCookie(utils.formatCookie(cookieData, 'facebook'), 'https://www.facebook.com');
});
// ---------- Very Hacky Part Ends -----------------
log.info('login', 'Logging in...');
return await utils.post(loginUrl, jar, form, loginOptions).then(async (res: Response<string>) => {
utils.saveCookies(jar)(res);
const headers = res.headers;
// Facebook used to put "location" response header when the password was correct,
// now they do it differently - they change "window.location" in a script
if (!res.body.includes('window.location.replace')) throw { error: 'Wrong username/password.' };
const redirect = utils.getFrom(res.body, 'window.location.replace("', '")');
log.info('login', `Redirected to ${redirect}`);
// This means the account has login approvals turned on.
if (headers.location && headers.location.indexOf('https://www.facebook.com/checkpoint/') > -1) {
log.info('login', 'You have login approvals turned on.');
const nextURL = 'https://www.facebook.com/checkpoint/?next=https%3A%2F%2Fwww.facebook.com%2Fhome.php';
return await utils
.get(headers.location, jar, null, loginOptions)
.then(utils.saveCookies(jar))
.then(async (res: any) => {
const html = res.body;
// Make the form in advance which will contain the fb_dtsg and nh
const $ = cheerio.load(html);
let arr: any[] = [];
$('form input').map(function (i, v) {
arr.push({ val: $(v).val(), name: $(v).attr('name') });
});
arr = arr.filter(function (v) {
return v.val && v.val.length;
});
const form = utils.arrToForm(arr);
if (html.indexOf('checkpoint/?next') > -1) {
throw {
error: 'login-approval',
continue: async (code: string) => {
form.approvals_code = code;
form['submit[Continue]'] = 'Continue';
return await utils
.post(nextURL, jar, form, loginOptions)
.then(utils.saveCookies(jar))
.then(async () => {
// Use the same form (safe I hope)
form.name_action_selected = 'save_device';
return await utils.post(nextURL, jar, form, loginOptions).then(utils.saveCookies(jar));
})
.then(async (res: any) => {
const headers = res.headers;
if (!headers.location && res.body.indexOf('Review Recent Login') > -1) {
throw { error: 'Something went wrong with login approvals.' };
}
const appState = utils.getAppState(jar);
// Simply call loginHelper because all it needs is the jar
// and will then complete the login process
return await loginHelper({ email, password }, loginOptions);
})
.catch((err: any) => {
throw err;
});
}
};
} else {
if (!loginOptions.forceLogin) {
throw {
error:
"Couldn't login. Facebook might have blocked this account. Please login with a browser or enable the option 'forceLogin' and try again."
};
}
if (html.indexOf('Suspicious Login Attempt') > -1) {
form['submit[This was me]'] = 'This was me';
} else {
form['submit[This Is Okay]'] = 'This Is Okay';
}
return await utils
.post(nextURL, jar, form, loginOptions)
.then(utils.saveCookies(jar))
.then(async () => {
// Use the same form (safe I hope)
form.name_action_selected = 'save_device';
return await utils.post(nextURL, jar, form, loginOptions).then(utils.saveCookies(jar));
})
.then(async (res: any) => {
const headers = res.headers;
if (!headers.location && res.body.indexOf('Review Recent Login') > -1) {
throw { error: 'Something went wrong with review recent login.' };
}
const appState = utils.getAppState(jar);
// Simply call loginHelper because all it needs is the jar
// and will then complete the login process
return await loginHelper({ email, password }, loginOptions);
})
.catch((e: any) => {
throw e;
});
}
});
}
return utils.get('https://www.facebook.com/', jar, null, loginOptions).then(utils.saveCookies(jar));
});
};
}