-
Notifications
You must be signed in to change notification settings - Fork 98
/
main.js
executable file
·381 lines (339 loc) · 12.6 KB
/
main.js
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
const EventEmitter = require('events');
const fs = require('fs');
const { getHostFromWebservice, cookiesToStr, parseCookieStr, fillCookies, newId, indexOfKey, fillMethods, fillDefaults} = require("./resources/helper");
Array.prototype.indexOfKey = indexOfKey;
class iCloud extends EventEmitter {
constructor(session = {}, username, password) {
super();
var self = this;
// LoggedIn is false because we can't be sure that the session is valid
self.loggedIn = false;
// enable push initially
self.enablePush = true;
// If the session argument is a string, it will be interpreted as a file path and the file will be read
if (typeof session === "string") {
// Set instances's sessionFile key to use it later as path
self.sessionFile = (" " + session).substring(1);
// Read the session file
fs.readFile(session, "utf8", function(err, contents) {
// If there was no error reading the file, set the session argument to the file's contents
if (!err) {
// Set session argument to the contents of the file
session = JSON.parse(contents);
// Continue with this session object as base
sessionInit(session);
}
else {
// If it was not possible to read the file, set the session to an empty object to work with it
session = {};
// Continue with the empty session
sessionInit(session);
}
});
}
else {
// The given session argument is actually an object literal, therefore there is no file to be read. Continue :)
sessionInit(session);
}
var currTopics = self.Setup.getPushTopics(self.apps);
function sessionInit(session) {
// Session Validation. This adds default properties to the session that doesn't exists
session = fillDefaults(session, {
username: username,
password: password,
auth: {
token: null,
xAppleTwosvTrustToken: null,
cookies: []
},
twoFactorAuthentication: false,
securityCode: null,
clientSettings: {
language: "en-us",
locale: "en_US",
xAppleWidgetKey: '83545bf919730e51dbfba24e7e8a78d2',
get ["xAppleIFDClientInfo"]() {
return {
"U": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/603.3.1 (KHTML, like Gecko) Version/10.1.2 Safari/603.3.1",
"L": session.clientSettings.locale,
"Z": "GMT+02:00",
"V": "1.1",
"F": ""
};
},
timezone: "US/Pacific",
clientBuildNumber: "2018Project35",
clientMasteringNumber: "2018B29",
defaultHeaders: {
'Referer': 'https://www.icloud.com/',
'Content-Type': 'text/plain',
'Origin': 'https://www.icloud.com',
'Host': '',
'Accept': '*/*',
'Connection': 'keep-alive',
get ["Accept-Language"]() {
return session.clientSettings.language;
},
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/604.1.25 (KHTML, like Gecko) Version/11.0 Safari/604.1.25',
'Cookie': '',
'X-Requested-With': "XMLHttpRequest"
}
},
clientId: self.Setup.getClientId(),
apps: self.apps,
push: {
topics: currTopics ? currTopics.filter((topic, index) => currTopics.indexOf(topic) == index) : [],
token: null,
ttl: 43200,
courierUrl: "",
registered: []
},
account: {},
logins: []
});
// Session object is validated. Now, the (self) instance will be extended with session's properties using the fill defaults function.
self = fillDefaults(self, session);
Object.keys(self.apps).forEach(function(appPropName) {
if ("instanceName" in self.apps[appPropName]) {
var service = require("./" + self.apps[appPropName].modulePath);
self[self.apps[appPropName].instanceName] = fillMethods({}, service, self);
}
});
// Now, validate the session with checking for important aspects that show that the session can be used to get data (e.g. there need to be a token, some cookies and account info)
self.loggedIn = (function() {
//console.log(self.auth.cookies.length > 0, !!self.auth.token, Object.keys(self.account).length > 0, self.username === username);
return ((self.auth.cookies.length > 0) && (self.auth.token && Object.keys(self.account).length > 0) && (username ? (self.username === username) : false));
})();
self.cookiesValid = (function() {
const timestamp = new Date().getTime();
// Get list of cookies, represented to a boolean value wether the cookie is expired or no
// ignore cookie wich is expiring in 1970 --> so no extra code auth, when starting app
const cookiesExpired = self.auth.cookies.map(function (cookie) {
if ('X-APPLE-WEBAUTH-HSA-LOGIN' in cookie && 'Expires' in cookie) {
return false;
} else {
return new Date(cookie.Expires).getTime() - timestamp < 0;
}
});
// If no cookie is expired, the array contains just 'false' keys
// Return wether there is no expired cookie (true)
return cookiesExpired.indexOf(true) === -1;
})();
// If the session is valid, the client is ready! Emit the 'ready' event of the (self) instance
if (self.loggedIn && self.cookiesValid) {
self.logins.push(new Date().getTime());
self.emit("ready");
}
// If not, the session is invalid: An error event occurs and username and password arguments will be used for logging in and creating a new session
else {
self.emit("err", {
error: "Session is expired or invalid",
errorCode: 6
});
// 'progress' event of login is fired because it's an automatic aspect of the algorithm that it tries to login if the session was invalid
self.emit("progress", {
action: "start",
parentAction: "login",
progress: 0,
message: "Trying to reset session and login"
});
// Login with username and password
self.login(self.username, self.password, function(err) {
if (err) {
// If an error ocurs, fire an 'error' event
// handle non-standard errors
if (err.error) {
return self.emit("err", err)
}
// otherwise, generic handling
return self.emit("err", {
error: "Account is broken or password and username are invalid",
errorCode: 7
});
}
self.username = username;
self.password = password;
self.auth.created = new Date().getTime();
self.logins.push(self.auth.created);
// Client is ready
self.emit("ready");
});
}
}
}
set securityCode(code) {
var self = this;
self.Setup.enterSecurityCode(self, code, function(result) {
if (!result) {
return self.emit("err", {
message: "Failed to enter security code",
code: 16
});
}
self.emit("ready");
});
self.__securityCode = code;
}
get securityCode() {
return this.__securityCode;
}
async sendSecurityCode(mode) {
if (mode === "sms") {
const { response, body } = await this.Setup.__securityPhone(this, "sms");
}
else if (mode === "voice") {
const { response, body } = await this.Setup.__securityPhone(this, "voice");
}
else {
const { response, body } = await this.Setup.__securityCode(this, null, "PUT");
}
}
get twoFactorAuthenticationIsRequired() {
return this.twoFactorAuthentication && !this.auth.xAppleTwosvTrustToken && !this.securityCode;
}
// Login method
login(account, password, callback) {
var self = this;
self.Setup.getAuthToken(account, password, self, function(err, authentification) {
if (err) return callback(err);
// Got token
self.auth.token = authentification.token;
self.clientSettings.xAppleIDSessionId = authentification.sessionID;
self.clientSettings.scnt = authentification.scnt;
// If two factor authentification is required
if (authentification.response.authType === "hsa2") {
// Set the 'twoFactorAuthentication' property to true to communicate this
self.twoFactorAuthentication = true;
self.emit("err", {
error: "Two-factor-authentication is required.",
code: 15
});
}
self.emit("progress", {
parentAction: "login",
action: "authToken",
progress: 1 / 3
});
self.Setup.accountLogin(self, function(err, result, response) {
if (err) return callback(err);
// Logged in
// Add result to instance
self.account = result;
// Parse cookies to objects
var cookies = parseCookieStr(response.headers["set-cookie"]);
self.auth.cookies = fillCookies(self.auth.cookies, cookies);
// Parse cookie objects to a cookie string array and join it to a single string
var cookiesStr = cookiesToStr(self.auth.cookies);
// Fire progress event
self.emit("progress", {
parentAction: "login",
action: "accountLogin",
progress: 2 / 3
});
self.loggedIn = true;
self.Setup.getPushToken(self, cookiesStr, function(err, token, url, cookies) {
if (err) return callback(err);
// Got push token.
self.push.token = token;
self.push.courierUrl = url;
self.emit("progress", {
parentAction: "login",
action: "pushToken",
progress: 3 / 3
});
callback(null, self);
self.emit("sessionUpdate");
});
});
});
//callback(null, "Hey you!");
}
registerPushService(service, callback = function() {}) {
var self = this;
self.Setup.registerPush(self, service, function(err, result) {
if (err) {
return callback(err);
}
self.push.registered.push(service);
self.emit("sessionUpdate");
callback(null, result);
});
}
initPush(callback = function () { }) {
// breaks the callback loop if we decide to disable push
if (!this.enablePush) {
this.enablePush = true;
return;
}
var self = this;
self.Setup.registerTopics(self, function(err, result) {
if (err) return console.error(err);
self.push.registered = self.push.registered.concat(result.registeredTopics);
});
for (let appName in self.apps) {
if (self.apps.hasOwnProperty(appName) && self.apps[appName].containerIdentifier) {
const customPushTopic = self.apps[appName];
this.registerPushService(customPushTopic.containerIdentifier);
}
}
self.Setup.initPush(self, function(err, result) {
if (err) {
self.emit("err", {
error: "Push token is expired. Getting new one...",
errorCode: 22
});
return self.Setup.getPushToken(self, cookiesToStr(self.auth.cookies), function(err, token, url, cookies) {
if (err) return callback(err);
// Got push token.
self.push.token = token;
self.push.courierUrl = url;
//callback(null, self);
self.initPush(callback);
self.emit("sessionUpdate");
});
}
// Push request is answered
self.emit("push", result);
self.initPush(callback);
});
}
deactivatePush() {
this.enablePush = false;
}
exportSession() {
// Export session as object
return {
username: this.username || null,
password: this.password || null,
twoFactorAuthentication: this.twoFactorAuthentication,
securityCode: this.__securityCode || null,
auth: this.auth,
clientId: this.clientId,
push: this.push,
account: this.account,
logins: this.logins,
clientSettings: this.clientSettings
}
}
saveSession(file = this.sessionFile) {
// If file argument is not given, try to use the source the session was read from (Only possible if given)
if (file) {
fs.writeFile(file, JSON.stringify(this.exportSession(), null, 2), (err) => {
if (err) return this.emit("error", err);
});
}
else {
return this.emit("err", {
error: "File path is invalid",
errorCode: 12
})
}
}
get Setup() {
return require("./setup");
}
get apps() {
return this.Setup.getApps();
}
}
module.exports = iCloud;