Compare commits
No commits in common. "master" and "v0.10.2" have entirely different histories.
56 changed files with 1454 additions and 2586 deletions
2
.github/ISSUE_TEMPLATE/bug.yml
vendored
2
.github/ISSUE_TEMPLATE/bug.yml
vendored
|
@ -10,7 +10,7 @@ body:
|
|||
id: version
|
||||
attributes:
|
||||
label: Version
|
||||
description: What version of steamguard-cli are you running? You can find this by running `steamguard --version`. **Do NOT just say "latest", or your issue will be automatically closed.**
|
||||
description: What version of steamguard-cli are you running? You can find this by running `steamguard --version`.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
|
|
5
.github/workflows/aur-checker.yml
vendored
5
.github/workflows/aur-checker.yml
vendored
|
@ -5,13 +5,12 @@ on:
|
|||
- cron: "32 5 */3 * *"
|
||||
push:
|
||||
branches: [ master, main ]
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
test-install:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v2
|
||||
- name: Install AUR package
|
||||
run: ./scripts/check-aur.sh
|
||||
run: ./scripts/check-aur.sh
|
12
.github/workflows/rust.yml
vendored
12
.github/workflows/rust.yml
vendored
|
@ -15,9 +15,9 @@ jobs:
|
|||
|
||||
steps:
|
||||
- run: rustup component add clippy rustfmt
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v3
|
||||
- name: Rust Cache
|
||||
uses: Swatinem/rust-cache@v2
|
||||
uses: Swatinem/rust-cache@v2.5.0
|
||||
- name: Check format
|
||||
run: cargo fmt --all -- --check
|
||||
- name: Check
|
||||
|
@ -27,20 +27,20 @@ jobs:
|
|||
- name: Validate documentation
|
||||
run: cargo doc --workspace --no-deps --all-features
|
||||
- name: Run tests
|
||||
run: cargo test --verbose --all-features --all-targets --workspace
|
||||
run: cargo test --verbose
|
||||
check:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
target: [x86_64-unknown-linux-musl, x86_64-pc-windows-gnu]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v3
|
||||
- name: Rust Cache
|
||||
uses: Swatinem/rust-cache@v2
|
||||
uses: Swatinem/rust-cache@v2.5.0
|
||||
with:
|
||||
prefix-key: v0-rust-${{ matrix.target }}
|
||||
- name: Install Cross
|
||||
uses: baptiste0928/cargo-install@v2
|
||||
uses: baptiste0928/cargo-install@v1
|
||||
with:
|
||||
crate: cross
|
||||
- name: Check
|
||||
|
|
2186
Cargo.lock
generated
2186
Cargo.lock
generated
File diff suppressed because it is too large
Load diff
46
Cargo.toml
46
Cargo.toml
|
@ -4,9 +4,9 @@ members = ["steamguard"]
|
|||
|
||||
[package]
|
||||
name = "steamguard-cli"
|
||||
version = "0.14.0"
|
||||
version = "0.10.2"
|
||||
authors = ["dyc3 (Carson McManus) <carson.mcmanus1@gmail.com>"]
|
||||
edition = "2021"
|
||||
edition = "2018"
|
||||
description = "A command line utility to generate Steam 2FA codes and respond to confirmations."
|
||||
keywords = ["steam", "2fa", "steamguard", "authentication", "cli"]
|
||||
categories = ["command-line-utilities"]
|
||||
|
@ -27,43 +27,39 @@ keyring = ["dep:keyring"]
|
|||
name = "steamguard"
|
||||
path = "src/main.rs"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
anyhow = "^1.0"
|
||||
base64 = "0.22.1"
|
||||
hmac-sha1 = "^0.1"
|
||||
base64 = "0.13.0"
|
||||
text_io = "0.1.8"
|
||||
rpassword = "7.2.0"
|
||||
reqwest = { version = "0.12", default-features = false, features = [
|
||||
"blocking",
|
||||
"json",
|
||||
"cookies",
|
||||
"gzip",
|
||||
"rustls-tls",
|
||||
] }
|
||||
rpassword = "5.0"
|
||||
reqwest = { version = "0.11", default-features = false, features = ["blocking", "json", "cookies", "gzip", "rustls-tls"] }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
rsa = "0.9.2"
|
||||
rand = "0.8.5"
|
||||
clap = { version = "4.5.4", features = ["derive", "cargo", "env"] }
|
||||
clap_complete = "4.5.2"
|
||||
standback = "0.2.17" # required to fix a compilation error on a transient dependency
|
||||
clap = { version = "3.1.18", features = ["derive", "cargo", "env"] }
|
||||
clap_complete = "3.2.1"
|
||||
log = "0.4.19"
|
||||
stderrlog = "0.6"
|
||||
cookie = "0.18"
|
||||
stderrlog = "0.4"
|
||||
cookie = "0.14"
|
||||
regex = "1"
|
||||
lazy_static = "1.4.0"
|
||||
uuid = { version = "1.8", features = ["v4"] }
|
||||
steamguard = { version = "^0.14.0", path = "./steamguard" }
|
||||
dirs = "5.0.1"
|
||||
uuid = { version = "0.8", features = ["v4"] }
|
||||
steamguard = { version = "^0.10.1", path = "./steamguard" }
|
||||
dirs = "3.0.2"
|
||||
aes = { version = "0.8.3", features = ["zeroize"] }
|
||||
thiserror = "1.0.61"
|
||||
thiserror = "1.0.26"
|
||||
crossterm = { version = "0.23.2", features = ["event-stream"] }
|
||||
qrcode = { version = "0.14.0", optional = true }
|
||||
qrcode = { version = "0.12.0", optional = true }
|
||||
gethostname = "0.4.3"
|
||||
secrecy = { version = "0.8", features = ["serde"] }
|
||||
zeroize = { version = "^1.6.0", features = ["std", "zeroize_derive"] }
|
||||
serde_path_to_error = "0.1.11"
|
||||
update-informer = { version = "1.0.0", optional = true, default-features = false, features = [
|
||||
"github",
|
||||
] }
|
||||
update-informer = { version = "1.0.0", optional = true, default-features = false, features = ["github"] }
|
||||
phonenumber = "0.3"
|
||||
cbc = { version = "0.1.2", features = ["std", "zeroize"] }
|
||||
inout = { version = "0.1.3", features = ["std"] }
|
||||
|
@ -72,11 +68,9 @@ argon2 = { version = "0.5.0", features = ["std", "zeroize"] }
|
|||
pbkdf2 = { version = "0.12.1", features = ["parallel"] }
|
||||
sha1 = "0.10.5"
|
||||
rayon = "1.7.0"
|
||||
rqrr = "0.7.1"
|
||||
image = "0.25"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
tempdir = "0.3"
|
||||
proptest = "1"
|
||||
|
||||
[profile.release]
|
||||
|
|
3
PKGBUILD
3
PKGBUILD
|
@ -3,7 +3,7 @@
|
|||
|
||||
_pkgname=steamguard-cli
|
||||
pkgname=${_pkgname}-git
|
||||
pkgver=0.14.0.r1.602acc66
|
||||
pkgver=0.8.1.r1.fe0d6e9a
|
||||
pkgrel=1
|
||||
pkgdesc="A command line utility to generate Steam 2FA codes and respond to confirmations."
|
||||
arch=('i686' 'x86_64' 'armv6h' 'armv7h')
|
||||
|
@ -12,7 +12,6 @@ license=('GPL3')
|
|||
makedepends=('rust' 'cargo' 'git')
|
||||
source=("git+https://github.com/dyc3/steamguard-cli.git")
|
||||
sha256sums=('SKIP')
|
||||
options=(!lto)
|
||||
|
||||
pkgver() {
|
||||
cd "${srcdir}/${_pkgname}"
|
||||
|
|
|
@ -3,7 +3,7 @@
|
|||
[](https://github.com/dyc3/steamguard-cli/actions/workflows/rust.yml)
|
||||
[](https://github.com/dyc3/steamguard-cli/actions/workflows/aur-checker.yml)
|
||||
|
||||
A command line utility for setting up and using Steam Mobile Authenticator (AKA Steam 2FA). It can also be used to respond to trade, market, and any other steam mobile confirmations that you would normally get in the app.
|
||||
A command line utility for setting up and using Steam Mobile Authenticator (AKA Steam 2FA). It can also be used to respond to trade and market confirmations.
|
||||
|
||||
**The only legitimate place to download steamguard-cli binaries is through this repo's releases, or by any package manager that is linked in this document.**
|
||||
|
||||
|
|
|
@ -1,2 +1,3 @@
|
|||
tab_spaces = 4
|
||||
hard_tabs = true
|
||||
normalize_comments = true
|
||||
|
|
|
@ -4,7 +4,6 @@ set -e
|
|||
|
||||
DRY_RUN=true
|
||||
SKIP_CRATE_PUBLISH=false
|
||||
ALLOW_DIRTY=false
|
||||
|
||||
POSITIONAL=()
|
||||
while [[ $# -gt 0 ]]; do
|
||||
|
@ -24,10 +23,6 @@ while [[ $# -gt 0 ]]; do
|
|||
SKIP_CRATE_PUBLISH=true
|
||||
shift # past argument
|
||||
;;
|
||||
--allow-dirty)
|
||||
ALLOW_DIRTY=true
|
||||
shift # past argument
|
||||
;;
|
||||
*) # unknown option
|
||||
POSITIONAL+=("$1") # save it in an array for later
|
||||
shift # past argument
|
||||
|
@ -52,21 +47,6 @@ This will do everything needed to release a new version:
|
|||
- publish crates on crates.io
|
||||
- upload artifacts to a new release on github
|
||||
"""
|
||||
|
||||
echo "Previewing changes..."
|
||||
params=()
|
||||
if [[ $BUMP != "" ]]; then
|
||||
params+=(--bump "$BUMP")
|
||||
params+=(--bump-dependencies "$BUMP")
|
||||
fi
|
||||
if [[ $SKIP_CRATE_PUBLISH == true ]]; then
|
||||
params+=(--no-publish)
|
||||
fi
|
||||
if [[ $ALLOW_DIRTY == true ]]; then
|
||||
params+=(--allow-dirty)
|
||||
fi
|
||||
cargo smart-release --update-crates-index --no-changelog --no-tag --no-push --no-publish "${params[@]}"
|
||||
|
||||
if [ "$DRY_RUN" = true ]; then
|
||||
echo "This is a dry run, nothing will be done. Artifacts will be built, but not published. Use --execute to do it for real."
|
||||
else
|
||||
|
@ -75,10 +55,17 @@ fi
|
|||
echo "Press any key to continue..."
|
||||
read -n 1 -s -r
|
||||
|
||||
|
||||
params=()
|
||||
if [[ $DRY_RUN == false ]]; then
|
||||
params+=(--execute)
|
||||
fi
|
||||
if [[ $BUMP != "" ]]; then
|
||||
params+=(--bump "$BUMP")
|
||||
params+=(--bump-dependencies "$BUMP")
|
||||
fi
|
||||
if [[ $SKIP_CRATE_PUBLISH == true ]]; then
|
||||
params+=(--no-publish)
|
||||
fi
|
||||
cargo smart-release --update-crates-index --no-changelog --no-tag --no-push --no-publish "${params[@]}"
|
||||
|
||||
#echo "Verify that the publish succeeded, and Press any key to continue..."
|
||||
|
@ -122,5 +109,5 @@ if [[ $DRY_RUN == false ]]; then
|
|||
if [[ $(gh release list | grep -i "Draft" | grep -i "$VERSION" && echo "true" || echo "false") == "true" ]]; then
|
||||
gh release delete --yes "$VERSION"
|
||||
fi
|
||||
gh release create "$VERSION" --discussion-category "General" --title "$VERSION" "$BIN_PATH" "$BIN_PATH2" "./steamguard-cli_$RAW_VERSION-0.deb"
|
||||
gh release create "$VERSION" --discussion-category "General" --title "$VERSION" --draft "$BIN_PATH" "$BIN_PATH2" "./steamguard-cli_$RAW_VERSION-0.deb"
|
||||
fi
|
||||
|
|
|
@ -32,12 +32,12 @@ Depends:
|
|||
Version: $VERSION
|
||||
Section: base
|
||||
Priority: optional
|
||||
Architecture: amd64
|
||||
Architecture: x86-64
|
||||
Maintainer: Carson McManus <carson.mcmanus1@gmail.com>
|
||||
Description: steamguard-cli
|
||||
A command line utility to generate Steam 2FA codes and respond to confirmations.
|
||||
EOT
|
||||
|
||||
dpkg-deb -Zxz --build "$TEMP_PKG_PATH" "steamguard-cli_$VERSION-0.deb"
|
||||
dpkg-deb --build "$TEMP_PKG_PATH" "steamguard-cli_$VERSION-0.deb"
|
||||
|
||||
rm -rf "$TEMP_PKG_PATH"
|
||||
|
|
|
@ -15,8 +15,6 @@ use thiserror::Error;
|
|||
mod legacy;
|
||||
pub mod manifest;
|
||||
pub mod migrate;
|
||||
mod steamv2;
|
||||
mod winauth;
|
||||
|
||||
pub use manifest::*;
|
||||
|
||||
|
@ -170,40 +168,32 @@ impl AccountManager {
|
|||
.insert(account.account_name.clone(), Arc::new(Mutex::new(account)));
|
||||
}
|
||||
|
||||
pub fn import_account(
|
||||
&mut self,
|
||||
import_path: &String,
|
||||
) -> anyhow::Result<(), ManifestAccountImportError> {
|
||||
pub fn import_account(&mut self, import_path: &String) -> anyhow::Result<()> {
|
||||
let path = Path::new(import_path);
|
||||
if !path.exists() {
|
||||
return Err(ManifestAccountImportError::FileNotFound);
|
||||
}
|
||||
if !path.is_file() {
|
||||
return Err(ManifestAccountImportError::NotAFile);
|
||||
}
|
||||
ensure!(path.exists(), "{} does not exist.", import_path);
|
||||
ensure!(path.is_file(), "{} is not a file.", import_path);
|
||||
|
||||
let file = File::open(path)?;
|
||||
let reader = BufReader::new(file);
|
||||
let mut deser = serde_json::Deserializer::from_reader(reader);
|
||||
let account: SteamGuardAccount = serde_path_to_error::deserialize(&mut deser)?;
|
||||
if self.account_exists(&account.account_name) {
|
||||
return Err(ManifestAccountImportError::AlreadyExists {
|
||||
account_name: account.account_name,
|
||||
});
|
||||
}
|
||||
ensure!(
|
||||
!self.account_exists(&account.account_name),
|
||||
"Account already exists in manifest, please remove it first."
|
||||
);
|
||||
self.add_account(account);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn remove_account(&mut self, account_name: &String) {
|
||||
pub fn remove_account(&mut self, account_name: String) {
|
||||
let index = self
|
||||
.manifest
|
||||
.entries
|
||||
.iter()
|
||||
.position(|a| &a.account_name == account_name)
|
||||
.position(|a| a.account_name == account_name)
|
||||
.unwrap();
|
||||
self.accounts.remove(account_name);
|
||||
self.accounts.remove(&account_name);
|
||||
self.manifest.entries.remove(index);
|
||||
}
|
||||
|
||||
|
@ -339,9 +329,8 @@ impl AccountManager {
|
|||
debug!("Adding missing account names");
|
||||
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
|
||||
.clone_from(&account.lock().unwrap().account_name);
|
||||
self.manifest.entries[i].account_name =
|
||||
account.lock().unwrap().account_name.clone();
|
||||
}
|
||||
upgraded = true;
|
||||
}
|
||||
|
@ -449,41 +438,23 @@ impl From<std::io::Error> for ManifestAccountLoadError {
|
|||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum ManifestAccountImportError {
|
||||
#[error("Could not find the specified file.")]
|
||||
FileNotFound,
|
||||
#[error("The specified path is not a file.")]
|
||||
NotAFile,
|
||||
#[error(
|
||||
"The account you are trying to import, \"{account_name}\", already exists in the manifest."
|
||||
)]
|
||||
AlreadyExists { account_name: String },
|
||||
#[error(transparent)]
|
||||
IOError(#[from] std::io::Error),
|
||||
#[error("Failed to deserialize the account. {self:?}")]
|
||||
DeserializationFailed(#[from] serde_path_to_error::Error<serde_json::Error>),
|
||||
#[error(transparent)]
|
||||
Unknown(#[from] anyhow::Error),
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use steamguard::ExposeSecret;
|
||||
use tempfile::TempDir;
|
||||
use tempdir::TempDir;
|
||||
|
||||
#[test]
|
||||
fn test_should_save_new_manifest() {
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
let tmp_dir = TempDir::new("steamguard-cli-test").unwrap();
|
||||
let manifest_path = tmp_dir.path().join("manifest.json");
|
||||
let manager = AccountManager::new(manifest_path.as_path());
|
||||
assert!(manager.save().is_ok());
|
||||
assert!(matches!(manager.save(), Ok(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_should_save_and_load_manifest() -> anyhow::Result<()> {
|
||||
let tmp_dir = TempDir::new()?;
|
||||
let tmp_dir = TempDir::new("steamguard-cli-test")?;
|
||||
let manifest_path = tmp_dir.path().join("manifest.json");
|
||||
println!("tempdir: {}", manifest_path.display());
|
||||
let mut manager = AccountManager::new(manifest_path.as_path());
|
||||
|
@ -519,7 +490,7 @@ mod tests {
|
|||
#[test]
|
||||
fn test_should_save_and_load_manifest_encrypted() -> anyhow::Result<()> {
|
||||
let passkey = Some(SecretString::new("password".into()));
|
||||
let tmp_dir = TempDir::new()?;
|
||||
let tmp_dir = TempDir::new("steamguard-cli-test")?;
|
||||
let manifest_path = tmp_dir.path().join("manifest.json");
|
||||
let mut manager = AccountManager::new(manifest_path.as_path());
|
||||
let mut account = SteamGuardAccount::new();
|
||||
|
@ -531,7 +502,7 @@ mod tests {
|
|||
manager.add_account(account);
|
||||
manager.manifest.entries[0].encryption = Some(EncryptionScheme::generate());
|
||||
manager.submit_passkey(passkey.clone());
|
||||
assert!(manager.save().is_ok());
|
||||
assert!(matches!(manager.save(), Ok(_)));
|
||||
|
||||
let mut loaded_manager = AccountManager::load(manifest_path.as_path()).unwrap();
|
||||
loaded_manager.submit_passkey(passkey);
|
||||
|
@ -544,7 +515,7 @@ mod tests {
|
|||
if _r.is_err() {
|
||||
eprintln!("{:?}", _r);
|
||||
}
|
||||
assert!(_r.is_ok());
|
||||
assert!(matches!(_r, Ok(_)));
|
||||
assert_eq!(
|
||||
loaded_manager.manifest.entries.len(),
|
||||
loaded_manager.accounts.len()
|
||||
|
@ -568,7 +539,7 @@ mod tests {
|
|||
#[test]
|
||||
fn test_should_save_and_load_manifest_encrypted_longer() -> anyhow::Result<()> {
|
||||
let passkey = Some(SecretString::new("password".into()));
|
||||
let tmp_dir = TempDir::new()?;
|
||||
let tmp_dir = TempDir::new("steamguard-cli-test")?;
|
||||
let manifest_path = tmp_dir.path().join("manifest.json");
|
||||
let mut manager = AccountManager::new(manifest_path.as_path());
|
||||
let mut account = SteamGuardAccount::new();
|
||||
|
@ -615,7 +586,7 @@ mod tests {
|
|||
|
||||
#[test]
|
||||
fn test_should_import() -> anyhow::Result<()> {
|
||||
let tmp_dir = TempDir::new()?;
|
||||
let tmp_dir = TempDir::new("steamguard-cli-test")?;
|
||||
let manifest_path = tmp_dir.path().join("manifest.json");
|
||||
let mut manager = AccountManager::new(manifest_path.as_path());
|
||||
let mut account = SteamGuardAccount::new();
|
||||
|
@ -630,16 +601,17 @@ mod tests {
|
|||
std::fs::remove_file(&manifest_path)?;
|
||||
|
||||
let mut loaded_manager = AccountManager::new(manifest_path.as_path());
|
||||
assert!(loaded_manager
|
||||
.import_account(
|
||||
assert!(matches!(
|
||||
loaded_manager.import_account(
|
||||
&tmp_dir
|
||||
.path()
|
||||
.join("asdf1234.maFile")
|
||||
.into_os_string()
|
||||
.into_string()
|
||||
.unwrap()
|
||||
)
|
||||
.is_ok());
|
||||
),
|
||||
Ok(_)
|
||||
));
|
||||
assert_eq!(
|
||||
loaded_manager.manifest.entries.len(),
|
||||
loaded_manager.accounts.len()
|
||||
|
|
|
@ -128,11 +128,9 @@ pub struct SdaAccount {
|
|||
pub token_gid: String,
|
||||
#[serde(with = "crate::secret_string")]
|
||||
pub identity_secret: SecretString,
|
||||
#[serde(default)]
|
||||
pub server_time: u64,
|
||||
#[serde(with = "crate::secret_string")]
|
||||
pub uri: SecretString,
|
||||
#[serde(default)]
|
||||
pub fully_enrolled: bool,
|
||||
pub device_id: String,
|
||||
#[serde(with = "crate::secret_string")]
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
use std::{fs::File, io::Read, path::Path};
|
||||
|
||||
use log::*;
|
||||
use log::debug;
|
||||
use secrecy::SecretString;
|
||||
use serde::{de::Error, Deserialize};
|
||||
use steamguard::SteamGuardAccount;
|
||||
|
@ -11,8 +11,6 @@ use crate::encryption::EncryptionScheme;
|
|||
use super::{
|
||||
legacy::{SdaAccount, SdaManifest},
|
||||
manifest::ManifestV1,
|
||||
steamv2::SteamMobileV2,
|
||||
winauth::parse_winauth_exports,
|
||||
EntryLoader, Manifest,
|
||||
};
|
||||
|
||||
|
@ -147,11 +145,7 @@ impl MigratingManifest {
|
|||
errors
|
||||
));
|
||||
}
|
||||
accounts
|
||||
.into_iter()
|
||||
.map(ExternalAccount::Sda)
|
||||
.map(MigratingAccount::External)
|
||||
.collect()
|
||||
accounts.into_iter().map(MigratingAccount::Sda).collect()
|
||||
}
|
||||
Self::ManifestV1(manifest) => {
|
||||
let (accounts, errors) = manifest
|
||||
|
@ -234,16 +228,15 @@ fn deserialize_manifest(
|
|||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
enum MigratingAccount {
|
||||
External(ExternalAccount),
|
||||
Sda(SdaAccount),
|
||||
ManifestV1(SteamGuardAccount),
|
||||
}
|
||||
|
||||
impl MigratingAccount {
|
||||
pub fn upgrade(self) -> Self {
|
||||
match self {
|
||||
Self::External(account) => Self::ManifestV1(account.into()),
|
||||
Self::Sda(sda) => Self::ManifestV1(sda.into()),
|
||||
Self::ManifestV1(_) => self,
|
||||
}
|
||||
}
|
||||
|
@ -262,65 +255,19 @@ impl From<MigratingAccount> for SteamGuardAccount {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn load_and_upgrade_external_accounts(path: &Path) -> anyhow::Result<Vec<SteamGuardAccount>> {
|
||||
let mut file = File::open(path)?;
|
||||
let mut buf = vec![];
|
||||
file.read_to_end(&mut buf)?;
|
||||
let mut deser = serde_json::Deserializer::from_slice(&buf);
|
||||
let accounts = match serde_path_to_error::deserialize(&mut deser) {
|
||||
Ok(account) => {
|
||||
vec![MigratingAccount::External(account)]
|
||||
}
|
||||
Err(json_err) => {
|
||||
// the file is not JSON, so it's probably a winauth export
|
||||
match parse_winauth_exports(buf) {
|
||||
Ok(accounts) => accounts
|
||||
.into_iter()
|
||||
.map(MigratingAccount::External)
|
||||
.collect(),
|
||||
Err(winauth_err) => {
|
||||
bail!(
|
||||
"Failed to parse as JSON: {}\nFailed to parse as Winauth export: {}",
|
||||
json_err,
|
||||
winauth_err
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Ok(accounts
|
||||
.into_iter()
|
||||
.map(|mut account| {
|
||||
while !account.is_latest() {
|
||||
account = account.upgrade();
|
||||
}
|
||||
account.into()
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(untagged)]
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
pub(crate) enum ExternalAccount {
|
||||
Sda(SdaAccount),
|
||||
SteamMobileV2(SteamMobileV2),
|
||||
}
|
||||
|
||||
impl From<ExternalAccount> for SteamGuardAccount {
|
||||
fn from(account: ExternalAccount) -> Self {
|
||||
match account {
|
||||
ExternalAccount::Sda(account) => account.into(),
|
||||
ExternalAccount::SteamMobileV2(account) => account.into(),
|
||||
}
|
||||
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 tempfile::TempDir;
|
||||
|
||||
use crate::{accountmanager::CURRENT_MANIFEST_VERSION, AccountManager};
|
||||
|
||||
use super::*;
|
||||
|
@ -361,10 +308,6 @@ mod tests {
|
|||
manifest: "src/fixtures/maFiles/compat/difficult-migration/manifest.json",
|
||||
passkey: None,
|
||||
},
|
||||
Test {
|
||||
manifest: "src/fixtures/maFiles/compat/missing-unnecessary/manifest.json",
|
||||
passkey: None,
|
||||
},
|
||||
];
|
||||
for case in cases {
|
||||
eprintln!("testing: {:?}", case);
|
||||
|
@ -417,26 +360,10 @@ mod tests {
|
|||
account_name: "example",
|
||||
steam_id: 1234,
|
||||
},
|
||||
Test {
|
||||
mafile: "src/fixtures/maFiles/compat/steamv2/sample.maFile",
|
||||
account_name: "afarihm",
|
||||
steam_id: 76561199441992970,
|
||||
},
|
||||
Test {
|
||||
mafile: "src/fixtures/maFiles/compat/winauth/exports.txt",
|
||||
account_name: "example",
|
||||
steam_id: 1234,
|
||||
},
|
||||
Test {
|
||||
mafile: "src/fixtures/maFiles/compat/missing-unnecessary/1234.maFile",
|
||||
account_name: "example",
|
||||
steam_id: 1234,
|
||||
},
|
||||
];
|
||||
for case in cases {
|
||||
eprintln!("testing: {:?}", case);
|
||||
let accounts = load_and_upgrade_external_accounts(Path::new(case.mafile))?;
|
||||
let account = accounts[0].clone();
|
||||
let account = load_and_upgrade_sda_account(Path::new(case.mafile))?;
|
||||
assert_eq!(account.account_name, case.account_name);
|
||||
assert_eq!(account.steam_id, case.steam_id);
|
||||
}
|
||||
|
@ -479,7 +406,7 @@ mod tests {
|
|||
];
|
||||
for case in cases {
|
||||
eprintln!("testing: {:?}", case);
|
||||
let temp = TempDir::new()?;
|
||||
let temp = tempdir::TempDir::new("steamguard-cli-test")?;
|
||||
for file in std::fs::read_dir(case.dir)? {
|
||||
let file = file?;
|
||||
let path = file.path();
|
||||
|
|
|
@ -1,73 +0,0 @@
|
|||
use secrecy::SecretString;
|
||||
use serde::{Deserialize, Deserializer};
|
||||
use serde_json::Value;
|
||||
use steamguard::{token::TwoFactorSecret, SteamGuardAccount};
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Defines the schema for loading steamguard accounts extracted from backups of the official Steam app (v2).
|
||||
///
|
||||
/// ```json
|
||||
/// {
|
||||
/// "steamid": "X",
|
||||
/// "shared_secret": "X",
|
||||
/// "serial_number": "X",
|
||||
/// "revocation_code": "X",
|
||||
/// "uri": "otpauth:\/\/totp\/Steam:USERNAME?secret=X&issuer=Steam",
|
||||
/// "server_time": "X",
|
||||
/// "account_name": "USERNAME",
|
||||
/// "token_gid": "X",
|
||||
/// "identity_secret": "X",
|
||||
/// "secret_1": "X",
|
||||
/// "status": 1,
|
||||
/// "steamguard_scheme": "2"
|
||||
/// }
|
||||
/// ```
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct SteamMobileV2 {
|
||||
#[serde(deserialize_with = "de_parse_number")]
|
||||
pub steamid: u64,
|
||||
pub shared_secret: TwoFactorSecret,
|
||||
pub serial_number: String,
|
||||
#[serde(with = "crate::secret_string")]
|
||||
pub revocation_code: SecretString,
|
||||
#[serde(with = "crate::secret_string")]
|
||||
pub uri: SecretString,
|
||||
pub server_time: Option<serde_json::Value>,
|
||||
pub account_name: String,
|
||||
pub token_gid: String,
|
||||
#[serde(with = "crate::secret_string")]
|
||||
pub identity_secret: SecretString,
|
||||
#[serde(with = "crate::secret_string")]
|
||||
pub secret_1: SecretString,
|
||||
pub status: Option<serde_json::Value>,
|
||||
pub steamguard_scheme: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
impl From<SteamMobileV2> for SteamGuardAccount {
|
||||
fn from(account: SteamMobileV2) -> Self {
|
||||
Self {
|
||||
shared_secret: account.shared_secret,
|
||||
identity_secret: account.identity_secret,
|
||||
revocation_code: account.revocation_code,
|
||||
uri: account.uri,
|
||||
account_name: account.account_name,
|
||||
token_gid: account.token_gid,
|
||||
serial_number: account.serial_number,
|
||||
steam_id: account.steamid,
|
||||
// device_id is unknown, so we just make one up
|
||||
device_id: format!("android:{}", Uuid::new_v4()),
|
||||
secret_1: account.secret_1,
|
||||
tokens: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn de_parse_number<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u64, D::Error> {
|
||||
Ok(match Value::deserialize(deserializer)? {
|
||||
Value::String(s) => s.parse().map_err(serde::de::Error::custom)?,
|
||||
Value::Number(num) => num
|
||||
.as_u64()
|
||||
.ok_or(serde::de::Error::custom("Invalid number"))?,
|
||||
_ => return Err(serde::de::Error::custom("wrong type")),
|
||||
})
|
||||
}
|
|
@ -1,50 +0,0 @@
|
|||
//! Accounts exported from Winauth are in the following format:
|
||||
//!
|
||||
//! One account per line, with each account represented as a URL.
|
||||
//!
|
||||
//! ```ignore
|
||||
//! otpauth://totp/Steam:<steamaccountname>?secret=<ABCDEFG1234_secret_dunno_what_for>&digits=5&issuer=Steam&deviceid=<URL_Escaped_device_name>&data=<url_encoded_data_json>
|
||||
//! ```
|
||||
//!
|
||||
//! The `data` field is a URL encoded JSON object with the following fields:
|
||||
//!
|
||||
//! ```json
|
||||
//! {"steamid":"<steam_id>","status":1,"shared_secret":"<shared_secret>","serial_number":"<serial_number>","revocation_code":"<revocation_code>","uri":"<uri>","server_time":"<server_time>","account_name":"<steam_login_name>","token_gid":"<token_gid>","identity_secret":"<identity_secret>","secret_1":"<secret_1>","steamguard_scheme":"2"}
|
||||
//! ```
|
||||
|
||||
use anyhow::Context;
|
||||
use log::*;
|
||||
use reqwest::Url;
|
||||
|
||||
use super::migrate::ExternalAccount;
|
||||
|
||||
pub(crate) fn parse_winauth_exports(buf: Vec<u8>) -> anyhow::Result<Vec<ExternalAccount>> {
|
||||
let buf = String::from_utf8(buf)?;
|
||||
let mut accounts = Vec::new();
|
||||
for line in buf.split('\n') {
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let url = Url::parse(line).context("parsing as winauth export URL")?;
|
||||
let mut query = url.query_pairs();
|
||||
let issuer = query
|
||||
.find(|(key, _)| key == "issuer")
|
||||
.context("missing issuer field")?
|
||||
.1;
|
||||
if issuer != "Steam" {
|
||||
debug!("skipping non-Steam account: {}", issuer);
|
||||
continue;
|
||||
}
|
||||
let data = query
|
||||
.find(|(key, _)| key == "data")
|
||||
.context("missing data field")?
|
||||
.1;
|
||||
|
||||
trace!("data: {}", data);
|
||||
|
||||
let mut deser = serde_json::Deserializer::from_str(&data);
|
||||
let account = serde_path_to_error::deserialize(&mut deser)?;
|
||||
accounts.push(account);
|
||||
}
|
||||
Ok(accounts)
|
||||
}
|
|
@ -1,6 +1,6 @@
|
|||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use clap::{Parser, Subcommand, ValueEnum};
|
||||
use clap::{clap_derive::ArgEnum, Parser};
|
||||
use clap_complete::Shell;
|
||||
use secrecy::SecretString;
|
||||
use std::str::FromStr;
|
||||
|
@ -10,7 +10,6 @@ use crate::AccountManager;
|
|||
|
||||
pub mod code;
|
||||
pub mod completions;
|
||||
pub mod confirm;
|
||||
pub mod debug;
|
||||
pub mod decrypt;
|
||||
pub mod encrypt;
|
||||
|
@ -20,10 +19,10 @@ pub mod qr;
|
|||
pub mod qr_login;
|
||||
pub mod remove;
|
||||
pub mod setup;
|
||||
pub mod trade;
|
||||
|
||||
pub use code::CodeCommand;
|
||||
pub use completions::CompletionsCommand;
|
||||
pub use confirm::ConfirmCommand;
|
||||
pub use debug::DebugCommand;
|
||||
pub use decrypt::DecryptCommand;
|
||||
pub use encrypt::EncryptCommand;
|
||||
|
@ -33,6 +32,7 @@ pub use qr::QrCommand;
|
|||
pub use qr_login::QrLoginCommand;
|
||||
pub use remove::RemoveCommand;
|
||||
pub use setup::SetupCommand;
|
||||
pub use trade::TradeCommand;
|
||||
|
||||
/// A command that does not operate on the manifest or individual accounts.
|
||||
pub(crate) trait ConstCommand {
|
||||
|
@ -44,12 +44,7 @@ pub(crate) trait ManifestCommand<T>
|
|||
where
|
||||
T: Transport,
|
||||
{
|
||||
fn execute(
|
||||
&self,
|
||||
transport: T,
|
||||
manager: &mut AccountManager,
|
||||
args: &GlobalArgs,
|
||||
) -> anyhow::Result<()>;
|
||||
fn execute(&self, transport: T, manager: &mut AccountManager) -> anyhow::Result<()>;
|
||||
}
|
||||
|
||||
/// A command that operates on individual accounts.
|
||||
|
@ -62,7 +57,6 @@ where
|
|||
transport: T,
|
||||
manager: &mut AccountManager,
|
||||
accounts: Vec<Arc<Mutex<SteamGuardAccount>>>,
|
||||
args: &GlobalArgs,
|
||||
) -> anyhow::Result<()>;
|
||||
}
|
||||
|
||||
|
@ -98,13 +92,6 @@ pub(crate) struct GlobalArgs {
|
|||
long_help = "Select the account you want by steam username. Case-sensitive. By default, the first account in the manifest is selected."
|
||||
)]
|
||||
pub username: Option<String>,
|
||||
#[clap(
|
||||
long,
|
||||
conflicts_with = "all",
|
||||
help = "Steam account password. You really shouldn't use this if you can avoid it.",
|
||||
env = "STEAMGUARD_CLI_STEAM_PASSWORD"
|
||||
)]
|
||||
pub password: Option<SecretString>,
|
||||
#[clap(
|
||||
short,
|
||||
long,
|
||||
|
@ -127,7 +114,7 @@ pub(crate) struct GlobalArgs {
|
|||
help = "Specify your encryption passkey."
|
||||
)]
|
||||
pub passkey: Option<SecretString>,
|
||||
#[clap(short, long, value_enum, default_value_t=Verbosity::Info, help = "Set the log level. Be warned, trace is capable of printing sensitive data.")]
|
||||
#[clap(short, long, arg_enum, default_value_t=Verbosity::Info, help = "Set the log level. Be warned, trace is capable of printing sensitive data.")]
|
||||
pub verbosity: Verbosity,
|
||||
|
||||
#[cfg(feature = "updater")]
|
||||
|
@ -160,14 +147,13 @@ pub(crate) struct GlobalArgs {
|
|||
pub danger_accept_invalid_certs: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Subcommand)]
|
||||
#[derive(Debug, Clone, Parser)]
|
||||
pub(crate) enum Subcommands {
|
||||
Debug(DebugCommand),
|
||||
Completion(CompletionsCommand),
|
||||
Setup(SetupCommand),
|
||||
Import(ImportCommand),
|
||||
#[clap(alias = "trade")]
|
||||
Confirm(ConfirmCommand),
|
||||
Trade(TradeCommand),
|
||||
Remove(RemoveCommand),
|
||||
Encrypt(EncryptCommand),
|
||||
Decrypt(DecryptCommand),
|
||||
|
@ -177,7 +163,7 @@ pub(crate) enum Subcommands {
|
|||
QrLogin(QrLoginCommand),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, ValueEnum)]
|
||||
#[derive(Debug, Clone, Copy, ArgEnum)]
|
||||
pub(crate) enum Verbosity {
|
||||
Error = 0,
|
||||
Warn = 1,
|
||||
|
@ -223,14 +209,3 @@ impl From<Args> for CodeCommand {
|
|||
args.code
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn verify_cli() {
|
||||
use clap::CommandFactory;
|
||||
Args::command().debug_assert()
|
||||
}
|
||||
}
|
||||
|
|
|
@ -29,7 +29,6 @@ where
|
|||
transport: T,
|
||||
_manager: &mut AccountManager,
|
||||
accounts: Vec<Arc<Mutex<SteamGuardAccount>>>,
|
||||
_args: &GlobalArgs,
|
||||
) -> anyhow::Result<()> {
|
||||
let server_time = if self.offline {
|
||||
SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs()
|
||||
|
|
|
@ -5,12 +5,7 @@ use super::*;
|
|||
#[derive(Debug, Clone, Parser)]
|
||||
#[clap(about = "Generate shell completions")]
|
||||
pub struct CompletionsCommand {
|
||||
#[clap(
|
||||
short,
|
||||
long,
|
||||
value_enum,
|
||||
help = "The shell to generate completions for."
|
||||
)]
|
||||
#[clap(short, long, arg_enum, help = "The shell to generate completions for.")]
|
||||
pub shell: Shell,
|
||||
}
|
||||
|
||||
|
|
|
@ -12,12 +12,7 @@ impl<T> ManifestCommand<T> for DecryptCommand
|
|||
where
|
||||
T: Transport,
|
||||
{
|
||||
fn execute(
|
||||
&self,
|
||||
_transport: T,
|
||||
manager: &mut AccountManager,
|
||||
_args: &GlobalArgs,
|
||||
) -> anyhow::Result<()> {
|
||||
fn execute(&self, _transport: T, manager: &mut AccountManager) -> anyhow::Result<()> {
|
||||
load_accounts_with_prompts(manager)?;
|
||||
|
||||
#[cfg(feature = "keyring")]
|
||||
|
@ -30,7 +25,7 @@ where
|
|||
Err(e) => warn!("Failed to clear passkey from keyring: {}", e),
|
||||
}
|
||||
}
|
||||
for entry in manager.iter_mut() {
|
||||
for mut entry in manager.iter_mut() {
|
||||
entry.encryption = None;
|
||||
}
|
||||
manager.submit_passkey(None);
|
||||
|
|
|
@ -16,12 +16,7 @@ impl<T> ManifestCommand<T> for EncryptCommand
|
|||
where
|
||||
T: Transport,
|
||||
{
|
||||
fn execute(
|
||||
&self,
|
||||
_transport: T,
|
||||
manager: &mut AccountManager,
|
||||
_args: &GlobalArgs,
|
||||
) -> anyhow::Result<()> {
|
||||
fn execute(&self, _transport: T, manager: &mut AccountManager) -> anyhow::Result<()> {
|
||||
if !manager.has_passkey() {
|
||||
let passkey: Option<SecretString>;
|
||||
loop {
|
||||
|
@ -30,8 +25,9 @@ where
|
|||
error!("Passkey cannot be empty, try again.");
|
||||
continue;
|
||||
}
|
||||
let passkey_confirm = rpassword::prompt_password("Confirm encryption passkey: ")
|
||||
.map(SecretString::new)?;
|
||||
let passkey_confirm =
|
||||
rpassword::prompt_password_stdout("Confirm encryption passkey: ")
|
||||
.map(SecretString::new)?;
|
||||
if passkey1.expose_secret() == passkey_confirm.expose_secret() {
|
||||
passkey = Some(passkey1);
|
||||
break;
|
||||
|
|
|
@ -2,7 +2,7 @@ use std::path::Path;
|
|||
|
||||
use log::*;
|
||||
|
||||
use crate::{accountmanager::ManifestAccountImportError, AccountManager};
|
||||
use crate::AccountManager;
|
||||
|
||||
use super::*;
|
||||
|
||||
|
@ -11,6 +11,9 @@ use super::*;
|
|||
about = "Import an account with steamguard already set up. It must not be encrypted. If you haven't used steamguard-cli before, you probably don't need to use this command."
|
||||
)]
|
||||
pub struct ImportCommand {
|
||||
#[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>,
|
||||
}
|
||||
|
@ -19,51 +22,24 @@ impl<T> ManifestCommand<T> for ImportCommand
|
|||
where
|
||||
T: Transport,
|
||||
{
|
||||
fn execute(
|
||||
&self,
|
||||
_transport: T,
|
||||
manager: &mut AccountManager,
|
||||
_args: &GlobalArgs,
|
||||
) -> anyhow::Result<()> {
|
||||
let mut accounts_added = 0;
|
||||
fn execute(&self, _transport: T, manager: &mut AccountManager) -> anyhow::Result<()> {
|
||||
for file_path in self.files.iter() {
|
||||
debug!("loading entry: {:?}", file_path);
|
||||
match manager.import_account(file_path) {
|
||||
Ok(_) => {
|
||||
info!("Imported account: {}", &file_path);
|
||||
}
|
||||
Err(ManifestAccountImportError::AlreadyExists { .. }) => {
|
||||
warn!("Account already exists: {} -- Ignoring", &file_path);
|
||||
}
|
||||
Err(ManifestAccountImportError::DeserializationFailed(orig_err)) => {
|
||||
debug!("Falling back to external account import",);
|
||||
|
||||
let path = Path::new(&file_path);
|
||||
let accounts =
|
||||
match crate::accountmanager::migrate::load_and_upgrade_external_accounts(
|
||||
path,
|
||||
) {
|
||||
Ok(accounts) => accounts,
|
||||
Err(err) => {
|
||||
error!("Failed to import account: {} {}", &file_path, err);
|
||||
error!("The original error was: {}", orig_err);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
for account in accounts {
|
||||
manager.add_account(account);
|
||||
if self.sda {
|
||||
let path = Path::new(&file_path);
|
||||
let account = crate::accountmanager::migrate::load_and_upgrade_sda_account(path)?;
|
||||
manager.add_account(account);
|
||||
info!("Imported account: {}", &file_path);
|
||||
} else {
|
||||
match manager.import_account(file_path) {
|
||||
Ok(_) => {
|
||||
info!("Imported account: {}", &file_path);
|
||||
accounts_added += 1;
|
||||
}
|
||||
Err(err) => {
|
||||
bail!("Failed to import account: {} {}", &file_path, err);
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
bail!("Failed to import account: {} {}", &file_path, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
if accounts_added > 0 {
|
||||
info!("Imported {} accounts", accounts_added);
|
||||
}
|
||||
|
||||
manager.save()?;
|
||||
Ok(())
|
||||
|
|
|
@ -27,7 +27,6 @@ where
|
|||
_transport: T,
|
||||
_manager: &mut AccountManager,
|
||||
accounts: Vec<Arc<Mutex<SteamGuardAccount>>>,
|
||||
_args: &GlobalArgs,
|
||||
) -> anyhow::Result<()> {
|
||||
use anyhow::Context;
|
||||
|
||||
|
|
|
@ -1,10 +1,6 @@
|
|||
use std::{
|
||||
path::{Path, PathBuf},
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use log::*;
|
||||
use rqrr::PreparedImage;
|
||||
use steamguard::{QrApprover, QrApproverError};
|
||||
|
||||
use crate::AccountManager;
|
||||
|
@ -14,8 +10,11 @@ use super::*;
|
|||
#[derive(Debug, Clone, Parser)]
|
||||
#[clap(about = "Log in to Steam on another device using the QR code that it's displaying.")]
|
||||
pub struct QrLoginCommand {
|
||||
#[clap(flatten)]
|
||||
login_url_source: LoginUrlSource,
|
||||
#[clap(
|
||||
long,
|
||||
help = "The URL that would normally open in the Steam app. This is the URL that the QR code is displaying. It should start with \"https://s.team/...\""
|
||||
)]
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
impl<T> AccountCommand<T> for QrLoginCommand
|
||||
|
@ -27,7 +26,6 @@ where
|
|||
transport: T,
|
||||
_manager: &mut AccountManager,
|
||||
accounts: Vec<Arc<Mutex<SteamGuardAccount>>>,
|
||||
args: &GlobalArgs,
|
||||
) -> anyhow::Result<()> {
|
||||
ensure!(
|
||||
accounts.len() == 1,
|
||||
|
@ -39,29 +37,24 @@ where
|
|||
info!("Approving login to {}", account.account_name);
|
||||
|
||||
if account.tokens.is_none() {
|
||||
crate::do_login(transport.clone(), &mut account, args.password.clone())?;
|
||||
crate::do_login(transport.clone(), &mut account)?;
|
||||
}
|
||||
|
||||
let url = self.login_url_source.url()?;
|
||||
debug!("Using login URL to approve: {}", url);
|
||||
loop {
|
||||
let Some(tokens) = account.tokens.as_ref() else {
|
||||
error!(
|
||||
"No tokens found for {}. Can't approve login if we aren't logged in ourselves.",
|
||||
account.account_name
|
||||
);
|
||||
error!("No tokens found for {}. Can't approve login if we aren't logged in ourselves.", account.account_name);
|
||||
return Err(anyhow!("No tokens found for {}", account.account_name));
|
||||
};
|
||||
|
||||
let mut approver = QrApprover::new(transport.clone(), tokens);
|
||||
match approver.approve(&account, url.to_owned()) {
|
||||
match approver.approve(&account, &self.url) {
|
||||
Ok(_) => {
|
||||
info!("Login approved.");
|
||||
break;
|
||||
}
|
||||
Err(QrApproverError::Unauthorized) => {
|
||||
warn!("tokens are invalid. Attempting to log in again.");
|
||||
crate::do_login(transport.clone(), &mut account, args.password.clone())?;
|
||||
crate::do_login(transport.clone(), &mut account)?;
|
||||
}
|
||||
Err(e) => {
|
||||
error!("Failed to approve login: {}", e);
|
||||
|
@ -73,56 +66,3 @@ where
|
|||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, clap::Args)]
|
||||
#[group(required = true, multiple = false)]
|
||||
pub struct LoginUrlSource {
|
||||
/// The URL that would normally open in the Steam app. This is the URL that the QR code is displaying. It should start with \"https://s.team/...\"
|
||||
#[clap(long)]
|
||||
url: Option<String>,
|
||||
/// Path to an image file containing the QR code. The QR code will be scanned from this image.
|
||||
#[clap(long)]
|
||||
image: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl LoginUrlSource {
|
||||
fn url(&self) -> anyhow::Result<String> {
|
||||
match self {
|
||||
Self { url: Some(url), .. } => Ok(url.clone()),
|
||||
Self {
|
||||
image: Some(path), ..
|
||||
} => read_qr_image(path),
|
||||
_ => Err(anyhow!(
|
||||
"You must provide either a URL with --url or an image file with --image."
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_qr_image(path: &Path) -> anyhow::Result<String> {
|
||||
use image::io::Reader as ImageReader;
|
||||
let image = ImageReader::open(path)?.decode()?.to_luma8();
|
||||
let mut img = PreparedImage::prepare(image);
|
||||
let grids = img.detect_grids();
|
||||
for grid in grids {
|
||||
let (_meta, text) = grid.decode()?;
|
||||
// a rough validation that the QR code is a Steam login code
|
||||
if text.contains("s.team") {
|
||||
return Ok(text);
|
||||
}
|
||||
}
|
||||
Err(anyhow!("No Steam login url found in the QR code"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::Path;
|
||||
|
||||
#[test]
|
||||
fn test_read_qr_image() {
|
||||
let path = Path::new("src/fixtures/qr-codes/login-qr.png");
|
||||
let url = read_qr_image(path).unwrap();
|
||||
assert_eq!(url, "https://s.team/q/1/2372462679780599330");
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use log::*;
|
||||
use steamguard::{accountlinker::RemoveAuthenticatorError, transport::TransportError};
|
||||
use steamguard::{steamapi::TwoFactorClient, transport::TransportError, RemoveAuthenticatorError};
|
||||
|
||||
use crate::{errors::UserError, tui, AccountManager};
|
||||
|
||||
|
@ -20,7 +20,6 @@ where
|
|||
transport: T,
|
||||
manager: &mut AccountManager,
|
||||
accounts: Vec<Arc<Mutex<SteamGuardAccount>>>,
|
||||
args: &GlobalArgs,
|
||||
) -> anyhow::Result<()> {
|
||||
eprintln!(
|
||||
"This will remove the mobile authenticator from {} accounts: {}",
|
||||
|
@ -43,10 +42,11 @@ where
|
|||
let mut successful = vec![];
|
||||
for a in accounts {
|
||||
let mut account = a.lock().unwrap();
|
||||
let client = TwoFactorClient::new(transport.clone());
|
||||
|
||||
let mut revocation: Option<String> = None;
|
||||
loop {
|
||||
match account.remove_authenticator(transport.clone(), revocation.as_ref()) {
|
||||
match account.remove_authenticator(&client, revocation.as_ref()) {
|
||||
Ok(_) => {
|
||||
info!("Removed authenticator from {}", account.account_name);
|
||||
successful.push(account.account_name.clone());
|
||||
|
@ -54,7 +54,7 @@ where
|
|||
}
|
||||
Err(RemoveAuthenticatorError::TransportError(TransportError::Unauthorized)) => {
|
||||
error!("Account {} is not logged in", account.account_name);
|
||||
crate::do_login(transport.clone(), &mut account, args.password.clone())?;
|
||||
crate::do_login(transport.clone(), &mut account)?;
|
||||
continue;
|
||||
}
|
||||
Err(RemoveAuthenticatorError::IncorrectRevocationCode {
|
||||
|
@ -68,17 +68,17 @@ where
|
|||
error!("No attempts remaining, aborting!");
|
||||
break;
|
||||
}
|
||||
let code = tui::prompt_non_empty(format!(
|
||||
"Enter the revocation code for {}: ",
|
||||
account.account_name
|
||||
));
|
||||
eprint!("Enter the revocation code for {}: ", account.account_name);
|
||||
let code = tui::prompt();
|
||||
revocation = Some(code);
|
||||
}
|
||||
Err(RemoveAuthenticatorError::MissingRevocationCode) => {
|
||||
let code = tui::prompt_non_empty(format!(
|
||||
"Enter the revocation code for {}: ",
|
||||
error!(
|
||||
"Account {} does not have a revocation code",
|
||||
account.account_name
|
||||
));
|
||||
);
|
||||
eprint!("Enter the revocation code for {}: ", account.account_name);
|
||||
let code = tui::prompt();
|
||||
revocation = Some(code);
|
||||
}
|
||||
Err(err) => {
|
||||
|
@ -93,7 +93,7 @@ where
|
|||
}
|
||||
|
||||
for account_name in successful {
|
||||
manager.remove_account(&account_name);
|
||||
manager.remove_account(account_name);
|
||||
}
|
||||
|
||||
manager.save()?;
|
||||
|
|
|
@ -2,11 +2,8 @@ use log::*;
|
|||
use phonenumber::PhoneNumber;
|
||||
use secrecy::ExposeSecret;
|
||||
use steamguard::{
|
||||
accountlinker::{AccountLinkConfirmType, AccountLinkSuccess, RemoveAuthenticatorError},
|
||||
phonelinker::PhoneLinker,
|
||||
steamapi::PhoneClient,
|
||||
token::Tokens,
|
||||
AccountLinkError, AccountLinker, FinalizeLinkError,
|
||||
accountlinker::AccountLinkSuccess, phonelinker::PhoneLinker, steamapi::PhoneClient,
|
||||
token::Tokens, AccountLinkError, AccountLinker, FinalizeLinkError,
|
||||
};
|
||||
|
||||
use crate::{tui, AccountManager};
|
||||
|
@ -21,12 +18,7 @@ impl<T> ManifestCommand<T> for SetupCommand
|
|||
where
|
||||
T: Transport + Clone,
|
||||
{
|
||||
fn execute(
|
||||
&self,
|
||||
transport: T,
|
||||
manager: &mut AccountManager,
|
||||
args: &GlobalArgs,
|
||||
) -> anyhow::Result<()> {
|
||||
fn execute(&self, transport: T, manager: &mut AccountManager) -> anyhow::Result<()> {
|
||||
eprintln!("Log in to the account that you want to link to steamguard-cli");
|
||||
eprint!("Username: ");
|
||||
let username = tui::prompt().to_lowercase();
|
||||
|
@ -38,18 +30,19 @@ where
|
|||
);
|
||||
}
|
||||
info!("Logging in to {}", username);
|
||||
let tokens = crate::do_login_raw(transport.clone(), username, args.password.clone())
|
||||
let tokens = crate::do_login_raw(transport.clone(), username)
|
||||
.expect("Failed to log in. Account has not been linked.");
|
||||
|
||||
info!("Adding authenticator...");
|
||||
let mut linker = AccountLinker::new(transport.clone(), tokens);
|
||||
let link: AccountLinkSuccess;
|
||||
loop {
|
||||
match linker.link() {
|
||||
Ok(link) => {
|
||||
return Self::add_new_account(link, manager, account_name, linker);
|
||||
Ok(a) => {
|
||||
link = a;
|
||||
break;
|
||||
}
|
||||
Err(AccountLinkError::MustProvidePhoneNumber) => {
|
||||
// As of Dec 12, 2023, Steam no longer appears to require a phone number to add an authenticator. Keeping this code here just in case.
|
||||
eprintln!("Looks like you don't have a phone number on this account.");
|
||||
do_add_phone_number(transport.clone(), linker.tokens())?;
|
||||
}
|
||||
|
@ -57,49 +50,6 @@ where
|
|||
println!("Check your email and click the link.");
|
||||
tui::pause();
|
||||
}
|
||||
Err(AccountLinkError::AuthenticatorPresent) => {
|
||||
eprintln!("It looks like there's already an authenticator on this account. If you want to link it to steamguard-cli, you'll need to remove it first. If you remove it using your revocation code (R#####), you'll get a 15 day trade ban.");
|
||||
eprintln!("However, you can \"transfer\" the authenticator to steamguard-cli if you have access to the phone number associated with your account. This will cause you to get only a 2 day trade ban.");
|
||||
eprintln!("If you were using SDA or WinAuth, you can import it into steamguard-cli with the `import` command, and have no trade ban.");
|
||||
eprintln!("You can't have the same authenticator on steamguard-cli and the steam mobile app at the same time.");
|
||||
|
||||
eprintln!("\nHere are your options:");
|
||||
eprintln!("[T] Transfer authenticator to steamguard-cli (2 day trade ban)");
|
||||
eprintln!("[R] Revoke authenticator with revocation code (15 day trade ban)");
|
||||
eprintln!("[A] Abort setup");
|
||||
let answer = tui::prompt_char("What would you like to do?", "Tra");
|
||||
match answer {
|
||||
't' => return Self::transfer_new_account(linker, manager),
|
||||
'r' => {
|
||||
loop {
|
||||
let revocation_code =
|
||||
tui::prompt_non_empty("Enter your revocation code (R#####): ");
|
||||
match linker.remove_authenticator(Some(&revocation_code)) {
|
||||
Ok(_) => break,
|
||||
Err(RemoveAuthenticatorError::IncorrectRevocationCode {
|
||||
attempts_remaining,
|
||||
}) => {
|
||||
error!(
|
||||
"Revocation code was incorrect ({} attempts remaining)",
|
||||
attempts_remaining
|
||||
);
|
||||
if attempts_remaining == 0 {
|
||||
error!("No attempts remaining, aborting!");
|
||||
bail!("Failed to remove authenticator: no attempts remaining")
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
error!("Failed to remove authenticator: {}", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
info!("Aborting account linking.");
|
||||
return Err(AccountLinkError::AuthenticatorPresent.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
error!(
|
||||
"Failed to link authenticator. Account has not been linked. {}",
|
||||
|
@ -109,64 +59,39 @@ where
|
|||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SetupCommand {
|
||||
/// Add a new account to the manifest after linking has started.
|
||||
fn add_new_account<T>(
|
||||
link: AccountLinkSuccess,
|
||||
manager: &mut AccountManager,
|
||||
account_name: String,
|
||||
mut linker: AccountLinker<T>,
|
||||
) -> Result<(), anyhow::Error>
|
||||
where
|
||||
T: Transport + Clone,
|
||||
{
|
||||
let mut server_time = link.server_time();
|
||||
let phone_number_hint = link.phone_number_hint().to_owned();
|
||||
let confirm_type = link.confirm_type();
|
||||
manager.add_account(link.into_account());
|
||||
match manager.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);
|
||||
eprintln!(
|
||||
"Just in case, here is the account info. Save it somewhere just in case!\n{:#?}",
|
||||
manager.get_account(&account_name).unwrap().lock().unwrap()
|
||||
);
|
||||
"Just in case, here is the account info. Save it somewhere just in case!\n{:#?}",
|
||||
manager.get_account(&account_name).unwrap().lock().unwrap()
|
||||
);
|
||||
return Err(err);
|
||||
}
|
||||
}
|
||||
|
||||
let account_arc = manager
|
||||
.get_account(&account_name)
|
||||
.expect("account was not present in manifest");
|
||||
let mut account = account_arc.lock().unwrap();
|
||||
|
||||
eprintln!("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");
|
||||
let confirm_code = match confirm_type {
|
||||
AccountLinkConfirmType::Email => {
|
||||
eprintln!(
|
||||
"A code has been sent to the email address associated with this account."
|
||||
);
|
||||
tui::prompt_non_empty("Enter email code: ")
|
||||
}
|
||||
AccountLinkConfirmType::SMS => {
|
||||
eprintln!(
|
||||
"A code has been sent to your phone number ending in {}.",
|
||||
phone_number_hint
|
||||
);
|
||||
tui::prompt_non_empty("Enter SMS code: ")
|
||||
}
|
||||
AccountLinkConfirmType::Unknown(t) => {
|
||||
error!("Unknown link confirm type: {}", t);
|
||||
bail!("Unknown link confirm type: {}", t);
|
||||
}
|
||||
};
|
||||
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(server_time, &mut account, confirm_code.clone()) {
|
||||
match linker.finalize(server_time, &mut account, sms_code.clone()) {
|
||||
Ok(_) => break,
|
||||
Err(FinalizeLinkError::WantMore { server_time: s }) => {
|
||||
server_time = s;
|
||||
|
@ -184,20 +109,8 @@ impl SetupCommand {
|
|||
}
|
||||
}
|
||||
let revocation_code = account.revocation_code.clone();
|
||||
drop(account);
|
||||
info!("Verifying authenticator status...");
|
||||
let status =
|
||||
linker.query_status(&manager.get_account(&account_name).unwrap().lock().unwrap())?;
|
||||
if status.state() == 0 {
|
||||
debug!(
|
||||
"authenticator state: {} -- did not actually finalize",
|
||||
status.state()
|
||||
);
|
||||
debug!("full status: {:#?}", status);
|
||||
manager.remove_account(&account_name);
|
||||
manager.save()?;
|
||||
bail!("Authenticator finalization was unsuccessful. You may have entered the wrong confirm code in the previous step. Try again.");
|
||||
}
|
||||
drop(account); // explicitly drop the lock so we don't hang on the mutex
|
||||
|
||||
info!("Authenticator finalized.");
|
||||
match manager.save() {
|
||||
Ok(_) => {}
|
||||
|
@ -209,52 +122,12 @@ impl SetupCommand {
|
|||
return Err(err);
|
||||
}
|
||||
}
|
||||
|
||||
eprintln!(
|
||||
"Authenticator has been finalized. Please actually write down your revocation code: {}",
|
||||
revocation_code.expose_secret()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Transfer an existing authenticator to steamguard-cli.
|
||||
fn transfer_new_account<T>(
|
||||
mut linker: AccountLinker<T>,
|
||||
manager: &mut AccountManager,
|
||||
) -> anyhow::Result<()>
|
||||
where
|
||||
T: Transport + Clone,
|
||||
{
|
||||
info!("Transferring authenticator to steamguard-cli");
|
||||
linker.transfer_start()?;
|
||||
|
||||
let account: SteamGuardAccount;
|
||||
loop {
|
||||
let sms_code = tui::prompt_non_empty("Enter SMS code: ");
|
||||
match linker.transfer_finish(sms_code) {
|
||||
Ok(acc) => {
|
||||
account = acc;
|
||||
break;
|
||||
}
|
||||
Err(err) => {
|
||||
error!("Failed to transfer authenticator: {}", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
info!("Transfer successful, adding account to manifest");
|
||||
let revocation_code = account.revocation_code.clone();
|
||||
eprintln!(
|
||||
"Take a moment to write down your revocation code: {}",
|
||||
revocation_code.expose_secret()
|
||||
);
|
||||
|
||||
manager.add_account(account);
|
||||
|
||||
manager.save()?;
|
||||
|
||||
eprintln!(
|
||||
"Make sure you have your revocation code written down: {}",
|
||||
revocation_code.expose_secret()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
|
@ -9,12 +9,12 @@ use crate::{tui, AccountManager};
|
|||
use super::*;
|
||||
|
||||
#[derive(Debug, Clone, Parser)]
|
||||
#[clap(about = "Interactive interface for steam mobile confirmations")]
|
||||
pub struct ConfirmCommand {
|
||||
#[clap(about = "Interactive interface for trade confirmations")]
|
||||
pub struct TradeCommand {
|
||||
#[clap(
|
||||
short,
|
||||
long,
|
||||
help = "Accept all open mobile confirmations. Does not open interactive interface."
|
||||
help = "Accept all open trade confirmations. Does not open interactive interface."
|
||||
)]
|
||||
pub accept_all: bool,
|
||||
#[clap(
|
||||
|
@ -25,7 +25,7 @@ pub struct ConfirmCommand {
|
|||
pub fail_fast: bool,
|
||||
}
|
||||
|
||||
impl<T> AccountCommand<T> for ConfirmCommand
|
||||
impl<T> AccountCommand<T> for TradeCommand
|
||||
where
|
||||
T: Transport + Clone,
|
||||
{
|
||||
|
@ -34,32 +34,31 @@ where
|
|||
transport: T,
|
||||
manager: &mut AccountManager,
|
||||
accounts: Vec<Arc<Mutex<SteamGuardAccount>>>,
|
||||
args: &GlobalArgs,
|
||||
) -> anyhow::Result<()> {
|
||||
for a in accounts {
|
||||
let mut account = a.lock().unwrap();
|
||||
|
||||
if !account.is_logged_in() {
|
||||
info!("Account does not have tokens, logging in");
|
||||
crate::do_login(transport.clone(), &mut account, args.password.clone())?;
|
||||
crate::do_login(transport.clone(), &mut account)?;
|
||||
}
|
||||
|
||||
info!("{}: Checking for confirmations", account.account_name);
|
||||
info!("{}: Checking for trade confirmations", account.account_name);
|
||||
let confirmations: Vec<Confirmation>;
|
||||
loop {
|
||||
let confirmer = Confirmer::new(transport.clone(), &account);
|
||||
|
||||
match confirmer.get_confirmations() {
|
||||
match confirmer.get_trade_confirmations() {
|
||||
Ok(confs) => {
|
||||
confirmations = confs;
|
||||
break;
|
||||
}
|
||||
Err(ConfirmerError::InvalidTokens) => {
|
||||
info!("obtaining new tokens");
|
||||
crate::do_login(transport.clone(), &mut account, args.password.clone())?;
|
||||
crate::do_login(transport.clone(), &mut account)?;
|
||||
}
|
||||
Err(err) => {
|
||||
error!("Failed to get confirmations: {}", err);
|
||||
error!("Failed to get trade confirmations: {}", err);
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
|
@ -72,82 +71,38 @@ where
|
|||
|
||||
let confirmer = Confirmer::new(transport.clone(), &account);
|
||||
let mut any_failed = false;
|
||||
|
||||
fn submit_loop(
|
||||
f: impl Fn() -> Result<(), ConfirmerError>,
|
||||
fail_fast: bool,
|
||||
) -> Result<(), ConfirmerError> {
|
||||
let mut attempts = 0;
|
||||
loop {
|
||||
match f() {
|
||||
Ok(_) => break,
|
||||
Err(ConfirmerError::InvalidTokens) => {
|
||||
error!("Invalid tokens, but they should be valid already. This is weird, stopping.");
|
||||
return Err(ConfirmerError::InvalidTokens);
|
||||
}
|
||||
Err(ConfirmerError::NetworkFailure(err)) => {
|
||||
error!("{}", err);
|
||||
return Err(ConfirmerError::NetworkFailure(err));
|
||||
}
|
||||
Err(ConfirmerError::DeserializeError(err)) => {
|
||||
error!("Failed to deserialize the response, but the submission may have succeeded: {}", err);
|
||||
return Err(ConfirmerError::DeserializeError(err));
|
||||
}
|
||||
Err(err) => {
|
||||
warn!("submit confirmation result: {}", err);
|
||||
if fail_fast || attempts >= 3 {
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
attempts += 1;
|
||||
let wait = std::time::Duration::from_secs(3 * attempts);
|
||||
info!(
|
||||
"retrying in {} seconds (attempt {})",
|
||||
wait.as_secs(),
|
||||
attempts
|
||||
);
|
||||
std::thread::sleep(wait);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
if self.accept_all {
|
||||
info!("accepting all confirmations");
|
||||
match submit_loop(
|
||||
|| confirmer.accept_confirmations(&confirmations),
|
||||
self.fail_fast,
|
||||
) {
|
||||
match confirmer.accept_confirmations(&confirmations) {
|
||||
Ok(_) => {}
|
||||
Err(err) => {
|
||||
warn!("accept confirmation result: {}", err);
|
||||
any_failed = true;
|
||||
if self.fail_fast {
|
||||
return Err(err.into());
|
||||
}
|
||||
any_failed = true;
|
||||
}
|
||||
}
|
||||
} else if std::io::stdout().is_tty() {
|
||||
let (accept, deny) = tui::prompt_confirmation_menu(confirmations)?;
|
||||
match submit_loop(|| confirmer.accept_confirmations(&accept), self.fail_fast) {
|
||||
match confirmer.accept_confirmations(&accept) {
|
||||
Ok(_) => {}
|
||||
Err(err) => {
|
||||
warn!("accept confirmation result: {}", err);
|
||||
any_failed = true;
|
||||
if self.fail_fast {
|
||||
return Err(err.into());
|
||||
}
|
||||
any_failed = true;
|
||||
}
|
||||
}
|
||||
match submit_loop(|| confirmer.deny_confirmations(&deny), self.fail_fast) {
|
||||
match confirmer.deny_confirmations(&deny) {
|
||||
Ok(_) => {}
|
||||
Err(err) => {
|
||||
warn!("deny confirmation result: {}", err);
|
||||
any_failed = true;
|
||||
if self.fail_fast {
|
||||
return Err(err.into());
|
||||
}
|
||||
any_failed = true;
|
||||
}
|
||||
}
|
||||
} else {
|
|
@ -1,9 +1,7 @@
|
|||
use aes::cipher::block_padding::Pkcs7;
|
||||
use aes::cipher::{BlockDecryptMut, BlockEncryptMut, KeyIvInit};
|
||||
use aes::Aes256;
|
||||
use anyhow::Context;
|
||||
use argon2::Argon2;
|
||||
use base64::Engine;
|
||||
use log::*;
|
||||
|
||||
use super::*;
|
||||
|
@ -21,7 +19,7 @@ impl Argon2idAes256 {
|
|||
|
||||
fn get_encryption_key(passkey: &str, salt: &str) -> anyhow::Result<[u8; Self::KEY_SIZE_BYTES]> {
|
||||
let password_bytes = passkey.as_bytes();
|
||||
let salt_bytes = base64::engine::general_purpose::STANDARD.decode(salt)?;
|
||||
let salt_bytes = base64::decode(salt)?;
|
||||
let mut full_key: [u8; Self::KEY_SIZE_BYTES] = [0u8; Self::KEY_SIZE_BYTES];
|
||||
let deriver = Argon2::new(
|
||||
argon2::Algorithm::Argon2id,
|
||||
|
@ -42,14 +40,6 @@ impl Argon2idAes256 {
|
|||
)
|
||||
.expect("Unable to create Argon2 config.")
|
||||
}
|
||||
|
||||
fn decode_iv(&self) -> anyhow::Result<[u8; Self::IV_LENGTH]> {
|
||||
let mut iv = [0u8; Self::IV_LENGTH];
|
||||
base64::engine::general_purpose::STANDARD
|
||||
.decode_slice_unchecked(&self.iv, &mut iv)
|
||||
.context("decoding iv")?;
|
||||
Ok(iv)
|
||||
}
|
||||
}
|
||||
|
||||
impl EntryEncryptor for Argon2idAes256 {
|
||||
|
@ -60,8 +50,8 @@ impl EntryEncryptor for Argon2idAes256 {
|
|||
rng.fill(&mut salt);
|
||||
rng.fill(&mut iv);
|
||||
Argon2idAes256 {
|
||||
iv: base64::engine::general_purpose::STANDARD.encode(iv),
|
||||
salt: base64::engine::general_purpose::STANDARD.encode(salt),
|
||||
iv: base64::encode(iv),
|
||||
salt: base64::encode(salt),
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -75,11 +65,11 @@ impl EntryEncryptor for Argon2idAes256 {
|
|||
debug!("key derivation took: {:?}", start.elapsed());
|
||||
|
||||
let start = std::time::Instant::now();
|
||||
let iv = self.decode_iv()?;
|
||||
let cipher =
|
||||
cbc::Encryptor::<Aes256>::new_from_slices(&key, &iv).context("creating cipher")?;
|
||||
let mut iv = [0u8; Self::IV_LENGTH];
|
||||
base64::decode_config_slice(&self.iv, base64::STANDARD, &mut iv)?;
|
||||
let cipher = cbc::Encryptor::<Aes256>::new_from_slices(&key, &iv)?;
|
||||
let ciphertext = cipher.encrypt_padded_vec_mut::<Pkcs7>(&plaintext);
|
||||
let encoded = base64::engine::general_purpose::STANDARD.encode(ciphertext);
|
||||
let encoded = base64::encode(ciphertext);
|
||||
debug!("encryption took: {:?}", start.elapsed());
|
||||
Ok(encoded.as_bytes().to_vec())
|
||||
}
|
||||
|
@ -94,10 +84,10 @@ impl EntryEncryptor for Argon2idAes256 {
|
|||
debug!("key derivation took: {:?}", start.elapsed());
|
||||
|
||||
let start = std::time::Instant::now();
|
||||
let iv = self.decode_iv()?;
|
||||
let cipher =
|
||||
cbc::Decryptor::<Aes256>::new_from_slices(&key, &iv).context("creating cipher")?;
|
||||
let decoded = base64::engine::general_purpose::STANDARD.decode(ciphertext)?;
|
||||
let mut iv = [0u8; Self::IV_LENGTH];
|
||||
base64::decode_config_slice(&self.iv, base64::STANDARD, &mut iv)?;
|
||||
let cipher = cbc::Decryptor::<Aes256>::new_from_slices(&key, &iv)?;
|
||||
let decoded = base64::decode(ciphertext)?;
|
||||
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);
|
||||
|
@ -114,7 +104,7 @@ mod tests {
|
|||
#[test]
|
||||
fn test_encryption_key() {
|
||||
assert_eq!(
|
||||
base64::engine::general_purpose::STANDARD.encode(
|
||||
base64::encode(
|
||||
Argon2idAes256::get_encryption_key("password", "GMhL0N2hqXg=")
|
||||
.unwrap()
|
||||
.as_slice()
|
||||
|
@ -126,7 +116,7 @@ mod tests {
|
|||
#[test]
|
||||
fn test_encryption_key2() {
|
||||
assert_eq!(
|
||||
base64::engine::general_purpose::STANDARD.encode(
|
||||
base64::encode(
|
||||
Argon2idAes256::get_encryption_key("password", "wTzTE9A6aN8=")
|
||||
.unwrap()
|
||||
.as_slice()
|
||||
|
|
|
@ -1,8 +1,6 @@
|
|||
use aes::cipher::block_padding::Pkcs7;
|
||||
use aes::cipher::{BlockDecryptMut, BlockEncryptMut, KeyIvInit};
|
||||
use aes::Aes256;
|
||||
use anyhow::Context;
|
||||
use base64::Engine;
|
||||
use log::*;
|
||||
use sha1::Sha1;
|
||||
|
||||
|
@ -23,7 +21,7 @@ impl LegacySdaCompatible {
|
|||
|
||||
fn get_encryption_key(passkey: &str, salt: &str) -> anyhow::Result<[u8; Self::KEY_SIZE_BYTES]> {
|
||||
let password_bytes = passkey.as_bytes();
|
||||
let salt_bytes = base64::engine::general_purpose::STANDARD.decode(salt)?;
|
||||
let salt_bytes = base64::decode(salt)?;
|
||||
let mut full_key: [u8; Self::KEY_SIZE_BYTES] = [0u8; Self::KEY_SIZE_BYTES];
|
||||
pbkdf2::pbkdf2_hmac::<Sha1>(
|
||||
password_bytes,
|
||||
|
@ -33,14 +31,6 @@ impl LegacySdaCompatible {
|
|||
);
|
||||
Ok(full_key)
|
||||
}
|
||||
|
||||
fn decode_iv(&self) -> anyhow::Result<[u8; Self::IV_LENGTH]> {
|
||||
let mut iv = [0u8; Self::IV_LENGTH];
|
||||
base64::engine::general_purpose::STANDARD
|
||||
.decode_slice_unchecked(&self.iv, &mut iv)
|
||||
.context("decoding iv")?;
|
||||
Ok(iv)
|
||||
}
|
||||
}
|
||||
|
||||
impl EntryEncryptor for LegacySdaCompatible {
|
||||
|
@ -51,8 +41,8 @@ impl EntryEncryptor for LegacySdaCompatible {
|
|||
rng.fill(&mut salt);
|
||||
rng.fill(&mut iv);
|
||||
LegacySdaCompatible {
|
||||
iv: base64::engine::general_purpose::STANDARD.encode(iv),
|
||||
salt: base64::engine::general_purpose::STANDARD.encode(salt),
|
||||
iv: base64::encode(iv),
|
||||
salt: base64::encode(salt),
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -66,11 +56,11 @@ impl EntryEncryptor for LegacySdaCompatible {
|
|||
debug!("key derivation took: {:?}", start.elapsed());
|
||||
|
||||
let start = std::time::Instant::now();
|
||||
let iv = self.decode_iv()?;
|
||||
let cipher =
|
||||
cbc::Encryptor::<Aes256>::new_from_slices(&key, &iv).context("creating cipher")?;
|
||||
let mut iv = [0u8; Self::IV_LENGTH];
|
||||
base64::decode_config_slice(&self.iv, base64::STANDARD, &mut iv)?;
|
||||
let cipher = cbc::Encryptor::<Aes256>::new_from_slices(&key, &iv)?;
|
||||
let ciphertext = cipher.encrypt_padded_vec_mut::<Pkcs7>(&plaintext);
|
||||
let encoded = base64::engine::general_purpose::STANDARD.encode(ciphertext);
|
||||
let encoded = base64::encode(ciphertext);
|
||||
debug!("encryption took: {:?}", start.elapsed());
|
||||
Ok(encoded.as_bytes().to_vec())
|
||||
}
|
||||
|
@ -85,10 +75,10 @@ impl EntryEncryptor for LegacySdaCompatible {
|
|||
debug!("key derivation took: {:?}", start.elapsed());
|
||||
|
||||
let start = std::time::Instant::now();
|
||||
let iv = self.decode_iv()?;
|
||||
let cipher =
|
||||
cbc::Decryptor::<Aes256>::new_from_slices(&key, &iv).context("creating cipher")?;
|
||||
let decoded = base64::engine::general_purpose::STANDARD.decode(ciphertext)?;
|
||||
let mut iv = [0u8; Self::IV_LENGTH];
|
||||
base64::decode_config_slice(&self.iv, base64::STANDARD, &mut iv)?;
|
||||
let cipher = cbc::Decryptor::<Aes256>::new_from_slices(&key, &iv)?;
|
||||
let decoded = base64::decode(ciphertext)?;
|
||||
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);
|
||||
|
@ -110,8 +100,7 @@ mod tests {
|
|||
LegacySdaCompatible::get_encryption_key("password", "GMhL0N2hqXg=")
|
||||
.unwrap()
|
||||
.as_slice(),
|
||||
base64::engine::general_purpose::STANDARD
|
||||
.decode("KtiRa4/OxW83MlB6URf+Z8rAGj7CBY+pDlwD/NuVo6Y=")
|
||||
base64::decode("KtiRa4/OxW83MlB6URf+Z8rAGj7CBY+pDlwD/NuVo6Y=")
|
||||
.unwrap()
|
||||
.as_slice()
|
||||
);
|
||||
|
@ -120,8 +109,7 @@ mod tests {
|
|||
LegacySdaCompatible::get_encryption_key("password", "wTzTE9A6aN8=")
|
||||
.unwrap()
|
||||
.as_slice(),
|
||||
base64::engine::general_purpose::STANDARD
|
||||
.decode("Dqpej/3DqEat0roJaHmu3luYgDzRCUmzX94n4fqvWj8=")
|
||||
base64::decode("Dqpej/3DqEat0roJaHmu3luYgDzRCUmzX94n4fqvWj8=")
|
||||
.unwrap()
|
||||
.as_slice()
|
||||
);
|
||||
|
@ -152,8 +140,8 @@ mod tests {
|
|||
/// An insecure but reproducible strategy for generating encryption params.
|
||||
fn encryption_params()(salt in any::<[u8; LegacySdaCompatible::SALT_LENGTH]>(), iv in any::<[u8; LegacySdaCompatible::IV_LENGTH]>()) -> LegacySdaCompatible {
|
||||
LegacySdaCompatible {
|
||||
salt: base64::engine::general_purpose::STANDARD.encode(salt),
|
||||
iv: base64::engine::general_purpose::STANDARD.encode(iv),
|
||||
salt: base64::encode(salt),
|
||||
iv: base64::encode(iv),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1 +0,0 @@
|
|||
{"shared_secret":"zvIayp3JPvtvX/QGHqsqKBk/44s=","serial_number":"kljasfhds","revocation_code":"R12345","uri":"otpauth://totp/Steam:example?secret=ASDF&issuer=Steam","account_name":"example","token_gid":"jkkjlhkhjgf","identity_secret":"kjsdlwowiqe=","secret_1":"sklduhfgsdlkjhf=","status":1,"device_id":"android:99d2ad0e-4bad-4247-b111-26393aae0be3","Session":{"SessionID":"a;lskdjf","SteamLogin":"983498437543","SteamLoginSecure":"dlkjdsl;j%7C%32984730298","WebCookie":";lkjsed;klfjas98093","OAuthToken":"asdk;lf;dsjlkfd","SteamID":1234}}
|
|
@ -1 +0,0 @@
|
|||
{"encrypted":false,"first_run":true,"entries":[{"encryption_iv":null,"encryption_salt":null,"filename":"1234.maFile","steamid":1234}],"periodic_checking":false,"periodic_checking_interval":5,"periodic_checking_checkall":false,"auto_confirm_market_transactions":false,"auto_confirm_trades":false}
|
|
@ -1,14 +0,0 @@
|
|||
{
|
||||
"steamid": "76561199441992970",
|
||||
"shared_secret": "kSJa7hfbr8IvReG9/1Ax13BhTJA=",
|
||||
"serial_number": "5182004572898897156",
|
||||
"revocation_code": "R52260",
|
||||
"uri": "otpauth://totp/Steam:afarihm?secret=SERFV3QX3OX4EL2F4G676UBR25YGCTEQ&issuer=Steam",
|
||||
"server_time": "123",
|
||||
"account_name": "afarihm",
|
||||
"token_gid": "2d5a1b6cdbbfa9cc",
|
||||
"identity_secret": "f62XbJcml4r1j3NcFm0GGTtmcXw=",
|
||||
"secret_1": "BEelQHBr74ahsgiJbGArNV62/Bs=",
|
||||
"status": 1,
|
||||
"steamguard_scheme": "2"
|
||||
}
|
|
@ -1,2 +0,0 @@
|
|||
otpauth://totp/Steam:example?secret=ASDF&issuer=Steam&data=%7B%22shared%5Fsecret%22%3A%22zvIayp3JPvtvX%2FQGHqsqKBk%2F44s%3D%22%2C%22serial%5Fnumber%22%3A%22kljasfhds%22%2C%22revocation%5Fcode%22%3A%22R12345%22%2C%22uri%22%3A%22otpauth%3A%2F%2Ftotp%2FSteam%3Aexample%3Fsecret%3DASDF%26issuer%3DSteam%22%2C%22server%5Ftime%22%3A1602522478%2C%22account%5Fname%22%3A%22example%22%2C%22token%5Fgid%22%3A%22jkkjlhkhjgf%22%2C%22identity%5Fsecret%22%3A%22kjsdlwowiqe%3D%22%2C%22secret%5F1%22%3A%22sklduhfgsdlkjhf%3D%22%2C%22status%22%3A1%2C%22device%5Fid%22%3A%22android%3A99d2ad0e%2D4bad%2D4247%2Db111%2D26393aae0be3%22%2C%22fully%5Fenrolled%22%3Atrue%2C%22Session%22%3A%7B%22SessionID%22%3A%22a%3Blskdjf%22%2C%22SteamLogin%22%3A%22983498437543%22%2C%22SteamLoginSecure%22%3A%22dlkjdsl%3Bj%257C%2532984730298%22%2C%22WebCookie%22%3A%22%3Blkjsed%3Bklfjas98093%22%2C%22OAuthToken%22%3A%22asdk%3Blf%3Bdsjlkfd%22%2C%22SteamID%22%3A1234%7D%7D
|
||||
otpauth://totp/Steam:example2?secret=ASDF&issuer=Steam&data=%7B%22shared%5Fsecret%22%3A%22zvIayp3JPvtvX%2FQGHqsqKBk%2F44s%3D%22%2C%22serial%5Fnumber%22%3A%22kljasfhds%22%2C%22revocation%5Fcode%22%3A%22R56789%22%2C%22uri%22%3A%22otpauth%3A%2F%2Ftotp%2FSteam%3Aexample%3Fsecret%3DASDF%26issuer%3DSteam%22%2C%22server%5Ftime%22%3A1602522478%2C%22account%5Fname%22%3A%22example2%22%2C%22token%5Fgid%22%3A%22jkkjlhkhjgf%22%2C%22identity%5Fsecret%22%3A%22kjsdlwowiqe%3D%22%2C%22secret%5F1%22%3A%22sklduhfgsdlkjhf%3D%22%2C%22status%22%3A1%2C%22device%5Fid%22%3A%22android%3A99d2ad0e%2D4bad%2D4247%2Db111%2D26393aae0be3%22%2C%22fully%5Fenrolled%22%3Atrue%2C%22Session%22%3A%7B%22SessionID%22%3A%22a%3Blskdjf%22%2C%22SteamLogin%22%3A%22983498437543%22%2C%22SteamLoginSecure%22%3A%22dlkjdsl%3Bj%257C%2532984730298%22%2C%22WebCookie%22%3A%22%3Blkjsed%3Bklfjas98093%22%2C%22OAuthToken%22%3A%22asdk%3Blf%3Bdsjlkfd%22%2C%22SteamID%22%3A5678%7D%7D
|
Binary file not shown.
Before Width: | Height: | Size: 1.3 KiB |
78
src/login.rs
78
src/login.rs
|
@ -8,17 +8,14 @@ use steamguard::{
|
|||
steamapi::{self, AuthenticationClient},
|
||||
token::Tokens,
|
||||
transport::Transport,
|
||||
userlogin::UpdateAuthSessionError,
|
||||
DeviceDetails, LoginError, SteamGuardAccount, UserLogin,
|
||||
};
|
||||
|
||||
use crate::tui;
|
||||
|
||||
/// Performs a login, prompting for credentials if necessary.
|
||||
pub fn do_login<T: Transport + Clone>(
|
||||
transport: T,
|
||||
account: &mut SteamGuardAccount,
|
||||
password: Option<SecretString>,
|
||||
) -> anyhow::Result<()> {
|
||||
if let Some(tokens) = account.tokens.as_mut() {
|
||||
info!("Refreshing access token...");
|
||||
|
@ -46,11 +43,7 @@ pub fn do_login<T: Transport + Clone>(
|
|||
account.account_name = tui::prompt();
|
||||
}
|
||||
let _ = std::io::stdout().flush();
|
||||
let password = if let Some(p) = password {
|
||||
p
|
||||
} else {
|
||||
tui::prompt_password()?
|
||||
};
|
||||
let password = tui::prompt_password()?;
|
||||
if !password.expose_secret().is_empty() {
|
||||
debug!("password is present");
|
||||
} else {
|
||||
|
@ -71,14 +64,9 @@ pub fn do_login<T: Transport + Clone>(
|
|||
pub fn do_login_raw<T: Transport + Clone>(
|
||||
transport: T,
|
||||
username: String,
|
||||
password: Option<SecretString>,
|
||||
) -> anyhow::Result<Tokens> {
|
||||
let _ = std::io::stdout().flush();
|
||||
let password = if let Some(p) = password {
|
||||
p
|
||||
} else {
|
||||
tui::prompt_password()?
|
||||
};
|
||||
let password = tui::prompt_password()?;
|
||||
if !password.expose_secret().is_empty() {
|
||||
debug!("password is present");
|
||||
} else {
|
||||
|
@ -93,7 +81,6 @@ fn do_login_impl<T: Transport + Clone>(
|
|||
password: SecretString,
|
||||
account: Option<&SteamGuardAccount>,
|
||||
) -> anyhow::Result<Tokens> {
|
||||
debug!("starting login");
|
||||
let mut login = UserLogin::new(transport.clone(), build_device_details());
|
||||
|
||||
let mut password = password;
|
||||
|
@ -120,12 +107,6 @@ fn do_login_impl<T: Transport + Clone>(
|
|||
}
|
||||
}
|
||||
|
||||
debug!(
|
||||
"got {} confirmation methods: {:#?}",
|
||||
confirmation_methods.len(),
|
||||
confirmation_methods
|
||||
);
|
||||
|
||||
for method in confirmation_methods {
|
||||
match method.confirmation_type {
|
||||
EAuthSessionGuardType::k_EAuthSessionGuardType_DeviceConfirmation => {
|
||||
|
@ -142,52 +123,21 @@ fn do_login_impl<T: Transport + Clone>(
|
|||
eprintln!("Press enter when you have confirmed.");
|
||||
tui::pause();
|
||||
}
|
||||
EAuthSessionGuardType::k_EAuthSessionGuardType_DeviceCode
|
||||
| EAuthSessionGuardType::k_EAuthSessionGuardType_EmailCode => {
|
||||
let prompt = if method.confirmation_type
|
||||
== EAuthSessionGuardType::k_EAuthSessionGuardType_DeviceCode
|
||||
{
|
||||
"Enter the 2fa code from your device: "
|
||||
EAuthSessionGuardType::k_EAuthSessionGuardType_DeviceCode => {
|
||||
let code = if let Some(account) = account {
|
||||
debug!("Generating 2fa code...");
|
||||
let time = steamapi::get_server_time(transport)?.server_time();
|
||||
account.generate_code(time)
|
||||
} else {
|
||||
"Enter the 2fa code sent to your email: "
|
||||
eprint!("Enter the 2fa code from your device: ");
|
||||
tui::prompt().trim().to_owned()
|
||||
};
|
||||
let mut attempts = 0;
|
||||
loop {
|
||||
let code = if let Some(account) = account {
|
||||
debug!("Generating 2fa code...");
|
||||
let time = steamapi::get_server_time(transport.clone())?.server_time();
|
||||
account.generate_code(time)
|
||||
} else {
|
||||
tui::prompt_non_empty(prompt).trim().to_owned()
|
||||
};
|
||||
|
||||
match login.submit_steam_guard_code(method.confirmation_type, code) {
|
||||
Ok(_) => break,
|
||||
Err(err) => {
|
||||
error!("Failed to submit code: {}", err);
|
||||
|
||||
match err {
|
||||
UpdateAuthSessionError::TooManyAttempts
|
||||
| UpdateAuthSessionError::SessionExpired
|
||||
| UpdateAuthSessionError::InvalidGuardType => {
|
||||
error!("Error is unrecoverable. Aborting.");
|
||||
return Err(err.into());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
attempts += 1;
|
||||
debug!("Attempts: {}/3", attempts);
|
||||
if attempts >= 3 {
|
||||
error!("Too many failed attempts. Aborting.");
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
login.submit_steam_guard_code(method.confirmation_type, code)?;
|
||||
}
|
||||
EAuthSessionGuardType::k_EAuthSessionGuardType_None => {
|
||||
debug!("No login confirmation required. Proceeding with login.");
|
||||
continue;
|
||||
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);
|
||||
|
|
|
@ -86,7 +86,7 @@ fn run(args: commands::Args) -> anyhow::Result<()> {
|
|||
Subcommands::Import(args) => CommandType::Manifest(Box::new(args)),
|
||||
Subcommands::Encrypt(args) => CommandType::Manifest(Box::new(args)),
|
||||
Subcommands::Decrypt(args) => CommandType::Manifest(Box::new(args)),
|
||||
Subcommands::Confirm(args) => CommandType::Account(Box::new(args)),
|
||||
Subcommands::Trade(args) => CommandType::Account(Box::new(args)),
|
||||
Subcommands::Remove(args) => CommandType::Account(Box::new(args)),
|
||||
Subcommands::Code(args) => CommandType::Account(Box::new(args)),
|
||||
#[cfg(feature = "qr")]
|
||||
|
@ -162,7 +162,7 @@ fn run(args: commands::Args) -> anyhow::Result<()> {
|
|||
}
|
||||
let mut manager = AccountManager::from_manifest(manifest, mafiles_dir);
|
||||
manager.register_accounts(accounts);
|
||||
manager.submit_passkey(passkey.clone());
|
||||
manager.submit_passkey(globalargs.passkey.clone());
|
||||
manager.save()?;
|
||||
manager
|
||||
}
|
||||
|
@ -232,7 +232,7 @@ fn run(args: commands::Args) -> anyhow::Result<()> {
|
|||
let transport = WebApiTransport::new(http_client);
|
||||
|
||||
if let CommandType::Manifest(cmd) = cmd {
|
||||
cmd.execute(transport, &mut manager, &globalargs)?;
|
||||
cmd.execute(transport, &mut manager)?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
|
@ -269,7 +269,7 @@ fn run(args: commands::Args) -> anyhow::Result<()> {
|
|||
);
|
||||
|
||||
if let CommandType::Account(cmd) = cmd {
|
||||
return cmd.execute(transport, &mut manager, selected_accounts, &globalargs);
|
||||
return cmd.execute(transport, &mut manager, selected_accounts);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
|
33
src/tui.rs
33
src/tui.rs
|
@ -1,4 +1,3 @@
|
|||
use anyhow::Context;
|
||||
use crossterm::{
|
||||
cursor,
|
||||
event::{Event, KeyCode, KeyEvent, KeyModifiers},
|
||||
|
@ -7,7 +6,6 @@ use crossterm::{
|
|||
terminal::{Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen},
|
||||
QueueableCommand,
|
||||
};
|
||||
use log::debug;
|
||||
use secrecy::SecretString;
|
||||
use std::collections::HashSet;
|
||||
use std::io::{stderr, stdout, Write};
|
||||
|
@ -34,20 +32,9 @@ pub(crate) fn prompt() -> String {
|
|||
line
|
||||
}
|
||||
|
||||
pub(crate) fn prompt_non_empty(prompt_text: impl AsRef<str>) -> String {
|
||||
loop {
|
||||
eprint!("{}", prompt_text.as_ref());
|
||||
let input = prompt();
|
||||
if !input.is_empty() {
|
||||
return input;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Prompt the user for a single character response. Useful for asking yes or no questions.
|
||||
///
|
||||
/// `chars` should be all lowercase characters, with at most 1 uppercase character. The uppercase character is the default answer if no answer is provided.
|
||||
/// The selected character returned will always be lowercase.
|
||||
pub(crate) fn prompt_char(text: &str, chars: &str) -> char {
|
||||
loop {
|
||||
let _ = stderr().queue(Print(format!("{} [{}] ", text, chars)));
|
||||
|
@ -59,7 +46,10 @@ pub(crate) fn prompt_char(text: &str, chars: &str) -> char {
|
|||
}
|
||||
}
|
||||
|
||||
fn prompt_char_impl(input: impl Into<String>, chars: &str) -> anyhow::Result<char> {
|
||||
fn prompt_char_impl<T>(input: T, chars: &str) -> anyhow::Result<char>
|
||||
where
|
||||
T: Into<String>,
|
||||
{
|
||||
let uppers = chars.replace(char::is_lowercase, "");
|
||||
if uppers.len() > 1 {
|
||||
panic!("Invalid chars for prompt_char. Maximum 1 uppercase letter is allowed.");
|
||||
|
@ -255,21 +245,18 @@ pub(crate) fn pause() {
|
|||
}
|
||||
}
|
||||
|
||||
pub(crate) fn prompt_passkey() -> anyhow::Result<SecretString> {
|
||||
debug!("prompting for passkey");
|
||||
pub(crate) fn prompt_passkey() -> std::io::Result<SecretString> {
|
||||
loop {
|
||||
let raw = rpassword::prompt_password("Enter encryption passkey: ")
|
||||
.context("prompting for passkey")?;
|
||||
let raw = rpassword::prompt_password_stdout("Enter encryption passkey: ")?;
|
||||
if !raw.is_empty() {
|
||||
return Ok(SecretString::new(raw));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn prompt_password() -> anyhow::Result<SecretString> {
|
||||
debug!("prompting for password");
|
||||
pub(crate) fn prompt_password() -> std::io::Result<SecretString> {
|
||||
loop {
|
||||
let raw = rpassword::prompt_password("Password: ").context("prompting for password")?;
|
||||
let raw = rpassword::prompt_password_stdout("Password: ")?;
|
||||
if !raw.is_empty() {
|
||||
return Ok(SecretString::new(raw));
|
||||
}
|
||||
|
@ -301,7 +288,7 @@ mod prompt_char_tests {
|
|||
#[test]
|
||||
fn test_should_not_give_invalid() {
|
||||
let answer = prompt_char_impl("g", "yn");
|
||||
assert!(answer.is_err());
|
||||
assert!(matches!(answer, Err(_)));
|
||||
let answer = prompt_char_impl("n", "yn").unwrap();
|
||||
assert_eq!(answer, 'n');
|
||||
}
|
||||
|
@ -309,6 +296,6 @@ mod prompt_char_tests {
|
|||
#[test]
|
||||
fn test_should_not_give_multichar() {
|
||||
let answer = prompt_char_impl("yy", "yn");
|
||||
assert!(answer.is_err());
|
||||
assert!(matches!(answer, Err(_)));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,45 +1,40 @@
|
|||
[package]
|
||||
name = "steamguard"
|
||||
version = "0.14.0"
|
||||
version = "0.10.1"
|
||||
authors = ["Carson McManus <carson.mcmanus1@gmail.com>"]
|
||||
edition = "2021"
|
||||
edition = "2018"
|
||||
description = "Library for generating 2fa codes for Steam and responding to mobile confirmations."
|
||||
keywords = ["steam", "2fa", "steamguard", "authentication"]
|
||||
repository = "https://github.com/dyc3/steamguard-cli/tree/master/steamguard"
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
anyhow = "^1.0"
|
||||
sha1 = "^0.10"
|
||||
base64 = "^0.22.1"
|
||||
reqwest = { version = "0.12", default-features = false, features = [
|
||||
"blocking",
|
||||
"json",
|
||||
"cookies",
|
||||
"gzip",
|
||||
"rustls-tls",
|
||||
"multipart",
|
||||
] }
|
||||
hmac-sha1 = "^0.1"
|
||||
base64 = "0.13.0"
|
||||
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.9.2"
|
||||
rand = "0.8.4"
|
||||
cookie = "0.18"
|
||||
standback = "0.2.17" # required to fix a compilation error on a transient dependency
|
||||
cookie = "0.14"
|
||||
regex = "1"
|
||||
lazy_static = "1.4.0"
|
||||
uuid = { version = "1.8", features = ["v4"] }
|
||||
uuid = { version = "0.8", features = ["v4"] }
|
||||
log = "0.4.19"
|
||||
scraper = "0.12.0"
|
||||
maplit = "1.0.2"
|
||||
thiserror = "1.0.26"
|
||||
secrecy = { version = "0.8", features = ["serde"] }
|
||||
zeroize = { version = "^1.6.0", features = ["std", "zeroize_derive"] }
|
||||
protobuf = "3.2.0"
|
||||
protobuf-json-mapping = "3.2.0"
|
||||
hmac-sha256 = "1.1.7"
|
||||
phonenumber = "0.3"
|
||||
serde_path_to_error = "0.1.11"
|
||||
hmac = "^0.12"
|
||||
sha2 = "^0.10"
|
||||
num_enum = "0.7.2"
|
||||
|
||||
[build-dependencies]
|
||||
anyhow = "^1.0"
|
||||
|
|
|
@ -19,3 +19,5 @@ message CAuthentication_BeginAuthSessionViaCredentials_Request_BinaryGuardData {
|
|||
optional uint32 language = 11;
|
||||
optional int32 qos_level = 12 [default = 2, (description) = "[ENetQOSLevel] client-specified priority for this auth attempt"];
|
||||
}
|
||||
|
||||
message CTwoFactor_Time_Request {}
|
||||
|
|
|
@ -59,10 +59,9 @@ enum EPersonaStateFlag {
|
|||
|
||||
enum EContentCheckProvider {
|
||||
k_EContentCheckProvider_Invalid = 0;
|
||||
k_EContentCheckProvider_Google_DEPRECATED = 1;
|
||||
k_EContentCheckProvider_Google = 1;
|
||||
k_EContentCheckProvider_Amazon = 2;
|
||||
k_EContentCheckProvider_Local = 3;
|
||||
k_EContentCheckProvider_GoogleVertexAI = 4;
|
||||
}
|
||||
|
||||
enum EProfileCustomizationType {
|
||||
|
@ -90,7 +89,6 @@ enum EProfileCustomizationType {
|
|||
k_EProfileCustomizationTypeLoyaltyRewardReactions = 21;
|
||||
k_EProfileCustomizationTypeSingleArtworkShowcase = 22;
|
||||
k_EProfileCustomizationTypeAchievementsCompletionist = 23;
|
||||
k_EProfileCustomizationTypeReplay = 24;
|
||||
}
|
||||
|
||||
enum EPublishedFileStorageSystem {
|
||||
|
@ -115,32 +113,17 @@ enum ESDCardFormatStage {
|
|||
k_ESDCardFormatStage_Finalizing = 5;
|
||||
}
|
||||
|
||||
enum EStorageFormatStage {
|
||||
k_EStorageFormatStage_Invalid = 0;
|
||||
k_EStorageFormatStage_NotRunning = 1;
|
||||
k_EStorageFormatStage_Starting = 2;
|
||||
k_EStorageFormatStage_Testing = 3;
|
||||
k_EStorageFormatStage_Rescuing = 4;
|
||||
k_EStorageFormatStage_Formatting = 5;
|
||||
k_EStorageFormatStage_Finalizing = 6;
|
||||
}
|
||||
|
||||
enum ESystemFanControlMode {
|
||||
k_SystemFanControlMode_Invalid = 0;
|
||||
k_SystemFanControlMode_Disabled = 1;
|
||||
k_SystemFanControlMode_Default = 2;
|
||||
}
|
||||
|
||||
enum EStartupMovieVariant {
|
||||
k_EStartupMovieVariant_Invalid = 0;
|
||||
k_EStartupMovieVariant_Default = 1;
|
||||
k_EStartupMovieVariant_Orange = 2;
|
||||
}
|
||||
|
||||
enum EColorGamutLabelSet {
|
||||
k_ColorGamutLabelSet_Default = 0;
|
||||
k_ColorGamutLabelSet_sRGB_Native = 1;
|
||||
k_ColorGamutLabelSet_Native_sRGB_Boosted = 2;
|
||||
enum EColorProfile {
|
||||
k_EColorProfile_Invalid = 0;
|
||||
k_EColorProfile_Native = 1;
|
||||
k_EColorProfile_Standard = 2;
|
||||
k_EColorProfile_Vivid = 3;
|
||||
}
|
||||
|
||||
enum EBluetoothDeviceType {
|
||||
|
@ -223,52 +206,6 @@ enum EScalingFilter {
|
|||
k_EScalingFilter_NIS = 5;
|
||||
}
|
||||
|
||||
enum ESplitScalingFilter {
|
||||
k_ESplitScalingFilter_Invalid = 0;
|
||||
k_ESplitScalingFilter_Linear = 1;
|
||||
k_ESplitScalingFilter_Nearest = 2;
|
||||
k_ESplitScalingFilter_FSR = 3;
|
||||
k_ESplitScalingFilter_NIS = 4;
|
||||
}
|
||||
|
||||
enum ESplitScalingScaler {
|
||||
k_ESplitScalingScaler_Invalid = 0;
|
||||
k_ESplitScalingScaler_Auto = 1;
|
||||
k_ESplitScalingScaler_Integer = 2;
|
||||
k_ESplitScalingScaler_Fit = 3;
|
||||
k_ESplitScalingScaler_Fill = 4;
|
||||
k_ESplitScalingScaler_Stretch = 5;
|
||||
}
|
||||
|
||||
enum EGamescopeBlurMode {
|
||||
k_EGamescopeBlurMode_Disabled = 0;
|
||||
k_EGamescopeBlurMode_IfOccluded = 1;
|
||||
k_EGamescopeBlurMode_Always = 2;
|
||||
}
|
||||
|
||||
enum ESLSHelper {
|
||||
k_ESLSHelper_Invalid = 0;
|
||||
k_ESLSHelper_Minidump = 1;
|
||||
k_ESLSHelper_Kdump = 2;
|
||||
k_ESLSHelper_Journal = 3;
|
||||
k_ESLSHelper_Gpu = 4;
|
||||
k_ESLSHelper_SystemInfo = 5;
|
||||
}
|
||||
|
||||
enum EHDRVisualization {
|
||||
k_EHDRVisualization_None = 0;
|
||||
k_EHDRVisualization_Heatmap = 1;
|
||||
k_EHDRVisualization_Analysis = 2;
|
||||
k_EHDRVisualization_HeatmapExtended = 3;
|
||||
k_EHDRVisualization_HeatmapClassic = 4;
|
||||
}
|
||||
|
||||
enum EHDRToneMapOperator {
|
||||
k_EHDRToneMapOperator_Invalid = 0;
|
||||
k_EHDRToneMapOperator_Uncharted = 1;
|
||||
k_EHDRToneMapOperator_Reinhard = 2;
|
||||
}
|
||||
|
||||
enum ECPUGovernor {
|
||||
k_ECPUGovernor_Invalid = 0;
|
||||
k_ECPUGovernor_Perf = 1;
|
||||
|
@ -312,20 +249,6 @@ enum EStorageBlockFileSystemType {
|
|||
k_EStorageBlockFileSystemType_Ext4 = 3;
|
||||
}
|
||||
|
||||
enum EStorageDriveMediaType {
|
||||
k_EStorageDriveMediaType_Invalid = 0;
|
||||
k_EStorageDriveMediaType_Unknown = 1;
|
||||
k_EStorageDriveMediaType_HDD = 2;
|
||||
k_EStorageDriveMediaType_SSD = 3;
|
||||
k_EStorageDriveMediaType_Removable = 4;
|
||||
}
|
||||
|
||||
enum ESystemDisplayCompatibilityMode {
|
||||
k_ESystemDisplayCompatibilityMode_Invalid = 0;
|
||||
k_ESystemDisplayCompatibilityMode_None = 1;
|
||||
k_ESystemDisplayCompatibilityMode_MinimalBandwith = 2;
|
||||
}
|
||||
|
||||
enum ESteamDeckCompatibilityCategory {
|
||||
k_ESteamDeckCompatibilityCategory_Unknown = 0;
|
||||
k_ESteamDeckCompatibilityCategory_Unsupported = 1;
|
||||
|
@ -362,7 +285,6 @@ enum EOSBranch {
|
|||
k_EOSBranch_Beta = 3;
|
||||
k_EOSBranch_BetaCandidate = 4;
|
||||
k_EOSBranch_Main = 5;
|
||||
k_EOSBranch_Staging = 6;
|
||||
}
|
||||
|
||||
enum ECommunityItemClass {
|
||||
|
@ -383,7 +305,6 @@ enum ECommunityItemClass {
|
|||
k_ECommunityItemClass_AvatarFrame = 14;
|
||||
k_ECommunityItemClass_AnimatedAvatar = 15;
|
||||
k_ECommunityItemClass_SteamDeckKeyboardSkin = 16;
|
||||
k_ECommunityItemClass_SteamDeckStartupMovie = 17;
|
||||
}
|
||||
|
||||
enum ESteamDeckCompatibilityFeedback {
|
||||
|
@ -421,54 +342,3 @@ enum ESessionPersistence {
|
|||
k_ESessionPersistence_Ephemeral = 0;
|
||||
k_ESessionPersistence_Persistent = 1;
|
||||
}
|
||||
|
||||
enum ENewSteamAnnouncementState {
|
||||
k_ENewSteamAnnouncementState_Invalid = 0;
|
||||
k_ENewSteamAnnouncementState_AllRead = 1;
|
||||
k_ENewSteamAnnouncementState_NewAnnouncement = 2;
|
||||
k_ENewSteamAnnouncementState_FeaturedAnnouncement = 3;
|
||||
}
|
||||
|
||||
enum ECommentThreadType {
|
||||
k_ECommentThreadTypeInvalid = 0;
|
||||
k_ECommentThreadTypeScreenshot_Deprecated = 1;
|
||||
k_ECommentThreadTypeWorkshopAccount_Developer = 2;
|
||||
k_ECommentThreadTypeWorkshopAccount_Public = 3;
|
||||
k_ECommentThreadTypePublishedFile_Developer = 4;
|
||||
k_ECommentThreadTypePublishedFile_Public = 5;
|
||||
k_ECommentThreadTypeTest = 6;
|
||||
k_ECommentThreadTypeForumTopic = 7;
|
||||
k_ECommentThreadTypeRecommendation = 8;
|
||||
k_ECommentThreadTypeVideo_Deprecated = 9;
|
||||
k_ECommentThreadTypeProfile = 10;
|
||||
k_ECommentThreadTypeNewsPost = 11;
|
||||
k_ECommentThreadTypeClan = 12;
|
||||
k_ECommentThreadTypeClanAnnouncement = 13;
|
||||
k_ECommentThreadTypeClanEvent = 14;
|
||||
k_ECommentThreadTypeUserStatusPublished = 15;
|
||||
k_ECommentThreadTypeUserReceivedNewGame = 16;
|
||||
k_ECommentThreadTypePublishedFile_Announcement = 17;
|
||||
k_ECommentThreadTypeModeratorMessage = 18;
|
||||
k_ECommentThreadTypeClanCuratedApp = 19;
|
||||
k_ECommentThreadTypeQAndASession = 20;
|
||||
k_ECommentThreadTypeMax = 21;
|
||||
}
|
||||
|
||||
enum EBroadcastPermission {
|
||||
k_EBroadcastPermissionDisabled = 0;
|
||||
k_EBroadcastPermissionFriendsApprove = 1;
|
||||
k_EBroadcastPermissionFriendsAllowed = 2;
|
||||
k_EBroadcastPermissionPublic = 3;
|
||||
k_EBroadcastPermissionSubscribers = 4;
|
||||
}
|
||||
|
||||
enum EBroadcastEncoderSetting {
|
||||
k_EBroadcastEncoderBestQuality = 0;
|
||||
k_EBroadcastEncoderBestPerformance = 1;
|
||||
}
|
||||
|
||||
enum ECloudGamingPlatform {
|
||||
k_ECloudGamingPlatformNone = 0;
|
||||
k_ECloudGamingPlatformValve = 1;
|
||||
k_ECloudGamingPlatformNVIDIA = 2;
|
||||
}
|
|
@ -38,13 +38,20 @@ message CTwoFactor_AddAuthenticator_Response {
|
|||
optional bytes secret_1 = 9;
|
||||
optional int32 status = 10;
|
||||
optional string phone_number_hint = 11;
|
||||
optional int32 confirm_type = 12;
|
||||
}
|
||||
|
||||
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 {
|
||||
}
|
||||
|
||||
|
@ -125,10 +132,6 @@ message CTwoFactor_Status_Response {
|
|||
optional uint32 version = 14;
|
||||
}
|
||||
|
||||
message CTwoFactor_Time_Request {
|
||||
optional uint64 sender_time = 1;
|
||||
}
|
||||
|
||||
message CTwoFactor_Time_Response {
|
||||
optional uint64 server_time = 1;
|
||||
optional uint64 skew_tolerance_seconds = 2;
|
||||
|
@ -150,21 +153,25 @@ message CTwoFactor_UpdateTokenVersion_Request {
|
|||
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 (.NotImplemented) returns (.CTwoFactor_CreateEmergencyCodes_Response);
|
||||
rpc DestroyEmergencyCodes (.NotImplemented) returns (.CTwoFactor_DestroyEmergencyCodes_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 (.CTwoFactor_Time_Request) returns (.CTwoFactor_Time_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 (.NotImplemented) returns (.CTwoFactor_ValidateToken_Response);
|
||||
rpc ValidateToken (.CTwoFactor_ValidateToken_Request) returns (.CTwoFactor_ValidateToken_Response);
|
||||
}
|
||||
|
|
|
@ -28,20 +28,12 @@ enum EAuthSessionSecurityHistory {
|
|||
k_EAuthSessionSecurityHistory_NoPriorHistory = 2;
|
||||
}
|
||||
|
||||
enum ETokenRenewalType {
|
||||
k_ETokenRenewalType_None = 0;
|
||||
k_ETokenRenewalType_Allow = 1;
|
||||
}
|
||||
|
||||
enum EAuthTokenRevokeAction {
|
||||
k_EAuthTokenRevokeLogout = 0;
|
||||
k_EAuthTokenRevokePermanent = 1;
|
||||
k_EAuthTokenRevokeReplaced = 2;
|
||||
k_EAuthTokenRevokeSupport = 3;
|
||||
k_EAuthTokenRevokeConsume = 4;
|
||||
k_EAuthTokenRevokeNonRememberedLogout = 5;
|
||||
k_EAuthTokenRevokeNonRememberedPermanent = 6;
|
||||
k_EAuthTokenRevokeAutomatic = 7;
|
||||
}
|
||||
|
||||
enum EAuthTokenState {
|
||||
|
@ -70,8 +62,6 @@ message CAuthentication_DeviceDetails {
|
|||
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"];
|
||||
optional uint32 client_count = 5 [(description) = "For desktop clients, quantized number of users in history"];
|
||||
optional bytes machine_id = 6 [(description) = "Additional device context"];
|
||||
}
|
||||
|
||||
message CAuthentication_BeginAuthSessionViaQR_Request {
|
||||
|
@ -183,12 +173,10 @@ message CAuthentication_UpdateAuthSessionWithSteamGuardCode_Response {
|
|||
message CAuthentication_AccessToken_GenerateForApp_Request {
|
||||
optional string refresh_token = 1;
|
||||
optional fixed64 steamid = 2;
|
||||
optional .ETokenRenewalType renewal_type = 3 [default = k_ETokenRenewalType_None];
|
||||
}
|
||||
|
||||
message CAuthentication_AccessToken_GenerateForApp_Response {
|
||||
optional string access_token = 1;
|
||||
optional string refresh_token = 2;
|
||||
}
|
||||
|
||||
message CAuthentication_RefreshToken_Enumerate_Request {
|
||||
|
@ -240,14 +228,6 @@ message CAuthentication_MigrateMobileSession_Response {
|
|||
optional string access_token = 2;
|
||||
}
|
||||
|
||||
message CAuthentication_Token_Revoke_Request {
|
||||
optional string token = 1;
|
||||
optional .EAuthTokenRevokeAction revoke_action = 2 [default = k_EAuthTokenRevokePermanent, (description) = "Select between logout and logout-and-forget-machine"];
|
||||
}
|
||||
|
||||
message CAuthentication_Token_Revoke_Response {
|
||||
}
|
||||
|
||||
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"];
|
||||
|
@ -393,10 +373,6 @@ service Authentication {
|
|||
option (method_description) = "Migrates a WG token to an access and refresh token using a signature generated with the user's 2FA secret";
|
||||
}
|
||||
|
||||
rpc RevokeToken (.CAuthentication_Token_Revoke_Request) returns (.CAuthentication_Token_Revoke_Response) {
|
||||
option (method_description) = "Revoke a single token immediately, making it unable to renew or generate new access tokens";
|
||||
}
|
||||
|
||||
rpc RevokeRefreshToken (.CAuthentication_RefreshToken_Revoke_Request) returns (.CAuthentication_RefreshToken_Revoke_Response) {
|
||||
option (method_description) = "Mark the given refresh token as revoked";
|
||||
}
|
||||
|
|
|
@ -92,11 +92,6 @@ message CMsgGCRoutingProtoBufHeader {
|
|||
}
|
||||
|
||||
message CMsgProtoBufHeader {
|
||||
enum ESessionDisposition {
|
||||
k_ESessionDispositionNormal = 0;
|
||||
k_ESessionDispositionDisconnect = 1;
|
||||
}
|
||||
|
||||
optional fixed64 steamid = 1;
|
||||
optional int32 client_sessionid = 2;
|
||||
optional uint32 routing_appid = 3;
|
||||
|
@ -125,10 +120,6 @@ message CMsgProtoBufHeader {
|
|||
optional uint32 debug_source_string_index = 35;
|
||||
optional uint64 token_id = 36;
|
||||
optional .CMsgGCRoutingProtoBufHeader routing_gc = 37;
|
||||
optional .CMsgProtoBufHeader.ESessionDisposition session_disposition = 38 [default = k_ESessionDispositionNormal];
|
||||
optional string wg_token = 39;
|
||||
optional string webui_auth_key = 40;
|
||||
repeated int32 exclude_client_sessionids = 41;
|
||||
|
||||
oneof ip_addr {
|
||||
uint32 ip = 15;
|
||||
|
@ -154,7 +145,6 @@ message CMsgAuthTicket {
|
|||
optional uint32 ticket_crc = 6;
|
||||
optional bytes ticket = 7;
|
||||
optional bytes server_secret = 8;
|
||||
optional uint32 ticket_type = 9;
|
||||
}
|
||||
|
||||
message CCDDBAppDetailCommon {
|
||||
|
@ -312,8 +302,6 @@ message CPackageReservationStatus {
|
|||
optional bool expired = 6;
|
||||
optional uint32 time_expires = 7;
|
||||
optional uint32 time_reserved = 8;
|
||||
optional uint32 rtime_estimated_notification = 9;
|
||||
optional string notificaton_token = 10;
|
||||
}
|
||||
|
||||
message CMsgKeyValuePair {
|
||||
|
@ -324,12 +312,3 @@ message CMsgKeyValuePair {
|
|||
message CMsgKeyValueSet {
|
||||
repeated .CMsgKeyValuePair pairs = 1;
|
||||
}
|
||||
|
||||
message UserContentDescriptorPreferences {
|
||||
message ContentDescriptor {
|
||||
optional uint32 content_descriptorid = 1;
|
||||
optional uint32 timestamp_added = 2;
|
||||
}
|
||||
|
||||
repeated .UserContentDescriptorPreferences.ContentDescriptor content_descriptors_to_exclude = 1;
|
||||
}
|
||||
|
|
|
@ -99,11 +99,11 @@ message CMsgClientLogonResponse {
|
|||
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 string user_country = 16;
|
||||
optional fixed64 client_supplied_steamid = 20;
|
||||
optional string ip_country_code = 21;
|
||||
optional bytes parental_settings = 22;
|
||||
|
|
|
@ -1,15 +1,10 @@
|
|||
use crate::protobufs::service_twofactor::{
|
||||
CTwoFactor_AddAuthenticator_Request, CTwoFactor_FinalizeAddAuthenticator_Request,
|
||||
CTwoFactor_RemoveAuthenticatorViaChallengeContinue_Request,
|
||||
CTwoFactor_RemoveAuthenticatorViaChallengeStart_Request,
|
||||
CTwoFactor_RemoveAuthenticator_Request, CTwoFactor_Status_Request, CTwoFactor_Status_Response,
|
||||
};
|
||||
use crate::steamapi::twofactor::TwoFactorClient;
|
||||
use crate::token::TwoFactorSecret;
|
||||
use crate::transport::{Transport, TransportError};
|
||||
use crate::transport::Transport;
|
||||
use crate::{steamapi::EResult, token::Tokens, SteamGuardAccount};
|
||||
use anyhow::Context;
|
||||
use base64::Engine;
|
||||
use log::*;
|
||||
use thiserror::Error;
|
||||
|
||||
|
@ -45,10 +40,7 @@ where
|
|||
|
||||
pub fn link(&mut self) -> anyhow::Result<AccountLinkSuccess, AccountLinkError> {
|
||||
let access_token = self.tokens.access_token();
|
||||
let steam_id = access_token
|
||||
.decode()
|
||||
.context("decoding access token")?
|
||||
.steam_id();
|
||||
let steam_id = access_token.decode()?.steam_id();
|
||||
|
||||
let mut req = CTwoFactor_AddAuthenticator_Request::new();
|
||||
req.set_authenticator_type(1);
|
||||
|
@ -56,10 +48,7 @@ where
|
|||
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)
|
||||
.context("add authenticator request")?;
|
||||
let resp = self.client.add_authenticator(req, access_token)?;
|
||||
|
||||
if resp.result != EResult::OK {
|
||||
return Err(resp.result.into());
|
||||
|
@ -75,20 +64,15 @@ where
|
|||
uri: resp.take_uri().into(),
|
||||
shared_secret: TwoFactorSecret::from_bytes(resp.take_shared_secret()),
|
||||
token_gid: resp.take_token_gid(),
|
||||
identity_secret: base64::engine::general_purpose::STANDARD
|
||||
.encode(resp.take_identity_secret())
|
||||
.into(),
|
||||
identity_secret: base64::encode(resp.take_identity_secret()).into(),
|
||||
device_id: self.device_id.clone(),
|
||||
secret_1: base64::engine::general_purpose::STANDARD
|
||||
.encode(resp.take_secret_1())
|
||||
.into(),
|
||||
secret_1: base64::encode(resp.take_secret_1()).into(),
|
||||
tokens: Some(self.tokens.clone()),
|
||||
};
|
||||
let success = AccountLinkSuccess {
|
||||
account,
|
||||
server_time: resp.server_time(),
|
||||
phone_number_hint: resp.take_phone_number_hint(),
|
||||
confirm_type: resp.confirm_type().into(),
|
||||
};
|
||||
Ok(success)
|
||||
}
|
||||
|
@ -98,7 +82,7 @@ where
|
|||
&mut self,
|
||||
time: u64,
|
||||
account: &mut SteamGuardAccount,
|
||||
confirm_code: String,
|
||||
sms_code: String,
|
||||
) -> anyhow::Result<(), FinalizeLinkError> {
|
||||
let code = account.generate_code(time);
|
||||
|
||||
|
@ -109,8 +93,7 @@ where
|
|||
req.set_steamid(steam_id);
|
||||
req.set_authenticator_code(code);
|
||||
req.set_authenticator_time(time);
|
||||
req.set_activation_code(confirm_code);
|
||||
req.set_validate_sms_code(true);
|
||||
req.set_activation_code(sms_code);
|
||||
|
||||
let resp = self.client.finalize_authenticator(req, token)?;
|
||||
|
||||
|
@ -129,105 +112,6 @@ where
|
|||
self.finalized = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn query_status(
|
||||
&self,
|
||||
account: &SteamGuardAccount,
|
||||
) -> anyhow::Result<CTwoFactor_Status_Response> {
|
||||
let mut req = CTwoFactor_Status_Request::new();
|
||||
req.set_steamid(account.steam_id);
|
||||
|
||||
let resp = self.client.query_status(req, self.tokens.access_token())?;
|
||||
|
||||
Ok(resp.into_response_data())
|
||||
}
|
||||
|
||||
pub fn remove_authenticator(
|
||||
&self,
|
||||
revocation_code: Option<&String>,
|
||||
) -> Result<(), RemoveAuthenticatorError> {
|
||||
let Some(revocation_code) = revocation_code else {
|
||||
return Err(RemoveAuthenticatorError::MissingRevocationCode);
|
||||
};
|
||||
if revocation_code.is_empty() {
|
||||
return Err(RemoveAuthenticatorError::MissingRevocationCode);
|
||||
}
|
||||
let mut req = CTwoFactor_RemoveAuthenticator_Request::new();
|
||||
req.set_revocation_code(revocation_code.clone());
|
||||
let resp = self
|
||||
.client
|
||||
.remove_authenticator(req, self.tokens.access_token())?;
|
||||
|
||||
// returns EResult::TwoFactorCodeMismatch if the revocation code is incorrect
|
||||
if resp.result != EResult::OK && resp.result != EResult::TwoFactorCodeMismatch {
|
||||
return Err(resp.result.into());
|
||||
}
|
||||
let resp = resp.into_response_data();
|
||||
if !resp.success() {
|
||||
return Err(RemoveAuthenticatorError::IncorrectRevocationCode {
|
||||
attempts_remaining: resp.revocation_attempts_remaining(),
|
||||
});
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Begin the process of "transfering" a mobile authenticator from a different device to this device.
|
||||
///
|
||||
/// "Transfering" does not actually literally transfer the secrets from one device to another. Instead, it generates a new set of secrets on this device, and invalidates the old secrets on the other device. Call [`Self::transfer_finish`] to complete the process.
|
||||
pub fn transfer_start(&mut self) -> Result<(), TransferError> {
|
||||
let req = CTwoFactor_RemoveAuthenticatorViaChallengeStart_Request::new();
|
||||
let resp = self
|
||||
.client
|
||||
.remove_authenticator_via_challenge_start(req, self.tokens().access_token())?;
|
||||
if resp.result != EResult::OK {
|
||||
return Err(resp.result.into());
|
||||
}
|
||||
// the success field in the response is always None, so we can't check that
|
||||
// it appears to not be used at all
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Completes the process of "transfering" a mobile authenticator from a different device to this device.
|
||||
pub fn transfer_finish(
|
||||
&mut self,
|
||||
sms_code: impl AsRef<str>,
|
||||
) -> Result<SteamGuardAccount, TransferError> {
|
||||
let access_token = self.tokens.access_token();
|
||||
let steam_id = access_token
|
||||
.decode()
|
||||
.context("decoding access token")?
|
||||
.steam_id();
|
||||
let mut req = CTwoFactor_RemoveAuthenticatorViaChallengeContinue_Request::new();
|
||||
req.set_sms_code(sms_code.as_ref().to_owned());
|
||||
req.set_generate_new_token(true);
|
||||
let resp = self
|
||||
.client
|
||||
.remove_authenticator_via_challenge_continue(req, access_token)?;
|
||||
if resp.result != EResult::OK {
|
||||
return Err(resp.result.into());
|
||||
}
|
||||
let resp = resp.into_response_data();
|
||||
let mut resp = resp.replacement_token.clone().unwrap();
|
||||
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(),
|
||||
identity_secret: base64::engine::general_purpose::STANDARD
|
||||
.encode(resp.take_identity_secret())
|
||||
.into(),
|
||||
device_id: self.device_id.clone(),
|
||||
secret_1: base64::engine::general_purpose::STANDARD
|
||||
.encode(resp.take_secret_1())
|
||||
.into(),
|
||||
tokens: Some(self.tokens.clone()),
|
||||
};
|
||||
Ok(account)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
|
@ -235,7 +119,6 @@ pub struct AccountLinkSuccess {
|
|||
account: SteamGuardAccount,
|
||||
server_time: u64,
|
||||
phone_number_hint: String,
|
||||
confirm_type: AccountLinkConfirmType,
|
||||
}
|
||||
|
||||
impl AccountLinkSuccess {
|
||||
|
@ -254,28 +137,6 @@ impl AccountLinkSuccess {
|
|||
pub fn phone_number_hint(&self) -> &str {
|
||||
&self.phone_number_hint
|
||||
}
|
||||
|
||||
pub fn confirm_type(&self) -> AccountLinkConfirmType {
|
||||
self.confirm_type
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[repr(i32)]
|
||||
pub enum AccountLinkConfirmType {
|
||||
SMS = 1,
|
||||
Email = 3,
|
||||
Unknown(i32),
|
||||
}
|
||||
|
||||
impl From<i32> for AccountLinkConfirmType {
|
||||
fn from(i: i32) -> Self {
|
||||
match i {
|
||||
1 => AccountLinkConfirmType::SMS,
|
||||
3 => AccountLinkConfirmType::Email,
|
||||
_ => AccountLinkConfirmType::Unknown(i),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn generate_device_id() -> String {
|
||||
|
@ -339,44 +200,3 @@ impl From<EResult> for FinalizeLinkError {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum RemoveAuthenticatorError {
|
||||
#[error("Missing revocation code")]
|
||||
MissingRevocationCode,
|
||||
#[error("Incorrect revocation code, {attempts_remaining} attempts remaining")]
|
||||
IncorrectRevocationCode { attempts_remaining: u32 },
|
||||
#[error("Transport error: {0}")]
|
||||
TransportError(#[from] TransportError),
|
||||
#[error("Steam returned an enexpected result: {0:?}")]
|
||||
UnknownEResult(EResult),
|
||||
#[error("Unexpected error: {0}")]
|
||||
Unknown(#[from] anyhow::Error),
|
||||
}
|
||||
|
||||
impl From<EResult> for RemoveAuthenticatorError {
|
||||
fn from(e: EResult) -> Self {
|
||||
Self::UnknownEResult(e)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum TransferError {
|
||||
#[error("Provided SMS code was incorrect.")]
|
||||
BadSmsCode,
|
||||
#[error("Failed to send request to Steam: {0:?}")]
|
||||
Transport(#[from] crate::transport::TransportError),
|
||||
#[error("Steam returned an unexpected error code: {0:?}")]
|
||||
UnknownEResult(EResult),
|
||||
#[error(transparent)]
|
||||
Unknown(#[from] anyhow::Error),
|
||||
}
|
||||
|
||||
impl From<EResult> for TransferError {
|
||||
fn from(result: EResult) -> Self {
|
||||
match result {
|
||||
EResult::SMSCodeFailed => TransferError::BadSmsCode,
|
||||
r => TransferError::UnknownEResult(r),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,7 +1,6 @@
|
|||
use serde::Deserialize;
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[allow(dead_code)]
|
||||
pub struct OAuthData {
|
||||
pub oauth_token: String,
|
||||
pub steamid: String,
|
||||
|
|
|
@ -3,3 +3,5 @@ mod login;
|
|||
mod phone_ajax;
|
||||
|
||||
pub use i_authentication_service::*;
|
||||
pub use login::*;
|
||||
pub use phone_ajax::*;
|
||||
|
|
|
@ -1,7 +1,6 @@
|
|||
use std::borrow::Cow;
|
||||
|
||||
use base64::Engine;
|
||||
use hmac::{Hmac, Mac};
|
||||
use hmacsha1::hmac_sha1;
|
||||
use log::*;
|
||||
use reqwest::{
|
||||
cookie::CookieStore,
|
||||
|
@ -10,7 +9,6 @@ use reqwest::{
|
|||
};
|
||||
use secrecy::ExposeSecret;
|
||||
use serde::Deserialize;
|
||||
use sha1::Sha1;
|
||||
|
||||
use crate::{
|
||||
steamapi::{self},
|
||||
|
@ -82,7 +80,7 @@ where
|
|||
cookies
|
||||
}
|
||||
|
||||
pub fn get_confirmations(&self) -> Result<Vec<Confirmation>, ConfirmerError> {
|
||||
pub fn get_trade_confirmations(&self) -> Result<Vec<Confirmation>, ConfirmerError> {
|
||||
let cookies = self.build_cookie_jar();
|
||||
let client = self.transport.innner_http_client()?;
|
||||
|
||||
|
@ -109,11 +107,7 @@ where
|
|||
return Err(ConfirmerError::InvalidTokens);
|
||||
}
|
||||
if !body.success {
|
||||
if let Some(msg) = body.message {
|
||||
return Err(ConfirmerError::RemoteFailureWithMessage(msg));
|
||||
} else {
|
||||
return Err(ConfirmerError::RemoteFailure);
|
||||
}
|
||||
return Err(anyhow!("Server responded with failure.").into());
|
||||
}
|
||||
Ok(body.conf)
|
||||
}
|
||||
|
@ -166,11 +160,7 @@ where
|
|||
return Err(ConfirmerError::InvalidTokens);
|
||||
}
|
||||
if !body.success {
|
||||
if let Some(msg) = body.message {
|
||||
return Err(ConfirmerError::RemoteFailureWithMessage(msg));
|
||||
} else {
|
||||
return Err(ConfirmerError::RemoteFailure);
|
||||
}
|
||||
return Err(anyhow!("Server responded with failure.").into());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
@ -245,11 +235,7 @@ where
|
|||
return Err(ConfirmerError::InvalidTokens);
|
||||
}
|
||||
if !body.success {
|
||||
if let Some(msg) = body.message {
|
||||
return Err(ConfirmerError::RemoteFailureWithMessage(msg));
|
||||
} else {
|
||||
return Err(ConfirmerError::RemoteFailure);
|
||||
}
|
||||
return Err(anyhow!("Server responded with failure.").into());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
@ -328,10 +314,6 @@ pub enum ConfirmerError {
|
|||
NetworkFailure(#[from] reqwest::Error),
|
||||
#[error("Failed to deserialize response: {0}")]
|
||||
DeserializeError(#[from] serde_path_to_error::Error<serde_json::Error>),
|
||||
#[error("Remote failure: Valve's server responded with a failure and did not elaborate any further. This is likely not a steamguard-cli bug, Steam's confirmation API is just unreliable. Wait a bit and try again.")]
|
||||
RemoteFailure,
|
||||
#[error("Remote failure: Valve's server responded with a failure and said: {0}")]
|
||||
RemoteFailureWithMessage(String),
|
||||
#[error("Unknown error: {0}")]
|
||||
Unknown(#[from] anyhow::Error),
|
||||
}
|
||||
|
@ -367,27 +349,34 @@ impl Confirmation {
|
|||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, num_enum::FromPrimitive)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
|
||||
#[repr(u32)]
|
||||
#[serde(from = "u32")]
|
||||
/// Source: https://github.com/SteamDatabase/SteamTracking/blob/6e7797e69b714c59f4b5784780b24753c17732ba/Structs/enums.steamd#L1607-L1616
|
||||
/// There are also some additional undocumented types.
|
||||
/// Source: <https://github.com/SteamDatabase/SteamTracking/blob/6e7797e69b714c59f4b5784780b24753c17732ba/Structs/enums.steamd#L1607-L1616>
|
||||
pub enum ConfirmationType {
|
||||
Test = 1,
|
||||
/// Occurs when sending a trade offer or accepting a received trade offer, only when there is items on the user's side
|
||||
Trade = 2,
|
||||
/// Occurs when selling an item on the Steam community market
|
||||
MarketSell = 3,
|
||||
FeatureOptOut = 4,
|
||||
/// Occurs when changing the phone number associated with the account
|
||||
PhoneNumberChange = 5,
|
||||
AccountRecovery = 6,
|
||||
/// Occurs when a new web API key is created via https://steamcommunity.com/dev/apikey
|
||||
ApiKeyCreation = 9,
|
||||
#[num_enum(catch_all)]
|
||||
Unknown(u32),
|
||||
}
|
||||
|
||||
impl From<u32> for ConfirmationType {
|
||||
fn from(text: u32) -> Self {
|
||||
match text {
|
||||
1 => ConfirmationType::Test,
|
||||
2 => ConfirmationType::Trade,
|
||||
3 => ConfirmationType::MarketSell,
|
||||
4 => ConfirmationType::FeatureOptOut,
|
||||
5 => ConfirmationType::PhoneNumberChange,
|
||||
6 => ConfirmationType::AccountRecovery,
|
||||
v => ConfirmationType::Unknown(v),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct ConfirmationListResponse {
|
||||
pub success: bool,
|
||||
|
@ -395,17 +384,13 @@ pub struct ConfirmationListResponse {
|
|||
pub needauth: Option<bool>,
|
||||
#[serde(default)]
|
||||
pub conf: Vec<Confirmation>,
|
||||
#[serde(default)]
|
||||
pub message: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[derive(Debug, Clone, Copy, Deserialize)]
|
||||
pub struct SendConfirmationResponse {
|
||||
pub success: bool,
|
||||
#[serde(default)]
|
||||
pub needsauth: Option<bool>,
|
||||
#[serde(default)]
|
||||
pub message: Option<String>,
|
||||
}
|
||||
|
||||
fn build_time_bytes(time: u64) -> [u8; 8] {
|
||||
|
@ -417,15 +402,12 @@ fn generate_confirmation_hash_for_time(
|
|||
tag: &str,
|
||||
identity_secret: impl AsRef<[u8]>,
|
||||
) -> String {
|
||||
let decode: &[u8] = &base64::engine::general_purpose::STANDARD
|
||||
.decode(identity_secret)
|
||||
.unwrap();
|
||||
let mut mac = Hmac::<Sha1>::new_from_slice(decode).unwrap();
|
||||
mac.update(&build_time_bytes(time));
|
||||
mac.update(tag.as_bytes());
|
||||
let result = mac.finalize();
|
||||
let hash = result.into_bytes();
|
||||
base64::engine::general_purpose::STANDARD.encode(hash)
|
||||
let decode: &[u8] = &base64::decode(identity_secret).unwrap();
|
||||
let time_bytes = build_time_bytes(time);
|
||||
let tag_bytes = tag.as_bytes();
|
||||
let array = [&time_bytes, tag_bytes].concat();
|
||||
let hash = hmac_sha1(decode, &array);
|
||||
base64::encode(hash)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
use crate::token::TwoFactorSecret;
|
||||
use accountlinker::RemoveAuthenticatorError;
|
||||
use crate::protobufs::service_twofactor::CTwoFactor_RemoveAuthenticator_Request;
|
||||
use crate::steamapi::EResult;
|
||||
use crate::{steamapi::twofactor::TwoFactorClient, token::TwoFactorSecret};
|
||||
pub use accountlinker::{AccountLinkError, AccountLinker, FinalizeLinkError};
|
||||
pub use confirmation::*;
|
||||
pub use qrapprover::{QrApprover, QrApproverError};
|
||||
|
@ -31,6 +32,7 @@ pub mod userlogin;
|
|||
|
||||
extern crate base64;
|
||||
extern crate cookie;
|
||||
extern crate hmacsha1;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SteamGuardAccount {
|
||||
|
@ -95,21 +97,56 @@ impl SteamGuardAccount {
|
|||
|
||||
/// Removes the mobile authenticator from the steam account. If this operation succeeds, this object can no longer be considered valid.
|
||||
/// Returns whether or not the operation was successful.
|
||||
///
|
||||
/// A convenience method for [`AccountLinker::remove_authenticator`].
|
||||
pub fn remove_authenticator(
|
||||
pub fn remove_authenticator<T: Transport>(
|
||||
&self,
|
||||
transport: impl Transport,
|
||||
client: &TwoFactorClient<T>,
|
||||
revocation_code: Option<&String>,
|
||||
) -> Result<(), RemoveAuthenticatorError> {
|
||||
if !matches!(revocation_code, Some(_)) && self.revocation_code.expose_secret().is_empty() {
|
||||
return Err(RemoveAuthenticatorError::MissingRevocationCode);
|
||||
}
|
||||
let Some(tokens) = &self.tokens else {
|
||||
return Err(RemoveAuthenticatorError::TransportError(
|
||||
TransportError::Unauthorized,
|
||||
));
|
||||
return Err(RemoveAuthenticatorError::TransportError(TransportError::Unauthorized));
|
||||
};
|
||||
let revocation_code =
|
||||
Some(revocation_code.unwrap_or_else(|| self.revocation_code.expose_secret()));
|
||||
let linker = AccountLinker::new(transport, tokens.clone());
|
||||
linker.remove_authenticator(revocation_code)
|
||||
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())?;
|
||||
|
||||
// returns EResult::TwoFactorCodeMismatch if the revocation code is incorrect
|
||||
if resp.result != EResult::OK && resp.result != EResult::TwoFactorCodeMismatch {
|
||||
return Err(resp.result.into());
|
||||
}
|
||||
let resp = resp.into_response_data();
|
||||
if !resp.success() {
|
||||
return Err(RemoveAuthenticatorError::IncorrectRevocationCode {
|
||||
attempts_remaining: resp.revocation_attempts_remaining(),
|
||||
});
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum RemoveAuthenticatorError {
|
||||
#[error("Missing revocation code")]
|
||||
MissingRevocationCode,
|
||||
#[error("Incorrect revocation code, {attempts_remaining} attempts remaining")]
|
||||
IncorrectRevocationCode { attempts_remaining: u32 },
|
||||
#[error("Transport error: {0}")]
|
||||
TransportError(#[from] TransportError),
|
||||
#[error("Steam returned an enexpected result: {0:?}")]
|
||||
UnknownEResult(EResult),
|
||||
#[error("Unexpected error: {0}")]
|
||||
Unknown(#[from] anyhow::Error),
|
||||
}
|
||||
|
||||
impl From<EResult> for RemoveAuthenticatorError {
|
||||
fn from(e: EResult) -> Self {
|
||||
Self::UnknownEResult(e)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -24,7 +24,6 @@ impl Zeroize for Ip_addr {
|
|||
|
||||
#[cfg(test)]
|
||||
mod parse_tests {
|
||||
use base64::Engine;
|
||||
use protobuf::Message;
|
||||
|
||||
use super::steammessages_auth_steamclient::CAuthentication_GetPasswordRSAPublicKey_Request;
|
||||
|
@ -35,7 +34,7 @@ mod parse_tests {
|
|||
req.set_account_name("hydrastar2".to_owned());
|
||||
|
||||
let bytes = req.write_to_bytes().unwrap();
|
||||
let s = base64::engine::general_purpose::URL_SAFE.encode(bytes);
|
||||
let s = base64::encode_config(bytes, base64::URL_SAFE);
|
||||
assert_eq!(s, "CgpoeWRyYXN0YXIy");
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,7 +1,5 @@
|
|||
use hmac::{Hmac, Mac};
|
||||
use log::debug;
|
||||
use reqwest::IntoUrl;
|
||||
use sha2::Sha256;
|
||||
|
||||
use crate::{
|
||||
protobufs::steammessages_auth_steamclient::CAuthentication_UpdateAuthSessionWithMobileConfirmation_Request,
|
||||
|
@ -69,12 +67,12 @@ fn build_signature(
|
|||
steam_id: u64,
|
||||
challenge: &Challenge,
|
||||
) -> [u8; 32] {
|
||||
let mut mac = Hmac::<Sha256>::new_from_slice(shared_secret.expose_secret()).unwrap();
|
||||
mac.update(&challenge.version.to_le_bytes());
|
||||
mac.update(&challenge.client_id.to_le_bytes());
|
||||
mac.update(&steam_id.to_le_bytes());
|
||||
let result = mac.finalize();
|
||||
result.into_bytes().into()
|
||||
let mut data = Vec::<u8>::with_capacity(18);
|
||||
data.extend_from_slice(&challenge.version.to_le_bytes());
|
||||
data.extend_from_slice(&challenge.client_id.to_le_bytes());
|
||||
data.extend_from_slice(&steam_id.to_le_bytes());
|
||||
|
||||
hmac_sha256::HMAC::mac(data, shared_secret.expose_secret())
|
||||
}
|
||||
|
||||
fn parse_challenge_url(challenge_url: impl IntoUrl) -> Result<Challenge, QrApproverError> {
|
||||
|
|
|
@ -4,6 +4,7 @@ pub mod twofactor;
|
|||
|
||||
use crate::transport::Transport;
|
||||
use crate::{protobufs::service_twofactor::CTwoFactor_Time_Response, token::Jwt};
|
||||
use reqwest::Url;
|
||||
use serde::Deserialize;
|
||||
|
||||
pub use self::authentication::AuthenticationClient;
|
||||
|
@ -11,6 +12,7 @@ pub use self::phone::PhoneClient;
|
|||
pub use self::twofactor::TwoFactorClient;
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
|
|
|
@ -11,7 +11,7 @@ const SERVICE_NAME: &str = "IAuthenticationService";
|
|||
|
||||
use super::{ApiRequest, ApiResponse, BuildableRequest};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Debug)]
|
||||
pub struct AuthenticationClient<T>
|
||||
where
|
||||
T: Transport,
|
||||
|
|
|
@ -3,6 +3,7 @@ use crate::transport::{Transport, TransportError};
|
|||
|
||||
use super::{ApiRequest, ApiResponse, BuildableRequest};
|
||||
|
||||
use crate::protobufs::custom::CTwoFactor_Time_Request;
|
||||
use crate::protobufs::service_twofactor::*;
|
||||
|
||||
const SERVICE_NAME: &str = "ITwoFactorService";
|
||||
|
@ -69,45 +70,6 @@ where
|
|||
Ok(resp)
|
||||
}
|
||||
|
||||
pub fn remove_authenticator_via_challenge_start(
|
||||
&self,
|
||||
req: CTwoFactor_RemoveAuthenticatorViaChallengeStart_Request,
|
||||
access_token: &Jwt,
|
||||
) -> Result<ApiResponse<CTwoFactor_RemoveAuthenticatorViaChallengeStart_Response>, TransportError>
|
||||
{
|
||||
let req = ApiRequest::new(SERVICE_NAME, "RemoveAuthenticatorViaChallengeStart", 1, req)
|
||||
.with_access_token(access_token);
|
||||
let resp = self
|
||||
.transport
|
||||
.send_request::<CTwoFactor_RemoveAuthenticatorViaChallengeStart_Request, CTwoFactor_RemoveAuthenticatorViaChallengeStart_Response>(
|
||||
req,
|
||||
)?;
|
||||
Ok(resp)
|
||||
}
|
||||
|
||||
pub fn remove_authenticator_via_challenge_continue(
|
||||
&self,
|
||||
req: CTwoFactor_RemoveAuthenticatorViaChallengeContinue_Request,
|
||||
access_token: &Jwt,
|
||||
) -> Result<
|
||||
ApiResponse<CTwoFactor_RemoveAuthenticatorViaChallengeContinue_Response>,
|
||||
TransportError,
|
||||
> {
|
||||
let req = ApiRequest::new(
|
||||
SERVICE_NAME,
|
||||
"RemoveAuthenticatorViaChallengeContinue",
|
||||
1,
|
||||
req,
|
||||
)
|
||||
.with_access_token(access_token);
|
||||
let resp = self
|
||||
.transport
|
||||
.send_request::<CTwoFactor_RemoveAuthenticatorViaChallengeContinue_Request, CTwoFactor_RemoveAuthenticatorViaChallengeContinue_Response>(
|
||||
req,
|
||||
)?;
|
||||
Ok(resp)
|
||||
}
|
||||
|
||||
pub fn query_status(
|
||||
&self,
|
||||
req: CTwoFactor_Status_Request,
|
||||
|
@ -147,13 +109,5 @@ macro_rules! impl_buildable_req {
|
|||
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_RemoveAuthenticatorViaChallengeStart_Request,
|
||||
true
|
||||
);
|
||||
impl_buildable_req!(
|
||||
CTwoFactor_RemoveAuthenticatorViaChallengeContinue_Request,
|
||||
true
|
||||
);
|
||||
impl_buildable_req!(CTwoFactor_Status_Request, true);
|
||||
impl_buildable_req!(CTwoFactor_Time_Request, false);
|
||||
|
|
|
@ -1,8 +1,5 @@
|
|||
use base64::Engine;
|
||||
use hmac::{Hmac, Mac};
|
||||
use secrecy::{ExposeSecret, Secret, SecretString};
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
use sha1::Sha1;
|
||||
use std::convert::TryInto;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
|
@ -26,10 +23,7 @@ impl TwoFactorSecret {
|
|||
|
||||
pub fn parse_shared_secret(secret: String) -> anyhow::Result<Self> {
|
||||
ensure!(!secret.is_empty(), "unable to parse empty shared secret");
|
||||
let result: [u8; 20] = base64::engine::general_purpose::STANDARD
|
||||
.decode(secret)?
|
||||
.try_into()
|
||||
.unwrap();
|
||||
let result: [u8; 20] = base64::decode(secret)?.try_into().unwrap();
|
||||
Ok(Self(result.into()))
|
||||
}
|
||||
|
||||
|
@ -40,11 +34,9 @@ impl TwoFactorSecret {
|
|||
86, 87, 88, 89,
|
||||
];
|
||||
|
||||
let mut mac = Hmac::<Sha1>::new_from_slice(self.0.expose_secret()).unwrap();
|
||||
// this effectively makes it so that it creates a new code every 30 seconds.
|
||||
mac.update(&build_time_bytes(time / 30u64));
|
||||
let result = mac.finalize();
|
||||
let hashed_data = result.into_bytes();
|
||||
let time_bytes: [u8; 8] = build_time_bytes(time / 30u64);
|
||||
let hashed_data = hmacsha1::hmac_sha1(self.0.expose_secret(), &time_bytes);
|
||||
let mut code_array: [u8; 5] = [0; 5];
|
||||
let b = (hashed_data[19] & 0xF) as usize;
|
||||
let mut code_point: i32 = ((hashed_data[b] & 0x7F) as i32) << 24
|
||||
|
@ -71,11 +63,7 @@ impl Serialize for TwoFactorSecret {
|
|||
where
|
||||
S: Serializer,
|
||||
{
|
||||
serializer.serialize_str(
|
||||
base64::engine::general_purpose::STANDARD
|
||||
.encode(self.0.expose_secret())
|
||||
.as_str(),
|
||||
)
|
||||
serializer.serialize_str(base64::encode(self.0.expose_secret()).as_str())
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -160,7 +148,7 @@ fn decode_jwt(jwt: impl AsRef<str>) -> anyhow::Result<SteamJwtData> {
|
|||
ensure!(parts.len() == 3, "Invalid JWT");
|
||||
|
||||
let data = parts[1];
|
||||
let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(data)?;
|
||||
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)
|
||||
|
@ -259,13 +247,4 @@ mod tests {
|
|||
assert_eq!(data.sub, "76561199155706892");
|
||||
assert_eq!(data.jti, "18C5_22B3F431_CDF6A");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_decode_jwt_2() {
|
||||
let sample: Jwt = "eyAidHlwIjogIkpXVCIsICJhbGciOiAiRWREU0EiIH0.eyAiaXNzIjogInI6MTRCM18yMkZEQjg0RF9BMjJDRCIsICJzdWIiOiAiNzY1NjExOTk0NDE5OTI5NzAiLCAiYXVkIjogWyAid2ViIiwgIm1vYmlsZSIgXSwgImV4cCI6IDE2OTE3NTc5MzUsICJuYmYiOiAxNjgzMDMxMDUxLCAiaWF0IjogMTY5MTY3MTA1MSwgImp0aSI6ICIxNTI1XzIyRkRCOUJBXzZBRDkwIiwgIm9hdCI6IDE2OTE2NzEwNTEsICJydF9leHAiOiAxNzEwMDExNjg5LCAicGVyIjogMCwgImlwX3N1YmplY3QiOiAiMTA0LjI0Ni4xMjUuMTQxIiwgImlwX2NvbmZpcm1lciI6ICIxMDQuMjQ2LjEyNS4xNDEiIH0.ncqc5TpVlD05lnZvy8c3Bkx70gXDvQQXN0iG5Z4mOLgY_rwasXIJXnR-X4JczT8PmZ2v5cisW5VRHAdfsz_8CA".to_owned().into();
|
||||
let data = sample.decode().expect("Failed to decode JWT");
|
||||
|
||||
assert_eq!(data.aud, vec!["web", "mobile"]);
|
||||
assert_eq!(data.sub, "76561199441992970");
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,10 +1,15 @@
|
|||
use log::{debug, trace};
|
||||
use protobuf::MessageFull;
|
||||
use reqwest::blocking::multipart::Form;
|
||||
use reqwest::{blocking::multipart::Form, Url};
|
||||
|
||||
use super::{Transport, TransportError};
|
||||
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, Clone)]
|
||||
pub struct WebApiTransport {
|
||||
client: reqwest::blocking::Client,
|
||||
|
@ -38,10 +43,7 @@ impl Transport for WebApiTransport {
|
|||
let mut req = self.client.request(Req::method(), &url);
|
||||
|
||||
req = if Req::method() == reqwest::Method::GET {
|
||||
let encoded = encode_msg(
|
||||
apireq.request_data(),
|
||||
base64::engine::general_purpose::URL_SAFE,
|
||||
)?;
|
||||
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()));
|
||||
|
@ -51,10 +53,7 @@ impl Transport for WebApiTransport {
|
|||
if let Some(access_token) = apireq.access_token() {
|
||||
req = req.query(&[("access_token", access_token)]);
|
||||
}
|
||||
let encoded = encode_msg(
|
||||
apireq.request_data(),
|
||||
base64::engine::general_purpose::STANDARD,
|
||||
)?;
|
||||
let encoded = encode_msg(apireq.request_data(), base64::STANDARD)?;
|
||||
let form = Form::new().text("input_protobuf_encoded", encoded);
|
||||
req.multipart(form)
|
||||
};
|
||||
|
@ -120,9 +119,9 @@ impl Transport for WebApiTransport {
|
|||
}
|
||||
}
|
||||
|
||||
fn encode_msg<T: MessageFull>(msg: &T, engine: impl base64::Engine) -> anyhow::Result<String> {
|
||||
fn encode_msg<T: MessageFull>(msg: &T, config: base64::Config) -> anyhow::Result<String> {
|
||||
let bytes = msg.write_to_bytes()?;
|
||||
let b64 = engine.encode(bytes);
|
||||
let b64 = base64::encode_config(bytes, config);
|
||||
Ok(b64)
|
||||
}
|
||||
|
||||
|
@ -139,13 +138,12 @@ mod tests {
|
|||
};
|
||||
|
||||
use super::*;
|
||||
use base64::{engine::general_purpose::STANDARD, Engine};
|
||||
|
||||
#[test]
|
||||
fn test_parse_poll_response() {
|
||||
let sample = b"GuUDZXlBaWRIbHdJam9nSWtwWFZDSXNJQ0poYkdjaU9pQWlSV1JFVTBFaUlIMC5leUFpYVhOeklqb2dJbk4wWldGdElpd2dJbk4xWWlJNklDSTNOalUyTVRFNU9URTFOVGN3TmpnNU1pSXNJQ0poZFdRaU9pQmJJQ0ozWldJaUxDQWljbVZ1WlhjaUxDQWlaR1Z5YVhabElpQmRMQ0FpWlhod0lqb2dNVGN3TlRBeE1UazFOU3dnSW01aVppSTZJREUyTnpnME5qUTRNemNzSUNKcFlYUWlPaUF4TmpnM01UQTBPRE0zTENBaWFuUnBJam9nSWpFNFF6VmZNakpDTTBZME16RmZRMFJHTmtFaUxDQWliMkYwSWpvZ01UWTROekV3TkRnek55d2dJbkJsY2lJNklERXNJQ0pwY0Y5emRXSnFaV04wSWpvZ0lqWTVMakV5TUM0eE16WXVNVEkwSWl3Z0ltbHdYMk52Ym1acGNtMWxjaUk2SUNJMk9TNHhNakF1TVRNMkxqRXlOQ0lnZlEuR3A1VFBqOXBHUWJ4SXpXREROQ1NQOU9rS1lTZXduV0JFOEUtY1ZxalFxcVQ1M0FzRTRya213OER5TThoVXJ4T0VQQ1dDWHdyYkRVcmgxOTlSempQRHci/gNleUFpZEhsd0lqb2dJa3BYVkNJc0lDSmhiR2NpT2lBaVJXUkVVMEVpSUgwLmV5QWlhWE56SWpvZ0luSTZNVGhETlY4eU1rSXpSalF6TVY5RFJFWTJRU0lzSUNKemRXSWlPaUFpTnpZMU5qRXhPVGt4TlRVM01EWTRPVElpTENBaVlYVmtJam9nV3lBaWQyVmlJaUJkTENBaVpYaHdJam9nTVRZNE56RTVNamM0T0N3Z0ltNWlaaUk2SURFMk56ZzBOalE0TXpjc0lDSnBZWFFpT2lBeE5qZzNNVEEwT0RNM0xDQWlhblJwSWpvZ0lqRXlSREZmTWpKQ00wVTROekZmT1RaRk5EQWlMQ0FpYjJGMElqb2dNVFk0TnpFd05EZ3pOeXdnSW5KMFgyVjRjQ0k2SURFM01EVXdNVEU1TlRVc0lDSndaWElpT2lBd0xDQWlhWEJmYzNWaWFtVmpkQ0k2SUNJMk9TNHhNakF1TVRNMkxqRXlOQ0lzSUNKcGNGOWpiMjVtYVhKdFpYSWlPaUFpTmprdU1USXdMakV6Tmk0eE1qUWlJSDAuMVNnUEotSVZuWEp6Nk9nSW1udUdOQ0hMbEJTcGdvc0Z0UkxoOV9iVVBHQ1RaMmFtRWY2ZTZVYkJzVWZ3bnlYbEdFdG5LSHhPemhibTdLNzBwVFhEQ0EoADIKaHlkcmFzdGFyMg==";
|
||||
|
||||
let bytes = STANDARD.decode(sample).unwrap();
|
||||
let bytes = base64::decode_config(sample, base64::STANDARD).unwrap();
|
||||
|
||||
let resp: CAuthentication_PollAuthSessionStatus_Response = decode_msg(&bytes).unwrap();
|
||||
|
||||
|
@ -156,7 +154,7 @@ mod tests {
|
|||
fn parse_get_public_rsa_response() {
|
||||
let sample = b"CoAEYjYyMGI1ZWNhMWIxMjgyYjkxYzZkZmZkYWFhOWI0ODI0YjlhNmRiYmEyZDVmYjc0ODcxNDczZDc1MDYxNGEzNWM4ODQ3NDYzZTEyNjAwNTJmNzZlNTYxMDM5ODdlN2U3NGJkMWZjZGRjYWJhMDVmZGM5OTBjMWIyNmQ2ZDg5MGM2MTEzZmRkNTZmMmQ1YmZjNzU4ODhlMzZhNTM2NjM3N2IzZTE3ZTJiZWM5MjhlNGY4MmE1YzY0NGYxZTZlMTk3NzZkNjIzMDIxYjhmYTA0MGRjNWE5YjY0M2I0N2I5YmVhMjM2YmEyZjM4ODVjM2ZlNWVhNjMzZThlNjJjNGE1YTY4NjNmMzNiMzdlMTQ4M2MwZTUzZTg4ODIzMGFkNTVjNzg5ZmU4Y2NkMjVjNzdiMTkxOTg0ZThjN2JmNWYzNzY2MjI0OGI1NWVmOWM1OGY3NDM5YjA4ZjNhNWJiNzljNTc5ZDE5M2I3NzhmMzFiY2IwYTA3MmVhZWYxOGEyYjljZDY2M2VmYmY2YmRiZDU3MGEyMTNiOTIxNTc4ODk0MjJkMDY3ODFiNTVkY2VjYjQ4NjA4MjUyMmUzZWQyOWM4MjExYzQ5N2Q1YjNhYTk2OGM2MDY1YWFhZTNhNGVmYzZiMGJjNDYyMzMxNmVmYTUxN2JjNzRiZDYzODcxMWU4ZWYSBjAxMDAwMRiQn6Ly3wk=";
|
||||
|
||||
let bytes = STANDARD.decode(sample).unwrap();
|
||||
let bytes = base64::decode_config(sample, base64::STANDARD).unwrap();
|
||||
|
||||
let resp: CAuthentication_GetPasswordRSAPublicKey_Response = decode_msg(&bytes).unwrap();
|
||||
|
||||
|
@ -167,11 +165,11 @@ mod tests {
|
|||
fn test_decode_encode_roundtrip() {
|
||||
let sample = b"EgpoeWRyYXN0YXIyGtgCRUxaNTBXdHM2Z0kxWlZaVjl6bzRJNFBEcEhTMGRZR3RSNzJPbytqZkR5QmRBUitrbnBUcUVGcGF4NDd1UVdqdUQ1R2hpRC9JanA2cEtGQzlrdUZDdzBFT0RMSFpINERZUG5hci9IMktOZGoxSFNjWEhyemZjNmk1OWpsRE5OTTI0RVllNUEyUjVSdzBoa2lodU14Z1A4NDJESFUxMkgwNWFyYmdRUWp3NFJmVHh6cDBQQlRjdTk4VUViUjJnak1RajlVK3RsYStPdTN6WTQ5K1BKc0szTkpMTVdxWm4vaFZ1dTR3NFprZGhXNVBqNWphb2Flb3J6MG8zbWIvUXo2M0NlNFdwWmUra1lFYUlSa29oUXBaZkliaW4rTWdQcVpNelg4cW4vNDcyNFp5N05mblpETlVBV3RoTkowTkUxSDVESXZ4N0IwRFJHZVBwdk5FbVdqWEJ3PT0g4MCW2tYBOAFCBk1vYmlsZUocCgpHYWxheHkgUzIyEAMYjPz/////////ASCQBA==";
|
||||
|
||||
let bytes = STANDARD.decode(sample).unwrap();
|
||||
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, STANDARD).expect("Failed to encode");
|
||||
let encoded = encode_msg(&decoded, base64::STANDARD).expect("Failed to encode");
|
||||
|
||||
assert_eq!(encoded, String::from_utf8(sample.to_vec()).unwrap());
|
||||
}
|
||||
|
|
|
@ -13,13 +13,10 @@ use crate::protobufs::steammessages_auth_steamclient::{
|
|||
CAuthentication_UpdateAuthSessionWithSteamGuardCode_Request,
|
||||
CAuthentication_UpdateAuthSessionWithSteamGuardCode_Response, EAuthTokenPlatformType,
|
||||
};
|
||||
use crate::refresher::TokenRefresher;
|
||||
use crate::steamapi::authentication::AuthenticationClient;
|
||||
use crate::steamapi::EResult;
|
||||
use crate::token::Tokens;
|
||||
use crate::transport::Transport;
|
||||
use anyhow::Context;
|
||||
use base64::Engine;
|
||||
use log::*;
|
||||
use rsa::{Pkcs1v15Encrypt, RsaPublicKey};
|
||||
use std::time::Duration;
|
||||
|
@ -84,7 +81,7 @@ impl BeginQrLoginResponse {
|
|||
#[derive(Debug)]
|
||||
pub struct UserLogin<T>
|
||||
where
|
||||
T: Transport + Clone,
|
||||
T: Transport,
|
||||
{
|
||||
client: AuthenticationClient<T>,
|
||||
device_details: DeviceDetails,
|
||||
|
@ -94,7 +91,7 @@ where
|
|||
|
||||
impl<T> UserLogin<T>
|
||||
where
|
||||
T: Transport + Clone,
|
||||
T: Transport,
|
||||
{
|
||||
pub fn new(transport: T, device_details: DeviceDetails) -> Self {
|
||||
Self {
|
||||
|
@ -216,29 +213,11 @@ where
|
|||
loop {
|
||||
let mut next_poll = self.poll_until_info()?;
|
||||
|
||||
if next_poll.has_access_token() || next_poll.has_refresh_token() {
|
||||
// On 2023-09-12, Steam stopped issuing access tokens alongside refresh tokens for newly authenticated sessions.
|
||||
// If they decide to revert this change, we'll accept the access token if it's present.
|
||||
|
||||
let access_token = next_poll.take_access_token();
|
||||
if access_token.is_empty() {
|
||||
// Let's go ahead an fetch the access token, because we are going to need it anyway.
|
||||
let mut refresher = TokenRefresher::new(self.client.clone());
|
||||
let mut tokens = Tokens::new(
|
||||
next_poll.take_access_token(),
|
||||
next_poll.take_refresh_token(),
|
||||
);
|
||||
let steamid = tokens
|
||||
.refresh_token()
|
||||
.decode()
|
||||
.context("decoding refresh token for steam id")?
|
||||
.steam_id();
|
||||
let access_token = refresher.refresh(steamid, &tokens)?;
|
||||
tokens.set_access_token(access_token);
|
||||
return Ok(tokens);
|
||||
} else {
|
||||
return Ok(Tokens::new(access_token, next_poll.take_refresh_token()));
|
||||
};
|
||||
if next_poll.has_access_token() {
|
||||
return Ok(Tokens::new(
|
||||
next_poll.take_access_token(),
|
||||
next_poll.take_refresh_token(),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -296,7 +275,7 @@ fn encrypt_password(
|
|||
let mut rng = tests::MockStepRng(rand::rngs::mock::StepRng::new(2, 1));
|
||||
#[cfg(not(test))]
|
||||
let mut rng = rand::rngs::OsRng;
|
||||
base64::engine::general_purpose::STANDARD.encode(
|
||||
base64::encode(
|
||||
public_key
|
||||
.encrypt(&mut rng, Pkcs1v15Encrypt, password.as_ref())
|
||||
.unwrap(),
|
||||
|
|
Loading…
Add table
Reference in a new issue