Use IAuthenticationService for login, account migrations, other major refactors (#194)

fixes #193
fixes #192  
fixes #107

- [x] Implement the new login process
    - [x] Tested
- [x] Update the authenticator setup process
    - [x] Tested
- [x] Update the authenticator remove process
    - [x] Tested
- [x] Manifest format migrator
    - [x] Tested
- [x] Make it possible to import SDA accounts
- [x] Make sure confirmations still work
    - [x] Fetching
    - [x] Responding
- [x] Make it so that the login process doesn't prompt for which method
to use
- [x] Make it so that device confirmation and email confirmation auth
session guards work
This commit is contained in:
Carson McManus 2023-06-22 16:20:15 -04:00 committed by GitHub
parent 75fcf3c456
commit bfd0667f3a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
42 changed files with 5825 additions and 889 deletions

185
Cargo.lock generated
View file

@ -463,6 +463,12 @@ version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a68a4904193147e0a8dec3314640e6db742afd5f6e634f428a6af230d9b3591"
[[package]]
name = "either"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7fcaabb2fef8c910e7f4c7ce9f67a1283a1715879a7c230ca9d6d1ae31f16d91"
[[package]]
name = "encoding_rs"
version = "0.8.31"
@ -590,6 +596,16 @@ dependencies = [
"version_check",
]
[[package]]
name = "gethostname"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0176e0459c2e4a1fe232f984bca6890e681076abb9934f6cea7c326f3fc47818"
dependencies = [
"libc",
"windows-targets",
]
[[package]]
name = "getopts"
version = "0.2.21"
@ -843,9 +859,9 @@ dependencies = [
[[package]]
name = "libc"
version = "0.2.126"
version = "0.2.146"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "349d5a591cd28b49e1d1037471617a32ddcda5731b99419008085f72d5a53836"
checksum = "f92be4933c13fd498862a9e02a3055f8a8d9c039ce33db97306fd5a6caa7f29b"
[[package]]
name = "libm"
@ -916,6 +932,16 @@ version = "0.3.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a60c7ce501c71e03a9c9c0d35b861413ae925bd979cc7a4e30d060069aaac8d"
[[package]]
name = "mime_guess"
version = "2.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4192263c238a5f0d0c6bfd21f336a313a4ce1c450542449ca191bb657b4642ef"
dependencies = [
"mime",
"unicase",
]
[[package]]
name = "miniz_oxide"
version = "0.5.3"
@ -1261,6 +1287,68 @@ dependencies = [
"tempfile",
]
[[package]]
name = "protobuf"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b55bad9126f378a853655831eb7363b7b01b81d19f8cb1218861086ca4a1a61e"
dependencies = [
"once_cell",
"protobuf-support",
"thiserror",
]
[[package]]
name = "protobuf-codegen"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0dd418ac3c91caa4032d37cb80ff0d44e2ebe637b2fb243b6234bf89cdac4901"
dependencies = [
"anyhow",
"once_cell",
"protobuf",
"protobuf-parse",
"regex",
"tempfile",
"thiserror",
]
[[package]]
name = "protobuf-json-mapping"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce19fee00c35e62179f79d622f440c27466c9f8dff68ca907d8f59dfc8a88adb"
dependencies = [
"protobuf",
"protobuf-support",
"thiserror",
]
[[package]]
name = "protobuf-parse"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d39b14605eaa1f6a340aec7f320b34064feb26c93aec35d6a9a2272a8ddfa49"
dependencies = [
"anyhow",
"indexmap",
"log",
"protobuf",
"protobuf-support",
"tempfile",
"thiserror",
"which",
]
[[package]]
name = "protobuf-support"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5d4d7b8601c814cfb36bcebb79f0e61e45e1e93640cf778837833bbed05c372"
dependencies = [
"thiserror",
]
[[package]]
name = "psl-types"
version = "2.0.10"
@ -1516,6 +1604,7 @@ dependencies = [
"lazy_static 1.4.0",
"log",
"mime",
"mime_guess",
"percent-encoding",
"pin-project-lite",
"proc-macro-hack",
@ -1955,6 +2044,9 @@ dependencies = [
"lazy_static 1.4.0",
"log",
"maplit",
"protobuf",
"protobuf-codegen",
"protobuf-json-mapping",
"rand 0.8.5",
"regex",
"reqwest",
@ -1982,6 +2074,7 @@ dependencies = [
"cookie 0.14.4",
"crossterm",
"dirs",
"gethostname",
"hmac-sha1",
"lazy_static 1.4.0",
"log",
@ -1993,6 +2086,7 @@ dependencies = [
"ring",
"rpassword",
"rsa",
"secrecy",
"serde",
"serde_json",
"standback",
@ -2326,6 +2420,15 @@ version = "1.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dcf81ac59edc17cc8697ff311e8f5ef2d99fcbd9817b34cec66f90b6c3dfd987"
[[package]]
name = "unicase"
version = "2.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50f37be617794602aabbeee0be4f259dc1778fabe05e2d67ee8f79326d5cb4f6"
dependencies = [
"version_check",
]
[[package]]
name = "unicode-bidi"
version = "0.3.8"
@ -2545,6 +2648,17 @@ dependencies = [
"webpki",
]
[[package]]
name = "which"
version = "4.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2441c784c52b289a054b7201fc93253e288f094e2f4be9058343127c4226a269"
dependencies = [
"either",
"libc",
"once_cell",
]
[[package]]
name = "winapi"
version = "0.3.9"
@ -2582,43 +2696,100 @@ version = "0.36.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ea04155a16a59f9eab786fe12a4a450e75cdb175f9e0d80da1e17db09f55b8d2"
dependencies = [
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_msvc",
"windows_aarch64_msvc 0.36.1",
"windows_i686_gnu 0.36.1",
"windows_i686_msvc 0.36.1",
"windows_x86_64_gnu 0.36.1",
"windows_x86_64_msvc 0.36.1",
]
[[package]]
name = "windows-targets"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b1eb6f0cd7c80c79759c929114ef071b87354ce476d9d94271031c0497adfd5"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc 0.48.0",
"windows_i686_gnu 0.48.0",
"windows_i686_msvc 0.48.0",
"windows_x86_64_gnu 0.48.0",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc 0.48.0",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91ae572e1b79dba883e0d315474df7305d12f569b400fcf90581b06062f7e1bc"
[[package]]
name = "windows_aarch64_msvc"
version = "0.36.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9bb8c3fd39ade2d67e9874ac4f3db21f0d710bee00fe7cab16949ec184eeaa47"
[[package]]
name = "windows_aarch64_msvc"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b2ef27e0d7bdfcfc7b868b317c1d32c641a6fe4629c171b8928c7b08d98d7cf3"
[[package]]
name = "windows_i686_gnu"
version = "0.36.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "180e6ccf01daf4c426b846dfc66db1fc518f074baa793aa7d9b9aaeffad6a3b6"
[[package]]
name = "windows_i686_gnu"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "622a1962a7db830d6fd0a69683c80a18fda201879f0f447f065a3b7467daa241"
[[package]]
name = "windows_i686_msvc"
version = "0.36.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2e7917148b2812d1eeafaeb22a97e4813dfa60a3f8f78ebe204bcc88f12f024"
[[package]]
name = "windows_i686_msvc"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4542c6e364ce21bf45d69fdd2a8e455fa38d316158cfd43b3ac1c5b1b19f8e00"
[[package]]
name = "windows_x86_64_gnu"
version = "0.36.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4dcd171b8776c41b97521e5da127a2d86ad280114807d0b2ab1e462bc764d9e1"
[[package]]
name = "windows_x86_64_gnu"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca2b8a661f7628cbd23440e50b05d705db3686f894fc9580820623656af974b1"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7896dbc1f41e08872e9d5e8f8baa8fdd2677f29468c4e156210174edc7f7b953"
[[package]]
name = "windows_x86_64_msvc"
version = "0.36.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c811ca4a8c853ef420abd8592ba53ddbbac90410fab6903b3e79972a631f7680"
[[package]]
name = "windows_x86_64_msvc"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a515f5799fe4961cb532f983ce2b23082366b898e52ffbce459c86f67c8378a"
[[package]]
name = "winreg"
version = "0.10.1"

View file

@ -53,6 +53,8 @@ block-modes = "0.8.1"
thiserror = "1.0.26"
crossterm = { version = "0.23.2", features = ["event-stream"] }
qrcode = { version = "0.12.0", optional = true }
gethostname = "0.4.3"
secrecy = { version = "0.8", features = ["serde"] }
[dev-dependencies]
tempdir = "0.3"

View file

@ -1,7 +1,7 @@
use crate::accountmanager::legacy::SdaManifest;
pub use crate::encryption::EntryEncryptionParams;
use crate::encryption::EntryEncryptor;
use log::*;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufReader, Read, Write};
@ -10,81 +10,68 @@ use std::sync::{Arc, Mutex};
use steamguard::{ExposeSecret, SteamGuardAccount};
use thiserror::Error;
#[derive(Debug, Serialize, Deserialize)]
pub struct Manifest {
pub entries: Vec<ManifestEntry>,
/// Not really used, kept mostly for compatibility with SDA.
pub encrypted: bool,
/// Not implemented, kept for compatibility with SDA.
pub first_run: bool,
/// Not implemented, kept for compatibility with SDA.
pub periodic_checking: bool,
/// Not implemented, kept for compatibility with SDA.
pub periodic_checking_interval: i32,
/// Not implemented, kept for compatibility with SDA.
pub periodic_checking_checkall: bool,
/// Not implemented, kept for compatibility with SDA.
pub auto_confirm_market_transactions: bool,
/// Not implemented, kept for compatibility with SDA.
pub auto_confirm_trades: bool,
mod legacy;
pub mod manifest;
pub mod migrate;
#[serde(skip)]
pub use manifest::*;
#[derive(Debug, Default)]
pub struct AccountManager {
manifest: Manifest,
accounts: HashMap<String, Arc<Mutex<SteamGuardAccount>>>,
#[serde(skip)]
folder: String, // I wanted to use a Path here, but it was too hard to make it work...
#[serde(skip)]
folder: String,
passkey: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ManifestEntry {
pub filename: String,
#[serde(default, rename = "steamid")]
pub steam_id: u64,
#[serde(default)]
pub account_name: String,
#[serde(default, flatten)]
pub encryption: Option<EntryEncryptionParams>,
}
impl Default for Manifest {
fn default() -> Self {
Manifest {
encrypted: false,
entries: vec![],
first_run: false,
periodic_checking: false,
periodic_checking_interval: 0,
periodic_checking_checkall: false,
auto_confirm_market_transactions: false,
auto_confirm_trades: false,
accounts: HashMap::new(),
folder: "".into(),
passkey: None,
}
}
}
impl Manifest {
impl AccountManager {
/// `path` should be the path to manifest.json
pub fn new(path: &Path) -> Self {
Manifest {
Self {
folder: String::from(path.parent().unwrap().to_str().unwrap()),
..Default::default()
}
}
pub fn load(path: &Path) -> anyhow::Result<Self> {
debug!("loading manifest: {:?}", &path);
let file = File::open(path)?;
let reader = BufReader::new(file);
let mut manifest: Manifest = serde_json::from_reader(reader)?;
manifest.folder = String::from(path.parent().unwrap().to_str().unwrap());
return Ok(manifest);
pub fn from_manifest(manifest: Manifest, folder: String) -> Self {
Self {
manifest,
folder,
..Default::default()
}
}
/// Tells the manifest to keep track of the encryption passkey, and use it for encryption when loading or saving accounts.
pub fn register_accounts(&mut self, accounts: Vec<SteamGuardAccount>) {
for account in accounts {
self.register_loaded_account(Arc::new(Mutex::new(account)));
}
}
pub fn load(path: &Path) -> anyhow::Result<Self, ManifestLoadError> {
debug!("loading manifest: {:?}", &path);
let file = File::open(path)?;
let mut reader = BufReader::new(file);
let mut buffer = String::new();
reader.read_to_string(&mut buffer)?;
let manifest: Manifest = match serde_json::from_str(&buffer) {
Ok(m) => m,
Err(orig_err) => match serde_json::from_str::<SdaManifest>(&buffer) {
Ok(_) => return Err(ManifestLoadError::MigrationNeeded)?,
Err(_) => return Err(orig_err)?,
},
};
if manifest.version != CURRENT_MANIFEST_VERSION {
return Err(ManifestLoadError::MigrationNeeded)?;
}
let accountmanager = Self {
manifest,
folder: String::from(path.parent().unwrap().to_str().unwrap()),
..Default::default()
};
Ok(accountmanager)
}
/// Tells the manager to keep track of the encryption passkey, and use it for encryption when loading or saving accounts.
pub fn submit_passkey(&mut self, passkey: Option<String>) {
if let Some(p) = passkey.as_ref() {
if p.is_empty() {
@ -99,12 +86,11 @@ impl Manifest {
self.passkey = passkey;
}
/// Loads all accounts, registers them, and performs auto upgrades.
/// Loads all accounts, and registers them.
pub fn load_accounts(&mut self) -> anyhow::Result<(), ManifestAccountLoadError> {
self.auto_upgrade()?;
let mut accounts = vec![];
for entry in &self.entries {
let account = self.load_account_by_entry(&entry)?;
for entry in &self.manifest.entries {
let account = self.load_account_by_entry(entry)?;
accounts.push(account);
}
for account in accounts {
@ -120,7 +106,7 @@ impl Manifest {
account_name: &String,
) -> anyhow::Result<Arc<Mutex<SteamGuardAccount>>, ManifestAccountLoadError> {
let entry = self.get_entry(account_name)?;
self.load_account_by_entry(&entry)
self.load_account_by_entry(entry)
}
/// Loads an account from a manifest entry.
@ -130,29 +116,11 @@ impl Manifest {
entry: &ManifestEntry,
) -> anyhow::Result<Arc<Mutex<SteamGuardAccount>>, ManifestAccountLoadError> {
let path = Path::new(&self.folder).join(&entry.filename);
debug!("loading account: {:?}", path);
let file = File::open(path)?;
let mut reader = BufReader::new(file);
let account: SteamGuardAccount;
match (&self.passkey, entry.encryption.as_ref()) {
(Some(passkey), Some(params)) => {
let mut ciphertext: Vec<u8> = vec![];
reader.read_to_end(&mut ciphertext)?;
let plaintext =
crate::encryption::LegacySdaCompatible::decrypt(&passkey, params, ciphertext)?;
if plaintext[0] != '{' as u8 && plaintext[plaintext.len() - 1] != '}' as u8 {
return Err(ManifestAccountLoadError::IncorrectPasskey);
}
let s = std::str::from_utf8(&plaintext).unwrap();
account = serde_json::from_str(&s)?;
}
(None, Some(_)) => {
return Err(ManifestAccountLoadError::MissingPasskey);
}
(_, None) => {
account = serde_json::from_reader(reader)?;
}
};
let account = entry.load(
path.as_path(),
self.passkey.as_ref(),
entry.encryption.as_ref(),
)?;
let account = Arc::new(Mutex::new(account));
Ok(account)
}
@ -164,23 +132,19 @@ impl Manifest {
}
pub fn account_exists(&self, account_name: &String) -> bool {
for entry in &self.entries {
for entry in &self.manifest.entries {
if &entry.account_name == account_name {
return true;
}
}
return false;
false
}
pub fn add_account(&mut self, account: SteamGuardAccount) {
debug!("adding account to manifest: {}", account.account_name);
let steamid = account
.session
.as_ref()
.map_or(0, |s| s.expose_secret().steam_id);
self.entries.push(ManifestEntry {
self.manifest.entries.push(ManifestEntry {
filename: format!("{}.maFile", &account.account_name),
steam_id: steamid,
steam_id: account.steam_id,
account_name: account.account_name.clone(),
encryption: None,
});
@ -202,17 +166,18 @@ impl Manifest {
);
self.add_account(account);
return Ok(());
Ok(())
}
pub fn remove_account(&mut self, account_name: String) {
let index = self
.manifest
.entries
.iter()
.position(|a| a.account_name == account_name)
.unwrap();
self.accounts.remove(&account_name);
self.entries.remove(index);
self.manifest.entries.remove(index);
}
/// Saves the manifest and all loaded accounts.
@ -221,7 +186,6 @@ impl Manifest {
for account in self
.accounts
.values()
.into_iter()
.map(|a| a.clone().lock().unwrap().clone())
{
let entry = self.get_entry(&account.account_name)?.clone();
@ -232,19 +196,14 @@ impl Manifest {
"Something extra weird happened and the account was serialized into nothing."
);
let final_buffer: Vec<u8>;
match (&self.passkey, entry.encryption.as_ref()) {
let final_buffer: Vec<u8> = match (&self.passkey, entry.encryption.as_ref()) {
(Some(passkey), Some(params)) => {
final_buffer = crate::encryption::LegacySdaCompatible::encrypt(
&passkey, params, serialized,
)?;
crate::encryption::LegacySdaCompatible::encrypt(passkey, params, serialized)?
}
(None, Some(_)) => {
bail!("maFiles are encrypted, but no passkey was provided.");
}
(_, None) => {
final_buffer = serialized;
}
(_, None) => serialized,
};
let path = Path::new(&self.folder).join(&entry.filename);
@ -253,7 +212,7 @@ impl Manifest {
file.sync_data()?;
}
debug!("saving manifest");
let manifest_serialized = serde_json::to_string(&self)?;
let manifest_serialized = serde_json::to_string(&self.manifest)?;
let path = Path::new(&self.folder).join("manifest.json");
let mut file = File::create(path)?;
file.write_all(manifest_serialized.as_bytes())?;
@ -264,7 +223,7 @@ impl Manifest {
/// Return all loaded accounts. Order is not guarenteed.
#[allow(dead_code)]
pub fn get_all_loaded(&self) -> Vec<Arc<Mutex<SteamGuardAccount>>> {
return self.accounts.values().cloned().into_iter().collect();
return self.accounts.values().cloned().collect();
}
#[allow(dead_code)]
@ -272,7 +231,8 @@ impl Manifest {
&self,
account_name: &String,
) -> anyhow::Result<&ManifestEntry, ManifestAccountLoadError> {
self.entries
self.manifest
.entries
.iter()
.find(|e| &e.account_name == account_name)
.ok_or(ManifestAccountLoadError::MissingManifestEntry)
@ -283,7 +243,8 @@ impl Manifest {
&mut self,
account_name: &String,
) -> anyhow::Result<&mut ManifestEntry, ManifestAccountLoadError> {
self.entries
self.manifest
.entries
.iter_mut()
.find(|e| &e.account_name == account_name)
.ok_or(ManifestAccountLoadError::MissingManifestEntry)
@ -302,9 +263,9 @@ impl Manifest {
let account = self
.accounts
.get(account_name)
.map(|a| a.clone())
.cloned()
.ok_or(anyhow!("Account not loaded"));
return account;
account
}
/// Get or load the spcified account.
@ -313,21 +274,25 @@ impl Manifest {
account_name: &String,
) -> anyhow::Result<Arc<Mutex<SteamGuardAccount>>, ManifestAccountLoadError> {
let account = self.get_account(account_name);
if account.is_ok() {
return Ok(account.unwrap());
if let Ok(account) = account {
return Ok(account);
}
let account = self.load_account(&account_name)?;
let account = self.load_account(account_name)?;
self.register_loaded_account(account.clone());
return Ok(account);
Ok(account)
}
/// Determine if any manifest entries are missing `account_name`.
fn is_missing_account_name(&self) -> bool {
self.entries.iter().any(|e| e.account_name.is_empty())
self.manifest
.entries
.iter()
.any(|e| e.account_name.is_empty())
}
fn has_any_uppercase_in_account_names(&self) -> bool {
self.entries
self.manifest
.entries
.iter()
.any(|e| e.account_name != e.account_name.to_lowercase())
}
@ -338,23 +303,85 @@ impl Manifest {
let mut upgraded = false;
if self.is_missing_account_name() {
debug!("Adding missing account names");
for i in 0..self.entries.len() {
let account = self.load_account_by_entry(&self.entries[i].clone())?;
self.entries[i].account_name = account.lock().unwrap().account_name.clone();
for i in 0..self.manifest.entries.len() {
let account = self.load_account_by_entry(&self.manifest.entries[i].clone())?;
self.manifest.entries[i].account_name =
account.lock().unwrap().account_name.clone();
}
upgraded = true;
}
if self.has_any_uppercase_in_account_names() {
debug!("Lowercasing account names");
for i in 0..self.entries.len() {
self.entries[i].account_name = self.entries[i].account_name.to_lowercase();
for i in 0..self.manifest.entries.len() {
self.manifest.entries[i].account_name =
self.manifest.entries[i].account_name.to_lowercase();
}
upgraded = true;
}
Ok(upgraded)
}
pub fn iter(&self) -> impl Iterator<Item = &ManifestEntry> {
self.manifest.entries.iter()
}
pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut ManifestEntry> {
self.manifest.entries.iter_mut()
}
}
trait EntryLoader<T> {
fn load(
&self,
path: &Path,
passkey: Option<&String>,
encryption_params: Option<&EntryEncryptionParams>,
) -> anyhow::Result<T, ManifestAccountLoadError>;
}
impl EntryLoader<SteamGuardAccount> for ManifestEntry {
fn load(
&self,
path: &Path,
passkey: Option<&String>,
encryption_params: Option<&EntryEncryptionParams>,
) -> anyhow::Result<SteamGuardAccount, ManifestAccountLoadError> {
debug!("loading entry: {:?}", path);
let file = File::open(path)?;
let mut reader = BufReader::new(file);
let account: SteamGuardAccount = match (&passkey, encryption_params.as_ref()) {
(Some(passkey), Some(params)) => {
let mut ciphertext: Vec<u8> = vec![];
reader.read_to_end(&mut ciphertext)?;
let plaintext =
crate::encryption::LegacySdaCompatible::decrypt(passkey, params, ciphertext)?;
if plaintext[0] != b'{' && plaintext[plaintext.len() - 1] != b'}' {
return Err(ManifestAccountLoadError::IncorrectPasskey);
}
let s = std::str::from_utf8(&plaintext).unwrap();
serde_json::from_str(s)?
}
(None, Some(_)) => {
return Err(ManifestAccountLoadError::MissingPasskey);
}
(_, None) => serde_json::from_reader(reader)?,
};
Ok(account)
}
}
#[derive(Debug, Error)]
pub enum ManifestLoadError {
#[error("Could not find manifest.json in the specified directory.")]
Missing(#[from] std::io::Error),
#[error("Manifest needs to be migrated to the latest format.")]
MigrationNeeded,
#[error("Failed to deserialize the manifest.")]
DeserializationFailed(#[from] serde_json::Error),
#[error(transparent)]
Unknown(#[from] anyhow::Error),
}
#[derive(Debug, Error)]
@ -375,22 +402,22 @@ pub enum ManifestAccountLoadError {
impl From<block_modes::BlockModeError> for ManifestAccountLoadError {
fn from(error: block_modes::BlockModeError) -> Self {
return Self::Unknown(anyhow::Error::from(error));
Self::Unknown(anyhow::Error::from(error))
}
}
impl From<base64::DecodeError> for ManifestAccountLoadError {
fn from(error: base64::DecodeError) -> Self {
return Self::Unknown(anyhow::Error::from(error));
Self::Unknown(anyhow::Error::from(error))
}
}
impl From<block_modes::InvalidKeyIvLength> for ManifestAccountLoadError {
fn from(error: block_modes::InvalidKeyIvLength) -> Self {
return Self::Unknown(anyhow::Error::from(error));
Self::Unknown(anyhow::Error::from(error))
}
}
impl From<std::io::Error> for ManifestAccountLoadError {
fn from(error: std::io::Error) -> Self {
return Self::Unknown(anyhow::Error::from(error));
Self::Unknown(anyhow::Error::from(error))
}
}
@ -404,8 +431,8 @@ mod tests {
fn test_should_save_new_manifest() {
let tmp_dir = TempDir::new("steamguard-cli-test").unwrap();
let manifest_path = tmp_dir.path().join("manifest.json");
let manifest = Manifest::new(manifest_path.as_path());
assert!(matches!(manifest.save(), Ok(_)));
let manager = AccountManager::new(manifest_path.as_path());
assert!(matches!(manager.save(), Ok(_)));
}
#[test]
@ -413,27 +440,24 @@ mod tests {
let tmp_dir = TempDir::new("steamguard-cli-test")?;
let manifest_path = tmp_dir.path().join("manifest.json");
println!("tempdir: {}", manifest_path.display());
let mut manifest = Manifest::new(manifest_path.as_path());
let mut manager = AccountManager::new(manifest_path.as_path());
let mut account = SteamGuardAccount::new();
account.account_name = "asdf1234".into();
account.revocation_code = String::from("R12345").into();
account.shared_secret = steamguard::token::TwoFactorSecret::parse_shared_secret(
"zvIayp3JPvtvX/QGHqsqKBk/44s=".into(),
)?;
manifest.add_account(account);
manifest.save()?;
manager.add_account(account);
manager.save()?;
let mut loaded_manifest = Manifest::load(manifest_path.as_path())?;
assert_eq!(loaded_manifest.entries.len(), 1);
assert_eq!(loaded_manifest.entries[0].filename, "asdf1234.maFile");
loaded_manifest.load_accounts()?;
assert_eq!(
loaded_manifest.entries.len(),
loaded_manifest.accounts.len()
);
let mut manager = AccountManager::load(manifest_path.as_path())?;
assert_eq!(manager.manifest.entries.len(), 1);
assert_eq!(manager.manifest.entries[0].filename, "asdf1234.maFile");
manager.load_accounts()?;
assert_eq!(manager.manifest.entries.len(), manager.accounts.len());
let account_name = "asdf1234".into();
assert_eq!(
loaded_manifest
manager
.get_account(&account_name)?
.lock()
.unwrap()
@ -441,7 +465,7 @@ mod tests {
"asdf1234"
);
assert_eq!(
loaded_manifest
manager
.get_account(&account_name)?
.lock()
.unwrap()
@ -450,7 +474,7 @@ mod tests {
"R12345"
);
assert_eq!(
loaded_manifest
manager
.get_account(&account_name)?
.lock()
.unwrap()
@ -459,7 +483,7 @@ mod tests {
"zvIayp3JPvtvX/QGHqsqKBk/44s=".into()
)?,
);
return Ok(());
Ok(())
}
#[test]
@ -467,34 +491,37 @@ mod tests {
let passkey = Some("password".into());
let tmp_dir = TempDir::new("steamguard-cli-test")?;
let manifest_path = tmp_dir.path().join("manifest.json");
let mut manifest = Manifest::new(manifest_path.as_path());
let mut manager = AccountManager::new(manifest_path.as_path());
let mut account = SteamGuardAccount::new();
account.account_name = "asdf1234".into();
account.revocation_code = String::from("R12345").into();
account.shared_secret = steamguard::token::TwoFactorSecret::parse_shared_secret(
"zvIayp3JPvtvX/QGHqsqKBk/44s=".into(),
)?;
manifest.add_account(account);
manifest.entries[0].encryption = Some(EntryEncryptionParams::generate());
manifest.submit_passkey(passkey.clone());
assert!(matches!(manifest.save(), Ok(_)));
manager.add_account(account);
manager.manifest.entries[0].encryption = Some(EntryEncryptionParams::generate());
manager.submit_passkey(passkey.clone());
assert!(matches!(manager.save(), Ok(_)));
let mut loaded_manifest = Manifest::load(manifest_path.as_path()).unwrap();
loaded_manifest.submit_passkey(passkey);
assert_eq!(loaded_manifest.entries.len(), 1);
assert_eq!(loaded_manifest.entries[0].filename, "asdf1234.maFile");
let _r = loaded_manifest.load_accounts();
let mut loaded_manager = AccountManager::load(manifest_path.as_path()).unwrap();
loaded_manager.submit_passkey(passkey);
assert_eq!(loaded_manager.manifest.entries.len(), 1);
assert_eq!(
loaded_manager.manifest.entries[0].filename,
"asdf1234.maFile"
);
let _r = loaded_manager.load_accounts();
if _r.is_err() {
eprintln!("{:?}", _r);
}
assert!(matches!(_r, Ok(_)));
assert_eq!(
loaded_manifest.entries.len(),
loaded_manifest.accounts.len()
loaded_manager.manifest.entries.len(),
loaded_manager.accounts.len()
);
let account_name = "asdf1234".into();
assert_eq!(
loaded_manifest
loaded_manager
.get_account(&account_name)?
.lock()
.unwrap()
@ -502,7 +529,7 @@ mod tests {
"asdf1234"
);
assert_eq!(
loaded_manifest
loaded_manager
.get_account(&account_name)?
.lock()
.unwrap()
@ -511,7 +538,7 @@ mod tests {
"R12345"
);
assert_eq!(
loaded_manifest
loaded_manager
.get_account(&account_name)?
.lock()
.unwrap()
@ -529,7 +556,7 @@ mod tests {
let passkey = Some("password".into());
let tmp_dir = TempDir::new("steamguard-cli-test")?;
let manifest_path = tmp_dir.path().join("manifest.json");
let mut manifest = Manifest::new(manifest_path.as_path());
let mut manager = AccountManager::new(manifest_path.as_path());
let mut account = SteamGuardAccount::new();
account.account_name = "asdf1234".into();
account.revocation_code = String::from("R12345").into();
@ -539,23 +566,26 @@ mod tests {
.unwrap();
account.uri = String::from("otpauth://;laksdjf;lkasdjf;lkasdj;flkasdjlkf;asjdlkfjslk;adjfl;kasdjf;lksdjflk;asjd;lfajs;ldkfjaslk;djf;lsakdjf;lksdj").into();
account.token_gid = "asdf1234".into();
manifest.add_account(account);
manifest.submit_passkey(passkey.clone());
manifest.entries[0].encryption = Some(EntryEncryptionParams::generate());
manifest.save()?;
manager.add_account(account);
manager.submit_passkey(passkey.clone());
manager.manifest.entries[0].encryption = Some(EntryEncryptionParams::generate());
manager.save()?;
let mut loaded_manifest = Manifest::load(manifest_path.as_path())?;
loaded_manifest.submit_passkey(passkey.clone());
assert_eq!(loaded_manifest.entries.len(), 1);
assert_eq!(loaded_manifest.entries[0].filename, "asdf1234.maFile");
loaded_manifest.load_accounts()?;
let mut loaded_manager = AccountManager::load(manifest_path.as_path())?;
loaded_manager.submit_passkey(passkey);
assert_eq!(loaded_manager.manifest.entries.len(), 1);
assert_eq!(
loaded_manifest.entries.len(),
loaded_manifest.accounts.len()
loaded_manager.manifest.entries[0].filename,
"asdf1234.maFile"
);
loaded_manager.load_accounts()?;
assert_eq!(
loaded_manager.manifest.entries.len(),
loaded_manager.accounts.len()
);
let account_name = "asdf1234".into();
assert_eq!(
loaded_manifest
loaded_manager
.get_account(&account_name)?
.lock()
.unwrap()
@ -563,7 +593,7 @@ mod tests {
"asdf1234"
);
assert_eq!(
loaded_manifest
loaded_manager
.get_account(&account_name)?
.lock()
.unwrap()
@ -572,7 +602,7 @@ mod tests {
"R12345"
);
assert_eq!(
loaded_manifest
loaded_manager
.get_account(&account_name)?
.lock()
.unwrap()
@ -583,14 +613,14 @@ mod tests {
.unwrap(),
);
return Ok(());
Ok(())
}
#[test]
fn test_should_import() -> anyhow::Result<()> {
let tmp_dir = TempDir::new("steamguard-cli-test")?;
let manifest_path = tmp_dir.path().join("manifest.json");
let mut manifest = Manifest::new(manifest_path.as_path());
let mut manager = AccountManager::new(manifest_path.as_path());
let mut account = SteamGuardAccount::new();
account.account_name = "asdf1234".into();
account.revocation_code = String::from("R12345").into();
@ -598,13 +628,13 @@ mod tests {
"zvIayp3JPvtvX/QGHqsqKBk/44s=".into(),
)
.unwrap();
manifest.add_account(account);
manifest.save()?;
manager.add_account(account);
manager.save()?;
std::fs::remove_file(&manifest_path)?;
let mut loaded_manifest = Manifest::new(manifest_path.as_path());
let mut loaded_manager = AccountManager::new(manifest_path.as_path());
assert!(matches!(
loaded_manifest.import_account(
loaded_manager.import_account(
&tmp_dir
.path()
.join("asdf1234.maFile")
@ -615,12 +645,12 @@ mod tests {
Ok(_)
));
assert_eq!(
loaded_manifest.entries.len(),
loaded_manifest.accounts.len()
loaded_manager.manifest.entries.len(),
loaded_manager.accounts.len()
);
let account_name = "asdf1234".into();
assert_eq!(
loaded_manifest
loaded_manager
.get_account(&account_name)?
.lock()
.unwrap()
@ -628,7 +658,7 @@ mod tests {
"asdf1234"
);
assert_eq!(
loaded_manifest
loaded_manager
.get_account(&account_name)?
.lock()
.unwrap()
@ -637,7 +667,7 @@ mod tests {
"R12345"
);
assert_eq!(
loaded_manifest
loaded_manager
.get_account(&account_name)?
.lock()
.unwrap()
@ -651,134 +681,134 @@ mod tests {
Ok(())
}
#[test]
fn test_sda_compatibility_1() -> anyhow::Result<()> {
let path = Path::new("src/fixtures/maFiles/compat/1-account/manifest.json");
assert!(path.is_file());
let mut manifest = Manifest::load(path)?;
assert!(matches!(manifest.entries.last().unwrap().encryption, None));
manifest.load_accounts()?;
let account_name = manifest.entries.last().unwrap().account_name.clone();
assert_eq!(
account_name,
manifest
.get_account(&account_name)?
.lock()
.unwrap()
.account_name
);
Ok(())
}
// #[test]
// fn test_sda_compatibility_1() -> anyhow::Result<()> {
// let path = Path::new("src/fixtures/maFiles/compat/1-account/manifest.json");
// assert!(path.is_file());
// let mut manager = AccountManager::load(path)?;
// assert!(matches!(manager.entries.last().unwrap().encryption, None));
// manager.load_accounts()?;
// let account_name = manager.entries.last().unwrap().account_name.clone();
// assert_eq!(
// account_name,
// manager
// .get_account(&account_name)?
// .lock()
// .unwrap()
// .account_name
// );
// Ok(())
// }
#[test]
fn test_sda_compatibility_1_encrypted() -> anyhow::Result<()> {
let path = Path::new("src/fixtures/maFiles/compat/1-account-encrypted/manifest.json");
assert!(path.is_file());
let mut manifest = Manifest::load(path)?;
assert!(matches!(
manifest.entries.last().unwrap().encryption,
Some(_)
));
manifest.submit_passkey(Some("password".into()));
manifest.load_accounts()?;
let account_name = manifest.entries.last().unwrap().account_name.clone();
assert_eq!(
account_name,
manifest
.get_account(&account_name)?
.lock()
.unwrap()
.account_name
);
Ok(())
}
// #[test]
// fn test_sda_compatibility_1_encrypted() -> anyhow::Result<()> {
// let path = Path::new("src/fixtures/maFiles/compat/1-account-encrypted/manifest.json");
// assert!(path.is_file());
// let mut manifest = Manifest::load(path)?;
// assert!(matches!(
// manifest.entries.last().unwrap().encryption,
// Some(_)
// ));
// manifest.submit_passkey(Some("password".into()));
// manifest.load_accounts()?;
// let account_name = manifest.entries.last().unwrap().account_name.clone();
// assert_eq!(
// account_name,
// manifest
// .get_account(&account_name)?
// .lock()
// .unwrap()
// .account_name
// );
// Ok(())
// }
#[test]
fn test_sda_compatibility_no_webcookie() -> anyhow::Result<()> {
let path = Path::new("src/fixtures/maFiles/compat/no-webcookie/manifest.json");
assert!(path.is_file());
let mut manifest = Manifest::load(path)?;
assert!(matches!(manifest.entries.last().unwrap().encryption, None));
assert!(matches!(manifest.load_accounts(), Ok(_)));
let account_name = manifest.entries.last().unwrap().account_name.clone();
let account = manifest.get_account(&account_name)?;
assert_eq!(account_name, account.lock().unwrap().account_name);
assert_eq!(
account
.lock()
.unwrap()
.session
.as_ref()
.unwrap()
.expose_secret()
.web_cookie,
None
);
Ok(())
}
// #[test]
// fn test_sda_compatibility_no_webcookie() -> anyhow::Result<()> {
// let path = Path::new("src/fixtures/maFiles/compat/no-webcookie/manifest.json");
// assert!(path.is_file());
// let mut manifest = Manifest::load(path)?;
// assert!(matches!(manifest.entries.last().unwrap().encryption, None));
// assert!(matches!(manifest.load_accounts(), Ok(_)));
// let account_name = manifest.entries.last().unwrap().account_name.clone();
// let account = manifest.get_account(&account_name)?;
// assert_eq!(account_name, account.lock().unwrap().account_name);
// assert_eq!(
// account
// .lock()
// .unwrap()
// .session
// .as_ref()
// .unwrap()
// .expose_secret()
// .web_cookie,
// None
// );
// Ok(())
// }
#[test]
fn test_sda_compatibility_2() -> anyhow::Result<()> {
let path = Path::new("src/fixtures/maFiles/compat/2-account/manifest.json");
assert!(path.is_file());
let mut manifest = Manifest::load(path)?;
assert!(matches!(manifest.entries.last().unwrap().encryption, None));
manifest.load_accounts()?;
let account_name = manifest.entries[0].account_name.clone();
let account = manifest.get_account(&account_name)?;
assert_eq!(account_name, account.lock().unwrap().account_name);
assert_eq!(
account.lock().unwrap().revocation_code.expose_secret(),
"R12345"
);
assert_eq!(
account
.lock()
.unwrap()
.session
.as_ref()
.unwrap()
.expose_secret()
.steam_id,
1234
);
// #[test]
// fn test_sda_compatibility_2() -> anyhow::Result<()> {
// let path = Path::new("src/fixtures/maFiles/compat/2-account/manifest.json");
// assert!(path.is_file());
// let mut manifest = Manifest::load(path)?;
// assert!(matches!(manifest.entries.last().unwrap().encryption, None));
// manifest.load_accounts()?;
// let account_name = manifest.entries[0].account_name.clone();
// let account = manifest.get_account(&account_name)?;
// assert_eq!(account_name, account.lock().unwrap().account_name);
// assert_eq!(
// account.lock().unwrap().revocation_code.expose_secret(),
// "R12345"
// );
// assert_eq!(
// account
// .lock()
// .unwrap()
// .session
// .as_ref()
// .unwrap()
// .expose_secret()
// .steam_id,
// 1234
// );
let account_name = manifest.entries[1].account_name.clone();
let account = manifest.get_account(&account_name)?;
assert_eq!(account_name, account.lock().unwrap().account_name);
assert_eq!(
account.lock().unwrap().revocation_code.expose_secret(),
"R56789"
);
assert_eq!(
account
.lock()
.unwrap()
.session
.as_ref()
.unwrap()
.expose_secret()
.steam_id,
5678
);
Ok(())
}
// let account_name = manifest.entries[1].account_name.clone();
// let account = manifest.get_account(&account_name)?;
// assert_eq!(account_name, account.lock().unwrap().account_name);
// assert_eq!(
// account.lock().unwrap().revocation_code.expose_secret(),
// "R56789"
// );
// assert_eq!(
// account
// .lock()
// .unwrap()
// .session
// .as_ref()
// .unwrap()
// .expose_secret()
// .steam_id,
// 5678
// );
// Ok(())
// }
#[cfg(test)]
mod manifest_upgrades {
use super::*;
// #[cfg(test)]
// mod manifest_upgrades {
// use super::*;
#[test]
fn test_missing_account_name() {
let path = Path::new("src/fixtures/maFiles/compat/missing-account-name/manifest.json");
assert!(path.is_file());
let mut manifest = Manifest::load(path).unwrap();
assert_eq!(manifest.entries.len(), 1);
assert_eq!(manifest.entries[0].account_name, "".to_string());
assert!(manifest.is_missing_account_name());
// #[test]
// fn test_missing_account_name() {
// let path = Path::new("src/fixtures/maFiles/compat/missing-account-name/manifest.json");
// assert!(path.is_file());
// let mut manager = AccountManager::load(path).unwrap();
// assert_eq!(manager.entries.len(), 1);
// assert_eq!(manager.entries[0].account_name, "".to_string());
// assert!(manager.is_missing_account_name());
manifest.auto_upgrade().unwrap();
assert_eq!(manifest.entries[0].account_name, "example".to_string());
}
}
// manager.auto_upgrade().unwrap();
// assert_eq!(manager.entries[0].account_name, "example".to_string());
// }
// }
}

View file

@ -0,0 +1,162 @@
use std::{
fs::File,
io::{BufReader, Read},
path::Path,
};
use log::debug;
use secrecy::ExposeSecret;
use serde::Deserialize;
use steamguard::{token::TwoFactorSecret, SecretString, SteamGuardAccount};
use crate::encryption::{EncryptionScheme, EntryEncryptor};
use super::{
EntryEncryptionParams, EntryLoader, ManifestAccountLoadError, ManifestEntry, ManifestV1,
};
#[derive(Debug, Deserialize)]
pub struct SdaManifest {
#[serde(default)]
pub version: u32,
pub entries: Vec<SdaManifestEntry>,
/// Not really used, kept mostly for compatibility with SDA.
pub encrypted: bool,
/// Not implemented, kept for compatibility with SDA.
pub first_run: bool,
/// Not implemented, kept for compatibility with SDA.
pub periodic_checking: bool,
/// Not implemented, kept for compatibility with SDA.
pub periodic_checking_interval: i32,
/// Not implemented, kept for compatibility with SDA.
pub periodic_checking_checkall: bool,
/// Not implemented, kept for compatibility with SDA.
pub auto_confirm_market_transactions: bool,
/// Not implemented, kept for compatibility with SDA.
pub auto_confirm_trades: bool,
}
impl From<SdaManifest> for ManifestV1 {
fn from(sda: SdaManifest) -> Self {
Self {
version: 1,
entries: sda.entries.into_iter().map(|e| e.into()).collect(),
}
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct SdaManifestEntry {
pub filename: String,
#[serde(default, rename = "steamid")]
pub steam_id: u64,
#[serde(default, flatten)]
pub encryption: Option<SdaEntryEncryptionParams>,
}
impl From<SdaManifestEntry> for ManifestEntry {
fn from(sda: SdaManifestEntry) -> Self {
Self {
filename: sda.filename,
steam_id: sda.steam_id,
account_name: Default::default(),
encryption: sda.encryption.map(|e| e.into()),
}
}
}
impl EntryLoader<SdaAccount> for SdaManifestEntry {
fn load(
&self,
path: &Path,
passkey: Option<&String>,
encryption_params: Option<&EntryEncryptionParams>,
) -> anyhow::Result<SdaAccount, ManifestAccountLoadError> {
debug!("loading entry: {:?}", path);
let file = File::open(path)?;
let mut reader = BufReader::new(file);
let account: SdaAccount;
match (&passkey, encryption_params.as_ref()) {
(Some(passkey), Some(params)) => {
let mut ciphertext: Vec<u8> = vec![];
reader.read_to_end(&mut ciphertext)?;
let plaintext =
crate::encryption::LegacySdaCompatible::decrypt(passkey, params, ciphertext)?;
if plaintext[0] != b'{' && plaintext[plaintext.len() - 1] != b'}' {
return Err(ManifestAccountLoadError::IncorrectPasskey);
}
let s = std::str::from_utf8(&plaintext).unwrap();
account = serde_json::from_str(s)?;
}
(None, Some(_)) => {
return Err(ManifestAccountLoadError::MissingPasskey);
}
(_, None) => {
account = serde_json::from_reader(reader)?;
}
};
Ok(account)
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct SdaEntryEncryptionParams {
#[serde(rename = "encryption_iv")]
pub iv: String,
#[serde(rename = "encryption_salt")]
pub salt: String,
}
impl From<SdaEntryEncryptionParams> for EntryEncryptionParams {
fn from(sda: SdaEntryEncryptionParams) -> Self {
Self {
iv: sda.iv,
salt: sda.salt,
scheme: EncryptionScheme::LegacySdaCompatible,
}
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct SdaAccount {
pub account_name: String,
pub serial_number: String,
#[serde(with = "crate::secret_string")]
pub revocation_code: SecretString,
pub shared_secret: TwoFactorSecret,
pub token_gid: String,
#[serde(with = "crate::secret_string")]
pub identity_secret: SecretString,
pub server_time: u64,
#[serde(with = "crate::secret_string")]
pub uri: SecretString,
pub fully_enrolled: bool,
pub device_id: String,
#[serde(with = "crate::secret_string")]
pub secret_1: SecretString,
#[serde(default, rename = "Session")]
pub session: Option<secrecy::Secret<steamguard::steamapi::Session>>,
}
impl From<SdaAccount> for SteamGuardAccount {
fn from(value: SdaAccount) -> Self {
let steam_id = value
.session
.as_ref()
.map(|s| s.expose_secret().steam_id)
.unwrap_or(0);
Self {
account_name: value.account_name,
steam_id,
serial_number: value.serial_number,
revocation_code: value.revocation_code,
shared_secret: value.shared_secret,
token_gid: value.token_gid,
identity_secret: value.identity_secret,
uri: value.uri,
device_id: value.device_id,
secret_1: value.secret_1,
tokens: None,
}
}
}

View file

@ -0,0 +1,30 @@
use serde::{Deserialize, Serialize};
use super::EntryEncryptionParams;
pub const CURRENT_MANIFEST_VERSION: u32 = 1;
pub type Manifest = ManifestV1;
pub type ManifestEntry = ManifestEntryV1;
#[derive(Debug, Serialize, Deserialize)]
pub struct ManifestV1 {
pub version: u32,
pub entries: Vec<ManifestEntry>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ManifestEntryV1 {
pub filename: String,
pub steam_id: u64,
pub account_name: String,
pub encryption: Option<EntryEncryptionParams>,
}
impl Default for ManifestV1 {
fn default() -> Self {
Self {
version: 1,
entries: vec![],
}
}
}

View file

@ -0,0 +1,267 @@
// notes for migration:
// account names must be made lowercase
use std::{fs::File, io::Read, path::Path};
use log::debug;
use steamguard::SteamGuardAccount;
use super::{
legacy::{SdaAccount, SdaManifest},
manifest::ManifestV1,
EntryEncryptionParams, EntryLoader, Manifest,
};
pub fn load_and_migrate(
manifest_path: &Path,
passkey: Option<&String>,
) -> anyhow::Result<(Manifest, Vec<SteamGuardAccount>)> {
backup_file(manifest_path)?;
let parent = manifest_path.parent().unwrap();
parent.read_dir()?.for_each(|e| {
let entry = e.unwrap();
if entry.file_type().unwrap().is_file() {
let path = entry.path();
if path.extension().unwrap() == "maFile" {
backup_file(&path).unwrap();
}
}
});
do_migrate(manifest_path, passkey)
}
fn do_migrate(
manifest_path: &Path,
passkey: Option<&String>,
) -> anyhow::Result<(Manifest, Vec<SteamGuardAccount>)> {
let mut file = File::open(manifest_path)?;
let mut buffer = String::new();
file.read_to_string(&mut buffer)?;
let mut manifest: MigratingManifest = deserialize_manifest(buffer)?;
let folder = manifest_path.parent().unwrap();
let mut accounts = manifest.load_all_accounts(folder, passkey)?;
while !manifest.is_latest() {
manifest = manifest.upgrade();
for account in accounts.iter_mut() {
*account = account.clone().upgrade();
}
}
// HACK: force account names onto manifest entries
let mut manifest: Manifest = manifest.into();
let accounts: Vec<SteamGuardAccount> = accounts.into_iter().map(|a| a.into()).collect();
for (i, entry) in manifest.entries.iter_mut().enumerate() {
entry.account_name = accounts[i].account_name.to_lowercase();
}
Ok((manifest, accounts))
}
fn backup_file(path: &Path) -> anyhow::Result<()> {
let backup_path = Path::join(
path.parent().unwrap(),
format!("{}.bak", path.file_name().unwrap().to_str().unwrap()),
);
std::fs::copy(path, backup_path)?;
Ok(())
}
#[derive(Debug)]
enum MigratingManifest {
SDA(SdaManifest),
ManifestV1(ManifestV1),
}
impl MigratingManifest {
pub fn upgrade(self) -> Self {
match self {
Self::SDA(sda) => Self::ManifestV1(sda.into()),
Self::ManifestV1(_) => self,
}
}
pub fn is_latest(&self) -> bool {
match self {
Self::ManifestV1(_) => true,
_ => false,
}
}
pub fn version(&self) -> u32 {
match self {
Self::SDA(_) => 0,
Self::ManifestV1(_) => 1,
}
}
pub fn load_all_accounts(
&self,
folder: &Path,
passkey: Option<&String>,
) -> anyhow::Result<Vec<MigratingAccount>> {
debug!("loading all accounts for migration");
let accounts = match self {
Self::SDA(sda) => {
let (accounts, errors) = sda
.entries
.iter()
.map(|e| {
let params: Option<EntryEncryptionParams> =
e.encryption.clone().map(|e| e.into());
e.load(&Path::join(folder, &e.filename), passkey, params.as_ref())
})
.partition::<Vec<_>, _>(Result::is_ok);
let accounts: Vec<_> = accounts.into_iter().map(Result::unwrap).collect();
let errors: Vec<_> = errors.into_iter().map(Result::unwrap_err).collect();
if !errors.is_empty() {
return Err(anyhow::anyhow!(
"Failed to load some accounts: {:?}",
errors
));
}
accounts.into_iter().map(MigratingAccount::Sda).collect()
}
Self::ManifestV1(manifest) => {
let (accounts, errors) = manifest
.entries
.iter()
.map(|e| {
e.load(
&Path::join(folder, &e.filename),
passkey,
e.encryption.as_ref(),
)
})
.partition::<Vec<_>, _>(Result::is_ok);
let accounts: Vec<_> = accounts.into_iter().map(Result::unwrap).collect();
let errors: Vec<_> = errors.into_iter().map(Result::unwrap_err).collect();
if !errors.is_empty() {
return Err(anyhow::anyhow!(
"Failed to load some accounts: {:?}",
errors
));
}
accounts
.into_iter()
.map(MigratingAccount::ManifestV1)
.collect()
}
};
Ok(accounts)
}
}
impl From<MigratingManifest> for Manifest {
fn from(migrating: MigratingManifest) -> Self {
match migrating {
MigratingManifest::ManifestV1(manifest) => manifest,
_ => panic!("Manifest is not at the latest version!"),
}
}
}
fn deserialize_manifest(text: String) -> anyhow::Result<MigratingManifest> {
let json: serde_json::Value = serde_json::from_str(&text)?;
debug!("deserializing manifest: version {}", json["version"]);
if json["version"] == 1 {
let manifest: ManifestV1 = serde_json::from_str(&text)?;
Ok(MigratingManifest::ManifestV1(manifest))
} else {
let manifest: SdaManifest = serde_json::from_str(&text)?;
Ok(MigratingManifest::SDA(manifest))
}
}
#[derive(Debug, Clone)]
enum MigratingAccount {
Sda(SdaAccount),
ManifestV1(SteamGuardAccount),
}
impl MigratingAccount {
pub fn upgrade(self) -> Self {
match self {
Self::Sda(sda) => Self::ManifestV1(sda.into()),
Self::ManifestV1(_) => self,
}
}
pub fn is_latest(&self) -> bool {
match self {
Self::ManifestV1(_) => true,
_ => false,
}
}
}
impl From<MigratingAccount> for SteamGuardAccount {
fn from(migrating: MigratingAccount) -> Self {
match migrating {
MigratingAccount::ManifestV1(account) => account,
_ => panic!("Account is not at the latest version!"),
}
}
}
pub fn load_and_upgrade_sda_account(path: &Path) -> anyhow::Result<SteamGuardAccount> {
let file = File::open(path)?;
let account: SdaAccount = serde_json::from_reader(file)?;
let mut account = MigratingAccount::Sda(account);
while !account.is_latest() {
account = account.upgrade();
}
Ok(account.into())
}
#[cfg(test)]
mod tests {
use crate::accountmanager::CURRENT_MANIFEST_VERSION;
use super::*;
#[test]
fn should_migrate_to_latest_version() -> anyhow::Result<()> {
#[derive(Debug)]
struct Test {
manifest: &'static str,
passkey: Option<String>,
}
let cases = vec![
Test {
manifest: "src/fixtures/maFiles/compat/1-account/manifest.json",
passkey: None,
},
Test {
manifest: "src/fixtures/maFiles/compat/1-account-encrypted/manifest.json",
passkey: Some("password".into()),
},
Test {
manifest: "src/fixtures/maFiles/compat/2-account/manifest.json",
passkey: None,
},
Test {
manifest: "src/fixtures/maFiles/compat/missing-account-name/manifest.json",
passkey: None,
},
Test {
manifest: "src/fixtures/maFiles/compat/no-webcookie/manifest.json",
passkey: None,
},
];
for case in cases {
eprintln!("testing: {:?}", case);
let (manifest, accounts) = do_migrate(Path::new(case.manifest), case.passkey.as_ref())?;
assert_eq!(manifest.version, CURRENT_MANIFEST_VERSION);
assert_eq!(manifest.entries[0].account_name, "example");
assert_eq!(manifest.entries[0].steam_id, 1234);
assert_eq!(accounts[0].account_name, "example");
assert_eq!(accounts[0].steam_id, 1234);
}
Ok(())
}
}

View file

@ -57,6 +57,8 @@ pub(crate) enum Subcommands {
Code(ArgsCode),
#[cfg(feature = "qr")]
Qr(ArgsQr),
#[cfg(debug_assertions)]
TestLogin,
}
#[derive(Debug, Clone, Copy, ArgEnum)]
@ -125,6 +127,9 @@ pub(crate) struct ArgsSetup {}
#[derive(Debug, Clone, Parser)]
#[clap(about = "Import an account with steamguard already set up")]
pub(crate) struct ArgsImport {
#[clap(long, help = "Whether or not the provided maFiles are from SDA.")]
pub sda: bool,
#[clap(long, help = "Paths to one or more maFiles, eg. \"./gaben.maFile\"")]
pub files: Vec<String>,
}

View file

@ -31,32 +31,32 @@ pub fn demo_confirmation_menu() {
info!("showing demo menu");
let (accept, deny) = tui::prompt_confirmation_menu(vec![
Confirmation {
id: 1234,
key: 12345,
id: "1234".to_owned(),
nonce: "12345".to_owned(),
conf_type: ConfirmationType::Trade,
creator: 09870987,
description: "example confirmation".into(),
creator_id: "09870987".to_owned(),
headline: "example confirmation".into(),
type_name: "Trade".to_owned(),
creation_time: 1687457923,
cancel: "Cancel".to_owned(),
accept: "Confirm".to_owned(),
icon: "".to_owned(),
multi: false,
summary: vec![],
},
Confirmation {
id: 1234,
key: 12345,
id: "1234".to_owned(),
nonce: "12345".to_owned(),
conf_type: ConfirmationType::MarketSell,
creator: 09870987,
description: "example confirmation".into(),
},
Confirmation {
id: 1234,
key: 12345,
conf_type: ConfirmationType::AccountRecovery,
creator: 09870987,
description: "example confirmation".into(),
},
Confirmation {
id: 1234,
key: 12345,
conf_type: ConfirmationType::Trade,
creator: 09870987,
description: "example confirmation".into(),
creator_id: "09870987".to_owned(),
headline: "example confirmation".into(),
type_name: "Market Sell".to_owned(),
creation_time: 1687457923,
cancel: "Cancel".to_owned(),
accept: "Confirm".to_owned(),
icon: "".to_owned(),
multi: false,
summary: vec![],
},
])
.expect("confirmation menu demo failed");

View file

@ -11,11 +11,8 @@ const IV_LENGTH: usize = 16;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EntryEncryptionParams {
#[serde(rename = "encryption_iv")]
pub iv: String,
#[serde(rename = "encryption_salt")]
pub salt: String,
#[serde(default, rename = "encryption_scheme")]
pub scheme: EncryptionScheme,
}
@ -80,7 +77,7 @@ impl LegacySdaCompatible {
password_bytes,
&mut full_key,
);
return Ok(full_key);
Ok(full_key)
}
}
@ -104,7 +101,7 @@ impl EntryEncryptor for LegacySdaCompatible {
let chunksize = chunk.len();
let buffersize = (chunksize / 16 + (if chunksize % 16 == 0 { 0 } else { 1 })) * 16;
let mut chunkbuffer = vec![0xffu8; buffersize];
chunkbuffer[..chunksize].copy_from_slice(&chunk);
chunkbuffer[..chunksize].copy_from_slice(chunk);
if buffersize != chunksize {
// pad the last chunk
chunkbuffer = Pkcs7::pad(&mut chunkbuffer, chunksize, buffersize)
@ -114,7 +111,7 @@ impl EntryEncryptor for LegacySdaCompatible {
buffer.append(&mut chunkbuffer);
}
let ciphertext = cipher.encrypt(&mut buffer, buffersize)?;
let final_buffer = base64::encode(&ciphertext);
let final_buffer = base64::encode(ciphertext);
return Ok(final_buffer.as_bytes().to_vec());
}
@ -131,9 +128,9 @@ impl EntryEncryptor for LegacySdaCompatible {
let size: usize = decoded.len() / 16 + (if decoded.len() % 16 == 0 { 0 } else { 1 });
let mut buffer = vec![0xffu8; 16 * size];
buffer[..decoded.len()].copy_from_slice(&decoded);
let mut decrypted = cipher.decrypt(&mut buffer)?;
let unpadded = Pkcs7::unpad(&mut decrypted)?;
return Ok(unpadded.to_vec());
let decrypted = cipher.decrypt(&mut buffer)?;
let unpadded = Pkcs7::unpad(decrypted)?;
Ok(unpadded.to_vec())
}
}
@ -146,32 +143,32 @@ pub enum EntryEncryptionError {
/// For some reason, these errors do not get converted to `ManifestAccountLoadError`s, even though they get converted into `anyhow::Error` just fine. I am too lazy to figure out why right now.
impl From<block_modes::BlockModeError> for EntryEncryptionError {
fn from(error: block_modes::BlockModeError) -> Self {
return Self::Unknown(anyhow::Error::from(error));
Self::Unknown(anyhow::Error::from(error))
}
}
impl From<block_modes::InvalidKeyIvLength> for EntryEncryptionError {
fn from(error: block_modes::InvalidKeyIvLength) -> Self {
return Self::Unknown(anyhow::Error::from(error));
Self::Unknown(anyhow::Error::from(error))
}
}
impl From<block_modes::block_padding::PadError> for EntryEncryptionError {
fn from(error: block_modes::block_padding::PadError) -> Self {
return Self::Unknown(anyhow!("PadError"));
fn from(_error: block_modes::block_padding::PadError) -> Self {
Self::Unknown(anyhow!("PadError"))
}
}
impl From<block_modes::block_padding::UnpadError> for EntryEncryptionError {
fn from(error: block_modes::block_padding::UnpadError) -> Self {
return Self::Unknown(anyhow!("UnpadError"));
fn from(_error: block_modes::block_padding::UnpadError) -> Self {
Self::Unknown(anyhow!("UnpadError"))
}
}
impl From<base64::DecodeError> for EntryEncryptionError {
fn from(error: base64::DecodeError) -> Self {
return Self::Unknown(anyhow::Error::from(error));
Self::Unknown(anyhow::Error::from(error))
}
}
impl From<std::io::Error> for EntryEncryptionError {
fn from(error: std::io::Error) -> Self {
return Self::Unknown(anyhow::Error::from(error));
Self::Unknown(anyhow::Error::from(error))
}
}
@ -209,15 +206,15 @@ mod tests {
LegacySdaCompatible::encrypt(&passkey.clone().into(), &params, orig.clone()).unwrap();
let result = LegacySdaCompatible::decrypt(&passkey.into(), &params, encrypted).unwrap();
assert_eq!(orig, result.to_vec());
return Ok(());
Ok(())
}
prop_compose! {
/// An insecure but reproducible strategy for generating encryption params.
fn encryption_params()(salt in any::<[u8; SALT_LENGTH]>(), iv in any::<[u8; IV_LENGTH]>()) -> EntryEncryptionParams {
EntryEncryptionParams {
salt: base64::encode(&salt),
iv: base64::encode(&iv),
salt: base64::encode(salt),
iv: base64::encode(iv),
scheme: EncryptionScheme::LegacySdaCompatible,
}
}

View file

@ -10,12 +10,18 @@ use std::{
path::Path,
sync::{Arc, Mutex},
};
use steamguard::accountlinker::AccountLinkSuccess;
use steamguard::protobufs::steammessages_auth_steamclient::{
EAuthSessionGuardType, EAuthTokenPlatformType,
};
use steamguard::token::Tokens;
use steamguard::{
steamapi, AccountLinkError, AccountLinker, Confirmation, ExposeSecret, FinalizeLinkError,
LoginError, SteamGuardAccount, UserLogin,
steamapi, AccountLinkError, AccountLinker, Confirmation, DeviceDetails, ExposeSecret,
FinalizeLinkError, LoginError, SteamGuardAccount, UserLogin,
};
use crate::accountmanager::ManifestAccountLoadError;
use crate::accountmanager::migrate::load_and_migrate;
use crate::accountmanager::{AccountManager, ManifestAccountLoadError, ManifestLoadError};
#[macro_use]
extern crate lazy_static;
@ -31,6 +37,8 @@ mod cli;
mod demos;
mod encryption;
mod errors;
mod secret_string;
mod test_login;
pub(crate) mod tui;
fn main() {
@ -71,7 +79,7 @@ fn run() -> anyhow::Result<()> {
};
info!("reading manifest from {}", mafiles_dir);
let path = Path::new(&mafiles_dir).join("manifest.json");
let mut manifest: accountmanager::Manifest;
let mut manager: accountmanager::AccountManager;
if !path.exists() {
error!("Did not find manifest in {}", mafiles_dir);
match tui::prompt_char(
@ -86,21 +94,35 @@ fn run() -> anyhow::Result<()> {
}
std::fs::create_dir_all(mafiles_dir)?;
manifest = accountmanager::Manifest::new(path.as_path());
manifest.save()?;
manager = accountmanager::AccountManager::new(path.as_path());
manager.save()?;
} else {
manifest = accountmanager::Manifest::load(path.as_path())?;
manager = match accountmanager::AccountManager::load(path.as_path()) {
Ok(m) => m,
Err(ManifestLoadError::MigrationNeeded) => {
info!("Migrating manifest");
let (manifest, accounts) = load_and_migrate(path.as_path(), args.passkey.as_ref())?;
let mut manager = AccountManager::from_manifest(manifest, mafiles_dir);
manager.register_accounts(accounts);
manager.save()?;
manager
}
Err(err) => {
error!("Failed to load manifest: {}", err);
return Err(err.into());
}
}
}
let mut passkey: Option<String> = args.passkey.clone();
manifest.submit_passkey(passkey);
manager.submit_passkey(passkey);
loop {
match manifest.auto_upgrade() {
match manager.auto_upgrade() {
Ok(upgraded) => {
if upgraded {
info!("Manifest auto-upgraded");
manifest.save()?;
manager.save()?;
} else {
debug!("Manifest is up to date");
}
@ -110,11 +132,11 @@ fn run() -> anyhow::Result<()> {
accountmanager::ManifestAccountLoadError::MissingPasskey
| accountmanager::ManifestAccountLoadError::IncorrectPasskey,
) => {
if manifest.has_passkey() {
if manager.has_passkey() {
error!("Incorrect passkey");
}
passkey = rpassword::prompt_password_stderr("Enter encryption passkey: ").ok();
manifest.submit_passkey(passkey);
manager.submit_passkey(passkey);
}
Err(e) => {
error!("Could not load accounts: {}", e);
@ -125,23 +147,23 @@ fn run() -> anyhow::Result<()> {
match args.sub {
Some(cli::Subcommands::Setup(args)) => {
return do_subcmd_setup(args, &mut manifest);
return do_subcmd_setup(args, &mut manager);
}
Some(cli::Subcommands::Import(args)) => {
return do_subcmd_import(args, &mut manifest);
return do_subcmd_import(args, &mut manager);
}
Some(cli::Subcommands::Encrypt(args)) => {
return do_subcmd_encrypt(args, &mut manifest);
return do_subcmd_encrypt(args, &mut manager);
}
Some(cli::Subcommands::Decrypt(args)) => {
return do_subcmd_decrypt(args, &mut manifest);
return do_subcmd_decrypt(args, &mut manager);
}
_ => {}
}
let selected_accounts: Vec<Arc<Mutex<SteamGuardAccount>>>;
loop {
match get_selected_accounts(&args, &mut manifest) {
match get_selected_accounts(&args, &mut manager) {
Ok(accounts) => {
selected_accounts = accounts;
break;
@ -150,11 +172,11 @@ fn run() -> anyhow::Result<()> {
accountmanager::ManifestAccountLoadError::MissingPasskey
| accountmanager::ManifestAccountLoadError::IncorrectPasskey,
) => {
if manifest.has_passkey() {
if manager.has_passkey() {
error!("Incorrect passkey");
}
passkey = rpassword::prompt_password_stdout("Enter encryption passkey: ").ok();
manifest.submit_passkey(passkey);
manager.submit_passkey(passkey);
}
Err(e) => {
error!("Could not load accounts: {}", e);
@ -172,44 +194,38 @@ fn run() -> anyhow::Result<()> {
);
match args.sub.unwrap_or(cli::Subcommands::Code(args.code)) {
cli::Subcommands::Trade(args) => {
return do_subcmd_trade(args, &mut manifest, selected_accounts);
}
cli::Subcommands::Remove(args) => {
return do_subcmd_remove(args, &mut manifest, selected_accounts);
}
cli::Subcommands::Code(args) => {
return do_subcmd_code(args, selected_accounts);
}
cli::Subcommands::Trade(args) => do_subcmd_trade(args, &mut manager, selected_accounts),
cli::Subcommands::Remove(args) => do_subcmd_remove(args, &mut manager, selected_accounts),
cli::Subcommands::Code(args) => do_subcmd_code(args, selected_accounts),
#[cfg(feature = "qr")]
cli::Subcommands::Qr(args) => {
return do_subcmd_qr(args, selected_accounts);
}
cli::Subcommands::Qr(args) => do_subcmd_qr(args, selected_accounts),
#[cfg(debug_assertions)]
cli::Subcommands::TestLogin => test_login::do_subcmd_test_login(selected_accounts),
s => {
error!("Unknown subcommand: {:?}", s);
return Err(errors::UserError::UnknownSubcommand.into());
Err(errors::UserError::UnknownSubcommand.into())
}
}
}
fn get_selected_accounts(
args: &cli::Args,
manifest: &mut accountmanager::Manifest,
manifest: &mut accountmanager::AccountManager,
) -> anyhow::Result<Vec<Arc<Mutex<SteamGuardAccount>>>, ManifestAccountLoadError> {
let mut selected_accounts: Vec<Arc<Mutex<SteamGuardAccount>>> = vec![];
if args.all {
manifest.load_accounts()?;
for entry in &manifest.entries {
for entry in manifest.iter() {
selected_accounts.push(manifest.get_account(&entry.account_name).unwrap().clone());
}
} else {
let entry = if let Some(username) = &args.username {
manifest.get_entry(&username)
manifest.get_entry(username)
} else {
manifest
.entries
.first()
.iter()
.next()
.ok_or(ManifestAccountLoadError::MissingManifestEntry)
}?;
@ -217,11 +233,11 @@ fn get_selected_accounts(
let account = manifest.get_or_load_account(&account_name)?;
selected_accounts.push(account);
}
return Ok(selected_accounts);
Ok(selected_accounts)
}
fn do_login(account: &mut SteamGuardAccount) -> anyhow::Result<()> {
if account.account_name.len() > 0 {
if !account.account_name.is_empty() {
info!("Username: {}", account.account_name);
} else {
eprint!("Username: ");
@ -229,72 +245,124 @@ fn do_login(account: &mut SteamGuardAccount) -> anyhow::Result<()> {
}
let _ = std::io::stdout().flush();
let password = rpassword::prompt_password_stdout("Password: ").unwrap();
if password.len() > 0 {
if !password.is_empty() {
debug!("password is present");
} else {
debug!("password is empty");
}
account.set_session(do_login_impl(
account.account_name.clone(),
password,
Some(account),
)?);
return Ok(());
let tokens = do_login_impl(account.account_name.clone(), password, Some(account))?;
let steam_id = tokens.access_token().decode()?.steam_id();
account.set_tokens(tokens);
account.steam_id = steam_id;
Ok(())
}
fn do_login_raw(username: String) -> anyhow::Result<steamapi::Session> {
fn do_login_raw(username: String) -> anyhow::Result<Tokens> {
let _ = std::io::stdout().flush();
let password = rpassword::prompt_password_stdout("Password: ").unwrap();
if password.len() > 0 {
if !password.is_empty() {
debug!("password is present");
} else {
debug!("password is empty");
}
return do_login_impl(username, password, None);
do_login_impl(username, password, None)
}
fn do_login_impl(
username: String,
password: String,
account: Option<&SteamGuardAccount>,
) -> anyhow::Result<steamapi::Session> {
// TODO: reprompt if password is empty
let mut login = UserLogin::new(username, password);
let mut loops = 0;
) -> anyhow::Result<Tokens> {
let mut login = UserLogin::new(
EAuthTokenPlatformType::k_EAuthTokenPlatformType_MobileApp,
build_device_details(),
);
let mut password = password;
let mut confirmation_methods;
loop {
match login.login() {
Ok(s) => {
return Ok(s);
match login.begin_auth_via_credentials(&username, &password) {
Ok(methods) => {
confirmation_methods = methods;
break;
}
Err(LoginError::Need2FA) => match account {
Some(a) => {
let server_time = steamapi::get_server_time()?.server_time;
login.twofactor_code = a.generate_code(server_time);
}
None => {
print!("Enter 2fa code: ");
login.twofactor_code = tui::prompt();
}
},
Err(LoginError::NeedCaptcha { captcha_gid }) => {
debug!("need captcha to log in");
login.captcha_text = tui::prompt_captcha_text(&captcha_gid);
Err(LoginError::TooManyAttempts) => {
error!("Too many login attempts. Steam is rate limiting you. Please wait a while and try again later.");
return Err(LoginError::TooManyAttempts.into());
}
Err(LoginError::NeedEmail) => {
println!("You should have received an email with a code. If you did not, check your spam folder, or abort and try again.");
print!("Enter code: ");
login.email_code = tui::prompt();
Err(LoginError::BadCredentials) => {
error!("Incorrect password.");
password = rpassword::prompt_password_stdout("Password: ")
.unwrap()
.trim()
.to_owned();
continue;
}
Err(r) => {
error!("Fatal login result: {:?}", r);
bail!(r);
Err(err) => {
error!("Unexpected error when trying to log in. If you report this as a bug, please rerun with `-v debug` or `-v trace` and include all output in your issue. {:?}", err);
return Err(err.into());
}
}
loops += 1;
if loops > 2 {
error!("Too many loops. Aborting login process, to avoid getting rate limited.");
bail!("Too many loops. Login process aborted to avoid getting rate limited.");
}
for (method) in confirmation_methods {
match method.confirmation_type {
EAuthSessionGuardType::k_EAuthSessionGuardType_DeviceConfirmation => {
eprintln!("Please confirm this login on your other device.");
eprintln!("Press enter when you have confirmed.");
tui::pause();
}
EAuthSessionGuardType::k_EAuthSessionGuardType_EmailConfirmation => {
eprint!("Please confirm this login by clicking the link in your email.");
if !method.associated_messsage.is_empty() {
eprint!(" ({})", method.associated_messsage);
}
eprintln!();
eprintln!("Press enter when you have confirmed.");
tui::pause();
}
EAuthSessionGuardType::k_EAuthSessionGuardType_DeviceCode => {
let code = if let Some(account) = account {
debug!("Generating 2fa code...");
let time = steamapi::get_server_time()?.server_time;
account.generate_code(time)
} else {
eprint!("Enter the 2fa code from your device: ");
tui::prompt().trim().to_owned()
};
login.submit_steam_guard_code(method.confirmation_type, code)?;
}
EAuthSessionGuardType::k_EAuthSessionGuardType_EmailCode => {
eprint!("Enter the 2fa code sent to your email: ");
let code = tui::prompt().trim().to_owned();
login.submit_steam_guard_code(method.confirmation_type, code)?;
}
_ => {
warn!("Unknown confirmation method: {:?}", method);
continue;
}
}
break;
}
info!("Polling for tokens... -- If this takes a long time, try logging in again.");
let tokens = login.poll_until_tokens()?;
info!("Logged in successfully!");
Ok(tokens)
}
fn build_device_details() -> DeviceDetails {
DeviceDetails {
friendly_name: format!(
"{} (steamguard-cli)",
gethostname::gethostname()
.into_string()
.expect("failed to get hostname")
),
platform_type: EAuthTokenPlatformType::k_EAuthTokenPlatformType_MobileApp,
os_type: -500,
gaming_device_type: 528,
}
}
@ -313,7 +381,7 @@ fn get_mafiles_dir() -> String {
return paths[0].to_str().unwrap().into();
}
fn load_accounts_with_prompts(manifest: &mut accountmanager::Manifest) -> anyhow::Result<()> {
fn load_accounts_with_prompts(manifest: &mut accountmanager::AccountManager) -> anyhow::Result<()> {
loop {
match manifest.load_accounts() {
Ok(_) => return Ok(()),
@ -348,18 +416,18 @@ fn do_subcmd_debug(args: cli::ArgsDebug) -> anyhow::Result<()> {
if args.demo_conf_menu {
demos::demo_confirmation_menu();
}
return Ok(());
Ok(())
}
fn do_subcmd_completion(args: cli::ArgsCompletions) -> Result<(), anyhow::Error> {
let mut app = cli::Args::command_for_update();
clap_complete::generate(args.shell, &mut app, "steamguard", &mut std::io::stdout());
return Ok(());
Ok(())
}
fn do_subcmd_setup(
_args: cli::ArgsSetup,
manifest: &mut accountmanager::Manifest,
manifest: &mut accountmanager::AccountManager,
) -> anyhow::Result<()> {
eprintln!("Log in to the account that you want to link to steamguard-cli");
eprint!("Username: ");
@ -376,11 +444,11 @@ fn do_subcmd_setup(
info!("Adding authenticator...");
let mut linker = AccountLinker::new(session);
let account: SteamGuardAccount;
let link: AccountLinkSuccess;
loop {
match linker.link() {
Ok(a) => {
account = a;
link = a;
break;
}
Err(AccountLinkError::MustRemovePhoneNumber) => {
@ -409,33 +477,42 @@ fn do_subcmd_setup(
}
}
}
manifest.add_account(account);
let mut server_time = link.server_time();
let phone_number_hint = link.phone_number_hint().to_owned();
manifest.add_account(link.into_account());
match manifest.save() {
Ok(_) => {}
Err(err) => {
error!("Aborting the account linking process because we failed to save the manifest. This is really bad. Here is the error: {}", err);
println!(
"Just in case, here is the account info. Save it somewhere just in case!\n{:?}",
"Just in case, here is the account info. Save it somewhere just in case!\n{:#?}",
manifest.get_account(&account_name).unwrap().lock().unwrap()
);
return Err(err.into());
return Err(err);
}
}
let account_arc = manifest.get_account(&account_name).unwrap();
let account_arc = manifest
.get_account(&account_name)
.expect("account was not present in manifest");
let mut account = account_arc.lock().unwrap();
println!("Authenticator has not yet been linked. Before continuing with finalization, please take the time to write down your revocation code: {}", account.revocation_code.expose_secret());
tui::pause();
debug!("attempting link finalization");
println!(
"A code has been sent to your phone number ending in {}.",
phone_number_hint
);
print!("Enter SMS code: ");
let sms_code = tui::prompt();
let mut tries = 0;
loop {
match linker.finalize(&mut account, sms_code.clone()) {
match linker.finalize(server_time, &mut account, sms_code.clone()) {
Ok(_) => break,
Err(FinalizeLinkError::WantMore) => {
Err(FinalizeLinkError::WantMore { server_time: s }) => {
server_time = s;
debug!("steam wants more 2fa codes (tries: {})", tries);
tries += 1;
if tries >= 30 {
@ -449,6 +526,8 @@ fn do_subcmd_setup(
}
}
}
let revocation_code = account.revocation_code.clone();
drop(account); // explicitly drop the lock so we don't hang on the mutex
println!("Authenticator finalized.");
match manifest.save() {
@ -464,39 +543,51 @@ fn do_subcmd_setup(
println!(
"Authenticator has been finalized. Please actually write down your revocation code: {}",
account.revocation_code.expose_secret()
revocation_code.expose_secret()
);
return Ok(());
Ok(())
}
fn do_subcmd_import(
args: cli::ArgsImport,
manifest: &mut accountmanager::Manifest,
manifest: &mut accountmanager::AccountManager,
) -> anyhow::Result<()> {
for file_path in args.files {
match manifest.import_account(&file_path) {
Ok(_) => {
info!("Imported account: {}", &file_path);
}
Err(err) => {
bail!("Failed to import account: {} {}", &file_path, err);
if args.sda {
let path = Path::new(&file_path);
let account = accountmanager::migrate::load_and_upgrade_sda_account(path)?;
manifest.add_account(account);
info!("Imported account: {}", &file_path);
} else {
match manifest.import_account(&file_path) {
Ok(_) => {
info!("Imported account: {}", &file_path);
}
Err(err) => {
bail!("Failed to import account: {} {}", &file_path, err);
}
}
}
}
manifest.save()?;
return Ok(());
Ok(())
}
fn do_subcmd_trade(
args: cli::ArgsTrade,
manifest: &mut accountmanager::Manifest,
manifest: &mut accountmanager::AccountManager,
mut selected_accounts: Vec<Arc<Mutex<SteamGuardAccount>>>,
) -> anyhow::Result<()> {
for a in selected_accounts.iter_mut() {
let mut account = a.lock().unwrap();
if !account.is_logged_in() {
info!("Account does not have tokens, logging in");
do_login(&mut account)?;
}
info!("Checking for trade confirmations");
let confirmations: Vec<Confirmation>;
loop {
@ -505,7 +596,8 @@ fn do_subcmd_trade(
confirmations = confs;
break;
}
Err(_) => {
Err(err) => {
error!("Failed to get trade confirmations: {:#?}", err);
info!("failed to get trade confirmations, asking user to log in");
do_login(&mut account)?;
}
@ -527,40 +619,38 @@ fn do_subcmd_trade(
debug!("accept confirmation result: {:?}", result);
}
}
} else {
if stdout().is_tty() {
let (accept, deny) = tui::prompt_confirmation_menu(confirmations)?;
for conf in &accept {
let result = account.accept_confirmation(conf);
if result.is_err() {
warn!("accept confirmation result: {:?}", result);
any_failed = true;
if args.fail_fast {
return result;
}
} else {
debug!("accept confirmation result: {:?}", result);
} else if stdout().is_tty() {
let (accept, deny) = tui::prompt_confirmation_menu(confirmations)?;
for conf in &accept {
let result = account.accept_confirmation(conf);
if result.is_err() {
warn!("accept confirmation result: {:?}", result);
any_failed = true;
if args.fail_fast {
return result;
}
} else {
debug!("accept confirmation result: {:?}", result);
}
for conf in &deny {
let result = account.deny_confirmation(conf);
}
for conf in &deny {
let result = account.deny_confirmation(conf);
debug!("deny confirmation result: {:?}", result);
if result.is_err() {
warn!("deny confirmation result: {:?}", result);
any_failed = true;
if args.fail_fast {
return result;
}
} else {
debug!("deny confirmation result: {:?}", result);
if result.is_err() {
warn!("deny confirmation result: {:?}", result);
any_failed = true;
if args.fail_fast {
return result;
}
} else {
debug!("deny confirmation result: {:?}", result);
}
}
} else {
warn!("not a tty, not showing menu");
for conf in &confirmations {
println!("{}", conf.description());
}
}
} else {
warn!("not a tty, not showing menu");
for conf in &confirmations {
println!("{}", conf.description());
}
}
if any_failed {
@ -569,12 +659,12 @@ fn do_subcmd_trade(
}
manifest.save()?;
return Ok(());
Ok(())
}
fn do_subcmd_remove(
_args: cli::ArgsRemove,
manifest: &mut accountmanager::Manifest,
manifest: &mut accountmanager::AccountManager,
selected_accounts: Vec<Arc<Mutex<SteamGuardAccount>>>,
) -> anyhow::Result<()> {
println!(
@ -597,7 +687,12 @@ fn do_subcmd_remove(
let mut successful = vec![];
for a in selected_accounts {
let account = a.lock().unwrap();
let mut account = a.lock().unwrap();
if !account.is_logged_in() {
info!("Account does not have tokens, logging in");
do_login(&mut account)?;
}
match account.remove_authenticator(None) {
Ok(success) => {
if success {
@ -633,12 +728,12 @@ fn do_subcmd_remove(
}
manifest.save()?;
return Ok(());
Ok(())
}
fn do_subcmd_encrypt(
_args: cli::ArgsEncrypt,
manifest: &mut accountmanager::Manifest,
manifest: &mut accountmanager::AccountManager,
) -> anyhow::Result<()> {
if !manifest.has_passkey() {
let mut passkey;
@ -660,24 +755,24 @@ fn do_subcmd_encrypt(
manifest.submit_passkey(passkey);
}
manifest.load_accounts()?;
for entry in &mut manifest.entries {
for entry in manifest.iter_mut() {
entry.encryption = Some(accountmanager::EntryEncryptionParams::generate());
}
manifest.save()?;
return Ok(());
Ok(())
}
fn do_subcmd_decrypt(
_args: cli::ArgsDecrypt,
manifest: &mut accountmanager::Manifest,
manifest: &mut accountmanager::AccountManager,
) -> anyhow::Result<()> {
load_accounts_with_prompts(manifest)?;
for entry in &mut manifest.entries {
for mut entry in manifest.iter_mut() {
entry.encryption = None;
}
manifest.submit_passkey(None);
manifest.save()?;
return Ok(());
Ok(())
}
fn do_subcmd_code(
@ -699,7 +794,7 @@ fn do_subcmd_code(
let code = account.lock().unwrap().generate_code(server_time);
println!("{}", code);
}
return Ok(());
Ok(())
}
#[cfg(feature = "qr")]
@ -736,5 +831,5 @@ fn do_subcmd_qr(
println!("{}", qr_string);
}
return Ok(());
Ok(())
}

55
src/secret_string.rs Normal file
View file

@ -0,0 +1,55 @@
use secrecy::{ExposeSecret, SecretString};
use serde::{Deserialize, Deserializer, Serializer};
/// Helper to allow serializing a [secrecy::SecretString] as a [String]
pub(crate) fn serialize<S>(secret_string: &SecretString, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(secret_string.expose_secret())
}
/// Helper to allow deserializing a [String] as a [secrecy::SecretString]
pub(crate) fn deserialize<'de, D>(d: D) -> Result<secrecy::SecretString, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(d)?;
Ok(SecretString::new(s))
}
#[cfg(test)]
mod test {
use serde::Serialize;
use super::*;
#[test]
fn test_secret_string_round_trip() {
#[derive(Serialize, Deserialize)]
struct Foo {
#[serde(with = "super")]
secret: SecretString,
}
let foo = Foo {
secret: String::from("hello").into(),
};
let s = serde_json::to_string(&foo).unwrap();
let foo2: Foo = serde_json::from_str(&s).unwrap();
assert_eq!(foo.secret.expose_secret(), foo2.secret.expose_secret());
}
#[test]
fn test_secret_string_deserialize() {
#[derive(Serialize, Deserialize)]
struct Foo {
#[serde(with = "super")]
secret: SecretString,
}
let foo: Foo = serde_json::from_str("{\"secret\": \"hello\"}").unwrap();
assert_eq!(foo.secret.expose_secret(), "hello");
}
}

18
src/test_login.rs Normal file
View file

@ -0,0 +1,18 @@
use std::sync::{Arc, Mutex};
use log::info;
use steamguard::SteamGuardAccount;
use crate::do_login;
pub fn do_subcmd_test_login(
selected_accounts: Vec<Arc<Mutex<SteamGuardAccount>>>,
) -> anyhow::Result<()> {
for account in selected_accounts {
let mut account = account.lock().unwrap();
do_login(&mut account)?;
info!("Logged in successfully!");
}
Ok(())
}

View file

@ -18,7 +18,7 @@ lazy_static! {
}
pub fn validate_captcha_text(text: &String) -> bool {
return CAPTCHA_VALID_CHARS.is_match(text);
CAPTCHA_VALID_CHARS.is_match(text)
}
#[test]
@ -66,12 +66,12 @@ pub(crate) fn prompt_captcha_text(captcha_gid: &String) -> String {
loop {
eprint!("Enter captcha text: ");
captcha_text = prompt();
if captcha_text.len() > 0 && validate_captcha_text(&captcha_text) {
if !captcha_text.is_empty() && validate_captcha_text(&captcha_text) {
break;
}
warn!("Invalid chars for captcha text found in user's input. Prompting again...");
}
return captcha_text;
captcha_text
}
/// Prompt the user for a single character response. Useful for asking yes or no questions.
@ -104,7 +104,7 @@ where
let answer: String = input.into().to_ascii_lowercase();
if answer.len() == 0 {
if answer.is_empty() {
if let Some(a) = default_answer {
return Ok(a);
} else {
@ -126,7 +126,7 @@ where
pub(crate) fn prompt_confirmation_menu(
confirmations: Vec<Confirmation>,
) -> anyhow::Result<(Vec<Confirmation>, Vec<Confirmation>)> {
if confirmations.len() == 0 {
if confirmations.is_empty() {
bail!("no confirmations")
}

View file

@ -14,7 +14,7 @@ license = "MIT OR Apache-2.0"
anyhow = "^1.0"
hmac-sha1 = "^0.1"
base64 = "0.13.0"
reqwest = { version = "0.11", default-features = false, features = ["blocking", "json", "cookies", "gzip", "rustls-tls"] }
reqwest = { version = "0.11", default-features = false, features = ["blocking", "json", "cookies", "gzip", "rustls-tls", "multipart"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
rsa = "0.5.0"
@ -30,3 +30,10 @@ maplit = "1.0.2"
thiserror = "1.0.26"
secrecy = { version = "0.8", features = ["serde"] }
zeroize = "^1.4.3"
protobuf = "3.2.0"
protobuf-json-mapping = "3.2.0"
[build-dependencies]
anyhow = "^1.0"
protobuf = "3.2.0"
protobuf-codegen = "3.2.0"

75
steamguard/build.rs Normal file
View file

@ -0,0 +1,75 @@
use std::path::Path;
use std::path::PathBuf;
use protobuf::reflect::MessageDescriptor;
use protobuf_codegen::Codegen;
use protobuf_codegen::Customize;
use protobuf_codegen::CustomizeCallback;
fn main() {
// let current_dir = std::env::current_dir().unwrap();
let mut codegen = Codegen::new();
codegen.pure();
codegen.include("protobufs");
// get all the .proto files in the protobufs directory using std
let proto_files = get_all_proto_paths("protobufs").expect("failed to read protobufs directory");
for proto_file in proto_files {
codegen.input(proto_file);
}
codegen.cargo_out_dir("protobufs");
codegen.customize_callback(GenSerde);
codegen.run_from_script();
println!("cargo:rerun-if-changed=protobufs");
println!("cargo:rerun-if-changed=build.rs");
}
fn get_all_proto_paths<P: AsRef<Path>>(dir: P) -> anyhow::Result<Vec<PathBuf>> {
let mut paths = Vec::new();
let proto_files = std::fs::read_dir(dir).expect("failed to read protobufs directory");
for proto_file in proto_files {
let proto_file = proto_file?;
if proto_file.file_type().unwrap().is_dir() {
let sub_paths = get_all_proto_paths(proto_file.path())?;
paths.extend(sub_paths);
} else {
paths.push(proto_file.path());
}
}
Ok(paths)
}
struct GenSerde;
impl CustomizeCallback for GenSerde {
fn message(&self, _message: &MessageDescriptor) -> Customize {
// Customize::default().before("#[derive(::serde::Serialize, ::serde::Deserialize)]")
Customize::default()
}
fn enumeration(&self, _enum_type: &protobuf::reflect::EnumDescriptor) -> Customize {
Customize::default().before("#[derive(::serde::Serialize, ::serde::Deserialize)]")
}
// fn field(&self, field: &FieldDescriptor) -> Customize {
// // if field.name() == "public_ip" {
// // eprintln!("type_name: {:?}", field.proto().type_name());
// // eprintln!("type_: {:?}", field.proto().type_());
// // eprintln!("{:?}", field.proto());
// // }
// if field.proto().type_() == Type::TYPE_ENUM {
// // `EnumOrUnknown` is not a part of rust-protobuf, so external serializer is needed.
// Customize::default().before(
// "#[serde(serialize_with = \"crate::protobufs::serialize_enum_or_unknown\", deserialize_with = \"crate::protobufs::deserialize_enum_or_unknown\")]")
// // } else if field.name() == "public_ip" {
// // Customize::default().before("#[serde(with = \"crate::protobufs::MessageFieldDef\")]")
// } else {
// Customize::default()
// }
// }
// fn special_field(&self, _message: &MessageDescriptor, _field: &str) -> Customize {
// Customize::default().before("#[serde(skip)]")
// }
}

View file

@ -0,0 +1,5 @@
message NoResponse {
}
message NotImplemented {
}

View file

@ -0,0 +1,23 @@
import "steammessages_base.proto";
import "steammessages_unified_base.steamclient.proto";
import "enums.proto";
import "steammessages_auth.steamclient.proto";
option cc_generic_services = true;
message CAuthentication_BeginAuthSessionViaCredentials_Request_BinaryGuardData {
optional string device_friendly_name = 1;
optional string account_name = 2;
optional string encrypted_password = 3 [(description) = "password, RSA encrypted client side"];
optional uint64 encryption_timestamp = 4 [(description) = "timestamp to map to a key - STime"];
optional bool remember_login = 5 [(description) = "deprecated"];
optional .EAuthTokenPlatformType platform_type = 6 [default = k_EAuthTokenPlatformType_Unknown];
optional .ESessionPersistence persistence = 7 [default = k_ESessionPersistence_Persistent, (description) = "whether we are requesting a persistent or an ephemeral session"];
optional string website_id = 8 [default = "Unknown", (description) = "(EMachineAuthWebDomain) identifier of client requesting auth"];
optional .CAuthentication_DeviceDetails device_details = 9 [(description) = "User-supplied details about the device attempting to sign in"];
optional bytes guard_data = 10 [(description) = "steam guard data for client login"];
optional uint32 language = 11;
optional int32 qos_level = 12 [default = 2, (description) = "[ENetQOSLevel] client-specified priority for this auth attempt"];
}
message CTwoFactor_Time_Request {}

View file

@ -0,0 +1,344 @@
import "steammessages_base.proto";
option optimize_for = SPEED;
option cc_generic_services = true;
option (force_php_generation) = true;
enum EPublishedFileQueryType {
k_PublishedFileQueryType_RankedByVote = 0;
k_PublishedFileQueryType_RankedByPublicationDate = 1;
k_PublishedFileQueryType_AcceptedForGameRankedByAcceptanceDate = 2;
k_PublishedFileQueryType_RankedByTrend = 3;
k_PublishedFileQueryType_FavoritedByFriendsRankedByPublicationDate = 4;
k_PublishedFileQueryType_CreatedByFriendsRankedByPublicationDate = 5;
k_PublishedFileQueryType_RankedByNumTimesReported = 6;
k_PublishedFileQueryType_CreatedByFollowedUsersRankedByPublicationDate = 7;
k_PublishedFileQueryType_NotYetRated = 8;
k_PublishedFileQueryType_RankedByTotalUniqueSubscriptions = 9;
k_PublishedFileQueryType_RankedByTotalVotesAsc = 10;
k_PublishedFileQueryType_RankedByVotesUp = 11;
k_PublishedFileQueryType_RankedByTextSearch = 12;
k_PublishedFileQueryType_RankedByPlaytimeTrend = 13;
k_PublishedFileQueryType_RankedByTotalPlaytime = 14;
k_PublishedFileQueryType_RankedByAveragePlaytimeTrend = 15;
k_PublishedFileQueryType_RankedByLifetimeAveragePlaytime = 16;
k_PublishedFileQueryType_RankedByPlaytimeSessionsTrend = 17;
k_PublishedFileQueryType_RankedByLifetimePlaytimeSessions = 18;
k_PublishedFileQueryType_RankedByInappropriateContentRating = 19;
k_PublishedFileQueryType_RankedByBanContentCheck = 20;
k_PublishedFileQueryType_RankedByLastUpdatedDate = 21;
}
enum EPublishedFileInappropriateProvider {
k_EPublishedFileInappropriateProvider_Invalid = 0;
k_EPublishedFileInappropriateProvider_Google = 1;
k_EPublishedFileInappropriateProvider_Amazon = 2;
}
enum EPublishedFileInappropriateResult {
k_EPublishedFileInappropriateResult_NotScanned = 0;
k_EPublishedFileInappropriateResult_VeryUnlikely = 1;
k_EPublishedFileInappropriateResult_Unlikely = 30;
k_EPublishedFileInappropriateResult_Possible = 50;
k_EPublishedFileInappropriateResult_Likely = 75;
k_EPublishedFileInappropriateResult_VeryLikely = 100;
}
enum EPersonaStateFlag {
k_EPersonaStateFlag_HasRichPresence = 1;
k_EPersonaStateFlag_InJoinableGame = 2;
k_EPersonaStateFlag_Golden = 4;
k_EPersonaStateFlag_RemotePlayTogether = 8;
k_EPersonaStateFlag_ClientTypeWeb = 256;
k_EPersonaStateFlag_ClientTypeMobile = 512;
k_EPersonaStateFlag_ClientTypeTenfoot = 1024;
k_EPersonaStateFlag_ClientTypeVR = 2048;
k_EPersonaStateFlag_LaunchTypeGamepad = 4096;
k_EPersonaStateFlag_LaunchTypeCompatTool = 8192;
}
enum EContentCheckProvider {
k_EContentCheckProvider_Invalid = 0;
k_EContentCheckProvider_Google = 1;
k_EContentCheckProvider_Amazon = 2;
k_EContentCheckProvider_Local = 3;
}
enum EProfileCustomizationType {
k_EProfileCustomizationTypeInvalid = 0;
k_EProfileCustomizationTypeRareAchievementShowcase = 1;
k_EProfileCustomizationTypeGameCollector = 2;
k_EProfileCustomizationTypeItemShowcase = 3;
k_EProfileCustomizationTypeTradeShowcase = 4;
k_EProfileCustomizationTypeBadges = 5;
k_EProfileCustomizationTypeFavoriteGame = 6;
k_EProfileCustomizationTypeScreenshotShowcase = 7;
k_EProfileCustomizationTypeCustomText = 8;
k_EProfileCustomizationTypeFavoriteGroup = 9;
k_EProfileCustomizationTypeRecommendation = 10;
k_EProfileCustomizationTypeWorkshopItem = 11;
k_EProfileCustomizationTypeMyWorkshop = 12;
k_EProfileCustomizationTypeArtworkShowcase = 13;
k_EProfileCustomizationTypeVideoShowcase = 14;
k_EProfileCustomizationTypeGuides = 15;
k_EProfileCustomizationTypeMyGuides = 16;
k_EProfileCustomizationTypeAchievements = 17;
k_EProfileCustomizationTypeGreenlight = 18;
k_EProfileCustomizationTypeMyGreenlight = 19;
k_EProfileCustomizationTypeSalien = 20;
k_EProfileCustomizationTypeLoyaltyRewardReactions = 21;
k_EProfileCustomizationTypeSingleArtworkShowcase = 22;
k_EProfileCustomizationTypeAchievementsCompletionist = 23;
}
enum EPublishedFileStorageSystem {
k_EPublishedFileStorageSystemInvalid = 0;
k_EPublishedFileStorageSystemLegacyCloud = 1;
k_EPublishedFileStorageSystemDepot = 2;
k_EPublishedFileStorageSystemUGCCloud = 3;
}
enum ECloudStoragePersistState {
k_ECloudStoragePersistStatePersisted = 0;
k_ECloudStoragePersistStateForgotten = 1;
k_ECloudStoragePersistStateDeleted = 2;
}
enum ESDCardFormatStage {
k_ESDCardFormatStage_Invalid = 0;
k_ESDCardFormatStage_Starting = 1;
k_ESDCardFormatStage_Testing = 2;
k_ESDCardFormatStage_Rescuing = 3;
k_ESDCardFormatStage_Formatting = 4;
k_ESDCardFormatStage_Finalizing = 5;
}
enum ESystemFanControlMode {
k_SystemFanControlMode_Invalid = 0;
k_SystemFanControlMode_Disabled = 1;
k_SystemFanControlMode_Default = 2;
}
enum EColorProfile {
k_EColorProfile_Invalid = 0;
k_EColorProfile_Native = 1;
k_EColorProfile_Standard = 2;
k_EColorProfile_Vivid = 3;
}
enum EBluetoothDeviceType {
k_BluetoothDeviceType_Invalid = 0;
k_BluetoothDeviceType_Unknown = 1;
k_BluetoothDeviceType_Phone = 2;
k_BluetoothDeviceType_Computer = 3;
k_BluetoothDeviceType_Headset = 4;
k_BluetoothDeviceType_Headphones = 5;
k_BluetoothDeviceType_Speakers = 6;
k_BluetoothDeviceType_OtherAudio = 7;
k_BluetoothDeviceType_Mouse = 8;
k_BluetoothDeviceType_Joystick = 9;
k_BluetoothDeviceType_Gamepad = 10;
k_BluetoothDeviceType_Keyboard = 11;
}
enum ESystemAudioDirection {
k_SystemAudioDirection_Invalid = 0;
k_SystemAudioDirection_Input = 1;
k_SystemAudioDirection_Output = 2;
}
enum ESystemAudioChannel {
k_SystemAudioChannel_Invalid = 0;
k_SystemAudioChannel_Aggregated = 1;
k_SystemAudioChannel_FrontLeft = 2;
k_SystemAudioChannel_FrontRight = 3;
k_SystemAudioChannel_LFE = 4;
k_SystemAudioChannel_BackLeft = 5;
k_SystemAudioChannel_BackRight = 6;
k_SystemAudioChannel_FrontCenter = 7;
k_SystemAudioChannel_Unknown = 8;
k_SystemAudioChannel_Mono = 9;
}
enum ESystemAudioPortType {
k_SystemAudioPortType_Invalid = 0;
k_SystemAudioPortType_Unknown = 1;
k_SystemAudioPortType_Audio32f = 2;
k_SystemAudioPortType_Midi8b = 3;
k_SystemAudioPortType_Video32RGBA = 4;
}
enum ESystemAudioPortDirection {
k_SystemAudioPortDirection_Invalid = 0;
k_SystemAudioPortDirection_Input = 1;
k_SystemAudioPortDirection_Output = 2;
}
enum ESystemServiceState {
k_ESystemServiceState_Unavailable = 0;
k_ESystemServiceState_Disabled = 1;
k_ESystemServiceState_Enabled = 2;
}
enum EGraphicsPerfOverlayLevel {
k_EGraphicsPerfOverlayLevel_Hidden = 0;
k_EGraphicsPerfOverlayLevel_Basic = 1;
k_EGraphicsPerfOverlayLevel_Medium = 2;
k_EGraphicsPerfOverlayLevel_Full = 3;
k_EGraphicsPerfOverlayLevel_Minimal = 4;
}
enum EGPUPerformanceLevel {
k_EGPUPerformanceLevel_Invalid = 0;
k_EGPUPerformanceLevel_Auto = 1;
k_EGPUPerformanceLevel_Manual = 2;
k_EGPUPerformanceLevel_Low = 3;
k_EGPUPerformanceLevel_High = 4;
k_EGPUPerformanceLevel_Profiling = 5;
}
enum EScalingFilter {
k_EScalingFilter_Invalid = 0;
k_EScalingFilter_FSR = 1;
k_EScalingFilter_Nearest = 2;
k_EScalingFilter_Integer = 3;
k_EScalingFilter_Linear = 4;
k_EScalingFilter_NIS = 5;
}
enum ECPUGovernor {
k_ECPUGovernor_Invalid = 0;
k_ECPUGovernor_Perf = 1;
k_ECPUGovernor_Powersave = 2;
k_ECPUGovernor_Manual = 3;
}
enum EUpdaterType {
k_EUpdaterType_Invalid = 0;
k_EUpdaterType_Client = 1;
k_EUpdaterType_OS = 2;
k_EUpdaterType_BIOS = 3;
k_EUpdaterType_Aggregated = 4;
k_EUpdaterType_Test1 = 5;
k_EUpdaterType_Test2 = 6;
k_EUpdaterType_Dummy = 7;
}
enum EUpdaterState {
k_EUpdaterState_Invalid = 0;
k_EUpdaterState_UpToDate = 2;
k_EUpdaterState_Checking = 3;
k_EUpdaterState_Available = 4;
k_EUpdaterState_Applying = 5;
k_EUpdaterState_ClientRestartPending = 6;
k_EUpdaterState_SystemRestartPending = 7;
}
enum EStorageBlockContentType {
k_EStorageBlockContentType_Invalid = 0;
k_EStorageBlockContentType_Unknown = 1;
k_EStorageBlockContentType_FileSystem = 2;
k_EStorageBlockContentType_Crypto = 3;
k_EStorageBlockContentType_Raid = 4;
}
enum EStorageBlockFileSystemType {
k_EStorageBlockFileSystemType_Invalid = 0;
k_EStorageBlockFileSystemType_Unknown = 1;
k_EStorageBlockFileSystemType_VFat = 2;
k_EStorageBlockFileSystemType_Ext4 = 3;
}
enum ESteamDeckCompatibilityCategory {
k_ESteamDeckCompatibilityCategory_Unknown = 0;
k_ESteamDeckCompatibilityCategory_Unsupported = 1;
k_ESteamDeckCompatibilityCategory_Playable = 2;
k_ESteamDeckCompatibilityCategory_Verified = 3;
}
enum ESteamDeckCompatibilityResultDisplayType {
k_ESteamDeckCompatibilityResultDisplayType_Invisible = 0;
k_ESteamDeckCompatibilityResultDisplayType_Informational = 1;
k_ESteamDeckCompatibilityResultDisplayType_Unsupported = 2;
k_ESteamDeckCompatibilityResultDisplayType_Playable = 3;
k_ESteamDeckCompatibilityResultDisplayType_Verified = 4;
}
enum EACState {
k_EACState_Unknown = 0;
k_EACState_Disconnected = 1;
k_EACState_Connected = 2;
k_EACState_ConnectedSlow = 3;
}
enum EBatteryState {
k_EBatteryState_Unknown = 0;
k_EBatteryState_Discharging = 1;
k_EBatteryState_Charging = 2;
k_EBatteryState_Full = 3;
}
enum EOSBranch {
k_EOSBranch_Unknown = 0;
k_EOSBranch_Release = 1;
k_EOSBranch_ReleaseCandidate = 2;
k_EOSBranch_Beta = 3;
k_EOSBranch_BetaCandidate = 4;
k_EOSBranch_Main = 5;
}
enum ECommunityItemClass {
k_ECommunityItemClass_Invalid = 0;
k_ECommunityItemClass_Badge = 1;
k_ECommunityItemClass_GameCard = 2;
k_ECommunityItemClass_ProfileBackground = 3;
k_ECommunityItemClass_Emoticon = 4;
k_ECommunityItemClass_BoosterPack = 5;
k_ECommunityItemClass_Consumable = 6;
k_ECommunityItemClass_GameGoo = 7;
k_ECommunityItemClass_ProfileModifier = 8;
k_ECommunityItemClass_Scene = 9;
k_ECommunityItemClass_SalienItem = 10;
k_ECommunityItemClass_Sticker = 11;
k_ECommunityItemClass_ChatEffect = 12;
k_ECommunityItemClass_MiniProfileBackground = 13;
k_ECommunityItemClass_AvatarFrame = 14;
k_ECommunityItemClass_AnimatedAvatar = 15;
k_ECommunityItemClass_SteamDeckKeyboardSkin = 16;
}
enum ESteamDeckCompatibilityFeedback {
k_ESteamDeckCompatibilityFeedback_Unset = 0;
k_ESteamDeckCompatibilityFeedback_Agree = 1;
k_ESteamDeckCompatibilityFeedback_Disagree = 2;
k_ESteamDeckCompatibilityFeedback_Ignore = 3;
}
enum EProvideDeckFeedbackPreference {
k_EProvideDeckFeedbackPreference_Unset = 0;
k_EProvideDeckFeedbackPreference_Yes = 1;
k_EProvideDeckFeedbackPreference_No = 2;
}
enum ETouchGesture {
k_ETouchGestureNone = 0;
k_ETouchGestureTouch = 1;
k_ETouchGestureTap = 2;
k_ETouchGestureDoubleTap = 3;
k_ETouchGestureShortPress = 4;
k_ETouchGestureLongPress = 5;
k_ETouchGestureLongTap = 6;
k_ETouchGestureTwoFingerTap = 7;
k_ETouchGestureTapCancelled = 8;
k_ETouchGesturePinchBegin = 9;
k_ETouchGesturePinchUpdate = 10;
k_ETouchGesturePinchEnd = 11;
k_ETouchGestureFlingStart = 12;
k_ETouchGestureFlingCancelled = 13;
}
enum ESessionPersistence {
k_ESessionPersistence_Invalid = -1;
k_ESessionPersistence_Ephemeral = 0;
k_ESessionPersistence_Persistent = 1;
}

View file

@ -0,0 +1,935 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// The messages in this file describe the definitions found in .proto files.
// A valid .proto file can be translated directly to a FileDescriptorProto
// without any other information (e.g. without reading its imports).
syntax = "proto2";
package google.protobuf;
option go_package = "google.golang.org/protobuf/types/descriptorpb";
option java_package = "com.google.protobuf";
option java_outer_classname = "DescriptorProtos";
option csharp_namespace = "Google.Protobuf.Reflection";
option objc_class_prefix = "GPB";
option cc_enable_arenas = true;
// descriptor.proto must be optimized for speed because reflection-based
// algorithms don't work during bootstrapping.
option optimize_for = SPEED;
// The protocol compiler can output a FileDescriptorSet containing the .proto
// files it parses.
message FileDescriptorSet {
repeated FileDescriptorProto file = 1;
}
// Describes a complete .proto file.
message FileDescriptorProto {
optional string name = 1; // file name, relative to root of source tree
optional string package = 2; // e.g. "foo", "foo.bar", etc.
// Names of files imported by this file.
repeated string dependency = 3;
// Indexes of the public imported files in the dependency list above.
repeated int32 public_dependency = 10;
// Indexes of the weak imported files in the dependency list.
// For Google-internal migration only. Do not use.
repeated int32 weak_dependency = 11;
// All top-level definitions in this file.
repeated DescriptorProto message_type = 4;
repeated EnumDescriptorProto enum_type = 5;
repeated ServiceDescriptorProto service = 6;
repeated FieldDescriptorProto extension = 7;
optional FileOptions options = 8;
// This field contains optional information about the original source code.
// You may safely remove this entire field without harming runtime
// functionality of the descriptors -- the information is needed only by
// development tools.
optional SourceCodeInfo source_code_info = 9;
// The syntax of the proto file.
// The supported values are "proto2", "proto3", and "editions".
//
// If `edition` is present, this value must be "editions".
optional string syntax = 12;
// The edition of the proto file, which is an opaque string.
optional string edition = 13;
}
// Describes a message type.
message DescriptorProto {
optional string name = 1;
repeated FieldDescriptorProto field = 2;
repeated FieldDescriptorProto extension = 6;
repeated DescriptorProto nested_type = 3;
repeated EnumDescriptorProto enum_type = 4;
message ExtensionRange {
optional int32 start = 1; // Inclusive.
optional int32 end = 2; // Exclusive.
optional ExtensionRangeOptions options = 3;
}
repeated ExtensionRange extension_range = 5;
repeated OneofDescriptorProto oneof_decl = 8;
optional MessageOptions options = 7;
// Range of reserved tag numbers. Reserved tag numbers may not be used by
// fields or extension ranges in the same message. Reserved ranges may
// not overlap.
message ReservedRange {
optional int32 start = 1; // Inclusive.
optional int32 end = 2; // Exclusive.
}
repeated ReservedRange reserved_range = 9;
// Reserved field names, which may not be used by fields in the same message.
// A given name may only be reserved once.
repeated string reserved_name = 10;
}
message ExtensionRangeOptions {
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
// Describes a field within a message.
message FieldDescriptorProto {
enum Type {
// 0 is reserved for errors.
// Order is weird for historical reasons.
TYPE_DOUBLE = 1;
TYPE_FLOAT = 2;
// Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if
// negative values are likely.
TYPE_INT64 = 3;
TYPE_UINT64 = 4;
// Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if
// negative values are likely.
TYPE_INT32 = 5;
TYPE_FIXED64 = 6;
TYPE_FIXED32 = 7;
TYPE_BOOL = 8;
TYPE_STRING = 9;
// Tag-delimited aggregate.
// Group type is deprecated and not supported in proto3. However, Proto3
// implementations should still be able to parse the group wire format and
// treat group fields as unknown fields.
TYPE_GROUP = 10;
TYPE_MESSAGE = 11; // Length-delimited aggregate.
// New in version 2.
TYPE_BYTES = 12;
TYPE_UINT32 = 13;
TYPE_ENUM = 14;
TYPE_SFIXED32 = 15;
TYPE_SFIXED64 = 16;
TYPE_SINT32 = 17; // Uses ZigZag encoding.
TYPE_SINT64 = 18; // Uses ZigZag encoding.
}
enum Label {
// 0 is reserved for errors
LABEL_OPTIONAL = 1;
LABEL_REQUIRED = 2;
LABEL_REPEATED = 3;
}
optional string name = 1;
optional int32 number = 3;
optional Label label = 4;
// If type_name is set, this need not be set. If both this and type_name
// are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP.
optional Type type = 5;
// For message and enum types, this is the name of the type. If the name
// starts with a '.', it is fully-qualified. Otherwise, C++-like scoping
// rules are used to find the type (i.e. first the nested types within this
// message are searched, then within the parent, on up to the root
// namespace).
optional string type_name = 6;
// For extensions, this is the name of the type being extended. It is
// resolved in the same manner as type_name.
optional string extendee = 2;
// For numeric types, contains the original text representation of the value.
// For booleans, "true" or "false".
// For strings, contains the default text contents (not escaped in any way).
// For bytes, contains the C escaped value. All bytes >= 128 are escaped.
optional string default_value = 7;
// If set, gives the index of a oneof in the containing type's oneof_decl
// list. This field is a member of that oneof.
optional int32 oneof_index = 9;
// JSON name of this field. The value is set by protocol compiler. If the
// user has set a "json_name" option on this field, that option's value
// will be used. Otherwise, it's deduced from the field's name by converting
// it to camelCase.
optional string json_name = 10;
optional FieldOptions options = 8;
// If true, this is a proto3 "optional". When a proto3 field is optional, it
// tracks presence regardless of field type.
//
// When proto3_optional is true, this field must be belong to a oneof to
// signal to old proto3 clients that presence is tracked for this field. This
// oneof is known as a "synthetic" oneof, and this field must be its sole
// member (each proto3 optional field gets its own synthetic oneof). Synthetic
// oneofs exist in the descriptor only, and do not generate any API. Synthetic
// oneofs must be ordered after all "real" oneofs.
//
// For message fields, proto3_optional doesn't create any semantic change,
// since non-repeated message fields always track presence. However it still
// indicates the semantic detail of whether the user wrote "optional" or not.
// This can be useful for round-tripping the .proto file. For consistency we
// give message fields a synthetic oneof also, even though it is not required
// to track presence. This is especially important because the parser can't
// tell if a field is a message or an enum, so it must always create a
// synthetic oneof.
//
// Proto2 optional fields do not set this flag, because they already indicate
// optional with `LABEL_OPTIONAL`.
optional bool proto3_optional = 17;
}
// Describes a oneof.
message OneofDescriptorProto {
optional string name = 1;
optional OneofOptions options = 2;
}
// Describes an enum type.
message EnumDescriptorProto {
optional string name = 1;
repeated EnumValueDescriptorProto value = 2;
optional EnumOptions options = 3;
// Range of reserved numeric values. Reserved values may not be used by
// entries in the same enum. Reserved ranges may not overlap.
//
// Note that this is distinct from DescriptorProto.ReservedRange in that it
// is inclusive such that it can appropriately represent the entire int32
// domain.
message EnumReservedRange {
optional int32 start = 1; // Inclusive.
optional int32 end = 2; // Inclusive.
}
// Range of reserved numeric values. Reserved numeric values may not be used
// by enum values in the same enum declaration. Reserved ranges may not
// overlap.
repeated EnumReservedRange reserved_range = 4;
// Reserved enum value names, which may not be reused. A given name may only
// be reserved once.
repeated string reserved_name = 5;
}
// Describes a value within an enum.
message EnumValueDescriptorProto {
optional string name = 1;
optional int32 number = 2;
optional EnumValueOptions options = 3;
}
// Describes a service.
message ServiceDescriptorProto {
optional string name = 1;
repeated MethodDescriptorProto method = 2;
optional ServiceOptions options = 3;
}
// Describes a method of a service.
message MethodDescriptorProto {
optional string name = 1;
// Input and output type names. These are resolved in the same way as
// FieldDescriptorProto.type_name, but must refer to a message type.
optional string input_type = 2;
optional string output_type = 3;
optional MethodOptions options = 4;
// Identifies if client streams multiple client messages
optional bool client_streaming = 5 [default = false];
// Identifies if server streams multiple server messages
optional bool server_streaming = 6 [default = false];
}
// ===================================================================
// Options
// Each of the definitions above may have "options" attached. These are
// just annotations which may cause code to be generated slightly differently
// or may contain hints for code that manipulates protocol messages.
//
// Clients may define custom options as extensions of the *Options messages.
// These extensions may not yet be known at parsing time, so the parser cannot
// store the values in them. Instead it stores them in a field in the *Options
// message called uninterpreted_option. This field must have the same name
// across all *Options messages. We then use this field to populate the
// extensions when we build a descriptor, at which point all protos have been
// parsed and so all extensions are known.
//
// Extension numbers for custom options may be chosen as follows:
// * For options which will only be used within a single application or
// organization, or for experimental options, use field numbers 50000
// through 99999. It is up to you to ensure that you do not use the
// same number for multiple options.
// * For options which will be published and used publicly by multiple
// independent entities, e-mail protobuf-global-extension-registry@google.com
// to reserve extension numbers. Simply provide your project name (e.g.
// Objective-C plugin) and your project website (if available) -- there's no
// need to explain how you intend to use them. Usually you only need one
// extension number. You can declare multiple options with only one extension
// number by putting them in a sub-message. See the Custom Options section of
// the docs for examples:
// https://developers.google.com/protocol-buffers/docs/proto#options
// If this turns out to be popular, a web service will be set up
// to automatically assign option numbers.
message FileOptions {
// Sets the Java package where classes generated from this .proto will be
// placed. By default, the proto package is used, but this is often
// inappropriate because proto packages do not normally start with backwards
// domain names.
optional string java_package = 1;
// Controls the name of the wrapper Java class generated for the .proto file.
// That class will always contain the .proto file's getDescriptor() method as
// well as any top-level extensions defined in the .proto file.
// If java_multiple_files is disabled, then all the other classes from the
// .proto file will be nested inside the single wrapper outer class.
optional string java_outer_classname = 8;
// If enabled, then the Java code generator will generate a separate .java
// file for each top-level message, enum, and service defined in the .proto
// file. Thus, these types will *not* be nested inside the wrapper class
// named by java_outer_classname. However, the wrapper class will still be
// generated to contain the file's getDescriptor() method as well as any
// top-level extensions defined in the file.
optional bool java_multiple_files = 10 [default = false];
// This option does nothing.
optional bool java_generate_equals_and_hash = 20 [deprecated=true];
// If set true, then the Java2 code generator will generate code that
// throws an exception whenever an attempt is made to assign a non-UTF-8
// byte sequence to a string field.
// Message reflection will do the same.
// However, an extension field still accepts non-UTF-8 byte sequences.
// This option has no effect on when used with the lite runtime.
optional bool java_string_check_utf8 = 27 [default = false];
// Generated classes can be optimized for speed or code size.
enum OptimizeMode {
SPEED = 1; // Generate complete code for parsing, serialization,
// etc.
CODE_SIZE = 2; // Use ReflectionOps to implement these methods.
LITE_RUNTIME = 3; // Generate code using MessageLite and the lite runtime.
}
optional OptimizeMode optimize_for = 9 [default = SPEED];
// Sets the Go package where structs generated from this .proto will be
// placed. If omitted, the Go package will be derived from the following:
// - The basename of the package import path, if provided.
// - Otherwise, the package statement in the .proto file, if present.
// - Otherwise, the basename of the .proto file, without extension.
optional string go_package = 11;
// Should generic services be generated in each language? "Generic" services
// are not specific to any particular RPC system. They are generated by the
// main code generators in each language (without additional plugins).
// Generic services were the only kind of service generation supported by
// early versions of google.protobuf.
//
// Generic services are now considered deprecated in favor of using plugins
// that generate code specific to your particular RPC system. Therefore,
// these default to false. Old code which depends on generic services should
// explicitly set them to true.
optional bool cc_generic_services = 16 [default = false];
optional bool java_generic_services = 17 [default = false];
optional bool py_generic_services = 18 [default = false];
optional bool php_generic_services = 42 [default = false];
// Is this file deprecated?
// Depending on the target platform, this can emit Deprecated annotations
// for everything in the file, or it will be completely ignored; in the very
// least, this is a formalization for deprecating files.
optional bool deprecated = 23 [default = false];
// Enables the use of arenas for the proto messages in this file. This applies
// only to generated classes for C++.
optional bool cc_enable_arenas = 31 [default = true];
// Sets the objective c class prefix which is prepended to all objective c
// generated classes from this .proto. There is no default.
optional string objc_class_prefix = 36;
// Namespace for generated classes; defaults to the package.
optional string csharp_namespace = 37;
// By default Swift generators will take the proto package and CamelCase it
// replacing '.' with underscore and use that to prefix the types/symbols
// defined. When this options is provided, they will use this value instead
// to prefix the types/symbols defined.
optional string swift_prefix = 39;
// Sets the php class prefix which is prepended to all php generated classes
// from this .proto. Default is empty.
optional string php_class_prefix = 40;
// Use this option to change the namespace of php generated classes. Default
// is empty. When this option is empty, the package name will be used for
// determining the namespace.
optional string php_namespace = 41;
// Use this option to change the namespace of php generated metadata classes.
// Default is empty. When this option is empty, the proto file name will be
// used for determining the namespace.
optional string php_metadata_namespace = 44;
// Use this option to change the package of ruby generated classes. Default
// is empty. When this option is not set, the package name will be used for
// determining the ruby package.
optional string ruby_package = 45;
// The parser stores options it doesn't recognize here.
// See the documentation for the "Options" section above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message.
// See the documentation for the "Options" section above.
extensions 1000 to max;
reserved 38;
}
message MessageOptions {
// Set true to use the old proto1 MessageSet wire format for extensions.
// This is provided for backwards-compatibility with the MessageSet wire
// format. You should not use this for any other reason: It's less
// efficient, has fewer features, and is more complicated.
//
// The message must be defined exactly as follows:
// message Foo {
// option message_set_wire_format = true;
// extensions 4 to max;
// }
// Note that the message cannot have any defined fields; MessageSets only
// have extensions.
//
// All extensions of your type must be singular messages; e.g. they cannot
// be int32s, enums, or repeated messages.
//
// Because this is an option, the above two restrictions are not enforced by
// the protocol compiler.
optional bool message_set_wire_format = 1 [default = false];
// Disables the generation of the standard "descriptor()" accessor, which can
// conflict with a field of the same name. This is meant to make migration
// from proto1 easier; new code should avoid fields named "descriptor".
optional bool no_standard_descriptor_accessor = 2 [default = false];
// Is this message deprecated?
// Depending on the target platform, this can emit Deprecated annotations
// for the message, or it will be completely ignored; in the very least,
// this is a formalization for deprecating messages.
optional bool deprecated = 3 [default = false];
reserved 4, 5, 6;
// Whether the message is an automatically generated map entry type for the
// maps field.
//
// For maps fields:
// map<KeyType, ValueType> map_field = 1;
// The parsed descriptor looks like:
// message MapFieldEntry {
// option map_entry = true;
// optional KeyType key = 1;
// optional ValueType value = 2;
// }
// repeated MapFieldEntry map_field = 1;
//
// Implementations may choose not to generate the map_entry=true message, but
// use a native map in the target language to hold the keys and values.
// The reflection APIs in such implementations still need to work as
// if the field is a repeated message field.
//
// NOTE: Do not set the option in .proto files. Always use the maps syntax
// instead. The option should only be implicitly set by the proto compiler
// parser.
optional bool map_entry = 7;
reserved 8; // javalite_serializable
reserved 9; // javanano_as_lite
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
message FieldOptions {
// The ctype option instructs the C++ code generator to use a different
// representation of the field than it normally would. See the specific
// options below. This option is not yet implemented in the open source
// release -- sorry, we'll try to include it in a future version!
optional CType ctype = 1 [default = STRING];
enum CType {
// Default mode.
STRING = 0;
CORD = 1;
STRING_PIECE = 2;
}
// The packed option can be enabled for repeated primitive fields to enable
// a more efficient representation on the wire. Rather than repeatedly
// writing the tag and type for each element, the entire array is encoded as
// a single length-delimited blob. In proto3, only explicit setting it to
// false will avoid using packed encoding.
optional bool packed = 2;
// The jstype option determines the JavaScript type used for values of the
// field. The option is permitted only for 64 bit integral and fixed types
// (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING
// is represented as JavaScript string, which avoids loss of precision that
// can happen when a large value is converted to a floating point JavaScript.
// Specifying JS_NUMBER for the jstype causes the generated JavaScript code to
// use the JavaScript "number" type. The behavior of the default option
// JS_NORMAL is implementation dependent.
//
// This option is an enum to permit additional types to be added, e.g.
// goog.math.Integer.
optional JSType jstype = 6 [default = JS_NORMAL];
enum JSType {
// Use the default type.
JS_NORMAL = 0;
// Use JavaScript strings.
JS_STRING = 1;
// Use JavaScript numbers.
JS_NUMBER = 2;
}
// Should this field be parsed lazily? Lazy applies only to message-type
// fields. It means that when the outer message is initially parsed, the
// inner message's contents will not be parsed but instead stored in encoded
// form. The inner message will actually be parsed when it is first accessed.
//
// This is only a hint. Implementations are free to choose whether to use
// eager or lazy parsing regardless of the value of this option. However,
// setting this option true suggests that the protocol author believes that
// using lazy parsing on this field is worth the additional bookkeeping
// overhead typically needed to implement it.
//
// This option does not affect the public interface of any generated code;
// all method signatures remain the same. Furthermore, thread-safety of the
// interface is not affected by this option; const methods remain safe to
// call from multiple threads concurrently, while non-const methods continue
// to require exclusive access.
//
//
// Note that implementations may choose not to check required fields within
// a lazy sub-message. That is, calling IsInitialized() on the outer message
// may return true even if the inner message has missing required fields.
// This is necessary because otherwise the inner message would have to be
// parsed in order to perform the check, defeating the purpose of lazy
// parsing. An implementation which chooses not to check required fields
// must be consistent about it. That is, for any particular sub-message, the
// implementation must either *always* check its required fields, or *never*
// check its required fields, regardless of whether or not the message has
// been parsed.
//
// As of May 2022, lazy verifies the contents of the byte stream during
// parsing. An invalid byte stream will cause the overall parsing to fail.
optional bool lazy = 5 [default = false];
// unverified_lazy does no correctness checks on the byte stream. This should
// only be used where lazy with verification is prohibitive for performance
// reasons.
optional bool unverified_lazy = 15 [default = false];
// Is this field deprecated?
// Depending on the target platform, this can emit Deprecated annotations
// for accessors, or it will be completely ignored; in the very least, this
// is a formalization for deprecating fields.
optional bool deprecated = 3 [default = false];
// For Google-internal migration only. Do not use.
optional bool weak = 10 [default = false];
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
reserved 4; // removed jtype
}
message OneofOptions {
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
message EnumOptions {
// Set this option to true to allow mapping different tag names to the same
// value.
optional bool allow_alias = 2;
// Is this enum deprecated?
// Depending on the target platform, this can emit Deprecated annotations
// for the enum, or it will be completely ignored; in the very least, this
// is a formalization for deprecating enums.
optional bool deprecated = 3 [default = false];
reserved 5; // javanano_as_lite
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
message EnumValueOptions {
// Is this enum value deprecated?
// Depending on the target platform, this can emit Deprecated annotations
// for the enum value, or it will be completely ignored; in the very least,
// this is a formalization for deprecating enum values.
optional bool deprecated = 1 [default = false];
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
message ServiceOptions {
// Note: Field numbers 1 through 32 are reserved for Google's internal RPC
// framework. We apologize for hoarding these numbers to ourselves, but
// we were already using them long before we decided to release Protocol
// Buffers.
// Is this service deprecated?
// Depending on the target platform, this can emit Deprecated annotations
// for the service, or it will be completely ignored; in the very least,
// this is a formalization for deprecating services.
optional bool deprecated = 33 [default = false];
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
message MethodOptions {
// Note: Field numbers 1 through 32 are reserved for Google's internal RPC
// framework. We apologize for hoarding these numbers to ourselves, but
// we were already using them long before we decided to release Protocol
// Buffers.
// Is this method deprecated?
// Depending on the target platform, this can emit Deprecated annotations
// for the method, or it will be completely ignored; in the very least,
// this is a formalization for deprecating methods.
optional bool deprecated = 33 [default = false];
// Is this method side-effect-free (or safe in HTTP parlance), or idempotent,
// or neither? HTTP based RPC implementation may choose GET verb for safe
// methods, and PUT verb for idempotent methods instead of the default POST.
enum IdempotencyLevel {
IDEMPOTENCY_UNKNOWN = 0;
NO_SIDE_EFFECTS = 1; // implies idempotent
IDEMPOTENT = 2; // idempotent, but may have side effects
}
optional IdempotencyLevel idempotency_level = 34
[default = IDEMPOTENCY_UNKNOWN];
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
// A message representing a option the parser does not recognize. This only
// appears in options protos created by the compiler::Parser class.
// DescriptorPool resolves these when building Descriptor objects. Therefore,
// options protos in descriptor objects (e.g. returned by Descriptor::options(),
// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions
// in them.
message UninterpretedOption {
// The name of the uninterpreted option. Each string represents a segment in
// a dot-separated name. is_extension is true iff a segment represents an
// extension (denoted with parentheses in options specs in .proto files).
// E.g.,{ ["foo", false], ["bar.baz", true], ["moo", false] } represents
// "foo.(bar.baz).moo".
message NamePart {
required string name_part = 1;
required bool is_extension = 2;
}
repeated NamePart name = 2;
// The value of the uninterpreted option, in whatever type the tokenizer
// identified it as during parsing. Exactly one of these should be set.
optional string identifier_value = 3;
optional uint64 positive_int_value = 4;
optional int64 negative_int_value = 5;
optional double double_value = 6;
optional bytes string_value = 7;
optional string aggregate_value = 8;
}
// ===================================================================
// Optional source code info
// Encapsulates information about the original source file from which a
// FileDescriptorProto was generated.
message SourceCodeInfo {
// A Location identifies a piece of source code in a .proto file which
// corresponds to a particular definition. This information is intended
// to be useful to IDEs, code indexers, documentation generators, and similar
// tools.
//
// For example, say we have a file like:
// message Foo {
// optional string foo = 1;
// }
// Let's look at just the field definition:
// optional string foo = 1;
// ^ ^^ ^^ ^ ^^^
// a bc de f ghi
// We have the following locations:
// span path represents
// [a,i) [ 4, 0, 2, 0 ] The whole field definition.
// [a,b) [ 4, 0, 2, 0, 4 ] The label (optional).
// [c,d) [ 4, 0, 2, 0, 5 ] The type (string).
// [e,f) [ 4, 0, 2, 0, 1 ] The name (foo).
// [g,h) [ 4, 0, 2, 0, 3 ] The number (1).
//
// Notes:
// - A location may refer to a repeated field itself (i.e. not to any
// particular index within it). This is used whenever a set of elements are
// logically enclosed in a single code segment. For example, an entire
// extend block (possibly containing multiple extension definitions) will
// have an outer location whose path refers to the "extensions" repeated
// field without an index.
// - Multiple locations may have the same path. This happens when a single
// logical declaration is spread out across multiple places. The most
// obvious example is the "extend" block again -- there may be multiple
// extend blocks in the same scope, each of which will have the same path.
// - A location's span is not always a subset of its parent's span. For
// example, the "extendee" of an extension declaration appears at the
// beginning of the "extend" block and is shared by all extensions within
// the block.
// - Just because a location's span is a subset of some other location's span
// does not mean that it is a descendant. For example, a "group" defines
// both a type and a field in a single declaration. Thus, the locations
// corresponding to the type and field and their components will overlap.
// - Code which tries to interpret locations should probably be designed to
// ignore those that it doesn't understand, as more types of locations could
// be recorded in the future.
repeated Location location = 1;
message Location {
// Identifies which part of the FileDescriptorProto was defined at this
// location.
//
// Each element is a field number or an index. They form a path from
// the root FileDescriptorProto to the place where the definition occurs.
// For example, this path:
// [ 4, 3, 2, 7, 1 ]
// refers to:
// file.message_type(3) // 4, 3
// .field(7) // 2, 7
// .name() // 1
// This is because FileDescriptorProto.message_type has field number 4:
// repeated DescriptorProto message_type = 4;
// and DescriptorProto.field has field number 2:
// repeated FieldDescriptorProto field = 2;
// and FieldDescriptorProto.name has field number 1:
// optional string name = 1;
//
// Thus, the above path gives the location of a field name. If we removed
// the last element:
// [ 4, 3, 2, 7 ]
// this path refers to the whole field declaration (from the beginning
// of the label to the terminating semicolon).
repeated int32 path = 1 [packed = true];
// Always has exactly three or four elements: start line, start column,
// end line (optional, otherwise assumed same as start line), end column.
// These are packed into a single field for efficiency. Note that line
// and column numbers are zero-based -- typically you will want to add
// 1 to each before displaying to a user.
repeated int32 span = 2 [packed = true];
// If this SourceCodeInfo represents a complete declaration, these are any
// comments appearing before and after the declaration which appear to be
// attached to the declaration.
//
// A series of line comments appearing on consecutive lines, with no other
// tokens appearing on those lines, will be treated as a single comment.
//
// leading_detached_comments will keep paragraphs of comments that appear
// before (but not connected to) the current element. Each paragraph,
// separated by empty lines, will be one comment element in the repeated
// field.
//
// Only the comment content is provided; comment markers (e.g. //) are
// stripped out. For block comments, leading whitespace and an asterisk
// will be stripped from the beginning of each line other than the first.
// Newlines are included in the output.
//
// Examples:
//
// optional int32 foo = 1; // Comment attached to foo.
// // Comment attached to bar.
// optional int32 bar = 2;
//
// optional string baz = 3;
// // Comment attached to baz.
// // Another line attached to baz.
//
// // Comment attached to moo.
// //
// // Another line attached to moo.
// optional double moo = 4;
//
// // Detached comment for corge. This is not leading or trailing comments
// // to moo or corge because there are blank lines separating it from
// // both.
//
// // Detached comment for corge paragraph 2.
//
// optional string corge = 5;
// /* Block comment attached
// * to corge. Leading asterisks
// * will be removed. */
// /* Block comment attached to
// * grault. */
// optional int32 grault = 6;
//
// // ignored detached comments.
optional string leading_comments = 3;
optional string trailing_comments = 4;
repeated string leading_detached_comments = 6;
}
}
// Describes the relationship between generated code and its original source
// file. A GeneratedCodeInfo message is associated with only one generated
// source file, but may contain references to different source .proto files.
message GeneratedCodeInfo {
// An Annotation connects some span of text in generated code to an element
// of its generating .proto file.
repeated Annotation annotation = 1;
message Annotation {
// Identifies the element in the original source .proto file. This field
// is formatted the same as SourceCodeInfo.Location.path.
repeated int32 path = 1 [packed = true];
// Identifies the filesystem path to the original source .proto.
optional string source_file = 2;
// Identifies the starting offset in bytes in the generated code
// that relates to the identified object.
optional int32 begin = 3;
// Identifies the ending offset in bytes in the generated code that
// relates to the identified object. The end offset should be one past
// the last relevant byte (so the length of the text = end - begin).
optional int32 end = 4;
// Represents the identified object's effect on the element in the original
// .proto file.
enum Semantic {
// There is no effect or the effect is indescribable.
NONE = 0;
// The element is set or otherwise mutated.
SET = 1;
// An alias to the element is returned.
ALIAS = 2;
}
optional Semantic semantic = 5;
}
}

View file

@ -0,0 +1,177 @@
import "common_base.proto";
message CRemoveAuthenticatorViaChallengeContinue_Replacement_Token {
optional bytes shared_secret = 1;
optional fixed64 serial_number = 2;
optional string revocation_code = 3;
optional string uri = 4;
optional uint64 server_time = 5;
optional string account_name = 6;
optional string token_gid = 7;
optional bytes identity_secret = 8;
optional bytes secret_1 = 9;
optional int32 status = 10;
optional uint32 steamguard_scheme = 11;
optional fixed64 steamid = 12;
}
message CTwoFactor_AddAuthenticator_Request {
optional fixed64 steamid = 1;
optional uint64 authenticator_time = 2;
optional fixed64 serial_number = 3;
optional uint32 authenticator_type = 4;
optional string device_identifier = 5;
optional string sms_phone_id = 6;
repeated string http_headers = 7;
optional uint32 version = 8 [default = 1];
}
message CTwoFactor_AddAuthenticator_Response {
optional bytes shared_secret = 1;
optional fixed64 serial_number = 2;
optional string revocation_code = 3;
optional string uri = 4;
optional uint64 server_time = 5;
optional string account_name = 6;
optional string token_gid = 7;
optional bytes identity_secret = 8;
optional bytes secret_1 = 9;
optional int32 status = 10;
optional string phone_number_hint = 11;
}
message CTwoFactor_CreateEmergencyCodes_Request {
optional string code = 1;
}
message CTwoFactor_CreateEmergencyCodes_Response {
repeated string codes = 1;
}
message CTwoFactor_DestroyEmergencyCodes_Request {
optional fixed64 steamid = 1;
}
message CTwoFactor_DestroyEmergencyCodes_Response {
}
message CTwoFactor_FinalizeAddAuthenticator_Request {
optional fixed64 steamid = 1;
optional string authenticator_code = 2;
optional uint64 authenticator_time = 3;
optional string activation_code = 4;
repeated string http_headers = 5;
optional bool validate_sms_code = 6;
}
message CTwoFactor_FinalizeAddAuthenticator_Response {
optional bool success = 1;
optional bool want_more = 2;
optional uint64 server_time = 3;
optional int32 status = 4;
}
message CTwoFactor_RemoveAuthenticator_Request {
optional string revocation_code = 2;
optional uint32 revocation_reason = 5;
optional uint32 steamguard_scheme = 6;
optional bool remove_all_steamguard_cookies = 7;
}
message CTwoFactor_RemoveAuthenticator_Response {
optional bool success = 1;
optional uint64 server_time = 3;
optional uint32 revocation_attempts_remaining = 5;
}
message CTwoFactor_RemoveAuthenticatorViaChallengeContinue_Request {
optional string sms_code = 1;
optional bool generate_new_token = 2;
optional uint32 version = 3 [default = 1];
}
message CTwoFactor_RemoveAuthenticatorViaChallengeContinue_Response {
optional bool success = 1;
optional .CRemoveAuthenticatorViaChallengeContinue_Replacement_Token replacement_token = 2;
}
message CTwoFactor_RemoveAuthenticatorViaChallengeStart_Request {
}
message CTwoFactor_RemoveAuthenticatorViaChallengeStart_Response {
optional bool success = 1;
}
message CTwoFactor_SendEmail_Request {
optional fixed64 steamid = 1;
optional uint32 email_type = 2;
optional bool include_activation_code = 3;
}
message CTwoFactor_SendEmail_Response {
}
message CTwoFactor_Status_Request {
optional fixed64 steamid = 1;
}
message CTwoFactor_Status_Response {
optional uint32 state = 1;
optional uint32 inactivation_reason = 2;
optional uint32 authenticator_type = 3;
optional bool authenticator_allowed = 4;
optional uint32 steamguard_scheme = 5;
optional string token_gid = 6;
optional bool email_validated = 7;
optional string device_identifier = 8;
optional uint32 time_created = 9;
optional uint32 revocation_attempts_remaining = 10;
optional string classified_agent = 11;
optional bool allow_external_authenticator = 12;
optional uint32 time_transferred = 13;
optional uint32 version = 14;
}
message CTwoFactor_Time_Response {
optional uint64 server_time = 1;
optional uint64 skew_tolerance_seconds = 2;
optional uint64 large_time_jink = 3;
optional uint32 probe_frequency_seconds = 4;
optional uint32 adjusted_time_probe_frequency_seconds = 5;
optional uint32 hint_probe_frequency_seconds = 6;
optional uint32 sync_timeout = 7;
optional uint32 try_again_seconds = 8;
optional uint32 max_attempts = 9;
}
message CTwoFactor_UpdateTokenVersion_Request {
optional fixed64 steamid = 1;
optional uint32 version = 2;
optional bytes signature = 3;
}
message CTwoFactor_UpdateTokenVersion_Response {
}
message CTwoFactor_ValidateToken_Request {
optional string code = 1;
}
message CTwoFactor_ValidateToken_Response {
optional bool valid = 1;
}
service TwoFactor {
rpc AddAuthenticator (.CTwoFactor_AddAuthenticator_Request) returns (.CTwoFactor_AddAuthenticator_Response);
rpc CreateEmergencyCodes (.CTwoFactor_CreateEmergencyCodes_Request) returns (.CTwoFactor_CreateEmergencyCodes_Response);
rpc DestroyEmergencyCodes (.CTwoFactor_DestroyEmergencyCodes_Request) returns (.CTwoFactor_DestroyEmergencyCodes_Response);
rpc FinalizeAddAuthenticator (.CTwoFactor_FinalizeAddAuthenticator_Request) returns (.CTwoFactor_FinalizeAddAuthenticator_Response);
rpc QueryStatus (.CTwoFactor_Status_Request) returns (.CTwoFactor_Status_Response);
rpc QueryTime (.NotImplemented) returns (.CTwoFactor_Time_Response);
rpc RemoveAuthenticator (.CTwoFactor_RemoveAuthenticator_Request) returns (.CTwoFactor_RemoveAuthenticator_Response);
rpc RemoveAuthenticatorViaChallengeContinue (.CTwoFactor_RemoveAuthenticatorViaChallengeContinue_Request) returns (.CTwoFactor_RemoveAuthenticatorViaChallengeContinue_Response);
rpc RemoveAuthenticatorViaChallengeStart (.CTwoFactor_RemoveAuthenticatorViaChallengeStart_Request) returns (.CTwoFactor_RemoveAuthenticatorViaChallengeStart_Response);
rpc SendEmail (.CTwoFactor_SendEmail_Request) returns (.CTwoFactor_SendEmail_Response);
rpc UpdateTokenVersion (.CTwoFactor_UpdateTokenVersion_Request) returns (.CTwoFactor_UpdateTokenVersion_Response);
rpc ValidateToken (.CTwoFactor_ValidateToken_Request) returns (.CTwoFactor_ValidateToken_Response);
}

View file

@ -0,0 +1,411 @@
import "steammessages_base.proto";
import "steammessages_unified_base.steamclient.proto";
import "enums.proto";
option cc_generic_services = true;
enum EAuthTokenPlatformType {
k_EAuthTokenPlatformType_Unknown = 0;
k_EAuthTokenPlatformType_SteamClient = 1;
k_EAuthTokenPlatformType_WebBrowser = 2;
k_EAuthTokenPlatformType_MobileApp = 3;
}
enum EAuthSessionGuardType {
k_EAuthSessionGuardType_Unknown = 0;
k_EAuthSessionGuardType_None = 1;
k_EAuthSessionGuardType_EmailCode = 2;
k_EAuthSessionGuardType_DeviceCode = 3;
k_EAuthSessionGuardType_DeviceConfirmation = 4;
k_EAuthSessionGuardType_EmailConfirmation = 5;
k_EAuthSessionGuardType_MachineToken = 6;
k_EAuthSessionGuardType_LegacyMachineAuth = 7;
}
enum EAuthSessionSecurityHistory {
k_EAuthSessionSecurityHistory_Invalid = 0;
k_EAuthSessionSecurityHistory_UsedPreviously = 1;
k_EAuthSessionSecurityHistory_NoPriorHistory = 2;
}
enum EAuthTokenRevokeAction {
k_EAuthTokenRevokeLogout = 0;
k_EAuthTokenRevokePermanent = 1;
k_EAuthTokenRevokeReplaced = 2;
k_EAuthTokenRevokeSupport = 3;
k_EAuthTokenRevokeConsume = 4;
}
enum EAuthTokenState {
k_EAuthTokenState_Invalid = 0;
k_EAuthTokenState_New = 1;
k_EAuthTokenState_Confirmed = 2;
k_EAuthTokenState_Issued = 3;
k_EAuthTokenState_Denied = 4;
k_EAuthTokenState_LoggedOut = 5;
k_EAuthTokenState_Consumed = 6;
k_EAuthTokenState_Revoked = 99;
}
message CAuthentication_GetPasswordRSAPublicKey_Request {
optional string account_name = 1 [(description) = "user-provided account name to get an RSA key for"];
}
message CAuthentication_GetPasswordRSAPublicKey_Response {
optional string publickey_mod = 1 [(description) = "the public key modulus"];
optional string publickey_exp = 2 [(description) = "the public key exponent"];
optional uint64 timestamp = 3 [(description) = "the timestamp the key was generated"];
}
message CAuthentication_DeviceDetails {
optional string device_friendly_name = 1 [(description) = "User-supplied, or client-supplied, friendly name of device"];
optional .EAuthTokenPlatformType platform_type = 2 [default = k_EAuthTokenPlatformType_Unknown, (description) = "EAuthTokenPlatformType, claimed, of device"];
optional int32 os_type = 3 [(description) = "EOSType, claimed, of authorized device"];
optional uint32 gaming_device_type = 4 [(description) = "EGamingDeviceType, claimed, of authorized device for steam client-type devices"];
}
message CAuthentication_BeginAuthSessionViaQR_Request {
optional string device_friendly_name = 1;
optional .EAuthTokenPlatformType platform_type = 2 [default = k_EAuthTokenPlatformType_Unknown];
optional .CAuthentication_DeviceDetails device_details = 3 [(description) = "User-supplied details about the device attempting to sign in"];
optional string website_id = 4 [default = "Unknown", (description) = "(EMachineAuthWebDomain) identifier of client requesting auth"];
}
message CAuthentication_AllowedConfirmation {
optional .EAuthSessionGuardType confirmation_type = 1 [default = k_EAuthSessionGuardType_Unknown, (description) = "authentication can proceed with this confirmation type"];
optional string associated_message = 2 [(description) = "message to be interpreted depending on the confirmation type. for email confirmation, this might be the redacted email address to which email was sent."];
}
message CAuthentication_BeginAuthSessionViaQR_Response {
optional uint64 client_id = 1 [(description) = "unique identifier of requestor, also used for routing, portion of QR code"];
optional string challenge_url = 2 [(description) = "URL based on client ID, which will be rendered as QR code"];
optional bytes request_id = 3 [(description) = "unique request ID to be presented by requestor at poll time - must not be rendered in QR"];
optional float interval = 4 [(description) = "refresh interval with which requestor should call PollAuthSessionStatus"];
repeated .CAuthentication_AllowedConfirmation allowed_confirmations = 5 [(description) = "the confirmation types that will be able to confirm the request"];
optional int32 version = 6 [(description) = "version of the QR data"];
}
message CAuthentication_BeginAuthSessionViaCredentials_Request {
optional string device_friendly_name = 1;
optional string account_name = 2;
optional string encrypted_password = 3 [(description) = "password, RSA encrypted client side"];
optional uint64 encryption_timestamp = 4 [(description) = "timestamp to map to a key - STime"];
optional bool remember_login = 5 [(description) = "deprecated"];
optional .EAuthTokenPlatformType platform_type = 6 [default = k_EAuthTokenPlatformType_Unknown];
optional .ESessionPersistence persistence = 7 [default = k_ESessionPersistence_Persistent, (description) = "whether we are requesting a persistent or an ephemeral session"];
optional string website_id = 8 [default = "Unknown", (description) = "(EMachineAuthWebDomain) identifier of client requesting auth"];
optional .CAuthentication_DeviceDetails device_details = 9 [(description) = "User-supplied details about the device attempting to sign in"];
optional string guard_data = 10 [(description) = "steam guard data for client login"];
optional uint32 language = 11;
optional int32 qos_level = 12 [default = 2, (description) = "[ENetQOSLevel] client-specified priority for this auth attempt"];
}
message CAuthentication_BeginAuthSessionViaCredentials_Response {
optional uint64 client_id = 1 [(description) = "unique identifier of requestor, also used for routing"];
optional bytes request_id = 2 [(description) = "unique request ID to be presented by requestor at poll time - must not be transferred or displayed"];
optional float interval = 3 [(description) = "refresh interval with which requestor should call PollAuthSessionStatus"];
repeated .CAuthentication_AllowedConfirmation allowed_confirmations = 4 [(description) = "the confirmation types that will be able to confirm the request"];
optional uint64 steamid = 5 [(description) = "steamid of the account logging in - will only be included if the credentials were correct"];
optional string weak_token = 6 [(description) = "partial-authentication token - limited lifetime and scope, included only if credentials were valid"];
optional string agreement_session_url = 7 [(description) = "agreement the user needs to agree to"];
optional string extended_error_message = 8 [(description) = "error string to display if supported by the client"];
}
message CAuthentication_PollAuthSessionStatus_Request {
optional uint64 client_id = 1;
optional bytes request_id = 2;
optional fixed64 token_to_revoke = 3 [(description) = "If this is set to a token owned by this user, that token will be retired"];
}
message CAuthentication_PollAuthSessionStatus_Response {
optional uint64 new_client_id = 1 [(description) = "if challenge is old, this is the new client id"];
optional string new_challenge_url = 2 [(description) = "if challenge is old, this is the new challenge ID to re-render for mobile confirmation"];
optional string refresh_token = 3 [(description) = "if login has been confirmed, this is the requestor's new refresh token"];
optional string access_token = 4 [(description) = "if login has been confirmed, this is a new token subordinate to refresh_token"];
optional bool had_remote_interaction = 5 [(description) = "whether or not the auth session appears to have had remote interaction from a potential confirmer"];
optional string account_name = 6 [(description) = "account name of authenticating account, for use by UI layer"];
optional string new_guard_data = 7 [(description) = "if login has been confirmed, may contain remembered machine ID for future login"];
optional string agreement_session_url = 8 [(description) = "agreement the user needs to agree to"];
}
message CAuthentication_GetAuthSessionInfo_Request {
optional uint64 client_id = 1 [(description) = "client ID from scanned QR Code, used for routing"];
}
message CAuthentication_GetAuthSessionInfo_Response {
optional string ip = 1 [(description) = "IP address of requestor"];
optional string geoloc = 2 [(description) = "geoloc info of requestor"];
optional string city = 3 [(description) = "city of requestor"];
optional string state = 4 [(description) = "state of requestor"];
optional string country = 5 [(description) = "country of requestor"];
optional .EAuthTokenPlatformType platform_type = 6 [default = k_EAuthTokenPlatformType_Unknown, (description) = "platform type of requestor"];
optional string device_friendly_name = 7 [(description) = "name of requestor device"];
optional int32 version = 8 [(description) = "version field"];
optional .EAuthSessionSecurityHistory login_history = 9 [default = k_EAuthSessionSecurityHistory_Invalid, (description) = "whether the ip has previuously been used on the account successfully"];
optional bool requestor_location_mismatch = 10 [(description) = "whether the requestor location matches this requests location"];
optional bool high_usage_login = 11 [(description) = "whether this login has seen high usage recently"];
optional .ESessionPersistence requested_persistence = 12 [default = k_ESessionPersistence_Invalid, (description) = "session persistence requestor has indicated they want"];
}
message CAuthentication_UpdateAuthSessionWithMobileConfirmation_Request {
optional int32 version = 1 [(description) = "version field"];
optional uint64 client_id = 2 [(description) = "pending client ID, from scanned QR Code"];
optional fixed64 steamid = 3 [(description) = "user who wants to login"];
optional bytes signature = 4 [(description) = "HMAC digest over {version,client_id,steamid} via user's private key"];
optional bool confirm = 5 [default = false, (description) = "Whether to confirm the login (true) or deny the login (false)"];
optional .ESessionPersistence persistence = 6 [default = k_ESessionPersistence_Persistent, (description) = "whether we are requesting a persistent or an ephemeral session"];
}
message CAuthentication_UpdateAuthSessionWithMobileConfirmation_Response {
}
message CAuthentication_UpdateAuthSessionWithSteamGuardCode_Request {
optional uint64 client_id = 1 [(description) = "pending client ID, from initialized session"];
optional fixed64 steamid = 2 [(description) = "user who wants to login"];
optional string code = 3 [(description) = "confirmation code"];
optional .EAuthSessionGuardType code_type = 4 [default = k_EAuthSessionGuardType_Unknown, (description) = "type of confirmation code"];
}
message CAuthentication_UpdateAuthSessionWithSteamGuardCode_Response {
optional string agreement_session_url = 7 [(description) = "agreement the user needs to agree to"];
}
message CAuthentication_AccessToken_GenerateForApp_Request {
optional string refresh_token = 1;
optional fixed64 steamid = 2;
}
message CAuthentication_AccessToken_GenerateForApp_Response {
optional string access_token = 1;
}
message CAuthentication_RefreshToken_Enumerate_Request {
}
message CAuthentication_RefreshToken_Enumerate_Response {
message TokenUsageEvent {
optional uint32 time = 1 [(description) = "Approximate time of history event (may be deliberately fuzzed or omitted)"];
optional .CMsgIPAddress ip = 2 [(description) = "IP at which event was observed"];
optional string locale = 3;
optional string country = 4 [(description) = "Location (country code) of event, as inferred from IP"];
optional string state = 5 [(description) = "Location (state code) of event, as inferred from IP"];
optional string city = 6 [(description) = "Location (city) of event, as inferred from IP"];
}
message RefreshTokenDescription {
optional fixed64 token_id = 1 [(description) = "Persistent token/device identifier"];
optional string token_description = 2 [(description) = "client-supplied friendly name for the device"];
optional uint32 time_updated = 3;
optional .EAuthTokenPlatformType platform_type = 4 [default = k_EAuthTokenPlatformType_Unknown, (description) = "gross platform type (mobile/client/browser)"];
optional bool logged_in = 5 [(description) = "If true, this token is currently valid. False indicates it is a machine token - ok for steamguard if you know the credential"];
optional uint32 os_platform = 6 [(description) = "EPlatformType - rough classification of device OS, if known"];
optional uint32 auth_type = 7 [(description) = "EAuthTokenGuardType - device authorization mechanism, if known"];
optional uint32 gaming_device_type = 8 [(description) = "EGamingDeviceType - classify console/PC/SteamDeck, if known; applies only for Steam Client devices"];
optional .CAuthentication_RefreshToken_Enumerate_Response.TokenUsageEvent first_seen = 9 [(description) = "Information about original authorization event"];
optional .CAuthentication_RefreshToken_Enumerate_Response.TokenUsageEvent last_seen = 10 [(description) = "Information about most-recently seen, if known for this device"];
optional int32 os_type = 11 [(description) = "EOSType - specific device OS, if known"];
}
repeated .CAuthentication_RefreshToken_Enumerate_Response.RefreshTokenDescription refresh_tokens = 1;
optional fixed64 requesting_token = 2;
}
message CAuthentication_GetAuthSessionsForAccount_Request {
}
message CAuthentication_GetAuthSessionsForAccount_Response {
repeated uint64 client_ids = 1 [(description) = "unique identifier of requestor, also used for routing"];
}
message CAuthentication_MigrateMobileSession_Request {
optional fixed64 steamid = 1 [(description) = "Steam ID of the user to migrate"];
optional string token = 2 [(description) = "WG Token to migrate"];
optional string signature = 3 [(description) = "Signature over the wg token using the user's 2FA token"];
}
message CAuthentication_MigrateMobileSession_Response {
optional string refresh_token = 1;
optional string access_token = 2;
}
message CAuthentication_RefreshToken_Revoke_Request {
optional fixed64 token_id = 1;
optional fixed64 steamid = 2 [(description) = "Token holder if an admin action on behalf of another user"];
optional .EAuthTokenRevokeAction revoke_action = 3 [default = k_EAuthTokenRevokePermanent, (description) = "Select between logout and logout-and-forget-machine"];
optional bytes signature = 4 [(description) = "required signature over token_id"];
}
message CAuthentication_RefreshToken_Revoke_Response {
}
message CAuthenticationSupport_QueryRefreshTokensByAccount_Request {
optional fixed64 steamid = 1 [(description) = "SteamID of the account to query (required)"];
optional bool include_revoked_tokens = 2 [(description) = "Includes tokens that are revoked or expired in the query"];
}
message CSupportRefreshTokenDescription {
message TokenUsageEvent {
optional uint32 time = 1 [(description) = "Approximate time of history event (may be deliberately fuzzed or omitted)"];
optional .CMsgIPAddress ip = 2 [(description) = "IP at which event was observed"];
optional string country = 3 [(description) = "Location (country code) of event, as inferred from IP"];
optional string state = 4 [(description) = "Location (state code) of event, as inferred from IP"];
optional string city = 5 [(description) = "Location (city) of event, as inferred from IP"];
}
optional fixed64 token_id = 1;
optional string token_description = 2;
optional uint32 time_updated = 3;
optional .EAuthTokenPlatformType platform_type = 4 [default = k_EAuthTokenPlatformType_Unknown];
optional .EAuthTokenState token_state = 5 [default = k_EAuthTokenState_Invalid];
optional fixed64 owner_steamid = 6;
optional uint32 os_platform = 7 [(description) = "EPlatformType - rough classification of device OS, if known"];
optional int32 os_type = 8 [(description) = "EOSType - specific device OS, if known"];
optional uint32 auth_type = 9 [(description) = "EAuthTokenGuardType - device authorization mechanism, if known"];
optional uint32 gaming_device_type = 10 [(description) = "EGamingDeviceType - classify console/PC/SteamDeck, if known; applies only for Steam Client devices"];
optional .CSupportRefreshTokenDescription.TokenUsageEvent first_seen = 11 [(description) = "Information about original authorization event"];
optional .CSupportRefreshTokenDescription.TokenUsageEvent last_seen = 12 [(description) = "Information about most-recently seen, if known for this device"];
}
message CAuthenticationSupport_QueryRefreshTokensByAccount_Response {
repeated .CSupportRefreshTokenDescription refresh_tokens = 1;
optional int32 last_token_reset = 2;
}
message CAuthenticationSupport_QueryRefreshTokenByID_Request {
optional fixed64 token_id = 1 [(description) = "Token ID of the token to look up (required)"];
}
message CAuthenticationSupport_QueryRefreshTokenByID_Response {
repeated .CSupportRefreshTokenDescription refresh_tokens = 1;
}
message CAuthenticationSupport_RevokeToken_Request {
optional fixed64 token_id = 1 [(description) = "Token ID of the token to revoke (required)"];
optional fixed64 steamid = 2 [(description) = "Steam ID of the owner of that token (required)"];
}
message CAuthenticationSupport_RevokeToken_Response {
}
message CAuthenticationSupport_GetTokenHistory_Request {
optional fixed64 token_id = 1 [(description) = "Token ID of the token to get history for (required)"];
}
message CSupportRefreshTokenAudit {
optional int32 action = 1;
optional uint32 time = 2;
optional .CMsgIPAddress ip = 3;
optional fixed64 actor = 4;
}
message CAuthenticationSupport_GetTokenHistory_Response {
repeated .CSupportRefreshTokenAudit history = 1;
}
message CCloudGaming_CreateNonce_Request {
optional string platform = 1;
optional uint32 appid = 2;
}
message CCloudGaming_CreateNonce_Response {
optional string nonce = 1;
optional uint32 expiry = 2;
}
message CCloudGaming_GetTimeRemaining_Request {
optional string platform = 1;
repeated uint32 appid_list = 2;
}
message CCloudGaming_TimeRemaining {
optional uint32 appid = 1;
optional uint32 minutes_remaining = 2;
}
message CCloudGaming_GetTimeRemaining_Response {
repeated .CCloudGaming_TimeRemaining entries = 2;
}
service Authentication {
option (service_description) = "Authentication Service";
rpc GetPasswordRSAPublicKey (.CAuthentication_GetPasswordRSAPublicKey_Request) returns (.CAuthentication_GetPasswordRSAPublicKey_Response) {
option (method_description) = "Fetches RSA public key to use to encrypt passwords for a given account name";
}
rpc BeginAuthSessionViaQR (.CAuthentication_BeginAuthSessionViaQR_Request) returns (.CAuthentication_BeginAuthSessionViaQR_Response) {
option (method_description) = "start authentication process";
}
rpc BeginAuthSessionViaCredentials (.CAuthentication_BeginAuthSessionViaCredentials_Request) returns (.CAuthentication_BeginAuthSessionViaCredentials_Response) {
option (method_description) = "start authentication process";
}
rpc PollAuthSessionStatus (.CAuthentication_PollAuthSessionStatus_Request) returns (.CAuthentication_PollAuthSessionStatus_Response) {
option (method_description) = "poll during authentication process";
}
rpc GetAuthSessionInfo (.CAuthentication_GetAuthSessionInfo_Request) returns (.CAuthentication_GetAuthSessionInfo_Response) {
option (method_description) = "get metadata of specific auth session, this will also implicitly bind the calling account";
}
rpc UpdateAuthSessionWithMobileConfirmation (.CAuthentication_UpdateAuthSessionWithMobileConfirmation_Request) returns (.CAuthentication_UpdateAuthSessionWithMobileConfirmation_Response) {
option (method_description) = "approve an authentication session via mobile 2fa";
}
rpc UpdateAuthSessionWithSteamGuardCode (.CAuthentication_UpdateAuthSessionWithSteamGuardCode_Request) returns (.CAuthentication_UpdateAuthSessionWithSteamGuardCode_Response) {
option (method_description) = "approve an authentication session via steam guard code";
}
rpc GenerateAccessTokenForApp (.CAuthentication_AccessToken_GenerateForApp_Request) returns (.CAuthentication_AccessToken_GenerateForApp_Response) {
option (method_description) = "Given a refresh token for a client app audience (e.g. desktop client / mobile client), generate an access token";
}
rpc EnumerateTokens (.CAuthentication_RefreshToken_Enumerate_Request) returns (.CAuthentication_RefreshToken_Enumerate_Response) {
option (method_description) = "Enumerate durable (refresh) tokens for the given subject account";
}
rpc GetAuthSessionsForAccount (.CAuthentication_GetAuthSessionsForAccount_Request) returns (.CAuthentication_GetAuthSessionsForAccount_Response) {
option (method_description) = "Gets all active auth sessions for an account for reference by the mobile app";
}
rpc MigrateMobileSession (.CAuthentication_MigrateMobileSession_Request) returns (.CAuthentication_MigrateMobileSession_Response) {
option (method_description) = "Migrates a WG token to an access and refresh token using a signature generated with the user's 2FA secret";
}
rpc RevokeRefreshToken (.CAuthentication_RefreshToken_Revoke_Request) returns (.CAuthentication_RefreshToken_Revoke_Response) {
option (method_description) = "Mark the given refresh token as revoked";
}
}
service AuthenticationSupport {
option (service_description) = "Authentication Support Service";
rpc QueryRefreshTokensByAccount (.CAuthenticationSupport_QueryRefreshTokensByAccount_Request) returns (.CAuthenticationSupport_QueryRefreshTokensByAccount_Response) {
option (method_description) = "Asks the server for a list of refresh tokens associated with an account";
}
rpc QueryRefreshTokenByID (.CAuthenticationSupport_QueryRefreshTokenByID_Request) returns (.CAuthenticationSupport_QueryRefreshTokenByID_Response) {
option (method_description) = "Asks the server for a list of refresh tokens associated with an account";
}
rpc RevokeToken (.CAuthenticationSupport_RevokeToken_Request) returns (.CAuthenticationSupport_RevokeToken_Response) {
option (method_description) = "Revokes a user's auth token";
}
rpc GetTokenHistory (.CAuthenticationSupport_GetTokenHistory_Request) returns (.CAuthenticationSupport_GetTokenHistory_Response) {
option (method_description) = "Gets the audit history for a user's auth token";
}
}
service CloudGaming {
option (service_description) = "Methods for Steam cloud gaming operations";
rpc CreateNonce (.CCloudGaming_CreateNonce_Request) returns (.CCloudGaming_CreateNonce_Response) {
option (method_description) = "Create a nonce for a cloud gaming service session";
}
rpc GetTimeRemaining (.CCloudGaming_GetTimeRemaining_Request) returns (.CCloudGaming_GetTimeRemaining_Response) {
option (method_description) = "Get the amount of streaming time remaining for a set of apps";
}
}

View file

@ -0,0 +1,314 @@
import "google/protobuf/descriptor.proto";
option optimize_for = SPEED;
option cc_generic_services = true;
option (force_php_generation) = true;
extend .google.protobuf.MessageOptions {
optional int32 msgpool_soft_limit = 50000 [default = 32];
optional int32 msgpool_hard_limit = 50001 [default = 384];
}
extend .google.protobuf.FileOptions {
optional bool force_php_generation = 50000 [default = false];
}
extend .google.protobuf.FieldOptions {
optional bool php_output_always_number = 50020 [default = false];
optional bool allow_field_named_steam_id = 50024 [default = false];
}
enum EBanContentCheckResult {
k_EBanContentCheckResult_NotScanned = 0;
k_EBanContentCheckResult_Reset = 1;
k_EBanContentCheckResult_NeedsChecking = 2;
k_EBanContentCheckResult_VeryUnlikely = 5;
k_EBanContentCheckResult_Unlikely = 30;
k_EBanContentCheckResult_Possible = 50;
k_EBanContentCheckResult_Likely = 75;
k_EBanContentCheckResult_VeryLikely = 100;
}
enum EProtoClanEventType {
k_EClanOtherEvent = 1;
k_EClanGameEvent = 2;
k_EClanPartyEvent = 3;
k_EClanMeetingEvent = 4;
k_EClanSpecialCauseEvent = 5;
k_EClanMusicAndArtsEvent = 6;
k_EClanSportsEvent = 7;
k_EClanTripEvent = 8;
k_EClanChatEvent = 9;
k_EClanGameReleaseEvent = 10;
k_EClanBroadcastEvent = 11;
k_EClanSmallUpdateEvent = 12;
k_EClanPreAnnounceMajorUpdateEvent = 13;
k_EClanMajorUpdateEvent = 14;
k_EClanDLCReleaseEvent = 15;
k_EClanFutureReleaseEvent = 16;
k_EClanESportTournamentStreamEvent = 17;
k_EClanDevStreamEvent = 18;
k_EClanFamousStreamEvent = 19;
k_EClanGameSalesEvent = 20;
k_EClanGameItemSalesEvent = 21;
k_EClanInGameBonusXPEvent = 22;
k_EClanInGameLootEvent = 23;
k_EClanInGamePerksEvent = 24;
k_EClanInGameChallengeEvent = 25;
k_EClanInGameContestEvent = 26;
k_EClanIRLEvent = 27;
k_EClanNewsEvent = 28;
k_EClanBetaReleaseEvent = 29;
k_EClanInGameContentReleaseEvent = 30;
k_EClanFreeTrial = 31;
k_EClanSeasonRelease = 32;
k_EClanSeasonUpdate = 33;
k_EClanCrosspostEvent = 34;
k_EClanInGameEventGeneral = 35;
}
enum PartnerEventNotificationType {
k_EEventStart = 0;
k_EEventBroadcastStart = 1;
k_EEventMatchStart = 2;
k_EEventPartnerMaxType = 3;
}
message CMsgIPAddress {
oneof ip {
fixed32 v4 = 1;
bytes v6 = 2;
}
}
message CMsgIPAddressBucket {
optional .CMsgIPAddress original_ip_address = 1;
optional fixed64 bucket = 2;
}
message CMsgGCRoutingProtoBufHeader {
optional uint64 dst_gcid_queue = 1;
optional uint32 dst_gc_dir_index = 2;
}
message CMsgProtoBufHeader {
optional fixed64 steamid = 1;
optional int32 client_sessionid = 2;
optional uint32 routing_appid = 3;
optional fixed64 jobid_source = 10 [default = 18446744073709551615];
optional fixed64 jobid_target = 11 [default = 18446744073709551615];
optional string target_job_name = 12;
optional int32 seq_num = 24;
optional int32 eresult = 13 [default = 2];
optional string error_message = 14;
optional uint32 auth_account_flags = 16;
optional uint32 token_source = 22;
optional bool admin_spoofing_user = 23;
optional int32 transport_error = 17 [default = 1];
optional uint64 messageid = 18 [default = 18446744073709551615];
optional uint32 publisher_group_id = 19;
optional uint32 sysid = 20;
optional uint64 trace_tag = 21;
optional uint32 webapi_key_id = 25;
optional bool is_from_external_source = 26;
repeated uint32 forward_to_sysid = 27;
optional uint32 cm_sysid = 28;
optional uint32 launcher_type = 31 [default = 0];
optional uint32 realm = 32 [default = 0];
optional int32 timeout_ms = 33 [default = -1];
optional string debug_source = 34;
optional uint32 debug_source_string_index = 35;
optional uint64 token_id = 36;
optional .CMsgGCRoutingProtoBufHeader routing_gc = 37;
oneof ip_addr {
uint32 ip = 15;
bytes ip_v6 = 29;
}
}
message CMsgMulti {
optional uint32 size_unzipped = 1;
optional bytes message_body = 2;
}
message CMsgProtobufWrapped {
optional bytes message_body = 1;
}
message CMsgAuthTicket {
optional uint32 estate = 1;
optional uint32 eresult = 2 [default = 2];
optional fixed64 steamid = 3;
optional fixed64 gameid = 4;
optional uint32 h_steam_pipe = 5;
optional uint32 ticket_crc = 6;
optional bytes ticket = 7;
optional bytes server_secret = 8;
}
message CCDDBAppDetailCommon {
optional uint32 appid = 1;
optional string name = 2;
optional string icon = 3;
optional bool tool = 6;
optional bool demo = 7;
optional bool media = 8;
optional bool community_visible_stats = 9;
optional string friendly_name = 10;
optional string propagation = 11;
optional bool has_adult_content = 12;
optional bool is_visible_in_steam_china = 13;
optional uint32 app_type = 14;
optional bool has_adult_content_sex = 15;
optional bool has_adult_content_violence = 16;
repeated uint32 content_descriptorids = 17;
}
message CMsgAppRights {
optional bool edit_info = 1;
optional bool publish = 2;
optional bool view_error_data = 3;
optional bool download = 4;
optional bool upload_cdkeys = 5;
optional bool generate_cdkeys = 6;
optional bool view_financials = 7;
optional bool manage_ceg = 8;
optional bool manage_signing = 9;
optional bool manage_cdkeys = 10;
optional bool edit_marketing = 11;
optional bool economy_support = 12;
optional bool economy_support_supervisor = 13;
optional bool manage_pricing = 14;
optional bool broadcast_live = 15;
optional bool view_marketing_traffic = 16;
optional bool edit_store_display_content = 17;
}
message CCuratorPreferences {
optional uint32 supported_languages = 1;
optional bool platform_windows = 2;
optional bool platform_mac = 3;
optional bool platform_linux = 4;
optional bool vr_content = 5;
optional bool adult_content_violence = 6;
optional bool adult_content_sex = 7;
optional uint32 timestamp_updated = 8;
repeated uint32 tagids_curated = 9;
repeated uint32 tagids_filtered = 10;
optional string website_title = 11;
optional string website_url = 12;
optional string discussion_url = 13;
optional bool show_broadcast = 14;
}
message CLocalizationToken {
optional uint32 language = 1;
optional string localized_string = 2;
}
message CClanEventUserNewsTuple {
optional uint32 clanid = 1;
optional fixed64 event_gid = 2;
optional fixed64 announcement_gid = 3;
optional uint32 rtime_start = 4;
optional uint32 rtime_end = 5;
optional uint32 priority_score = 6;
optional uint32 type = 7;
optional uint32 clamp_range_slot = 8;
optional uint32 appid = 9;
optional uint32 rtime32_last_modified = 10;
}
message CClanMatchEventByRange {
optional uint32 rtime_before = 1;
optional uint32 rtime_after = 2;
optional uint32 qualified = 3;
repeated .CClanEventUserNewsTuple events = 4;
}
message CCommunity_ClanAnnouncementInfo {
optional uint64 gid = 1;
optional uint64 clanid = 2;
optional uint64 posterid = 3;
optional string headline = 4;
optional uint32 posttime = 5;
optional uint32 updatetime = 6;
optional string body = 7;
optional int32 commentcount = 8;
repeated string tags = 9;
optional int32 language = 10;
optional bool hidden = 11;
optional fixed64 forum_topic_id = 12;
optional fixed64 event_gid = 13;
optional int32 voteupcount = 14;
optional int32 votedowncount = 15;
optional .EBanContentCheckResult ban_check_result = 16 [default = k_EBanContentCheckResult_NotScanned];
optional bool banned = 17;
}
message CClanEventData {
optional fixed64 gid = 1;
optional fixed64 clan_steamid = 2;
optional string event_name = 3;
optional .EProtoClanEventType event_type = 4 [default = k_EClanOtherEvent];
optional uint32 appid = 5;
optional string server_address = 6;
optional string server_password = 7;
optional uint32 rtime32_start_time = 8;
optional uint32 rtime32_end_time = 9;
optional int32 comment_count = 10;
optional fixed64 creator_steamid = 11;
optional fixed64 last_update_steamid = 12;
optional string event_notes = 13;
optional string jsondata = 14;
optional .CCommunity_ClanAnnouncementInfo announcement_body = 15;
optional bool published = 16;
optional bool hidden = 17;
optional uint32 rtime32_visibility_start = 18;
optional uint32 rtime32_visibility_end = 19;
optional uint32 broadcaster_accountid = 20;
optional uint32 follower_count = 21;
optional uint32 ignore_count = 22;
optional fixed64 forum_topic_id = 23;
optional uint32 rtime32_last_modified = 24;
optional fixed64 news_post_gid = 25;
optional uint32 rtime_mod_reviewed = 26;
optional uint32 featured_app_tagid = 27;
repeated uint32 referenced_appids = 28;
optional uint32 build_id = 29;
optional string build_branch = 30;
}
message CBilling_Address {
optional string first_name = 1;
optional string last_name = 2;
optional string address1 = 3;
optional string address2 = 4;
optional string city = 5;
optional string us_state = 6;
optional string country_code = 7;
optional string postcode = 8;
optional int32 zip_plus4 = 9;
optional string phone = 10;
}
message CPackageReservationStatus {
optional uint32 packageid = 1;
optional int32 reservation_state = 2;
optional int32 queue_position = 3;
optional int32 total_queue_size = 4;
optional string reservation_country_code = 5;
optional bool expired = 6;
optional uint32 time_expires = 7;
optional uint32 time_reserved = 8;
}
message CMsgKeyValuePair {
optional string name = 1;
optional string value = 2;
}
message CMsgKeyValueSet {
repeated .CMsgKeyValuePair pairs = 1;
}

View file

@ -0,0 +1,166 @@
import "steammessages_base.proto";
option optimize_for = SPEED;
option cc_generic_services = false;
message CMsgClientHeartBeat {
optional bool send_reply = 1;
}
message CMsgClientServerTimestampRequest {
optional uint64 client_request_timestamp = 1;
}
message CMsgClientServerTimestampResponse {
optional uint64 client_request_timestamp = 1;
optional uint64 server_timestamp_ms = 2;
}
message CMsgClientSecret {
optional uint32 version = 1;
optional uint32 appid = 2;
optional uint32 deviceid = 3;
optional fixed64 nonce = 4;
optional bytes hmac = 5;
}
message CMsgClientHello {
optional uint32 protocol_version = 1;
}
message CMsgClientLogon {
optional uint32 protocol_version = 1;
optional uint32 deprecated_obfustucated_private_ip = 2;
optional uint32 cell_id = 3;
optional uint32 last_session_id = 4;
optional uint32 client_package_version = 5;
optional string client_language = 6;
optional uint32 client_os_type = 7;
optional bool should_remember_password = 8 [default = false];
optional string wine_version = 9;
optional uint32 deprecated_10 = 10;
optional .CMsgIPAddress obfuscated_private_ip = 11;
optional uint32 deprecated_public_ip = 20;
optional uint32 qos_level = 21;
optional fixed64 client_supplied_steam_id = 22;
optional .CMsgIPAddress public_ip = 23;
optional bytes machine_id = 30;
optional uint32 launcher_type = 31 [default = 0];
optional uint32 ui_mode = 32 [default = 0];
optional uint32 chat_mode = 33 [default = 0];
optional bytes steam2_auth_ticket = 41;
optional string email_address = 42;
optional fixed32 rtime32_account_creation = 43;
optional string account_name = 50;
optional string password = 51;
optional string game_server_token = 52;
optional string login_key = 60;
optional bool was_converted_deprecated_msg = 70 [default = false];
optional string anon_user_target_account_name = 80;
optional fixed64 resolved_user_steam_id = 81;
optional int32 eresult_sentryfile = 82;
optional bytes sha_sentryfile = 83;
optional string auth_code = 84;
optional int32 otp_type = 85;
optional uint32 otp_value = 86;
optional string otp_identifier = 87;
optional bool steam2_ticket_request = 88;
optional bytes sony_psn_ticket = 90;
optional string sony_psn_service_id = 91;
optional bool create_new_psn_linked_account_if_needed = 92 [default = false];
optional string sony_psn_name = 93;
optional int32 game_server_app_id = 94;
optional bool steamguard_dont_remember_computer = 95;
optional string machine_name = 96;
optional string machine_name_userchosen = 97;
optional string country_override = 98;
optional bool is_steam_box = 99;
optional uint64 client_instance_id = 100;
optional string two_factor_code = 101;
optional bool supports_rate_limit_response = 102;
optional string web_logon_nonce = 103;
optional int32 priority_reason = 104;
optional .CMsgClientSecret embedded_client_secret = 105;
optional bool disable_partner_autogrants = 106;
optional bool is_steam_deck = 107;
optional string access_token = 108;
optional bool is_chrome_os = 109;
optional bool is_tesla = 110;
}
message CMsgClientLogonResponse {
optional int32 eresult = 1 [default = 2];
optional int32 legacy_out_of_game_heartbeat_seconds = 2;
optional int32 heartbeat_seconds = 3;
optional uint32 deprecated_public_ip = 4;
optional fixed32 rtime32_server_time = 5;
optional uint32 account_flags = 6;
optional uint32 cell_id = 7;
optional string email_domain = 8;
optional bytes steam2_ticket = 9;
optional int32 eresult_extended = 10;
optional string webapi_authenticate_user_nonce = 11;
optional uint32 cell_id_ping_threshold = 12;
optional bool deprecated_use_pics = 13;
optional string vanity_url = 14;
optional .CMsgIPAddress public_ip = 15;
optional fixed64 client_supplied_steamid = 20;
optional string ip_country_code = 21;
optional bytes parental_settings = 22;
optional bytes parental_setting_signature = 23;
optional int32 count_loginfailures_to_migrate = 24;
optional int32 count_disconnects_to_migrate = 25;
optional int32 ogs_data_report_time_window = 26;
optional uint64 client_instance_id = 27;
optional bool force_client_update_check = 28;
optional string agreement_session_url = 29;
optional uint64 token_id = 30;
}
message CMsgClientRequestWebAPIAuthenticateUserNonce {
optional int32 token_type = 1 [default = -1];
}
message CMsgClientRequestWebAPIAuthenticateUserNonceResponse {
optional int32 eresult = 1 [default = 2];
optional string webapi_authenticate_user_nonce = 11;
optional int32 token_type = 3 [default = -1];
}
message CMsgClientLogOff {
}
message CMsgClientLoggedOff {
optional int32 eresult = 1 [default = 2];
}
message CMsgClientNewLoginKey {
optional uint32 unique_id = 1;
optional string login_key = 2;
}
message CMsgClientNewLoginKeyAccepted {
optional uint32 unique_id = 1;
}
message CMsgClientAccountInfo {
optional string persona_name = 1;
optional string ip_country = 2;
optional int32 count_authed_computers = 5;
optional uint32 account_flags = 7;
optional uint64 facebook_id = 8;
optional string facebook_name = 9;
optional string steamguard_machine_name_user_chosen = 15;
optional bool is_phone_verified = 16;
optional uint32 two_factor_state = 17;
optional bool is_phone_identifying = 18;
optional bool is_phone_needing_reverify = 19;
}
message CMsgClientChallengeRequest {
optional fixed64 steamid = 1;
}
message CMsgClientChallengeResponse {
optional fixed64 challenge = 1;
}

View file

@ -0,0 +1,33 @@
import "google/protobuf/descriptor.proto";
option optimize_for = SPEED;
option cc_generic_services = false;
extend .google.protobuf.FieldOptions {
optional string description = 50000;
}
extend .google.protobuf.ServiceOptions {
optional string service_description = 50000;
optional .EProtoExecutionSite service_execution_site = 50008 [default = k_EProtoExecutionSiteUnknown];
}
extend .google.protobuf.MethodOptions {
optional string method_description = 50000;
}
extend .google.protobuf.EnumOptions {
optional string enum_description = 50000;
}
extend .google.protobuf.EnumValueOptions {
optional string enum_value_description = 50000;
}
enum EProtoExecutionSite {
k_EProtoExecutionSiteUnknown = 0;
k_EProtoExecutionSiteSteamClient = 2;
}
message NoResponse {
}

View file

@ -1,6 +1,12 @@
use crate::protobufs::service_twofactor::{
CTwoFactor_AddAuthenticator_Request, CTwoFactor_FinalizeAddAuthenticator_Request,
};
use crate::steamapi::twofactor::TwoFactorClient;
use crate::token::TwoFactorSecret;
use crate::transport::WebApiTransport;
use crate::{
api_responses::{AddAuthenticatorResponse, FinalizeAddAuthenticatorResponse},
steamapi::{Session, SteamApiClient},
steamapi::{EResult, Session, SteamApiClient},
token::Tokens,
SteamGuardAccount,
};
use log::*;
@ -12,25 +18,23 @@ pub struct AccountLinker {
pub phone_number: String,
pub account: Option<SteamGuardAccount>,
pub finalized: bool,
sent_confirmation_email: bool,
session: Session,
client: SteamApiClient,
tokens: Tokens,
client: TwoFactorClient<WebApiTransport>,
}
impl AccountLinker {
pub fn new(session: Session) -> AccountLinker {
return AccountLinker {
pub fn new(tokens: Tokens) -> AccountLinker {
Self {
device_id: generate_device_id(),
phone_number: "".into(),
account: None,
finalized: false,
sent_confirmation_email: false,
session: session.clone(),
client: SteamApiClient::new(Some(secrecy::Secret::new(session))),
};
tokens,
client: TwoFactorClient::new(WebApiTransport::new()),
}
}
pub fn link(&mut self) -> anyhow::Result<SteamGuardAccount, AccountLinkError> {
pub fn link(&mut self) -> anyhow::Result<AccountLinkSuccess, AccountLinkError> {
// let has_phone = self.client.has_phone()?;
// if has_phone && !self.phone_number.is_empty() {
@ -53,67 +57,106 @@ impl AccountLinker {
// }
// }
let resp: AddAuthenticatorResponse =
self.client.add_authenticator(self.device_id.clone())?;
let access_token = self.tokens.access_token();
let steam_id = access_token.decode()?.steam_id();
match resp.status {
29 => {
return Err(AccountLinkError::AuthenticatorPresent);
}
2 => {
// If the user has no phone number on their account, it will always return this status code.
// However, this does not mean that this status just means "no phone number". It can also
// be literally anything else, so that's why we return GenericFailure here.
return Err(AccountLinkError::GenericFailure);
}
1 => {
let mut account = resp.to_steam_guard_account();
account.device_id = self.device_id.clone();
account.session = self.client.session.clone();
return Ok(account);
}
status => {
return Err(anyhow!("Unknown add authenticator status code: {}", status))?;
}
let mut req = CTwoFactor_AddAuthenticator_Request::new();
req.set_authenticator_type(1);
req.set_steamid(steam_id);
req.set_sms_phone_id("1".to_owned());
req.set_device_identifier(self.device_id.clone());
let resp = self.client.add_authenticator(req, access_token)?;
if resp.result != EResult::OK {
return Err(resp.result.into());
}
let mut resp = resp.into_response_data();
let account = SteamGuardAccount {
account_name: resp.take_account_name(),
steam_id,
serial_number: resp.serial_number().to_string(),
revocation_code: resp.take_revocation_code().into(),
uri: resp.take_uri().into(),
shared_secret: TwoFactorSecret::from_bytes(resp.take_shared_secret()),
token_gid: resp.take_token_gid().into(),
identity_secret: base64::encode(&resp.take_identity_secret()).into(),
device_id: self.device_id.clone(),
secret_1: base64::encode(&resp.take_secret_1()).into(),
tokens: Some(self.tokens.clone()),
};
let success = AccountLinkSuccess {
account: account,
server_time: resp.server_time(),
phone_number_hint: resp.take_phone_number_hint(),
};
Ok(success)
}
/// You may have to call this multiple times. If you have to call it a bunch of times, then you can assume that you are unable to generate correct 2fa codes.
pub fn finalize(
&mut self,
time: u64,
account: &mut SteamGuardAccount,
sms_code: String,
) -> anyhow::Result<(), FinalizeLinkError> {
let time = crate::steamapi::get_server_time()?.server_time;
let code = account.generate_code(time);
let resp: FinalizeAddAuthenticatorResponse =
self.client
.finalize_authenticator(sms_code.clone(), code, time)?;
info!("finalize response status: {}", resp.status);
match resp.status {
89 => {
return Err(FinalizeLinkError::BadSmsCode);
}
_ => {}
let token = self.tokens.access_token();
let steam_id = account.steam_id;
let mut req = CTwoFactor_FinalizeAddAuthenticator_Request::new();
req.set_steamid(steam_id);
req.set_authenticator_code(code);
req.set_authenticator_time(time);
req.set_activation_code(sms_code);
let resp = self.client.finalize_authenticator(req, token)?;
if resp.result != EResult::OK {
return Err(resp.result.into());
}
if !resp.success {
return Err(FinalizeLinkError::Failure {
status: resp.status,
})?;
}
let resp = resp.into_response_data();
if resp.want_more {
return Err(FinalizeLinkError::WantMore);
if resp.want_more() {
return Err(FinalizeLinkError::WantMore {
server_time: resp.server_time(),
});
}
self.finalized = true;
account.fully_enrolled = true;
return Ok(());
}
}
#[derive(Debug)]
pub struct AccountLinkSuccess {
account: SteamGuardAccount,
server_time: u64,
phone_number_hint: String,
}
impl AccountLinkSuccess {
pub fn account(&self) -> &SteamGuardAccount {
&self.account
}
pub fn into_account(self) -> SteamGuardAccount {
self.account
}
pub fn server_time(&self) -> u64 {
self.server_time
}
pub fn phone_number_hint(&self) -> &str {
&self.phone_number_hint
}
}
fn generate_device_id() -> String {
return format!("android:{}", uuid::Uuid::new_v4().to_string());
}
@ -133,19 +176,43 @@ pub enum AccountLinkError {
AuthenticatorPresent,
#[error("Steam was unable to link the authenticator to the account. No additional information about this error is available. This is a Steam error, not a steamguard-cli error. Try adding a phone number to your Steam account (which you can do here: https://store.steampowered.com/phone/add), or try again later.")]
GenericFailure,
#[error("Steam returned an unexpected error code: {0:?}")]
UnknownEResult(EResult),
#[error(transparent)]
Unknown(#[from] anyhow::Error),
}
impl From<EResult> for AccountLinkError {
fn from(result: EResult) -> Self {
match result {
EResult::DuplicateRequest => AccountLinkError::AuthenticatorPresent,
// If the user has no phone number on their account, it will always return this status code.
// However, this does not mean that this status just means "no phone number". It can also
// be literally anything else, so that's why we return GenericFailure here.
EResult::Fail => AccountLinkError::GenericFailure,
r => AccountLinkError::UnknownEResult(r),
}
}
}
#[derive(Error, Debug)]
pub enum FinalizeLinkError {
#[error("Provided SMS code was incorrect.")]
BadSmsCode,
/// Steam wants more 2fa codes to verify that we can generate valid codes. Call finalize again.
#[error("Steam wants more 2fa codes for verification.")]
WantMore,
#[error("Finalization was not successful. Status code {status:?}")]
Failure { status: i32 },
WantMore { server_time: u64 },
#[error("Steam returned an unexpected error code: {0:?}")]
UnknownEResult(EResult),
#[error(transparent)]
Unknown(#[from] anyhow::Error),
}
impl From<EResult> for FinalizeLinkError {
fn from(result: EResult) -> Self {
match result {
EResult::TwoFactorActivationCodeMismatch => FinalizeLinkError::BadSmsCode,
r => FinalizeLinkError::UnknownEResult(r),
}
}
}

View file

@ -0,0 +1,29 @@
use serde::Deserialize;
use crate::protobufs::steammessages_auth_steamclient::{
CAuthentication_AllowedConfirmation, EAuthSessionGuardType,
};
#[derive(Deserialize, Debug, Clone)]
pub struct AllowedConfirmation {
pub confirmation_type: EAuthSessionGuardType,
pub associated_messsage: String,
}
impl From<AllowedConfirmation> for CAuthentication_AllowedConfirmation {
fn from(resp: AllowedConfirmation) -> Self {
let mut inner = Self::new();
inner.set_confirmation_type(resp.confirmation_type);
inner.set_associated_message(resp.associated_messsage);
inner
}
}
impl From<CAuthentication_AllowedConfirmation> for AllowedConfirmation {
fn from(mut resp: CAuthentication_AllowedConfirmation) -> Self {
Self {
confirmation_type: resp.confirmation_type(),
associated_messsage: resp.take_associated_message(),
}
}
}

View file

@ -4,6 +4,7 @@ use super::parse_json_string_as_number;
use serde::{Deserialize, Serialize};
/// Represents the response from `/ITwoFactorService/QueryTime/v0001`
#[deprecated]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueryTimeResponse {
/// The time that the server will use to check your two factor code.
@ -21,6 +22,7 @@ pub struct QueryTimeResponse {
pub max_attempts: u64,
}
#[deprecated]
#[derive(Debug, Clone, Deserialize)]
pub struct AddAuthenticatorResponse {
/// Shared secret between server and authenticator
@ -56,25 +58,7 @@ pub struct AddAuthenticatorResponse {
pub phone_number_hint: Option<String>,
}
impl AddAuthenticatorResponse {
pub fn to_steam_guard_account(self) -> SteamGuardAccount {
SteamGuardAccount {
shared_secret: TwoFactorSecret::parse_shared_secret(self.shared_secret).unwrap(),
serial_number: self.serial_number.clone(),
revocation_code: self.revocation_code.into(),
uri: self.uri.into(),
server_time: self.server_time,
account_name: self.account_name.clone(),
token_gid: self.token_gid.clone(),
identity_secret: self.identity_secret.into(),
secret_1: self.secret_1.into(),
fully_enrolled: false,
device_id: "".into(),
session: None,
}
}
}
#[deprecated]
#[derive(Debug, Clone, Deserialize)]
pub struct FinalizeAddAuthenticatorResponse {
pub status: i32,
@ -84,6 +68,7 @@ pub struct FinalizeAddAuthenticatorResponse {
pub success: bool,
}
#[deprecated]
#[derive(Debug, Clone, Deserialize)]
pub struct RemoveAuthenticatorResponse {
pub success: bool,

View file

@ -22,6 +22,7 @@ pub struct OAuthData {
}
#[derive(Debug, Clone, Deserialize)]
#[deprecated]
pub struct RsaResponse {
pub success: bool,
pub publickey_exp: String,

View file

@ -1,7 +1,9 @@
mod i_authentication_service;
mod i_two_factor_service;
mod login;
mod phone_ajax;
pub use i_authentication_service::*;
pub use i_two_factor_service::*;
pub use login::*;
pub use phone_ajax::*;

View file

@ -1,38 +1,85 @@
use serde::Deserialize;
/// A mobile confirmation. There are multiple things that can be confirmed, like trade offers.
#[derive(Debug, Clone, PartialEq)]
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct Confirmation {
pub id: u64,
pub key: u64,
/// Trade offer ID or market transaction ID
pub creator: u64,
#[serde(rename = "type")]
pub conf_type: ConfirmationType,
pub description: String,
pub type_name: String,
pub id: String,
/// Trade offer ID or market transaction ID
pub creator_id: String,
pub nonce: String,
pub creation_time: u64,
pub cancel: String,
pub accept: String,
pub icon: String,
pub multi: bool,
pub headline: String,
pub summary: Vec<String>,
}
impl Confirmation {
/// Human readable representation of this confirmation.
pub fn description(&self) -> String {
format!("{:?} - {}", self.conf_type, self.description)
format!(
"{:?} - {} - {}",
self.conf_type,
self.headline,
self.summary.join(", ")
)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[repr(u32)]
#[serde(from = "u32")]
pub enum ConfirmationType {
Generic = 1,
Trade = 2,
MarketSell = 3,
AccountRecovery = 6,
Unknown,
Unknown(u32),
}
impl From<&str> for ConfirmationType {
fn from(text: &str) -> Self {
impl From<u32> for ConfirmationType {
fn from(text: u32) -> Self {
match text {
"1" => ConfirmationType::Generic,
"2" => ConfirmationType::Trade,
"3" => ConfirmationType::MarketSell,
"6" => ConfirmationType::AccountRecovery,
_ => ConfirmationType::Unknown,
1 => ConfirmationType::Generic,
2 => ConfirmationType::Trade,
3 => ConfirmationType::MarketSell,
6 => ConfirmationType::AccountRecovery,
v => ConfirmationType::Unknown(v),
}
}
}
#[derive(Debug, Deserialize)]
pub struct ConfirmationListResponse {
pub success: bool,
pub conf: Vec<Confirmation>,
}
#[derive(Debug, Clone, Copy, Deserialize)]
pub struct SendConfirmationResponse {
pub success: bool,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_email_change() -> anyhow::Result<()> {
let text = include_str!("fixtures/confirmations/email-change.json");
let confirmations = serde_json::from_str::<ConfirmationListResponse>(text)?;
assert_eq!(confirmations.conf.len(), 1);
let confirmation = &confirmations.conf[0];
assert_eq!(confirmation.conf_type, ConfirmationType::AccountRecovery);
Ok(())
}
}

View file

@ -0,0 +1,4 @@
This contains the literal HTML pages that are used show confirmations to users.
Some notes:
- AccountRecovery confirmations can be found reliably by trying to change the email address of an account with an authenticator active.

View file

@ -0,0 +1,283 @@
<!DOCTYPE html>
<html class=" responsive touch mobile_client legacy_mobile" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
<meta name="theme-color" content="#171a21">
<title>Steam Community :: Confirmations</title>
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
<link href="https://community.akamai.steamstatic.com/public/shared/css/motiva_sans.css?v=-DH0xTYpnVe2&amp;l=english"
rel="stylesheet" type="text/css">
<link href="https://community.akamai.steamstatic.com/public/shared/css/buttons.css?v=n-eRNszNIRMH&amp;l=english"
rel="stylesheet" type="text/css">
<link
href="https://community.akamai.steamstatic.com/public/shared/css/shared_global.css?v=YdMOKHYz0_57&amp;l=english"
rel="stylesheet" type="text/css">
<link href="https://community.akamai.steamstatic.com/public/css/globalv2.css?v=GtBXfuM7ql2k&amp;l=english"
rel="stylesheet" type="text/css">
<link href="https://community.akamai.steamstatic.com/public/css/skin_1/modalContent.css?v=.TP5s6TzX6LLh"
rel="stylesheet" type="text/css">
<link
href="https://community.akamai.steamstatic.com/public/css/mobile/styles_mobileconf.css?v=7eOknd5U_Oiy&amp;l=english"
rel="stylesheet" type="text/css">
<link href="https://community.akamai.steamstatic.com/public/shared/css/motiva_sans.css?v=-DH0xTYpnVe2&amp;l=english"
rel="stylesheet" type="text/css">
<link href="https://community.akamai.steamstatic.com/public/css/skin_1/html5.css?v=.MtSlvoLZL0Tb" rel="stylesheet"
type="text/css">
<link href="https://community.akamai.steamstatic.com/public/css/skin_1/economy.css?v=W1lpCYkssBMO&amp;l=english"
rel="stylesheet" type="text/css">
<link href="https://community.akamai.steamstatic.com/public/css/skin_1/trade.css?v=HdcFTfHh9VyM&amp;l=english"
rel="stylesheet" type="text/css">
<link
href="https://community.akamai.steamstatic.com/public/css/skin_1/profile_tradeoffers.css?v=X4MCM7I71wwc&amp;l=english"
rel="stylesheet" type="text/css">
<link
href="https://community.akamai.steamstatic.com/public/shared/css/shared_responsive.css?v=BMF068jICwP9&amp;l=english"
rel="stylesheet" type="text/css">
<link href="https://community.akamai.steamstatic.com/public/css/skin_1/header.css?v=g7VmRhGIDEiu&amp;l=english"
rel="stylesheet" type="text/css">
<script>
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date(); a = s.createElement(o),
m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
ga('create', 'UA-33779068-1', 'auto', {
'sampleRate': 0.4
});
ga('set', 'dimension1', true);
ga('set', 'dimension2', 'Steam Mobile App');
ga('set', 'dimension3', 'mobileconf');
ga('set', 'dimension4', "mobileconf\/conf");
ga('send', 'pageview');
</script>
<script type="text/javascript">
var __PrototypePreserve = [];
__PrototypePreserve[0] = Array.from;
__PrototypePreserve[1] = Array.prototype.filter;
__PrototypePreserve[2] = Array.prototype.flatMap;
__PrototypePreserve[3] = Array.prototype.find;
__PrototypePreserve[4] = Array.prototype.some;
__PrototypePreserve[5] = Function.prototype.bind;
__PrototypePreserve[6] = HTMLElement.prototype.scrollTo;
</script>
<script type="text/javascript"
src="https://community.akamai.steamstatic.com/public/javascript/prototype-1.7.js?v=.55t44gwuwgvw"></script>
<script type="text/javascript">
Array.from = __PrototypePreserve[0] || Array.from;
Array.prototype.filter = __PrototypePreserve[1] || Array.prototype.filter;
Array.prototype.flatMap = __PrototypePreserve[2] || Array.prototype.flatMap;
Array.prototype.find = __PrototypePreserve[3] || Array.prototype.find;
Array.prototype.some = __PrototypePreserve[4] || Array.prototype.some;
Function.prototype.bind = __PrototypePreserve[5] || Function.prototype.bind;
HTMLElement.prototype.scrollTo = __PrototypePreserve[6] || HTMLElement.prototype.scrollTo;
</script>
<script type="text/javascript">VALVE_PUBLIC_PATH = "https:\/\/community.akamai.steamstatic.com\/public\/";</script>
<script type="text/javascript"
src="https://community.akamai.steamstatic.com/public/javascript/scriptaculous/_combined.js?v=OeNIgrpEF8tL&amp;l=english&amp;load=effects,controls,slider,dragdrop"></script>
<script type="text/javascript"
src="https://community.akamai.steamstatic.com/public/javascript/global.js?v=f12ZD-pRSaA_&amp;l=english"></script>
<script type="text/javascript"
src="https://community.akamai.steamstatic.com/public/javascript/jquery-1.11.1.min.js?v=.isFTSRckeNhC"></script>
<script type="text/javascript"
src="https://community.akamai.steamstatic.com/public/shared/javascript/tooltip.js?v=.zYHOpI1L3Rt0"></script>
<script type="text/javascript"
src="https://community.akamai.steamstatic.com/public/shared/javascript/shared_global.js?v=ymLq7HqPFUuU&amp;l=english"></script>
<script
type="text/javascript">Object.seal && [Object, Array, String, Number].map(function (builtin) { Object.seal(builtin.prototype); });</script>
<script type="text/javascript">$J = jQuery.noConflict();
if (typeof JSON != 'object' || !JSON.stringify || !JSON.parse) { document.write("<scr" + "ipt type=\"text\/javascript\" src=\"https:\/\/community.akamai.steamstatic.com\/public\/javascript\/json2.js?v=pmScf4470EZP&amp;l=english\" ><\/script>\n"); };
</script>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function (event) {
SetupTooltips({ tooltipCSSClass: 'community_tooltip' });
});
</script>
<script type="text/javascript"
src="https://community.akamai.steamstatic.com/public/javascript/jquery-ui-1.9.2.min.js?v=.ILEZTVPIP_6a"></script>
<script type="text/javascript"
src="https://community.akamai.steamstatic.com/public/shared/javascript/mobileappapi.js?v=KX5d7WjziQ7F&amp;l=english&amp;mobileClientType=android"></script>
<script type="text/javascript"
src="https://community.akamai.steamstatic.com/public/javascript/mobile/mobileconf.js?v=mzd_2xm8sUkb&amp;l=english"></script>
<script type="text/javascript"
src="https://community.akamai.steamstatic.com/public/javascript/economy_common.js?v=tsXdRVB0yEaR&amp;l=english"></script>
<script type="text/javascript"
src="https://community.akamai.steamstatic.com/public/javascript/economy.js?v=zBu5E2N7nc-G&amp;l=english"></script>
<script type="text/javascript"
src="https://community.akamai.steamstatic.com/public/javascript/modalv2.js?v=dfMhuy-Lrpyo&amp;l=english"></script>
<script type="text/javascript"
src="https://community.akamai.steamstatic.com/public/javascript/modalContent.js?v=L35TrLJDfqtD&amp;l=english"></script>
<script type="text/javascript"
src="https://community.akamai.steamstatic.com/public/shared/javascript/shared_responsive_adapter.js?v=pSvIAKtunfWg&amp;l=english"></script>
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:site" content="@steam" />
<meta property="og:title" content="Steam Community :: Confirmations">
<meta property="twitter:title" content="Steam Community :: Confirmations">
<meta property="og:type" content="website">
<meta property="fb:app_id" content="105386699540688">
<link rel="image_src"
href="https://community.akamai.steamstatic.com/public/shared/images/responsive/share_steam_logo.png">
<meta property="og:image"
content="https://community.akamai.steamstatic.com/public/shared/images/responsive/share_steam_logo.png">
<meta name="twitter:image"
content="https://community.akamai.steamstatic.com/public/shared/images/responsive/share_steam_logo.png" />
<meta property="og:image:secure"
content="https://community.akamai.steamstatic.com/public/shared/images/responsive/share_steam_logo.png">
<script type="text/javascript">
$J(function () {
window.location = "steammobile:\/\/settitle?title=Confirmations";
});
</script>
</head>
<body class=" responsive_page ">
<div class="responsive_page_frame no_header">
<div class="responsive_local_menu_tab"></div>
<div class="responsive_page_menu_ctn localmenu">
<div class="responsive_page_menu" id="responsive_page_local_menu"
data-panel="{&quot;onOptionsActionDescription&quot;:&quot;#filter_toggle&quot;,&quot;onOptionsButton&quot;:&quot;Responsive_ToggleLocalMenu()&quot;,&quot;onCancelButton&quot;:&quot;Responsive_ToggleLocalMenu()&quot;}">
<div class="localmenu_content"
data-panel="{&quot;maintainY&quot;:true,&quot;bFocusRingRoot&quot;:true,&quot;flow-children&quot;:&quot;column&quot;}">
</div>
</div>
</div>
<div class="responsive_page_content_overlay">
</div>
<div class="responsive_fixonscroll_ctn nonresponsive_hidden no_menu">
</div>
<div class="responsive_page_content">
<script type="text/javascript">
g_sessionID = "77bcaf85819d43c73c92247e";
g_steamID = "76561199155706892";
g_strLanguage = "english";
g_SNR = '2_mobileconf_conf_';
g_bAllowAppImpressions = true;
g_ContentDescriptorPreferences = [1, 3, 4];
// We always want to have the timezone cookie set for PHP to use
setTimezoneCookies();
$J(function () {
InitMiniprofileHovers(('https%3A%2F%2Fsteamcommunity.com'));
InitEmoticonHovers();
ApplyAdultContentPreferences();
});
$J(function () { InitEconomyHovers("https:\/\/community.akamai.steamstatic.com\/public\/css\/skin_1\/economy.css?v=W1lpCYkssBMO&l=english", "https:\/\/community.akamai.steamstatic.com\/public\/javascript\/economy_common.js?v=tsXdRVB0yEaR&l=english", "https:\/\/community.akamai.steamstatic.com\/public\/javascript\/economy.js?v=zBu5E2N7nc-G&l=english"); });</script>
<div class="responsive_page_template_content" id="responsive_page_template_content"
data-panel="{&quot;autoFocus&quot;:true}">
<div id="mobileconf_list">
<div class="mobileconf_list_entry" id="conf13780810717" data-confid="13780810717"
data-key="17156665999632629514" data-type="6" data-creator="2307544449623194939"
data-cancel="Cancel" data-accept="Confirm">
<div class="mobileconf_list_entry_content">
<div class="mobileconf_list_entry_icon">
<img src="https://community.akamai.steamstatic.com/public/shared/images/login/key.png"
style="width: 32px; height: 32px; margin-top: 6px">
</div>
<div class="mobileconf_list_entry_description">
<div>Account recovery</div>
<div></div>
<div>Just now</div>
</div>
</div>
<div class="mobileconf_list_entry_sep"></div>
</div>
</div>
<div id="mobileconf_done" class="mobileconf_done mobileconf_header" style="display: none">
<div>All done</div>
<div>You're all done, there's nothing left to confirm.</div>
</div>
<div id="mobileconf_details" style="display: none">
</div>
<div id="mobileconf_buttons" style="display: none">
<div>
<div class="mobileconf_button mobileconf_button_cancel">
</div>
<div class="mobileconf_button mobileconf_button_accept">
</div>
</div>
</div>
<div id="mobileconf_throbber" style="display: none">
<div style="text-align:center; margin: auto;">
<img src="https://community.akamai.steamstatic.com/public/images/login/throbber.gif"
alt="Loading">
</div>
</div>
</div> <!-- responsive_page_legacy_content -->
<div id="footer_spacer" class=""></div>
<div id="footer_responsive_optin_spacer"></div>
<div id="footer">
<div class="footer_content">
<span id="footerLogo"><img
src="https://community.akamai.steamstatic.com/public/images/skin_1/footerLogo_valve.png?v=1"
width="96" height="26" border="0" alt="Valve Logo" /></span>
<span id="footerText">
&copy; Valve Corporation. All rights reserved. All trademarks are property of their respective
owners in the US and other countries.<br />Some geospatial data on this website is provided by
<a href="https://steamcommunity.com/linkfilter/?url=http://www.geonames.org" target="_blank"
rel=" noopener">geonames.org</a>. <br>
<span class="valve_links">
<a href="http://store.steampowered.com/privacy_agreement/" target="_blank">Privacy
Policy</a>
&nbsp; | &nbsp;<a href="https://store.steampowered.com/legal/" target="_blank">Legal</a>
&nbsp;| &nbsp;<a href="http://store.steampowered.com/subscriber_agreement/"
target="_blank">Steam Subscriber Agreement</a>
&nbsp;| &nbsp;<a href="http://store.steampowered.com/account/cookiepreferences/"
target="_blank">Cookies</a>
</span>
</span>
</div>
<div class="responsive_optin_link">
<div class="btn_medium btnv6_grey_black" onclick="Responsive_RequestMobileView()">
<span>View mobile website</span>
</div>
</div>
</div>
</div> <!-- responsive_page_content -->
</div> <!-- responsive_page_frame -->
</body>
</html>

View file

@ -0,0 +1,22 @@
{
"success": true,
"conf": [
{
"type": 6,
"type_name": "Account details",
"id": "13810258093",
"creator_id": "5112001996116090268",
"nonce": "11854208935012684707",
"creation_time": 1687457923,
"cancel": "Cancel",
"accept": "Confirm",
"icon": "https:\/\/community.akamai.steamstatic.com\/public\/shared\/images\/login\/key.png",
"multi": false,
"headline": "Account recovery",
"summary": [
""
],
"warn": null
}
]
}

View file

@ -1,4 +1,12 @@
use crate::token::TwoFactorSecret;
use crate::api_responses::SteamApiResponse;
use crate::confirmation::{ConfirmationListResponse, SendConfirmationResponse};
use crate::protobufs::service_twofactor::{
CTwoFactor_RemoveAuthenticator_Request, CTwoFactor_RemoveAuthenticator_Response,
};
use crate::steamapi::EResult;
use crate::{
steamapi::twofactor::TwoFactorClient, token::TwoFactorSecret, transport::WebApiTransport,
};
pub use accountlinker::{AccountLinkError, AccountLinker, FinalizeLinkError};
use anyhow::Result;
pub use confirmation::{Confirmation, ConfirmationType};
@ -14,7 +22,9 @@ pub use secrecy::{ExposeSecret, SecretString};
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, convert::TryInto, io::Read};
use steamapi::SteamApiClient;
pub use userlogin::{LoginError, UserLogin};
use token::Tokens;
pub use userlogin::{DeviceDetails, LoginError, UserLogin};
#[macro_use]
extern crate lazy_static;
#[macro_use]
@ -22,20 +32,15 @@ extern crate anyhow;
#[macro_use]
extern crate maplit;
mod accountlinker;
pub mod accountlinker;
mod api_responses;
mod confirmation;
pub mod protobufs;
mod secret_string;
pub mod steamapi;
pub mod token;
mod userlogin;
// const STEAMAPI_BASE: String = "https://api.steampowered.com";
// const COMMUNITY_BASE: String = "https://steamcommunity.com";
// const MOBILEAUTH_BASE: String = STEAMAPI_BASE + "/IMobileAuthService/%s/v0001";
// static MOBILEAUTH_GETWGTOKEN: String = MOBILEAUTH_BASE.Replace("%s", "GetWGToken");
// const TWO_FACTOR_BASE: String = STEAMAPI_BASE + "/ITwoFactorService/%s/v0001";
// static TWO_FACTOR_TIME_QUERY: String = TWO_FACTOR_BASE.Replace("%s", "QueryTime");
pub mod transport;
pub mod userlogin;
extern crate base64;
extern crate cookie;
@ -44,6 +49,7 @@ extern crate hmacsha1;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SteamGuardAccount {
pub account_name: String,
pub steam_id: u64,
pub serial_number: String,
#[serde(with = "secret_string")]
pub revocation_code: SecretString,
@ -51,15 +57,12 @@ pub struct SteamGuardAccount {
pub token_gid: String,
#[serde(with = "secret_string")]
pub identity_secret: SecretString,
pub server_time: u64,
#[serde(with = "secret_string")]
pub uri: SecretString,
pub fully_enrolled: bool,
pub device_id: String,
#[serde(with = "secret_string")]
pub secret_1: SecretString,
#[serde(default, rename = "Session")]
pub session: Option<secrecy::Secret<steamapi::Session>>,
pub tokens: Option<Tokens>,
}
fn build_time_bytes(time: u64) -> [u8; 8] {
@ -80,17 +83,16 @@ impl SteamGuardAccount {
pub fn new() -> Self {
return SteamGuardAccount {
account_name: String::from(""),
steam_id: 0,
serial_number: String::from(""),
revocation_code: String::from("").into(),
shared_secret: TwoFactorSecret::new(),
token_gid: String::from(""),
identity_secret: String::from("").into(),
server_time: 0,
uri: String::from("").into(),
fully_enrolled: false,
device_id: String::from(""),
secret_1: String::from("").into(),
session: Option::None,
tokens: None,
};
}
@ -101,8 +103,12 @@ impl SteamGuardAccount {
Ok(serde_json::from_reader(r)?)
}
pub fn set_session(&mut self, session: steamapi::Session) {
self.session = Some(session.into());
pub fn set_tokens(&mut self, tokens: Tokens) {
self.tokens = Some(tokens);
}
pub fn is_logged_in(&self) -> bool {
return self.tokens.is_some();
}
pub fn generate_code(&self, time: u64) -> String {
@ -110,10 +116,9 @@ impl SteamGuardAccount {
}
fn get_confirmation_query_params(&self, tag: &str, time: u64) -> HashMap<&str, String> {
let session = self.session.as_ref().unwrap().expose_secret();
let mut params = HashMap::new();
params.insert("p", self.device_id.clone());
params.insert("a", session.steam_id.to_string());
params.insert("a", self.steam_id.to_string());
params.insert(
"k",
generate_confirmation_hash_for_time(time, tag, &self.identity_secret.expose_secret()),
@ -127,16 +132,21 @@ impl SteamGuardAccount {
fn build_cookie_jar(&self) -> reqwest::cookie::Jar {
let url = "https://steamcommunity.com".parse::<Url>().unwrap();
let cookies = reqwest::cookie::Jar::default();
let session = self.session.as_ref().unwrap().expose_secret();
// let session = self.session.as_ref().unwrap().expose_secret();
let tokens = self.tokens.as_ref().unwrap();
cookies.add_cookie_str("mobileClientVersion=0 (2.1.3)", &url);
cookies.add_cookie_str("mobileClient=android", &url);
cookies.add_cookie_str("Steam_Language=english", &url);
cookies.add_cookie_str("dob=", &url);
cookies.add_cookie_str(format!("sessionid={}", session.session_id).as_str(), &url);
cookies.add_cookie_str(format!("steamid={}", session.steam_id).as_str(), &url);
cookies.add_cookie_str(format!("steamLogin={}", session.steam_login).as_str(), &url);
// cookies.add_cookie_str(format!("sessionid={}", session.session_id).as_str(), &url);
cookies.add_cookie_str(format!("steamid={}", self.steam_id).as_str(), &url);
cookies.add_cookie_str(
format!("steamLoginSecure={}", session.steam_login_secure).as_str(),
format!(
"steamLoginSecure={}||{}",
self.steam_id,
tokens.access_token().expose_secret()
)
.as_str(),
&url,
);
return cookies;
@ -153,7 +163,7 @@ impl SteamGuardAccount {
let time = steamapi::get_server_time()?.server_time;
let resp = client
.get("https://steamcommunity.com/mobileconf/conf".parse::<Url>().unwrap())
.get("https://steamcommunity.com/mobileconf/getlist".parse::<Url>().unwrap())
.header("X-Requested-With", "com.valvesoftware.android.steam.community")
.header(USER_AGENT, "Mozilla/5.0 (Linux; U; Android 4.1.1; en-us; Google Nexus 4 - 4.1.1 - API 16 - 768x1280 Build/JRO03S) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30")
.header(COOKIE, cookies.cookies(&url).unwrap())
@ -164,7 +174,10 @@ impl SteamGuardAccount {
let text = resp.text().unwrap();
trace!("text: {:?}", text);
trace!("{}", text);
return parse_confirmations(text);
let body: ConfirmationListResponse = serde_json::from_str(text.as_str())?;
ensure!(body.success);
Ok(body.conf)
}
/// Respond to a confirmation.
@ -184,12 +197,7 @@ impl SteamGuardAccount {
let mut query_params = self.get_confirmation_query_params("conf", time);
query_params.insert("op", operation);
query_params.insert("cid", conf.id.to_string());
query_params.insert("ck", conf.key.to_string());
#[derive(Debug, Clone, Copy, Deserialize)]
struct SendConfirmationResponse {
pub success: bool,
}
query_params.insert("ck", conf.nonce.to_string());
let resp = client.get("https://steamcommunity.com/mobileconf/ajaxop".parse::<Url>().unwrap())
.header("X-Requested-With", "com.valvesoftware.android.steam.community")
@ -260,52 +268,21 @@ impl SteamGuardAccount {
matches!(revocation_code, Some(_)) || !self.revocation_code.expose_secret().is_empty(),
"Revocation code not provided."
);
let client: SteamApiClient = SteamApiClient::new(self.session.clone());
let resp = client.remove_authenticator(
revocation_code.unwrap_or(self.revocation_code.expose_secret().to_owned()),
)?;
Ok(resp.success)
}
}
fn parse_confirmations(text: String) -> anyhow::Result<Vec<Confirmation>> {
// possible errors:
//
// Invalid authenticator:
// <div>Invalid authenticator</div>
// <div>It looks like your Steam Guard Mobile Authenticator is providing incorrect Steam Guard codes. This could be caused by an inaccurate clock or bad timezone settings on your device. If your time settings are correct, it could be that a different device has been set up to provide the Steam Guard codes for your account, which means the authenticator on this device is no longer valid.</div>
//
// <div>Nothing to confirm</div>
let fragment = Html::parse_fragment(&text);
let selector = Selector::parse(".mobileconf_list_entry").unwrap();
let desc_selector = Selector::parse(".mobileconf_list_entry_description").unwrap();
let mut confirmations = vec![];
for elem in fragment.select(&selector) {
let desc: String = elem
.select(&desc_selector)
.next()
.unwrap()
.text()
.map(|t| t.trim())
.filter(|t| t.len() > 0)
.collect::<Vec<_>>()
.join(" ");
let conf = Confirmation {
id: elem.value().attr("data-confid").unwrap().parse()?,
key: elem.value().attr("data-key").unwrap().parse()?,
conf_type: elem
.value()
.attr("data-type")
.unwrap()
.try_into()
.unwrap_or(ConfirmationType::Unknown),
creator: elem.value().attr("data-creator").unwrap().parse()?,
description: desc,
let Some(tokens) = &self.tokens else {
return Err(anyhow!("Tokens not set, login required"));
};
confirmations.push(conf);
let mut client = TwoFactorClient::new(WebApiTransport::new());
let mut req = CTwoFactor_RemoveAuthenticator_Request::new();
req.set_revocation_code(
revocation_code.unwrap_or(self.revocation_code.expose_secret().to_owned()),
);
let resp = client.remove_authenticator(req, tokens.access_token())?;
if resp.result != EResult::OK {
Err(anyhow!("Failed to remove authenticator: {:?}", resp.result))
} else {
Ok(true)
}
}
return Ok(confirmations);
}
#[cfg(test)]
@ -323,78 +300,4 @@ mod tests {
String::from("NaL8EIMhfy/7vBounJ0CvpKbrPk=")
);
}
#[test]
fn test_parse_multiple_confirmations() {
let text = include_str!("fixtures/confirmations/multiple-confirmations.html");
let confirmations = parse_confirmations(text.into()).unwrap();
assert_eq!(confirmations.len(), 5);
assert_eq!(
confirmations[0],
Confirmation {
id: 9890792058,
key: 15509106087034649470,
conf_type: ConfirmationType::MarketSell,
creator: 3392884950693131245,
description: "Sell - Summer 2021 - Horror $0.05 ($0.03) 2 minutes ago".into(),
}
);
assert_eq!(
confirmations[1],
Confirmation {
id: 9890791666,
key: 2661901169510258722,
conf_type: ConfirmationType::MarketSell,
creator: 3392884950693130525,
description: "Sell - Summer 2021 - Horror $0.05 ($0.03) 2 minutes ago".into(),
}
);
assert_eq!(
confirmations[2],
Confirmation {
id: 9890791241,
key: 15784514761287735229,
conf_type: ConfirmationType::MarketSell,
creator: 3392884950693129565,
description: "Sell - Summer 2021 - Horror $0.05 ($0.03) 2 minutes ago".into(),
}
);
assert_eq!(
confirmations[3],
Confirmation {
id: 9890790828,
key: 5049250785011653560,
conf_type: ConfirmationType::MarketSell,
creator: 3392884950693128685,
description: "Sell - Summer 2021 - Rogue $0.05 ($0.03) 2 minutes ago".into(),
}
);
assert_eq!(
confirmations[4],
Confirmation {
id: 9890790159,
key: 6133112455066694993,
conf_type: ConfirmationType::MarketSell,
creator: 3392884950693127345,
description: "Sell - Summer 2021 - Horror $0.05 ($0.03) 2 minutes ago".into(),
}
);
}
#[test]
fn test_parse_phone_number_change() {
let text = include_str!("fixtures/confirmations/phone-number-change.html");
let confirmations = parse_confirmations(text.into()).unwrap();
assert_eq!(confirmations.len(), 1);
assert_eq!(
confirmations[0],
Confirmation {
id: 9931444017,
key: 9746021299562127894,
conf_type: ConfirmationType::AccountRecovery,
creator: 2861625242839108895,
description: "Account recovery Just now".into(),
}
);
}
}

View file

@ -0,0 +1,26 @@
use std::fmt::Formatter;
use std::marker::PhantomData;
use protobuf::EnumFull;
use protobuf::EnumOrUnknown;
use protobuf::MessageField;
use serde::{Deserialize, Serialize};
include!(concat!(env!("OUT_DIR"), "/protobufs/mod.rs"));
#[cfg(test)]
mod parse_tests {
use protobuf::Message;
use super::steammessages_auth_steamclient::CAuthentication_GetPasswordRSAPublicKey_Request;
#[test]
fn test_build_protobuf() {
let mut req = CAuthentication_GetPasswordRSAPublicKey_Request::new();
req.set_account_name("hydrastar2".to_owned());
let bytes = req.write_to_bytes().unwrap();
let s = base64::encode_config(bytes, base64::URL_SAFE);
assert_eq!(s, "CgpoeWRyYXN0YXIy");
}
}

View file

@ -1,4 +1,7 @@
use crate::api_responses::*;
pub mod authentication;
pub mod twofactor;
use crate::{api_responses::*, token::Jwt};
use log::*;
use reqwest::{
blocking::RequestBuilder,
@ -475,3 +478,354 @@ impl SteamApiClient {
return Ok(resp.response);
}
}
pub trait BuildableRequest {
fn method() -> reqwest::Method;
fn requires_access_token() -> bool;
}
#[derive(Debug, Clone)]
pub struct ApiRequest<'a, T> {
api_interface: String,
api_method: String,
api_version: u32,
access_token: Option<&'a Jwt>,
request_data: T,
}
impl<'a, T: BuildableRequest> ApiRequest<'a, T> {
pub fn new(
api_interface: impl Into<String>,
api_method: impl Into<String>,
api_version: u32,
request_data: T,
) -> Self {
Self {
api_interface: api_interface.into(),
api_method: api_method.into(),
api_version,
access_token: None,
request_data,
}
}
pub fn with_access_token(mut self, access_token: &'a Jwt) -> Self {
self.access_token = Some(access_token);
self
}
pub fn access_token(&self) -> Option<&Jwt> {
self.access_token
}
pub(crate) fn build_url(&self) -> String {
format!(
"{}/I{}Service/{}/v{}",
STEAM_API_BASE.to_string(),
self.api_interface,
self.api_method,
self.api_version
)
}
pub(crate) fn request_data(&self) -> &T {
&self.request_data
}
}
#[derive(Debug, Clone)]
pub struct ApiResponse<T> {
pub(crate) result: EResult,
pub(crate) error_message: Option<String>,
pub(crate) response_data: T,
}
impl<T> ApiResponse<T> {
pub fn result(&self) -> EResult {
self.result
}
pub(crate) fn with_error_message(mut self, error_message: Option<String>) -> Self {
self.error_message = error_message;
self
}
pub fn error_message(&self) -> Option<&String> {
self.error_message.as_ref()
}
pub fn response_data(&self) -> &T {
&self.response_data
}
pub fn into_response_data(self) -> T {
self.response_data
}
}
// TODO: generate from protobufs
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
pub enum EResult {
Invalid = 0,
OK = 1,
Fail = 2,
NoConnection = 3,
InvalidPassword = 5,
LoggedInElsewhere = 6,
InvalidProtocolVer = 7,
InvalidParam = 8,
FileNotFound = 9,
Busy = 10,
InvalidState = 11,
InvalidName = 12,
InvalidEmail = 13,
DuplicateName = 14,
AccessDenied = 15,
Timeout = 16,
Banned = 17,
AccountNotFound = 18,
InvalidSteamID = 19,
ServiceUnavailable = 20,
NotLoggedOn = 21,
Pending = 22,
EncryptionFailure = 23,
InsufficientPrivilege = 24,
LimitExceeded = 25,
Revoked = 26,
Expired = 27,
AlreadyRedeemed = 28,
DuplicateRequest = 29,
AlreadyOwned = 30,
IPNotFound = 31,
PersistFailed = 32,
LockingFailed = 33,
LogonSessionReplaced = 34,
ConnectFailed = 35,
HandshakeFailed = 36,
IOFailure = 37,
RemoteDisconnect = 38,
ShoppingCartNotFound = 39,
Blocked = 40,
Ignored = 41,
NoMatch = 42,
AccountDisabled = 43,
ServiceReadOnly = 44,
AccountNotFeatured = 45,
AdministratorOK = 46,
ContentVersion = 47,
TryAnotherCM = 48,
PasswordRequiredToKickSession = 49,
AlreadyLoggedInElsewhere = 50,
Suspended = 51,
Cancelled = 52,
DataCorruption = 53,
DiskFull = 54,
RemoteCallFailed = 55,
PasswordNotSetOrUnset = 56,
ExternalAccountUnlinked = 57,
PSNTicketInvalid = 58,
ExternalAccountAlreadyLinked = 59,
RemoteFileConflict = 60,
IllegalPassword = 61,
SameAsPreviousValue = 62,
AccountLogonDenied = 63,
CannotUseOldPassword = 64,
InvalidLoginAuthCode = 65,
AccountLogonDeniedNoMailSent = 66,
HardwareNotCapableOfIPT = 67,
IPTInitError = 68,
ParentalControlRestricted = 69,
FacebookQueryError = 70,
ExpiredLoginAuthCode = 71,
IPLoginRestrictionFailed = 72,
AccountLocked = 73,
AccountLogonDeniedVerifiedEmailRequired = 74,
NoMatchingURL = 75,
BadResponse = 76,
RequirePasswordReEntry = 77,
ValueOutOfRange = 78,
UnexpectedError = 79,
Disabled = 80,
InvalidCEGSubmission = 81,
RestrictedDevice = 82,
RegionLocked = 83,
RateLimitExceeded = 84,
AccountLoginDeniedNeedTwoFactor = 85,
ItemOrEntryHasBeenDeleted = 86,
AccountLoginDeniedThrottle = 87,
TwoFactorCodeMismatch = 88,
TwoFactorActivationCodeMismatch = 89,
AccountAssociatedToMultipleAccounts = 90,
NotModified = 91,
NoMobileDeviceAvailable = 92,
TimeNotSynced = 93,
SMSCodeFailed = 94,
AccountLimitExceeded = 95,
AccountActivityLimitExceeded = 96,
PhoneActivityLimitExceeded = 97,
RefundToWallet = 98,
EmailSendFailure = 99,
NotSettled = 100,
NeedCaptcha = 101,
GSLTDenied = 102,
GSOwnerDenied = 103,
InvalidItemType = 104,
IPBanned = 105,
GSLTExpired = 106,
InsufficientFunds = 107,
TooManyPending = 108,
NoSiteLicensesFound = 109,
WGNetworkSendExceeded = 110,
AccountNotFriends = 111,
LimitedUserAccount = 112,
CantRemoveItem = 113,
AccountDeleted = 114,
ExistingUserCancelledLicense = 115,
DeniedDueToCommunityCooldown = 116,
NoLauncherSpecified = 117,
MustAgreeToSSA = 118,
ClientNoLongerSupported = 119,
SteamRealmMismatch = 120,
InvalidSignature = 121,
ParseFailure = 122,
NoVerifiedPhone = 123,
InsufficientBattery = 124,
ChargerRequired = 125,
CachedCredentialInvalid = 126,
PhoneNumberIsVOIP = 127,
}
impl From<i32> for EResult {
fn from(value: i32) -> Self {
match value {
1 => EResult::OK,
2 => EResult::Fail,
3 => EResult::NoConnection,
5 => EResult::InvalidPassword,
6 => EResult::LoggedInElsewhere,
7 => EResult::InvalidProtocolVer,
8 => EResult::InvalidParam,
9 => EResult::FileNotFound,
10 => EResult::Busy,
11 => EResult::InvalidState,
12 => EResult::InvalidName,
13 => EResult::InvalidEmail,
14 => EResult::DuplicateName,
15 => EResult::AccessDenied,
16 => EResult::Timeout,
17 => EResult::Banned,
18 => EResult::AccountNotFound,
19 => EResult::InvalidSteamID,
20 => EResult::ServiceUnavailable,
21 => EResult::NotLoggedOn,
22 => EResult::Pending,
23 => EResult::EncryptionFailure,
24 => EResult::InsufficientPrivilege,
25 => EResult::LimitExceeded,
26 => EResult::Revoked,
27 => EResult::Expired,
28 => EResult::AlreadyRedeemed,
29 => EResult::DuplicateRequest,
30 => EResult::AlreadyOwned,
31 => EResult::IPNotFound,
32 => EResult::PersistFailed,
33 => EResult::LockingFailed,
34 => EResult::LogonSessionReplaced,
35 => EResult::ConnectFailed,
36 => EResult::HandshakeFailed,
37 => EResult::IOFailure,
38 => EResult::RemoteDisconnect,
39 => EResult::ShoppingCartNotFound,
40 => EResult::Blocked,
41 => EResult::Ignored,
42 => EResult::NoMatch,
43 => EResult::AccountDisabled,
44 => EResult::ServiceReadOnly,
45 => EResult::AccountNotFeatured,
46 => EResult::AdministratorOK,
47 => EResult::ContentVersion,
48 => EResult::TryAnotherCM,
49 => EResult::PasswordRequiredToKickSession,
50 => EResult::AlreadyLoggedInElsewhere,
51 => EResult::Suspended,
52 => EResult::Cancelled,
53 => EResult::DataCorruption,
54 => EResult::DiskFull,
55 => EResult::RemoteCallFailed,
56 => EResult::PasswordNotSetOrUnset,
57 => EResult::ExternalAccountUnlinked,
58 => EResult::PSNTicketInvalid,
59 => EResult::ExternalAccountAlreadyLinked,
60 => EResult::RemoteFileConflict,
61 => EResult::IllegalPassword,
62 => EResult::SameAsPreviousValue,
63 => EResult::AccountLogonDenied,
64 => EResult::CannotUseOldPassword,
65 => EResult::InvalidLoginAuthCode,
66 => EResult::AccountLogonDeniedNoMailSent,
67 => EResult::HardwareNotCapableOfIPT,
68 => EResult::IPTInitError,
69 => EResult::ParentalControlRestricted,
70 => EResult::FacebookQueryError,
71 => EResult::ExpiredLoginAuthCode,
72 => EResult::IPLoginRestrictionFailed,
73 => EResult::AccountLocked,
74 => EResult::AccountLogonDeniedVerifiedEmailRequired,
75 => EResult::NoMatchingURL,
76 => EResult::BadResponse,
77 => EResult::RequirePasswordReEntry,
78 => EResult::ValueOutOfRange,
79 => EResult::UnexpectedError,
80 => EResult::Disabled,
81 => EResult::InvalidCEGSubmission,
82 => EResult::RestrictedDevice,
83 => EResult::RegionLocked,
84 => EResult::RateLimitExceeded,
85 => EResult::AccountLoginDeniedNeedTwoFactor,
86 => EResult::ItemOrEntryHasBeenDeleted,
87 => EResult::AccountLoginDeniedThrottle,
88 => EResult::TwoFactorCodeMismatch,
89 => EResult::TwoFactorActivationCodeMismatch,
90 => EResult::AccountAssociatedToMultipleAccounts,
91 => EResult::NotModified,
92 => EResult::NoMobileDeviceAvailable,
93 => EResult::TimeNotSynced,
94 => EResult::SMSCodeFailed,
95 => EResult::AccountLimitExceeded,
96 => EResult::AccountActivityLimitExceeded,
97 => EResult::PhoneActivityLimitExceeded,
98 => EResult::RefundToWallet,
99 => EResult::EmailSendFailure,
100 => EResult::NotSettled,
101 => EResult::NeedCaptcha,
102 => EResult::GSLTDenied,
103 => EResult::GSOwnerDenied,
104 => EResult::InvalidItemType,
105 => EResult::IPBanned,
106 => EResult::GSLTExpired,
107 => EResult::InsufficientFunds,
108 => EResult::TooManyPending,
109 => EResult::NoSiteLicensesFound,
110 => EResult::WGNetworkSendExceeded,
111 => EResult::AccountNotFriends,
112 => EResult::LimitedUserAccount,
113 => EResult::CantRemoveItem,
114 => EResult::AccountDeleted,
115 => EResult::ExistingUserCancelledLicense,
116 => EResult::DeniedDueToCommunityCooldown,
117 => EResult::NoLauncherSpecified,
118 => EResult::MustAgreeToSSA,
119 => EResult::ClientNoLongerSupported,
120 => EResult::SteamRealmMismatch,
121 => EResult::InvalidSignature,
122 => EResult::ParseFailure,
123 => EResult::NoVerifiedPhone,
124 => EResult::InsufficientBattery,
125 => EResult::ChargerRequired,
126 => EResult::CachedCredentialInvalid,
127 => EResult::PhoneNumberIsVOIP,
_ => EResult::Invalid,
}
}
}

View file

@ -0,0 +1,260 @@
use crate::{
protobufs::{
custom::CAuthentication_BeginAuthSessionViaCredentials_Request_BinaryGuardData,
steammessages_auth_steamclient::{
CAuthenticationSupport_RevokeToken_Request,
CAuthenticationSupport_RevokeToken_Response,
CAuthentication_AccessToken_GenerateForApp_Request,
CAuthentication_AccessToken_GenerateForApp_Response,
CAuthentication_BeginAuthSessionViaCredentials_Request,
CAuthentication_BeginAuthSessionViaCredentials_Response,
CAuthentication_BeginAuthSessionViaQR_Request,
CAuthentication_BeginAuthSessionViaQR_Response,
CAuthentication_GetAuthSessionInfo_Request,
CAuthentication_GetPasswordRSAPublicKey_Request,
CAuthentication_GetPasswordRSAPublicKey_Response,
CAuthentication_MigrateMobileSession_Request,
CAuthentication_MigrateMobileSession_Response,
CAuthentication_PollAuthSessionStatus_Request,
CAuthentication_PollAuthSessionStatus_Response,
CAuthentication_RefreshToken_Revoke_Request,
CAuthentication_RefreshToken_Revoke_Response,
CAuthentication_UpdateAuthSessionWithMobileConfirmation_Request,
CAuthentication_UpdateAuthSessionWithMobileConfirmation_Response,
CAuthentication_UpdateAuthSessionWithSteamGuardCode_Request,
CAuthentication_UpdateAuthSessionWithSteamGuardCode_Response, EAuthSessionGuardType,
},
},
token::Jwt,
transport::Transport,
};
use super::{ApiRequest, ApiResponse, BuildableRequest};
#[derive(Debug)]
pub struct AuthenticationClient<T>
where
T: Transport,
{
transport: T,
}
impl<T> AuthenticationClient<T>
where
T: Transport,
{
#[must_use]
pub fn new(transport: T) -> Self {
Self { transport }
}
pub fn begin_auth_session_via_credentials(
&mut self,
req: CAuthentication_BeginAuthSessionViaCredentials_Request_BinaryGuardData,
) -> anyhow::Result<ApiResponse<CAuthentication_BeginAuthSessionViaCredentials_Response>> {
let req = ApiRequest::new(
"Authentication",
"BeginAuthSessionViaCredentials",
1u32,
req,
);
let resp = self.transport.send_request::<
CAuthentication_BeginAuthSessionViaCredentials_Request_BinaryGuardData,
CAuthentication_BeginAuthSessionViaCredentials_Response>(req)?;
Ok(resp)
}
pub fn begin_auth_session_via_qr(
&mut self,
req: CAuthentication_BeginAuthSessionViaQR_Request,
) -> anyhow::Result<ApiResponse<CAuthentication_BeginAuthSessionViaQR_Response>> {
let req = ApiRequest::new("Authentication", "BeginAuthSessionViaQR", 1u32, req);
let resp = self
.transport
.send_request::<CAuthentication_BeginAuthSessionViaQR_Request, CAuthentication_BeginAuthSessionViaQR_Response>(
req,
)?;
Ok(resp)
}
pub fn generate_access_token(
&mut self,
req: CAuthentication_AccessToken_GenerateForApp_Request,
access_token: &Jwt,
) -> anyhow::Result<ApiResponse<CAuthentication_AccessToken_GenerateForApp_Response>> {
let req = ApiRequest::new("Authentication", "GenerateAccessTokenForApp", 1u32, req)
.with_access_token(access_token);
let resp = self
.transport
.send_request::<CAuthentication_AccessToken_GenerateForApp_Request, CAuthentication_AccessToken_GenerateForApp_Response>(
req,
)?;
Ok(resp)
}
pub fn fetch_rsa_key(
&mut self,
account_name: String,
) -> anyhow::Result<ApiResponse<CAuthentication_GetPasswordRSAPublicKey_Response>> {
let mut inner = CAuthentication_GetPasswordRSAPublicKey_Request::new();
inner.set_account_name(account_name);
let req = ApiRequest::new("Authentication", "GetPasswordRSAPublicKey", 1u32, inner);
let resp = self
.transport
.send_request::<CAuthentication_GetPasswordRSAPublicKey_Request, CAuthentication_GetPasswordRSAPublicKey_Response>(
req,
)?;
return Ok(resp);
}
pub fn migrate_mobile_session(
&mut self,
req: CAuthentication_MigrateMobileSession_Request,
) -> anyhow::Result<ApiResponse<CAuthentication_MigrateMobileSession_Response>> {
let req = ApiRequest::new("Authentication", "MigrateMobileSession", 1u32, req);
let resp = self
.transport
.send_request::<CAuthentication_MigrateMobileSession_Request, CAuthentication_MigrateMobileSession_Response>(
req,
)?;
Ok(resp)
}
pub fn poll_auth_session(
&mut self,
req: CAuthentication_PollAuthSessionStatus_Request,
) -> anyhow::Result<ApiResponse<CAuthentication_PollAuthSessionStatus_Response>> {
let req = ApiRequest::new("Authentication", "PollAuthSessionStatus", 1u32, req);
let resp = self
.transport
.send_request::<CAuthentication_PollAuthSessionStatus_Request, CAuthentication_PollAuthSessionStatus_Response>(
req,
)?;
Ok(resp)
}
pub fn revoke_refresh_token(
&mut self,
req: CAuthentication_RefreshToken_Revoke_Request,
) -> anyhow::Result<ApiResponse<CAuthentication_RefreshToken_Revoke_Response>> {
let req = ApiRequest::new("Authentication", "RevokeRefreshToken", 1u32, req);
let resp = self
.transport
.send_request::<CAuthentication_RefreshToken_Revoke_Request, CAuthentication_RefreshToken_Revoke_Response>(
req,
)?;
Ok(resp)
}
pub fn revoke_access_token(
&mut self,
req: CAuthenticationSupport_RevokeToken_Request,
) -> anyhow::Result<ApiResponse<CAuthenticationSupport_RevokeToken_Response>> {
let req = ApiRequest::new("Authentication", "RevokeToken", 1u32, req);
let resp = self
.transport
.send_request::<CAuthenticationSupport_RevokeToken_Request, CAuthenticationSupport_RevokeToken_Response>(
req,
)?;
Ok(resp)
}
pub fn update_session_with_mobile_confirmation(
&mut self,
req: CAuthentication_UpdateAuthSessionWithMobileConfirmation_Request,
) -> anyhow::Result<ApiResponse<CAuthentication_UpdateAuthSessionWithMobileConfirmation_Response>>
{
let req = ApiRequest::new(
"Authentication",
"UpdateAuthSessionWithMobileConfirmation",
1u32,
req,
);
let resp = self
.transport
.send_request::<CAuthentication_UpdateAuthSessionWithMobileConfirmation_Request, CAuthentication_UpdateAuthSessionWithMobileConfirmation_Response>(
req,
)?;
Ok(resp)
}
pub fn update_session_with_steam_guard_code(
&mut self,
req: CAuthentication_UpdateAuthSessionWithSteamGuardCode_Request,
) -> anyhow::Result<ApiResponse<CAuthentication_UpdateAuthSessionWithSteamGuardCode_Response>> {
let req = ApiRequest::new(
"Authentication",
"UpdateAuthSessionWithSteamGuardCode",
1u32,
req,
);
let resp = self
.transport
.send_request::<CAuthentication_UpdateAuthSessionWithSteamGuardCode_Request, CAuthentication_UpdateAuthSessionWithSteamGuardCode_Response>(
req,
)?;
Ok(resp)
}
}
macro_rules! impl_buildable_req {
($type:ty, $needs_auth:literal) => {
impl BuildableRequest for $type {
fn method() -> reqwest::Method {
reqwest::Method::POST
}
fn requires_access_token() -> bool {
$needs_auth
}
}
};
}
impl_buildable_req!(
CAuthentication_BeginAuthSessionViaCredentials_Request,
false
);
impl_buildable_req!(
CAuthentication_BeginAuthSessionViaCredentials_Request_BinaryGuardData,
false
);
impl_buildable_req!(CAuthentication_BeginAuthSessionViaQR_Request, false);
impl_buildable_req!(CAuthentication_AccessToken_GenerateForApp_Request, true);
impl BuildableRequest for CAuthentication_GetPasswordRSAPublicKey_Request {
fn method() -> reqwest::Method {
reqwest::Method::GET
}
fn requires_access_token() -> bool {
false
}
}
impl_buildable_req!(CAuthentication_GetAuthSessionInfo_Request, true);
impl_buildable_req!(CAuthentication_MigrateMobileSession_Request, false);
impl_buildable_req!(CAuthentication_PollAuthSessionStatus_Request, false);
impl_buildable_req!(CAuthentication_RefreshToken_Revoke_Request, true);
impl_buildable_req!(CAuthenticationSupport_RevokeToken_Request, true);
impl_buildable_req!(
CAuthentication_UpdateAuthSessionWithMobileConfirmation_Request,
false
);
impl_buildable_req!(
CAuthentication_UpdateAuthSessionWithSteamGuardCode_Request,
false
);
impl EAuthSessionGuardType {
pub fn requires_prompt(self) -> bool {
match self {
EAuthSessionGuardType::k_EAuthSessionGuardType_DeviceCode => true,
EAuthSessionGuardType::k_EAuthSessionGuardType_EmailCode => true,
EAuthSessionGuardType::k_EAuthSessionGuardType_DeviceConfirmation => false,
EAuthSessionGuardType::k_EAuthSessionGuardType_EmailConfirmation => false,
_ => false,
}
}
}

View file

@ -0,0 +1,111 @@
use crate::token::Jwt;
use crate::transport::Transport;
use super::{ApiRequest, ApiResponse, BuildableRequest};
use crate::protobufs::custom::CTwoFactor_Time_Request;
use crate::protobufs::service_twofactor::*;
#[derive(Debug)]
pub struct TwoFactorClient<T>
where
T: Transport,
{
transport: T,
}
impl<T> TwoFactorClient<T>
where
T: Transport,
{
#[must_use]
pub fn new(transport: T) -> Self {
Self { transport }
}
pub fn add_authenticator(
&mut self,
req: CTwoFactor_AddAuthenticator_Request,
access_token: &Jwt,
) -> anyhow::Result<ApiResponse<CTwoFactor_AddAuthenticator_Response>> {
let req = ApiRequest::new("TwoFactor", "AddAuthenticator", 1, req)
.with_access_token(access_token);
let resp = self
.transport
.send_request::<CTwoFactor_AddAuthenticator_Request, CTwoFactor_AddAuthenticator_Response>(
req,
)?;
Ok(resp)
}
pub fn finalize_authenticator(
&mut self,
req: CTwoFactor_FinalizeAddAuthenticator_Request,
access_token: &Jwt,
) -> anyhow::Result<ApiResponse<CTwoFactor_FinalizeAddAuthenticator_Response>> {
let req = ApiRequest::new("TwoFactor", "FinalizeAddAuthenticator", 1, req)
.with_access_token(access_token);
let resp = self
.transport
.send_request::<CTwoFactor_FinalizeAddAuthenticator_Request, CTwoFactor_FinalizeAddAuthenticator_Response>(
req,
)?;
Ok(resp)
}
pub fn remove_authenticator(
&mut self,
req: CTwoFactor_RemoveAuthenticator_Request,
access_token: &Jwt,
) -> anyhow::Result<ApiResponse<CTwoFactor_RemoveAuthenticator_Response>> {
let req = ApiRequest::new("TwoFactor", "RemoveAuthenticator", 1, req)
.with_access_token(access_token);
let resp = self
.transport
.send_request::<CTwoFactor_RemoveAuthenticator_Request, CTwoFactor_RemoveAuthenticator_Response>(
req,
)?;
Ok(resp)
}
pub fn query_status(
&mut self,
req: CTwoFactor_Status_Request,
access_token: &Jwt,
) -> anyhow::Result<ApiResponse<CTwoFactor_Status_Response>> {
let req =
ApiRequest::new("TwoFactor", "QueryStatus", 1, req).with_access_token(access_token);
let resp = self
.transport
.send_request::<CTwoFactor_Status_Request, CTwoFactor_Status_Response>(req)?;
Ok(resp)
}
pub fn query_time(&mut self) -> anyhow::Result<ApiResponse<CTwoFactor_Time_Response>> {
let req = ApiRequest::new("TwoFactor", "QueryTime", 1, CTwoFactor_Time_Request::new());
let resp = self
.transport
.send_request::<CTwoFactor_Time_Request, CTwoFactor_Time_Response>(req)?;
Ok(resp)
}
}
macro_rules! impl_buildable_req {
($type:ty, $needs_auth:literal) => {
impl BuildableRequest for $type {
fn method() -> reqwest::Method {
reqwest::Method::POST
}
fn requires_access_token() -> bool {
$needs_auth
}
}
};
}
impl_buildable_req!(CTwoFactor_AddAuthenticator_Request, true);
impl_buildable_req!(CTwoFactor_FinalizeAddAuthenticator_Request, true);
impl_buildable_req!(CTwoFactor_RemoveAuthenticator_Request, true);
impl_buildable_req!(CTwoFactor_Status_Request, true);
impl_buildable_req!(CTwoFactor_Time_Request, false);

View file

@ -1,6 +1,8 @@
use secrecy::{ExposeSecret, Secret};
use regex::bytes;
use secrecy::{ExposeSecret, Secret, SecretString};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::convert::TryInto;
use zeroize::Zeroize;
#[derive(Debug, Clone)]
pub struct TwoFactorSecret(Secret<[u8; 20]>);
@ -11,6 +13,11 @@ impl TwoFactorSecret {
return Self([0u8; 20].into());
}
pub fn from_bytes(bytes: Vec<u8>) -> Self {
let bytes: [u8; 20] = bytes[..].try_into().unwrap();
return Self(bytes.into());
}
pub fn parse_shared_secret(secret: String) -> anyhow::Result<Self> {
ensure!(secret.len() != 0, "unable to parse empty shared secret");
let result: [u8; 20] = base64::decode(secret)?.try_into().unwrap();
@ -74,11 +81,91 @@ fn build_time_bytes(time: u64) -> [u8; 8] {
return time.to_be_bytes();
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Tokens {
access_token: Jwt,
refresh_token: Jwt,
}
impl Tokens {
pub fn new(access_token: impl Into<Jwt>, refresh_token: impl Into<Jwt>) -> Self {
Self {
access_token: access_token.into(),
refresh_token: refresh_token.into(),
}
}
pub fn access_token(&self) -> &Jwt {
&self.access_token
}
pub fn refresh_token(&self) -> &Jwt {
&self.refresh_token
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct Jwt(SecretString);
impl Serialize for Jwt {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&self.0.expose_secret())
}
}
impl Jwt {
pub fn decode(&self) -> anyhow::Result<SteamJwtData> {
decode_jwt(self.0.expose_secret())
}
pub fn expose_secret(&self) -> &str {
self.0.expose_secret()
}
}
impl From<String> for Jwt {
fn from(s: String) -> Self {
Self(SecretString::new(s))
}
}
fn decode_jwt(jwt: &String) -> anyhow::Result<SteamJwtData> {
let parts = jwt.split(".").collect::<Vec<&str>>();
ensure!(parts.len() == 3, "Invalid JWT");
let data = parts[1];
let bytes = base64::decode_config(data, base64::URL_SAFE)?;
let json = String::from_utf8(bytes)?;
let jwt_data: SteamJwtData = serde_json::from_str(&json)?;
Ok(jwt_data)
}
#[derive(Deserialize, Debug)]
pub struct SteamJwtData {
pub exp: u64,
pub iat: u64,
pub iss: String,
/// Audience
pub aud: Vec<String>,
/// Subject (steam id)
pub sub: String,
pub jti: String,
}
impl SteamJwtData {
pub fn steam_id(&self) -> u64 {
self.sub.parse::<u64>().unwrap()
}
}
mod tests {
use super::*;
#[test]
fn test_serialize() -> anyhow::Result<()> {
fn test_serialize_2fa_secret() -> anyhow::Result<()> {
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
struct FooBar {
secret: TwoFactorSecret,
@ -95,7 +182,7 @@ mod tests {
}
#[test]
fn test_deserialize() -> anyhow::Result<()> {
fn test_deserialize_2fa_secret() -> anyhow::Result<()> {
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
struct FooBar {
secret: TwoFactorSecret,
@ -111,7 +198,7 @@ mod tests {
}
#[test]
fn test_serialize_and_deserialize() -> anyhow::Result<()> {
fn test_serialize_and_deserialize_2fa_secret() -> anyhow::Result<()> {
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
struct FooBar {
secret: TwoFactorSecret,
@ -147,4 +234,17 @@ mod tests {
assert_eq!(code, "2F9J5");
return Ok(());
}
#[test]
fn test_decode_jwt() {
let sample: Jwt = "eyAidHlwIjogIkpXVCIsICJhbGciOiAiRWREU0EiIH0.eyAiaXNzIjogInN0ZWFtIiwgInN1YiI6ICI3NjU2MTE5OTE1NTcwNjg5MiIsICJhdWQiOiBbICJ3ZWIiLCAicmVuZXciLCAiZGVyaXZlIiBdLCAiZXhwIjogMTcwNTAxMTk1NSwgIm5iZiI6IDE2Nzg0NjQ4MzcsICJpYXQiOiAxNjg3MTA0ODM3LCAianRpIjogIjE4QzVfMjJCM0Y0MzFfQ0RGNkEiLCAib2F0IjogMTY4NzEwNDgzNywgInBlciI6IDEsICJpcF9zdWJqZWN0IjogIjY5LjEyMC4xMzYuMTI0IiwgImlwX2NvbmZpcm1lciI6ICI2OS4xMjAuMTM2LjEyNCIgfQ.7p5TPj9pGQbxIzWDDNCSP9OkKYSeDnWBE8E-M8hUrxOEPCW0XwrbDUrh199RzjPDw".to_owned().into();
let data = sample.decode().expect("Failed to decode JWT");
assert_eq!(data.exp, 1705011955);
assert_eq!(data.iat, 1687104837);
assert_eq!(data.iss, "steam");
assert_eq!(data.aud, vec!["web", "renew", "derive"]);
assert_eq!(data.sub, "76561199155706892");
assert_eq!(data.jti, "18C5_22B3F431_CDF6A");
}
}

View file

@ -0,0 +1,16 @@
pub mod webapi;
use protobuf::MessageFull;
use serde::{Deserialize, Serialize};
pub use webapi::WebApiTransport;
use crate::steamapi::{ApiRequest, ApiResponse, BuildableRequest};
pub trait Transport {
fn send_request<Req: BuildableRequest + MessageFull, Res: MessageFull>(
&mut self,
req: ApiRequest<Req>,
) -> anyhow::Result<ApiResponse<Res>>;
fn close(&mut self);
}

View file

@ -0,0 +1,160 @@
use log::{debug, trace};
use protobuf::MessageFull;
use reqwest::{blocking::multipart::Form, Url};
use super::Transport;
use crate::steamapi::{ApiRequest, ApiResponse, BuildableRequest, EResult};
lazy_static! {
static ref STEAM_COOKIE_URL: Url = "https://steamcommunity.com".parse::<Url>().unwrap();
static ref STEAM_API_BASE: String = "https://api.steampowered.com".into();
}
#[derive(Debug)]
pub struct WebApiTransport {
client: reqwest::blocking::Client,
}
impl WebApiTransport {
pub fn new() -> WebApiTransport {
return WebApiTransport {
client: reqwest::blocking::Client::new(),
// client: reqwest::blocking::Client::builder()
// .danger_accept_invalid_certs(true)
// .proxy(reqwest::Proxy::all("http://localhost:8080").unwrap())
// .build()
// .unwrap(),
};
}
}
impl Transport for WebApiTransport {
fn send_request<Req: BuildableRequest + MessageFull, Res: MessageFull>(
&mut self,
apireq: ApiRequest<Req>,
) -> anyhow::Result<ApiResponse<Res>> {
// All the API endpoints accept 2 data formats: json and protobuf.
// Depending on the http method for the request, the data can go in 2 places:
// - GET: query string, with the key `input_protobuf_encoded` or `input_json`
// - POST: multipart form body, with the key `input_protobuf_encoded` or `input_json`, however url encoded form data seems to also be accepted
// input protobuf data is always encoded in base64
if Req::requires_access_token() && apireq.access_token().is_none() {
return Err(anyhow::anyhow!("Access token required for this request"));
}
let url = apireq.build_url();
debug!("HTTP Request: {} {}", Req::method(), url);
trace!("Request body: {:#?}", apireq.request_data());
let mut req = self.client.request(Req::method(), &url);
req = if Req::method() == reqwest::Method::GET {
let encoded = encode_msg(apireq.request_data(), base64::URL_SAFE)?;
let mut params = vec![("input_protobuf_encoded", encoded.as_str())];
if let Some(access_token) = apireq.access_token() {
params.push(("access_token", access_token.expose_secret()));
}
req.query(&params)
} else {
if let Some(access_token) = apireq.access_token() {
req = req.query(&[("access_token", access_token)]);
}
let encoded = encode_msg(apireq.request_data(), base64::STANDARD)?;
let form = Form::new().text("input_protobuf_encoded", encoded);
req.multipart(form)
};
let resp = req.send()?;
let status = resp.status();
debug!("Response HTTP status: {}", status);
let eresult = if let Some(eresult) = resp.headers().get("x-eresult") {
debug!("HTTP Header x-eresult: {}", eresult.to_str()?);
eresult.to_str()?.parse::<i32>()?.into()
} else {
EResult::Invalid
};
let error_msg = if let Some(error_message) = resp.headers().get("x-error_message") {
debug!("HTTP Header x-error_message: {}", error_message.to_str()?);
Some(error_message.to_str()?.to_owned())
} else {
None
};
let bytes = resp.bytes()?;
if !status.is_success() {
trace!("Response body (raw): {:?}", bytes);
}
let res = decode_msg::<Res>(bytes.as_ref())?;
trace!("Response body (decoded): {:#?}", res);
let api_resp = ApiResponse {
result: eresult,
error_message: error_msg,
response_data: res,
};
return Ok(api_resp);
}
fn close(&mut self) {}
}
fn encode_msg<T: MessageFull>(msg: &T, config: base64::Config) -> anyhow::Result<String> {
let bytes = msg.write_to_bytes()?;
let b64 = base64::encode_config(bytes, config);
Ok(b64)
}
fn decode_msg<T: MessageFull>(bytes: &[u8]) -> anyhow::Result<T> {
// let bytes = base64::decode_config(b64, base64::STANDARD)?;
let msg = T::parse_from_bytes(bytes.as_ref())?;
Ok(msg)
}
#[cfg(test)]
mod tests {
use crate::protobufs::steammessages_auth_steamclient::{
CAuthentication_BeginAuthSessionViaCredentials_Request,
CAuthentication_GetPasswordRSAPublicKey_Response,
CAuthentication_PollAuthSessionStatus_Response,
};
use super::*;
#[test]
fn test_parse_poll_response() {
let sample = b"GuUDZXlBaWRIbHdJam9nSWtwWFZDSXNJQ0poYkdjaU9pQWlSV1JFVTBFaUlIMC5leUFpYVhOeklqb2dJbk4wWldGdElpd2dJbk4xWWlJNklDSTNOalUyTVRFNU9URTFOVGN3TmpnNU1pSXNJQ0poZFdRaU9pQmJJQ0ozWldJaUxDQWljbVZ1WlhjaUxDQWlaR1Z5YVhabElpQmRMQ0FpWlhod0lqb2dNVGN3TlRBeE1UazFOU3dnSW01aVppSTZJREUyTnpnME5qUTRNemNzSUNKcFlYUWlPaUF4TmpnM01UQTBPRE0zTENBaWFuUnBJam9nSWpFNFF6VmZNakpDTTBZME16RmZRMFJHTmtFaUxDQWliMkYwSWpvZ01UWTROekV3TkRnek55d2dJbkJsY2lJNklERXNJQ0pwY0Y5emRXSnFaV04wSWpvZ0lqWTVMakV5TUM0eE16WXVNVEkwSWl3Z0ltbHdYMk52Ym1acGNtMWxjaUk2SUNJMk9TNHhNakF1TVRNMkxqRXlOQ0lnZlEuR3A1VFBqOXBHUWJ4SXpXREROQ1NQOU9rS1lTZXduV0JFOEUtY1ZxalFxcVQ1M0FzRTRya213OER5TThoVXJ4T0VQQ1dDWHdyYkRVcmgxOTlSempQRHci/gNleUFpZEhsd0lqb2dJa3BYVkNJc0lDSmhiR2NpT2lBaVJXUkVVMEVpSUgwLmV5QWlhWE56SWpvZ0luSTZNVGhETlY4eU1rSXpSalF6TVY5RFJFWTJRU0lzSUNKemRXSWlPaUFpTnpZMU5qRXhPVGt4TlRVM01EWTRPVElpTENBaVlYVmtJam9nV3lBaWQyVmlJaUJkTENBaVpYaHdJam9nTVRZNE56RTVNamM0T0N3Z0ltNWlaaUk2SURFMk56ZzBOalE0TXpjc0lDSnBZWFFpT2lBeE5qZzNNVEEwT0RNM0xDQWlhblJwSWpvZ0lqRXlSREZmTWpKQ00wVTROekZmT1RaRk5EQWlMQ0FpYjJGMElqb2dNVFk0TnpFd05EZ3pOeXdnSW5KMFgyVjRjQ0k2SURFM01EVXdNVEU1TlRVc0lDSndaWElpT2lBd0xDQWlhWEJmYzNWaWFtVmpkQ0k2SUNJMk9TNHhNakF1TVRNMkxqRXlOQ0lzSUNKcGNGOWpiMjVtYVhKdFpYSWlPaUFpTmprdU1USXdMakV6Tmk0eE1qUWlJSDAuMVNnUEotSVZuWEp6Nk9nSW1udUdOQ0hMbEJTcGdvc0Z0UkxoOV9iVVBHQ1RaMmFtRWY2ZTZVYkJzVWZ3bnlYbEdFdG5LSHhPemhibTdLNzBwVFhEQ0EoADIKaHlkcmFzdGFyMg==";
let bytes = base64::decode_config(sample, base64::STANDARD).unwrap();
let resp: CAuthentication_PollAuthSessionStatus_Response = decode_msg(&bytes).unwrap();
println!("{:#?}", resp);
}
#[test]
fn parse_get_public_rsa_response() {
let sample = b"CoAEYjYyMGI1ZWNhMWIxMjgyYjkxYzZkZmZkYWFhOWI0ODI0YjlhNmRiYmEyZDVmYjc0ODcxNDczZDc1MDYxNGEzNWM4ODQ3NDYzZTEyNjAwNTJmNzZlNTYxMDM5ODdlN2U3NGJkMWZjZGRjYWJhMDVmZGM5OTBjMWIyNmQ2ZDg5MGM2MTEzZmRkNTZmMmQ1YmZjNzU4ODhlMzZhNTM2NjM3N2IzZTE3ZTJiZWM5MjhlNGY4MmE1YzY0NGYxZTZlMTk3NzZkNjIzMDIxYjhmYTA0MGRjNWE5YjY0M2I0N2I5YmVhMjM2YmEyZjM4ODVjM2ZlNWVhNjMzZThlNjJjNGE1YTY4NjNmMzNiMzdlMTQ4M2MwZTUzZTg4ODIzMGFkNTVjNzg5ZmU4Y2NkMjVjNzdiMTkxOTg0ZThjN2JmNWYzNzY2MjI0OGI1NWVmOWM1OGY3NDM5YjA4ZjNhNWJiNzljNTc5ZDE5M2I3NzhmMzFiY2IwYTA3MmVhZWYxOGEyYjljZDY2M2VmYmY2YmRiZDU3MGEyMTNiOTIxNTc4ODk0MjJkMDY3ODFiNTVkY2VjYjQ4NjA4MjUyMmUzZWQyOWM4MjExYzQ5N2Q1YjNhYTk2OGM2MDY1YWFhZTNhNGVmYzZiMGJjNDYyMzMxNmVmYTUxN2JjNzRiZDYzODcxMWU4ZWYSBjAxMDAwMRiQn6Ly3wk=";
let bytes = base64::decode_config(sample, base64::STANDARD).unwrap();
let resp: CAuthentication_GetPasswordRSAPublicKey_Response = decode_msg(&bytes).unwrap();
println!("{:#?}", resp);
}
#[test]
fn test_decode_encode_roundtrip() {
let sample = b"EgpoeWRyYXN0YXIyGtgCRUxaNTBXdHM2Z0kxWlZaVjl6bzRJNFBEcEhTMGRZR3RSNzJPbytqZkR5QmRBUitrbnBUcUVGcGF4NDd1UVdqdUQ1R2hpRC9JanA2cEtGQzlrdUZDdzBFT0RMSFpINERZUG5hci9IMktOZGoxSFNjWEhyemZjNmk1OWpsRE5OTTI0RVllNUEyUjVSdzBoa2lodU14Z1A4NDJESFUxMkgwNWFyYmdRUWp3NFJmVHh6cDBQQlRjdTk4VUViUjJnak1RajlVK3RsYStPdTN6WTQ5K1BKc0szTkpMTVdxWm4vaFZ1dTR3NFprZGhXNVBqNWphb2Flb3J6MG8zbWIvUXo2M0NlNFdwWmUra1lFYUlSa29oUXBaZkliaW4rTWdQcVpNelg4cW4vNDcyNFp5N05mblpETlVBV3RoTkowTkUxSDVESXZ4N0IwRFJHZVBwdk5FbVdqWEJ3PT0g4MCW2tYBOAFCBk1vYmlsZUocCgpHYWxheHkgUzIyEAMYjPz/////////ASCQBA==";
let bytes = base64::decode_config(sample, base64::STANDARD).unwrap();
let decoded: CAuthentication_BeginAuthSessionViaCredentials_Request =
decode_msg(&bytes).expect("Failed to decode");
let encoded = encode_msg(&decoded, base64::STANDARD).expect("Failed to encode");
assert_eq!(encoded, String::from_utf8(sample.to_vec()).unwrap());
}
}

View file

@ -1,20 +1,50 @@
use crate::api_responses::AllowedConfirmation;
use crate::protobufs::custom::CAuthentication_BeginAuthSessionViaCredentials_Request_BinaryGuardData;
use crate::protobufs::enums::ESessionPersistence;
use crate::protobufs::steammessages_auth_steamclient::{
CAuthentication_AllowedConfirmation, CAuthentication_DeviceDetails,
CAuthentication_PollAuthSessionStatus_Request, CAuthentication_PollAuthSessionStatus_Response,
EAuthSessionGuardType,
};
use crate::steamapi::authentication::AuthenticationClient;
use crate::steamapi::{ApiRequest, ApiResponse, EResult};
use crate::token::Tokens;
use crate::transport::Transport;
use crate::{
api_responses::{LoginResponse, RsaResponse},
protobufs::steammessages_auth_steamclient::{
CAuthenticationSupport_RevokeToken_Request, CAuthenticationSupport_RevokeToken_Response,
CAuthentication_AccessToken_GenerateForApp_Request,
CAuthentication_AccessToken_GenerateForApp_Response,
CAuthentication_BeginAuthSessionViaCredentials_Request,
CAuthentication_BeginAuthSessionViaCredentials_Response,
CAuthentication_BeginAuthSessionViaQR_Request,
CAuthentication_BeginAuthSessionViaQR_Response,
CAuthentication_GetPasswordRSAPublicKey_Request,
CAuthentication_GetPasswordRSAPublicKey_Response,
CAuthentication_MigrateMobileSession_Request,
CAuthentication_MigrateMobileSession_Response, CAuthentication_RefreshToken_Revoke_Request,
CAuthentication_RefreshToken_Revoke_Response,
CAuthentication_UpdateAuthSessionWithMobileConfirmation_Request,
CAuthentication_UpdateAuthSessionWithMobileConfirmation_Response,
CAuthentication_UpdateAuthSessionWithSteamGuardCode_Request,
CAuthentication_UpdateAuthSessionWithSteamGuardCode_Response, EAuthTokenPlatformType,
},
steamapi::{Session, SteamApiClient},
transport::WebApiTransport,
};
use log::*;
use rsa::{PublicKey, RsaPublicKey};
use secrecy::ExposeSecret;
use std::time::{SystemTime, UNIX_EPOCH};
use serde::{Deserialize, Serialize};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
#[derive(Debug)]
pub enum LoginError {
BadRSA,
BadCredentials,
NeedCaptcha { captcha_gid: String },
Need2FA,
NeedEmail,
TooManyAttempts,
UnknownEResult(EResult),
AuthAlreadyStarted,
NetworkFailure(reqwest::Error),
OtherFailure(anyhow::Error),
}
@ -39,138 +69,221 @@ impl From<anyhow::Error> for LoginError {
}
}
impl From<EResult> for LoginError {
fn from(err: EResult) -> Self {
match err {
EResult::InvalidPassword => LoginError::BadCredentials,
EResult::RateLimitExceeded => LoginError::TooManyAttempts,
err => LoginError::UnknownEResult(err),
}
}
}
#[derive(Debug, Clone)]
pub struct BeginQrLoginResponse {
challenge_url: String,
confirmation_methonds: Vec<AllowedConfirmation>,
}
impl BeginQrLoginResponse {
pub fn challenge_url(&self) -> &String {
&self.challenge_url
}
pub fn confirmation_methods(&self) -> &Vec<AllowedConfirmation> {
&self.confirmation_methonds
}
}
/// Handles the user login flow.
#[derive(Debug)]
pub struct UserLogin {
pub username: String,
pub password: String,
pub captcha_required: bool,
pub captcha_gid: String,
pub captcha_text: String,
pub twofactor_code: String,
pub email_code: String,
pub steam_id: u64,
platform_type: EAuthTokenPlatformType,
client: AuthenticationClient<WebApiTransport>,
device_details: DeviceDetails,
client: SteamApiClient,
started_auth: Option<StartAuth>,
}
impl UserLogin {
pub fn new(username: String, password: String) -> UserLogin {
return UserLogin {
username,
password,
captcha_required: false,
captcha_gid: String::from("-1"),
captcha_text: String::from(""),
twofactor_code: String::from(""),
email_code: String::from(""),
steam_id: 0,
client: SteamApiClient::new(None),
pub fn new(platform_type: EAuthTokenPlatformType, device_details: DeviceDetails) -> Self {
return Self {
platform_type,
client: AuthenticationClient::new(WebApiTransport::new()),
device_details,
started_auth: None,
};
}
pub fn login(&mut self) -> anyhow::Result<Session, LoginError> {
trace!("UserLogin::login");
if self.captcha_required && self.captcha_text.len() == 0 {
return Err(LoginError::NeedCaptcha {
captcha_gid: self.captcha_gid.clone(),
});
pub fn begin_auth_via_credentials(
&mut self,
account_name: &String,
password: &String,
) -> anyhow::Result<Vec<AllowedConfirmation>, LoginError> {
if self.started_auth.is_some() {
return Err(LoginError::AuthAlreadyStarted);
}
trace!("UserLogin::begin_auth_via_credentials");
let rsa = self.client.fetch_rsa_key(account_name.clone())?;
let mut req = CAuthentication_BeginAuthSessionViaCredentials_Request_BinaryGuardData::new();
req.set_account_name(account_name.clone());
let rsa_resp = rsa.into_response_data();
req.set_encryption_timestamp(rsa_resp.timestamp());
let encrypted_password = encrypt_password(rsa_resp, &password);
req.set_encrypted_password(encrypted_password);
req.set_persistence(ESessionPersistence::k_ESessionPersistence_Persistent);
req.device_details = self.device_details.clone().into_message_field();
req.set_language(0); // english, probably
req.set_qos_level(2); // value from observed traffic
let resp = self.client.begin_auth_session_via_credentials(req)?;
if resp.result != EResult::OK {
return Err(resp.result.into());
}
if self.client.session.is_none() {
self.client.update_session()?;
}
debug!("auth session started");
self.started_auth = Some(resp.into_response_data().into());
let params = hashmap! {
"donotcache" => format!(
"{}",
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
* 1000
),
"username" => self.username.clone(),
};
let resp = self
.client
.post("https://steamcommunity.com/login/getrsakey")
.form(&params)
.send()?;
let encrypted_password: String;
let rsa_timestamp: String;
match resp.json::<RsaResponse>() {
Ok(rsa_resp) => {
rsa_timestamp = rsa_resp.timestamp.clone();
encrypted_password = encrypt_password(rsa_resp, &self.password);
}
Err(error) => {
error!("rsa error: {:?}", error);
return Err(LoginError::BadRSA);
}
}
trace!("captchagid: {}", self.captcha_gid);
trace!("captcha_text: {}", self.captcha_text);
trace!("twofactorcode: {}", self.twofactor_code);
trace!("emailauth: {}", self.email_code);
let login_resp: LoginResponse = self.client.login(
self.username.clone(),
encrypted_password,
self.twofactor_code.clone(),
self.email_code.clone(),
self.captcha_gid.clone(),
self.captcha_text.clone(),
rsa_timestamp,
)?;
if login_resp.message.contains("too many login") {
return Err(LoginError::TooManyAttempts);
}
if login_resp.message.contains("Incorrect login") {
return Err(LoginError::BadCredentials);
}
if login_resp.captcha_needed {
self.captcha_gid = login_resp.captcha_gid.clone();
return Err(LoginError::NeedCaptcha {
captcha_gid: self.captcha_gid.clone(),
});
}
if login_resp.emailauth_needed {
self.steam_id = login_resp.emailsteamid.clone();
return Err(LoginError::NeedEmail);
}
if login_resp.requires_twofactor {
return Err(LoginError::Need2FA);
}
if !login_resp.login_complete {
return Err(LoginError::BadCredentials);
}
if login_resp.needs_transfer_login() {
self.client.transfer_login(login_resp)?;
}
return Ok(self
.client
.session
Ok(self
.started_auth
.as_ref()
.unwrap()
.expose_secret()
.to_owned());
.allowed_confirmations()
.iter()
.map(|c| c.clone().into())
.collect())
}
pub fn begin_auth_via_qr(&mut self) -> anyhow::Result<BeginQrLoginResponse, LoginError> {
if self.started_auth.is_some() {
return Err(LoginError::AuthAlreadyStarted);
}
let mut req = CAuthentication_BeginAuthSessionViaQR_Request::new();
req.set_platform_type(self.device_details.platform_type);
req.set_device_friendly_name(self.device_details.friendly_name.clone());
let resp = self.client.begin_auth_session_via_qr(req)?;
if resp.result != EResult::OK {
return Err(resp.result.into());
}
let data = resp.response_data();
let return_resp = BeginQrLoginResponse {
challenge_url: data.challenge_url().into(),
confirmation_methonds: data
.allowed_confirmations
.iter()
.map(|c| c.clone().into())
.collect(),
};
debug!("auth session started");
self.started_auth = Some(resp.into_response_data().into());
Ok(return_resp)
}
fn poll_until_info(
&mut self,
) -> anyhow::Result<CAuthentication_PollAuthSessionStatus_Response> {
let Some(started_auth) = self.started_auth.as_ref() else {
return Err(anyhow::anyhow!("no auth session started"));
};
loop {
let mut req = CAuthentication_PollAuthSessionStatus_Request::new();
req.set_client_id(started_auth.client_id());
req.set_request_id(started_auth.request_id().to_vec());
let resp = self.client.poll_auth_session(req)?;
if resp.result != EResult::OK {
// EResult::FileNotFound is returned when the server couldn't find the auth session
return Err(anyhow::anyhow!("poll failed: {:?}", resp.result));
}
let data = resp.response_data();
let has_data = data.has_access_token()
|| data.has_account_name()
|| data.has_agreement_session_url()
|| data.has_had_remote_interaction()
|| data.has_new_challenge_url()
|| data.has_new_client_id()
|| data.has_new_guard_data()
|| data.has_refresh_token();
if has_data {
return Ok(resp.into_response_data());
}
std::thread::sleep(Duration::from_secs_f32(started_auth.interval()));
}
}
pub fn poll_until_tokens(&mut self) -> anyhow::Result<Tokens> {
loop {
let mut next_poll = self.poll_until_info()?;
if next_poll.has_access_token() {
return Ok(Tokens::new(
next_poll.take_access_token(),
next_poll.take_refresh_token(),
));
}
}
}
/// Submit a 2fa code generated from a device, or received in an email.
pub fn submit_steam_guard_code(
&mut self,
guard_type: EAuthSessionGuardType,
code: String,
) -> anyhow::Result<
CAuthentication_UpdateAuthSessionWithSteamGuardCode_Response,
UpdateAuthSessionError,
> {
let Some(started_auth) = self.started_auth.as_ref() else {
return Err(UpdateAuthSessionError::SessionNotStarted);
};
if guard_type != EAuthSessionGuardType::k_EAuthSessionGuardType_DeviceCode
&& guard_type != EAuthSessionGuardType::k_EAuthSessionGuardType_EmailCode
{
return Err(UpdateAuthSessionError::InvalidGuardType);
}
let mut req = CAuthentication_UpdateAuthSessionWithSteamGuardCode_Request::new();
req.set_client_id(started_auth.client_id());
req.set_code_type(guard_type);
req.set_code(code);
match started_auth {
StartAuth::BeginAuthSessionViaCredentials(ref resp) => {
req.set_steamid(resp.steamid());
}
StartAuth::BeginAuthSessionViaQR(_) => {
return Err(anyhow::anyhow!("qr auth not supported").into());
}
}
let resp = self.client.update_session_with_steam_guard_code(req)?;
if resp.result != EResult::OK {
return Err(resp.result.into());
}
Ok(resp.into_response_data())
}
}
fn encrypt_password(rsa_resp: RsaResponse, password: &String) -> String {
let rsa_exponent = rsa::BigUint::parse_bytes(rsa_resp.publickey_exp.as_bytes(), 16).unwrap();
let rsa_modulus = rsa::BigUint::parse_bytes(rsa_resp.publickey_mod.as_bytes(), 16).unwrap();
fn encrypt_password(
rsa_resp: CAuthentication_GetPasswordRSAPublicKey_Response,
password: &String,
) -> String {
let rsa_exponent = rsa::BigUint::parse_bytes(rsa_resp.publickey_exp().as_bytes(), 16).unwrap();
let rsa_modulus = rsa::BigUint::parse_bytes(rsa_resp.publickey_mod().as_bytes(), 16).unwrap();
let public_key = RsaPublicKey::new(rsa_modulus, rsa_exponent).unwrap();
#[cfg(test)]
let mut rng = rand::rngs::mock::StepRng::new(2, 1);
@ -185,16 +298,147 @@ fn encrypt_password(rsa_resp: RsaResponse, password: &String) -> String {
return encrypted_password;
}
#[test]
fn test_encrypt_password() {
let rsa_resp = RsaResponse{
success: true,
publickey_exp: String::from("010001"),
publickey_mod: String::from("98f9088c1250b17fe19d2b2422d54a1eef0036875301731f11bd17900e215318eb6de1546727c0b7b61b86cefccdcb2f8108c813154d9a7d55631965eece810d4ab9d8a59c486bda778651b876176070598a93c2325c275cb9c17bdbcacf8edc9c18c0c5d59bc35703505ef8a09ed4c62b9f92a3fac5740ce25e490ab0e26d872140e4103d912d1e3958f844264211277ee08d2b4dd3ac58b030b25342bd5c949ae7794e46a8eab26d5a8deca683bfd381da6c305b19868b8c7cd321ce72c693310a6ebf2ecd43642518f825894602f6c239cf193cb4346ce64beac31e20ef88f934f2f776597734bb9eae1ebdf4a453973b6df9d5e90777bffe5db83dd1757b"),
timestamp: String::from("asdf"),
token_gid: String::from("asdf"),
};
let result = encrypt_password(rsa_resp, &String::from("kelwleofpsm3n4ofc"));
assert_eq!(result.len(), 344);
assert_eq!(result, "RUo/3IfbkVcJi1q1S5QlpKn1mEn3gNJoc/Z4VwxRV9DImV6veq/YISEuSrHB3885U5MYFLn1g94Y+cWRL6HGXoV+gOaVZe43m7O92RwiVz6OZQXMfAv3UC/jcqn/xkitnj+tNtmx55gCxmGbO2KbqQ0TQqAyqCOOw565B+Cwr2OOorpMZAViv9sKA/G3Q6yzscU6rhua179c8QjC1Hk3idUoSzpWfT4sHNBW/EREXZ3Dkjwu17xzpfwIUpnBVIlR8Vj3coHgUCpTsKVRA3T814v9BYPlvLYwmw5DW3ddx+2SyTY0P5uuog36TN2PqYS7ioF5eDe16gyfRR4Nzn/7wA==");
#[derive(Debug)]
enum StartAuth {
BeginAuthSessionViaCredentials(CAuthentication_BeginAuthSessionViaCredentials_Response),
BeginAuthSessionViaQR(CAuthentication_BeginAuthSessionViaQR_Response),
}
impl StartAuth {
pub(crate) fn client_id(&self) -> u64 {
match self {
StartAuth::BeginAuthSessionViaCredentials(resp) => resp.client_id(),
StartAuth::BeginAuthSessionViaQR(resp) => resp.client_id(),
}
}
pub(crate) fn request_id(&self) -> &[u8] {
match self {
StartAuth::BeginAuthSessionViaCredentials(resp) => resp.request_id(),
StartAuth::BeginAuthSessionViaQR(resp) => resp.request_id(),
}
}
pub(crate) fn interval(&self) -> f32 {
match self {
StartAuth::BeginAuthSessionViaCredentials(resp) => resp.interval(),
StartAuth::BeginAuthSessionViaQR(resp) => resp.interval(),
}
}
pub(crate) fn allowed_confirmations(&self) -> &Vec<CAuthentication_AllowedConfirmation> {
match self {
StartAuth::BeginAuthSessionViaCredentials(resp) => &resp.allowed_confirmations,
StartAuth::BeginAuthSessionViaQR(resp) => &resp.allowed_confirmations,
}
}
}
impl From<CAuthentication_BeginAuthSessionViaCredentials_Response> for StartAuth {
fn from(resp: CAuthentication_BeginAuthSessionViaCredentials_Response) -> Self {
Self::BeginAuthSessionViaCredentials(resp)
}
}
impl From<CAuthentication_BeginAuthSessionViaQR_Response> for StartAuth {
fn from(resp: CAuthentication_BeginAuthSessionViaQR_Response) -> Self {
Self::BeginAuthSessionViaQR(resp)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeviceDetails {
/// The name to display for this device. You should make this unique, identifiable, and human readable. Used when managing account sessions.
pub friendly_name: String,
pub platform_type: EAuthTokenPlatformType,
/// Corresponds to the EOSType enum.
pub os_type: i32,
/// Corresponds to the EGamingDeviceType enum.
pub gaming_device_type: u32,
}
impl DeviceDetails {
fn into_message_field(self) -> protobuf::MessageField<CAuthentication_DeviceDetails> {
Some(self.into()).into()
}
}
impl From<DeviceDetails> for CAuthentication_DeviceDetails {
fn from(details: DeviceDetails) -> Self {
let mut inner = CAuthentication_DeviceDetails::new();
inner.set_device_friendly_name(details.friendly_name);
inner.set_platform_type(details.platform_type);
inner.set_os_type(details.os_type);
inner.set_gaming_device_type(details.gaming_device_type);
inner
}
}
#[derive(Debug)]
pub enum UpdateAuthSessionError {
SessionNotStarted,
InvalidGuardType,
TooManyAttempts,
SessionExpired,
IncorrectSteamGuardCode,
UnknownEResult(EResult),
NetworkFailure(reqwest::Error),
OtherFailure(anyhow::Error),
}
impl std::fmt::Display for UpdateAuthSessionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
write!(f, "{:?}", self)
}
}
impl std::error::Error for UpdateAuthSessionError {}
impl From<EResult> for UpdateAuthSessionError {
fn from(err: EResult) -> Self {
match err {
EResult::RateLimitExceeded => UpdateAuthSessionError::TooManyAttempts,
EResult::Expired => UpdateAuthSessionError::SessionExpired,
EResult::TwoFactorCodeMismatch => UpdateAuthSessionError::IncorrectSteamGuardCode,
_ => UpdateAuthSessionError::UnknownEResult(err),
}
}
}
impl From<reqwest::Error> for UpdateAuthSessionError {
fn from(err: reqwest::Error) -> Self {
UpdateAuthSessionError::NetworkFailure(err)
}
}
impl From<anyhow::Error> for UpdateAuthSessionError {
fn from(err: anyhow::Error) -> Self {
UpdateAuthSessionError::OtherFailure(err)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_encrypt_password() {
let mut rsa_resp = CAuthentication_GetPasswordRSAPublicKey_Response::new();
rsa_resp.set_publickey_exp(String::from("010001"));
rsa_resp.set_publickey_mod(String::from("98f9088c1250b17fe19d2b2422d54a1eef0036875301731f11bd17900e215318eb6de1546727c0b7b61b86cefccdcb2f8108c813154d9a7d55631965eece810d4ab9d8a59c486bda778651b876176070598a93c2325c275cb9c17bdbcacf8edc9c18c0c5d59bc35703505ef8a09ed4c62b9f92a3fac5740ce25e490ab0e26d872140e4103d912d1e3958f844264211277ee08d2b4dd3ac58b030b25342bd5c949ae7794e46a8eab26d5a8deca683bfd381da6c305b19868b8c7cd321ce72c693310a6ebf2ecd43642518f825894602f6c239cf193cb4346ce64beac31e20ef88f934f2f776597734bb9eae1ebdf4a453973b6df9d5e90777bffe5db83dd1757b"));
rsa_resp.set_timestamp(1);
let result = encrypt_password(rsa_resp, &String::from("kelwleofpsm3n4ofc"));
assert_eq!(result.len(), 344);
assert_eq!(result, "RUo/3IfbkVcJi1q1S5QlpKn1mEn3gNJoc/Z4VwxRV9DImV6veq/YISEuSrHB3885U5MYFLn1g94Y+cWRL6HGXoV+gOaVZe43m7O92RwiVz6OZQXMfAv3UC/jcqn/xkitnj+tNtmx55gCxmGbO2KbqQ0TQqAyqCOOw565B+Cwr2OOorpMZAViv9sKA/G3Q6yzscU6rhua179c8QjC1Hk3idUoSzpWfT4sHNBW/EREXZ3Dkjwu17xzpfwIUpnBVIlR8Vj3coHgUCpTsKVRA3T814v9BYPlvLYwmw5DW3ddx+2SyTY0P5uuog36TN2PqYS7ioF5eDe16gyfRR4Nzn/7wA==");
}
#[test]
fn test_encrypt_password_2() {
let mut rsa_resp = CAuthentication_GetPasswordRSAPublicKey_Response::new();
rsa_resp.set_publickey_exp(String::from("010001"));
rsa_resp.set_publickey_mod(String::from("ca6a8dc290279b25c38a282b9a7b01306c5978bd7a2f60dcfd52134ac58faf121568ebd85ca6a2128413b76ec70fb3150b3181bbe2a1a8349b68da9c303960bdf4e34296b27bd4ea29b4d1a695168ddfc974bb6ba427206fdcdb088bf27261a52f343a51e19759fe4072b7a2047a6bc31361950d9e87d7977b31b71696572babe45ea6a7d132547984462fd5787607e0d9ff1c637e04d593e7538c880c3cdd252b75bcb703a7b8bb01cd8898b04980f40b76235d50fc1544c39ccbe763892322fc6d0a5acaf8be09efbc20fcfebcd3b02a1eb95d9d0c338e96674c17edbb0257cd43d04974423f1f995a28b9e159322d9db2708826804c0eccafffc94dd2a3d5"));
rsa_resp.set_timestamp(104444850000);
let result = encrypt_password(rsa_resp, &String::from("foo"));
assert_eq!(result, "jmlMXmhbweWn+wJnnf96W3Lsh0dRmzrBfMxREUuEW11rRYcfXWupBIT3eK1fmQHMZmyJeMhZiRpgIaZ7DafojQT6djJr+RKeREJs0ys9hKwxD5FGlqsTLXXEeuyopyd2smHBbmmF47voe59KEoiZZapP+eYnpJy3O2k7e1P9BH9LsKIN/nWF1ogM2jjJ328AejUpM64tPl/kInFJ1CHrLiAAKDPk42fLAAKs97xIi0JkosG6yp+8HhFqQxxZ8/bNI1IVkQC1Hdc2AN0QlNKxbDXquAn6ARgw/4b5DwUpnOb9de+Q6iX3v1/M07Se7JV8/4tuz8Thy2Chbxsf9E1TuQ==");
}
}