-
-
Notifications
You must be signed in to change notification settings - Fork 155
/
08-logon.js
662 lines (545 loc) · 20.7 KB
/
08-logon.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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
const ByteBuffer = require('bytebuffer');
const Crypto = require('crypto');
const StdLib = require('@doctormckay/stdlib');
const SteamID = require('steamid');
const Helpers = require('./helpers.js');
const Schema = require('../protobufs/generated/_load.js');
const TCPConnection = require('./connection_protocols/tcp.js');
const WebSocketConnection = require('./connection_protocols/websocket.js');
const EConnectionProtocol = require('../resources/EConnectionProtocol.js');
const EMachineIDType = require('../resources/EMachineIDType.js');
const EMsg = require('../enums/EMsg.js');
const EResult = require('../enums/EResult.js');
const SteamUserBase = require('./00-base.js');
const SteamUserWeb = require('./07-web.js');
const PROTOCOL_VERSION = 65580;
const PRIVATE_IP_OBFUSCATION_MASK = 0xbaadf00d;
class SteamUserLogon extends SteamUserWeb {
logOn(details) {
// Delay the actual logon by one tick, so if users call logOn from the error event they won't get a crash because
// they appear to be already logged on (the steamID property is set to null only *after* the error event is emitted)
process.nextTick(async () => {
if (this.steamID) {
throw new Error('Already logged on, cannot log on again');
}
this.steamID = null;
this._initProperties();
this._loggingOff = false;
if (details !== true) {
// We're not logging on with saved details
details = details || {};
let logonId = details.logonID;
if (logonId) {
let maxUint32 = Math.pow(2, 32) - 1;
if (typeof logonId == 'string' && logonId.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/)) {
logonId = StdLib.IPv4.stringToInt(logonId) ^ PRIVATE_IP_OBFUSCATION_MASK;
} else if (typeof logonId == 'number' && logonId > maxUint32) {
this._warn(`logonID ${details.logonID} is greater than ${maxUint32} and has been truncated.`);
logonId = maxUint32;
}
}
this._logOnDetails = {
account_name: details.accountName,
password: details.password,
login_key: details.loginKey,
auth_code: details.authCode,
two_factor_code: details.twoFactorCode,
should_remember_password: !!details.rememberPassword,
obfuscated_private_ip: {v4: logonId || 0},
protocol_version: PROTOCOL_VERSION,
supports_rate_limit_response: !!details.accountName,
machine_name: details.accountName ? (details.machineName || '') : '',
ping_ms_from_cell_search: details.accountName ? 4 + Math.floor(Math.random() * 30) : 0, // fake ping value
client_language: details.accountName ? 'english' : '',
client_os_type: Number.isInteger(details.clientOS) ? details.clientOS : Helpers.getOsType(),
anon_user_target_account_name: details.accountName ? '' : 'anonymous',
steamguard_dont_remember_computer: !!(details.accountName && details.authCode && details.dontRememberMachine),
ui_mode: undefined,
chat_mode: 2, // enable new chat
web_logon_nonce: details.webLogonToken && details.steamID ? details.webLogonToken : undefined,
_steamid: details.steamID
};
}
if (this._logOnDetails.web_logon_nonce) {
this._logOnDetails.client_os_type = 4294966596;
this._logOnDetails.ui_mode = 4;
delete this._logOnDetails.obfuscated_private_ip;
delete this._logOnDetails.cell_id;
delete this._logOnDetails.client_language;
delete this._logOnDetails.should_remember_password;
delete this._logOnDetails.ping_ms_from_cell_search;
delete this._logOnDetails.machine_id;
delete this._logOnDetails.password;
delete this._logOnDetails.login_key;
delete this._logOnDetails.sha_sentryfile;
delete this._logOnDetails.auth_code;
delete this._logOnDetails.steamguard_dont_remember_computer;
delete this._logOnDetails.machine_name;
delete this._logOnDetails.machine_name_userchosen;
delete this._logOnDetails.two_factor_code;
delete this._logOnDetails.supports_rate_limit_response;
}
let anonLogin = !this._logOnDetails.account_name;
// Read the required files
let filenames = [];
if (!this._cmList) {
filenames.push('cm_list.json');
}
if (!this._logOnDetails.cell_id) {
// Some people might be redirecting their storage to a database and running across multiple servers in multiple regions
// Let's account for this by saving cellid by a "machine ID" so different boxes will store different cellids
filenames.push('cellid-' + Helpers.getInternalMachineID() + '.txt');
}
let sentry = this._sentry;
let machineID;
if (!anonLogin) {
if (!this._logOnDetails.sha_sentryfile && !sentry) {
filenames.push(this.options.singleSentryfile ? 'sentry.bin' : 'sentry.' + this._logOnDetails.account_name + '.bin');
}
if (!this._logOnDetails.machine_id && this.options.machineIdType == EMachineIDType.PersistentRandom) {
filenames.push('machineid.bin');
}
}
let files = await this._readFiles(filenames);
files.forEach((file) => {
if (file.filename == 'cm_list.json' && file.contents) {
try {
this._cmList = JSON.parse(file.contents.toString('utf8'));
} catch (e) {
// don't care
}
}
if (file.filename.match(/^cellid/) && file.contents) {
let cellID = parseInt(file.contents.toString('utf8'), 10);
if (!isNaN(cellID)) {
this._logOnDetails.cell_id = cellID;
}
}
if (file.filename.match(/^sentry/) && file.contents) {
sentry = file.contents;
}
if (file.filename == 'machineid.bin' && file.contents) {
machineID = file.contents;
}
});
if (!this._cmList || !this._cmList.time || Date.now() - this._cmList.time > (1000 * 60 * 60 * 24 * 7)) {
// CM list is out of date (more than 7 days old, or doesn't exist). Let's grab a new copy from the WebAPI
this.emit('debug', 'Getting CM list from WebAPI');
try {
let res = await this._apiRequest('GET', 'ISteamDirectory', 'GetCMList', 1, {cellid: this._logOnDetails.cell_id || 0});
this._cmList = {
tcp_servers: Helpers.fixVdfArray(res.response.serverlist),
websocket_servers: Helpers.fixVdfArray(res.response.serverlist_websockets),
time: Date.now()
};
this._saveCMList();
} catch (ex) {
this.emit('debug', `WebAPI error getting CMList: ${ex.message}`);
}
}
if (!this._cmList) {
// Get built-in list as a last resort
this._cmList = require('../resources/servers.json');
}
// Sentry file
if (!this._logOnDetails.sha_sentryfile) {
if (sentry && sentry.length > 20) {
// Hash the sentry
let hash = Crypto.createHash('sha1');
hash.update(sentry);
sentry = hash.digest();
}
this._logOnDetails.sha_sentryfile = sentry;
this._logOnDetails.eresult_sentryfile = sentry ? 1 : 0;
}
// Machine ID
if (!anonLogin && !this._logOnDetails.machine_id) {
this._logOnDetails.machine_id = this._getMachineID(machineID);
}
// Do the login
if (this._logOnDetails._steamid) {
let sid = this._logOnDetails._steamid;
if (typeof sid == 'string') {
sid = new SteamID(sid);
}
this._tempSteamID = sid;
} else {
let sid = new SteamID();
sid.universe = SteamID.Universe.PUBLIC;
sid.type = anonLogin ? SteamID.Type.ANON_USER : SteamID.Type.INDIVIDUAL;
sid.instance = anonLogin ? SteamID.Instance.ALL : SteamID.Instance.DESKTOP;
sid.accountid = 0;
this._tempSteamID = sid;
}
if (anonLogin && (this._logOnDetails.password || this._logOnDetails.login_key)) {
this._warn('Logging into anonymous Steam account but a password was specified... did you specify your accountName improperly?');
}
this._doConnection();
});
}
/**
* @private
*/
_doConnection() {
let thisProtocol = this.options.webCompatibilityMode ? EConnectionProtocol.WebSocket : this.options.protocol;
if (thisProtocol == EConnectionProtocol.Auto) {
if (this._cmList.auto_pct_websocket) {
let roll = Math.floor(Math.random() * 100);
thisProtocol = roll <= this._cmList.auto_pct_websocket ? EConnectionProtocol.WebSocket : EConnectionProtocol.TCP;
this.emit('debug', 'Using ' + (thisProtocol == EConnectionProtocol.WebSocket ? 'WebSocket' : 'TCP') + '; we rolled ' + roll + ' and percent to use WS is ' + this._cmList.auto_pct_websocket);
} else {
thisProtocol = EConnectionProtocol.TCP;
}
}
switch (thisProtocol) {
case EConnectionProtocol.TCP:
this._connection = new TCPConnection(this);
break;
case EConnectionProtocol.WebSocket:
this._connection = new WebSocketConnection(this);
break;
default:
throw new Error('Unknown connection protocol: ' + this.options.protocol);
}
}
/**
* Send the actual ClientLogOn message.
* @private
*/
_sendLogOn() {
// Realistically, this should never need to elapse since at this point we have already established a successful connection
// with the CM. But sometimes, Steam appears to never respond to the logon message. Valve.
this._logonMsgTimeout = setTimeout(() => {
this.emit('debug', 'Logon message timeout elapsed. Attempting relog.');
this._disconnect(true);
this._enqueueLogonAttempt();
}, 5000);
this._send(this._logOnDetails.game_server_token ? EMsg.ClientLogonGameServer : EMsg.ClientLogon, this._logOnDetails);
}
/**
* Enqueue another logon attempt.
* Used after we get ServiceUnavailable, TryAnotherCM, or a timeout waiting for ClientLogOnResponse.
* @private
*/
_enqueueLogonAttempt() {
let timer = this._logonTimeoutDuration || 1000;
this._logonTimeoutDuration = Math.min(timer * 2, 60000); // exponential backoff, max 1 minute
this._logonTimeout = setTimeout(() => {
this.logOn(true);
}, timer);
}
/**
* Log off of Steam gracefully.
*/
logOff() {
this._disconnect(false);
}
/**
* Disconnect from Steam
* @param {boolean} suppressLogoff - If true, just disconnect immediately without sending a logoff message.
* @private
*/
_disconnect(suppressLogoff) {
this._clearChangelistUpdateTimer();
clearTimeout(this._logonTimeout); // cancel any queued reconnect attempt
clearTimeout(this._logonMsgTimeout);
this._incomingMessageQueue = []; // clear the incoming message queue. If we're disconnecting, we don't care about anything else in the queue.
this.emit('debug', 'Disconnecting' + (suppressLogoff ? ' without sending logoff' : ''));
if (this.steamID && !suppressLogoff) {
this._loggingOff = true;
this._send(EMsg.ClientLogOff, {});
let timeout = setTimeout(() => {
this.emit('disconnected', 0, "Logged off");
this._loggingOff = false;
this._connection && this._connection.end(true);
this.steamID = null;
}, 4000);
this.once('disconnected', (eresult) => {
clearTimeout(timeout);
this.steamID = null;
});
} else {
this._connection && this._connection.end(true);
this.steamID = null;
}
}
/**
* @param {Buffer} [localFile]
* @returns {null|Buffer}
* @private
*/
_getMachineID(localFile) {
if (!this._logOnDetails.account_name || this.options.machineIdType == EMachineIDType.None) {
// No machine IDs for anonymous logons
return null;
}
// The user wants to use a random machine ID that's saved to dataDirectory
if (this.options.machineIdType == EMachineIDType.PersistentRandom) {
if (localFile) {
return localFile;
}
let file = getRandomID();
this._saveFile('machineid.bin', file);
return file;
}
// The user wants to use a machine ID that's generated off the account name
if (this.options.machineIdType == EMachineIDType.AccountNameGenerated) {
return createMachineID(
this.options.machineIdFormat[0].replace(/\{account_name\}/g, this._logOnDetails.account_name),
this.options.machineIdFormat[1].replace(/\{account_name\}/g, this._logOnDetails.account_name),
this.options.machineIdFormat[2].replace(/\{account_name\}/g, this._logOnDetails.account_name)
);
}
// Default to random
return getRandomID();
function getRandomID() {
return createMachineID(Math.random().toString(), Math.random().toString(), Math.random().toString());
}
}
/**
* @private
*/
_saveCMList() {
if (!this._cmList) {
return;
}
this._saveFile('cm_list.json', JSON.stringify(this._cmList, null, "\t"));
}
relog() {
if (!this.steamID) {
throw new Error("Cannot relog if not already connected");
}
if (this.steamID.type == SteamID.Type.INDIVIDUAL && (!this._logOnDetails || !this._logOnDetails.should_remember_password || !this._logOnDetails.login_key)) {
throw new Error("To use relog(), you must specify rememberPassword=true when logging on and wait for loginKey to be emitted");
}
this._relogging = true;
this.logOff();
}
/**
* @param {number} result
* @param {string} msg
* @private
*/
_handleLogOff(result, msg) {
let fatal = true;
let nonFatalLogOffResults = [
0,
EResult.Fail,
EResult.NoConnection,
EResult.ServiceUnavailable,
EResult.TryAnotherCM
];
if (this.options.autoRelogin && nonFatalLogOffResults.includes(result)) {
fatal = false;
}
delete this.publicIP;
delete this.cellID;
this.contentServersReady = false;
this._jobCleanupTimers.forEach(timer => clearTimeout(timer));
this._initProperties();
this._clearChangelistUpdateTimer();
clearInterval(this._heartbeatInterval);
if (!this._relogging && fatal && !this._loggingOff) {
let e = new Error(msg);
e.eresult = result;
let steamID = this.steamID;
this._disconnect(true);
this.steamID = steamID;
this.emit('error', e);
this.steamID = null;
} else {
// Only emit "disconnected" if we were previously logged on
if (this.steamID) {
this.emit('disconnected', result, msg);
}
this._disconnect(true);
// if we're manually relogging, or we got disconnected because steam went down, enqueue a reconnect
if (!this._loggingOff || this._relogging) {
this._logonTimeout = setTimeout(() => {
this.logOn(true);
}, 1000);
}
this._loggingOff = false;
this._relogging = false;
this.steamID = null;
}
}
/**
* @param {string} domain
* @param {boolean} lastCodeWrong
* @param {function} callback
* @private
*/
_steamGuardPrompt(domain, lastCodeWrong, callback) {
if (this.listenerCount('steamGuard') == 0) {
// No steamGuard listeners, so prompt for one from stdin
let rl = require('readline').createInterface({
"input": process.stdin,
"output": process.stdout
});
rl.question('Steam Guard' + (!domain ? ' App' : '') + ' Code: ', function(code) {
rl.close();
callback(code);
});
} else {
this.emit('steamGuard', domain, callback, lastCodeWrong);
}
}
}
// Handlers
SteamUserBase.prototype._handlerManager.add(EMsg.ClientLogOnResponse, function(body) {
clearTimeout(this._logonMsgTimeout);
delete this._logonMsgTimeout;
switch (body.eresult) {
case EResult.OK:
delete this._logonTimeoutDuration; // success, so reset reconnect timer
this._logOnDetails.last_session_id = this._sessionID;
this._logOnDetails.client_instance_id = body.client_instance_id;
this._logOnDetails.cell_id = body.cell_id;
delete this._logOnDetails.auth_code;
delete this._logOnDetails.two_factor_code;
this.logOnResult = body;
this.publicIP = null;
if (body.public_ip && body.public_ip.v4) {
this.publicIP = StdLib.IPv4.intToString(body.public_ip.v4);
}
this.cellID = body.cell_id;
this.vanityURL = body.vanity_url;
this.contentServersReady = true;
this._connectTime = Date.now();
this._connectTimeout = 1000; // reset exponential connect backoff
if (this._logOnDetails.login_key) {
// Steam doesn't send a new loginkey all the time if you're using a persistent one (remember password). Let's manually emit it on a timer to handle any edge cases.
this._loginKeyTimer = setTimeout(() => {
this.emit('loginKey', this._logOnDetails.login_key);
}, 5000);
}
this._saveFile('cellid-' + Helpers.getInternalMachineID() + '.txt', body.cell_id);
let parental = body.parental_settings ? SteamUserLogon._decodeProto(Schema.ParentalSettings, body.parental_settings) : null;
if (parental && parental.salt && parental.passwordhash) {
let sid = new SteamID();
sid.universe = this.steamID.universe;
sid.type = SteamID.Type.INDIVIDUAL;
sid.instance = SteamID.Instance.DESKTOP;
sid.accountid = parental.steamid.low;
parental.steamid = sid;
}
if (!this.steamID && body.client_supplied_steamid) {
// This should ordinarily not happen. this.steamID is supposed to be set in messages.js according to
// the SteamID in the message header. But apparently, sometimes Steam doesn't set that SteamID
// appropriately in the log on response message. ¯\_(ツ)_/¯
this.steamID = new SteamID(body.client_supplied_steamid);
}
if (!this.steamID) {
// This should never happen, but apparently sometimes it does
this._disconnect(true);
let err = new Error('BadResponse');
err.eresult = EResult.BadResponse;
this.emit('error', err);
return;
}
this.emit('loggedOn', body, parental);
this.emit('contentServersReady');
this._getChangelistUpdate();
if (this.steamID.type == SteamID.Type.INDIVIDUAL) {
this._requestNotifications();
if (body.webapi_authenticate_user_nonce) {
this._webAuthenticate(body.webapi_authenticate_user_nonce);
}
} else if (this.steamID.type == SteamID.Type.ANON_USER) {
this._getLicenseInfo();
}
this._heartbeatInterval = setInterval(() => {
this._send(EMsg.ClientHeartBeat, {});
}, body.out_of_game_heartbeat_seconds * 1000);
break;
case EResult.AccountLogonDenied:
case EResult.AccountLoginDeniedNeedTwoFactor:
case EResult.TwoFactorCodeMismatch:
// server is up, so reset logon timer
delete this._logonTimeoutDuration;
this._disconnect(true);
let isEmailCode = body.eresult == EResult.AccountLogonDenied;
let lastCodeWrong = body.eresult == EResult.TwoFactorCodeMismatch;
this._steamGuardPrompt(isEmailCode ? body.email_domain : null, lastCodeWrong, (code) => {
this._logOnDetails[isEmailCode ? 'auth_code' : 'two_factor_code'] = code;
this.logOn(true);
});
break;
case EResult.Fail:
case EResult.ServiceUnavailable:
case EResult.TryAnotherCM:
this.emit('debug', 'Log on response: ' + EResult[body.eresult]);
this._disconnect(true);
this._enqueueLogonAttempt();
break;
default:
// server is up, so reset logon timer
delete this._logonTimeoutDuration;
let error = new Error(EResult[body.eresult] || body.eresult);
error.eresult = body.eresult;
this._disconnect(true);
this.emit('error', error);
}
});
SteamUserBase.prototype._handlerManager.add(EMsg.ClientLoggedOff, function(body) {
let msg = body.eresult;
for (let i in EResult) {
if (EResult.hasOwnProperty(i) && EResult[i] == body.eresult) {
msg = i;
break;
}
}
this.emit('debug', 'Logged off: ' + msg);
this._handleLogOff(body.eresult, msg);
});
SteamUserBase.prototype._handlerManager.add(EMsg.ClientNewLoginKey, function(body) {
if (this.steamID.type == SteamID.Type.INDIVIDUAL) {
delete this._logOnDetails.password;
this._logOnDetails.login_key = body.login_key;
if (this._loginKeyTimer) {
clearTimeout(this._loginKeyTimer);
}
if (this._logOnDetails.should_remember_password) {
this.emit('loginKey', body.login_key);
}
// Accept the key
this._send(EMsg.ClientNewLoginKeyAccepted, {"unique_id": body.unique_id});
}
});
SteamUserBase.prototype._handlerManager.add(EMsg.ClientCMList, function(body) {
this.emit('debug', `Got list of ${(body.cm_websocket_addresses || []).length} WebSocket CMs, with percentage to use at ${body.percent_default_to_websocket || 0}%`);
this._cmList = {
tcp_servers: (body.cm_addresses || []).map((addr, idx) => StdLib.IPv4.intToString(addr) + ':' + body.cm_ports[idx]),
websocket_servers: body.cm_websocket_addresses || [],
auto_pct_websocket: body.percent_default_to_websocket,
time: Date.now()
};
this._saveCMList();
});
// Private functions
function createMachineID(val_bb3, val_ff2, val_3b3) {
// Machine IDs are binary KV objects with root key MessageObject and three hashes named BB3, FF2, and 3B3.
// I don't feel like writing a proper BinaryKV serializer, so this will work fine.
let buffer = ByteBuffer.allocate(155, ByteBuffer.LITTLE_ENDIAN);
buffer.writeByte(0); // 1 byte, total 1
buffer.writeCString("MessageObject"); // 14 bytes, total 15
buffer.writeByte(1); // 1 byte, total 16
buffer.writeCString("BB3"); // 4 bytes, total 20
buffer.writeCString(sha1(val_bb3)); // 41 bytes, total 61
buffer.writeByte(1); // 1 byte, total 62
buffer.writeCString("FF2"); // 4 bytes, total 66
buffer.writeCString(sha1(val_ff2)); // 41 bytes, total 107
buffer.writeByte(1); // 1 byte, total 108
buffer.writeCString("3B3"); // 4 bytes, total 112
buffer.writeCString(sha1(val_3b3)); // 41 bytes, total 153
buffer.writeByte(8); // 1 byte, total 154
buffer.writeByte(8); // 1 byte, total 155
return buffer.flip().toBuffer();
function sha1(input) {
let hash = Crypto.createHash('sha1');
hash.update(input, 'utf8');
return hash.digest('hex');
}
}
module.exports = SteamUserLogon;