Compare commits

..

No commits in common. "master" and "steamguard-v0.7.1" have entirely different histories.

117 changed files with 4137 additions and 12864 deletions

3
.github/FUNDING.yml vendored
View file

@ -1,3 +0,0 @@
# These are supported funding model platforms
github: [dyc3]

View file

@ -1,42 +0,0 @@
name: Bug Report
description: Something isn't working as expected
labels: ["bug", "triage"]
body:
- type: markdown
attributes:
value: |
Thanks for taking the time to fill out this bug report!
- type: input
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.**
validations:
required: true
- type: textarea
id: what-happened
attributes:
label: What happened?
description: What did you expect to happen?
placeholder: Tell us what you see!
validations:
required: true
- type: textarea
attributes:
label: Steps To Reproduce
description: Steps to reproduce the behavior.
placeholder: |
1. In this environment...
2. With this config...
3. Run '...'
4. See error...
validations:
required: false
- type: textarea
id: logs
attributes:
label: Relevant log output
description: Please copy and paste any relevant log output. Make sure to use `-v debug` or `-v trace`. **If you use `-v trace`, make sure to remove any private information like 2fa secrets!** This will be automatically formatted into code, so no need for backticks.
placeholder: |
Paste your logs with at least `-v debug` enabled here
render: Shell

View file

@ -1,5 +0,0 @@
blank_issues_enabled: false
contact_links:
- name: Q&A and Troubleshooting Support
url: https://github.com/dyc3/steamguard-cli/discussions/new?category=q-a
about: Please ask and answer questions here.

View file

@ -1,13 +0,0 @@
name: Feature Request
description: Suggest an idea for this project
labels: ["enhancement"]
body:
- type: markdown
attributes:
value: |
Thanks for taking the time to fill out this feature request!
- type: textarea
attributes:
label: Description
validations:
required: true

View file

@ -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

View file

@ -10,38 +10,33 @@ env:
CARGO_TERM_COLOR: always
jobs:
test:
build:
runs-on: ubuntu-latest
steps:
- run: rustup component add clippy rustfmt
- uses: actions/checkout@v4
- name: Rust Cache
uses: Swatinem/rust-cache@v2
- name: Check format
run: cargo fmt --all -- --check
- name: Check
run: cargo check --verbose --all-targets --all-features
- name: Clippy
run: cargo clippy --workspace --no-deps --all-features --all-targets -- -D warnings
- name: Validate documentation
run: cargo doc --workspace --no-deps --all-features
- uses: actions/checkout@v2
- name: Build
run: cargo build --workspace --verbose
- name: Run tests
run: cargo test --verbose --all-features --all-targets --workspace
check:
run: cargo test --workspace --verbose
lint:
name: rustfmt
runs-on: ubuntu-latest
strategy:
matrix:
target: [x86_64-unknown-linux-musl, x86_64-pc-windows-gnu]
steps:
- uses: actions/checkout@v4
- name: Rust Cache
uses: Swatinem/rust-cache@v2
- name: Checkout sources
uses: actions/checkout@v2
- name: Install stable toolchain
uses: actions-rs/toolchain@v1
with:
prefix-key: v0-rust-${{ matrix.target }}
- name: Install Cross
uses: baptiste0928/cargo-install@v2
profile: minimal
toolchain: stable
override: true
components: rustfmt
- name: Run cargo fmt
uses: actions-rs/cargo@v1
with:
crate: cross
- name: Check
run: cross check --verbose --all-targets --all-features --target ${{ matrix.target }}
command: fmt
args: --all -- --check

8
.vscode/launch.json vendored
View file

@ -30,11 +30,11 @@
"cargo": {
"args": [
"build",
"--bin=steamguard",
"--bin=steamguard-cli",
"--package=steamguard-cli"
],
"filter": {
"name": "steamguard",
"name": "steamguard-cli",
"kind": "bin"
}
},
@ -49,11 +49,11 @@
"args": [
"test",
"--no-run",
"--bin=steamguard",
"--bin=steamguard-cli",
"--package=steamguard-cli"
],
"filter": {
"name": "steamguard",
"name": "steamguard-cli",
"kind": "bin"
}
},

3639
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -1,12 +1,14 @@
[workspace]
members = ["steamguard"]
members = [
"steamguard"
]
[package]
name = "steamguard-cli"
version = "0.14.0"
version = "0.7.1"
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"]
@ -14,69 +16,46 @@ repository = "https://github.com/dyc3/steamguard-cli"
license = "GPL-3.0-or-later"
[features]
default = ["qr", "updater", "keyring"]
qr = ["dep:qrcode"]
updater = ["dep:update-informer"]
keyring = ["dep:keyring"]
# [[bin]]
# name = "steamguard-cli"
# filename = "steamguard" # TODO: uncomment when https://github.com/rust-lang/cargo/issues/9778 is stablized.
default = ["qr"]
qr = ["qrcode"]
[[bin]]
name = "steamguard"
path = "src/main.rs"
name = "steamguard-cli"
# filename = "steamguard" # TODO: uncomment when https://github.com/rust-lang/cargo/issues/9778 is stablized.
# 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"
log = "0.4.19"
stderrlog = "0.6"
cookie = "0.18"
rsa = "0.5.0"
rand = "0.8.4"
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.14"
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"
aes = { version = "0.8.3", features = ["zeroize"] }
thiserror = "1.0.61"
uuid = { version = "0.8", features = ["v4"] }
steamguard = { version = "^0.7.1", path = "./steamguard" }
dirs = "3.0.2"
ring = "0.16.20"
aes = "0.7.4"
block-modes = "0.8.1"
thiserror = "1.0.26"
crossterm = { version = "0.23.2", features = ["event-stream"] }
qrcode = { version = "0.14.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",
] }
phonenumber = "0.3"
cbc = { version = "0.1.2", features = ["std", "zeroize"] }
inout = { version = "0.1.3", features = ["std"] }
keyring = { version = "2.0.4", optional = true }
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"
qrcode = { version = "0.12.0", optional = true }
[dev-dependencies]
tempfile = "3"
tempdir = "0.3"
proptest = "1"
[profile.release]

View file

@ -3,7 +3,7 @@
_pkgname=steamguard-cli
pkgname=${_pkgname}-git
pkgver=0.14.0.r1.602acc66
pkgver=0.4.3.r1.145c03e9
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}"
@ -25,6 +24,5 @@ build() {
}
package() {
install -Dm755 "${srcdir}/${_pkgname}/target/release/steamguard" "${pkgdir}/usr/bin/steamguard"
ln -s "${pkgdir}/usr/bin/steamguard" "${pkgdir}/usr/bin/${_pkgname}"
install -Dm755 "${srcdir}/${_pkgname}/target/release/${_pkgname}" "${pkgdir}/usr/bin/${_pkgname}"
}

View file

@ -3,29 +3,13 @@
[![Lint, Build, Test](https://github.com/dyc3/steamguard-cli/actions/workflows/rust.yml/badge.svg)](https://github.com/dyc3/steamguard-cli/actions/workflows/rust.yml)
[![AUR Tester](https://github.com/dyc3/steamguard-cli/actions/workflows/aur-checker.yml/badge.svg)](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.**
# Disclaimer
**This utility is effectively in beta. Use this software at your own risk. Make sure to back up your maFiles regularly, and make sure to actually write down your revocation code. If you lose both of these, we can't help you, your only recourse is to beg Steam support.**
# Quickstart
If you have no idea what the rest of this document is talking about, go read the [quickstart](docs/quickstart.md).
# Features
- Generate 2FA codes
- Respond to trade, market or any other confirmations
- Encrypted storage of your 2FA secrets
- With the option to store your encryption passkey in the system keyring
- Special memory-clearing data structures to prevent leaking secrets
- QR code generation for importing 2FA secrets into other applications, like KeeWeb
- QR code logins for quickly logging into Steam on a new device, like the Steam Deck
- Able to read Steam Desktop Authenticator's `maFiles` format
- Uses as many official Steam APIs as possible, unlikely to break
# Install
If you have the Rust toolchain installed:
@ -35,8 +19,8 @@ cargo install steamguard-cli
Arch-based systems can install from the AUR:
- [steamguard-cli](https://aur.archlinux.org/packages/steamguard-cli/) tracks the latest release
- [steamguard-cli-git](https://aur.archlinux.org/packages/steamguard-cli-git/) tracks the latest git commit
- For [steamguard-cli-git](https://aur.archlinux.org/packages/steamguard-cli-git/)
- *Non-git release is not officially provided. Please open an issue if you would like to help set that up.*
Otherwise, you can download binaries from the releases.
@ -48,15 +32,9 @@ cargo build --release
# Usage
`steamguard-cli` looks for your `maFiles/manifest.json` in at these paths, in this order:
Linux:
- `~/.config/steamguard-cli/maFiles/`
- `~/maFiles/`
Windows:
- `%APPDATA%\Roaming\steamguard-cli\maFiles\`
- `%USERPROFILE%\maFiles\`
Your `maFiles` can be created with or imported from [Steam Desktop Authenticator][SDA]. You can create `maFiles` with steamguard-cli using the `setup` action (`steamguard setup`).
**REMEMBER TO MAKE BACKUPS OF YOUR `maFiles`, AND TO WRITE DOWN YOUR RECOVERY CODE!**
@ -72,7 +50,7 @@ steamguard --help
Generate and copy a new code to clipboard:
```bash
steamguard | xclip -selection clipboard
steamguard-cli | xclip -selection clipboard
```
## Importing 2FA Secret Into Other Applications

View file

@ -1,55 +0,0 @@
# Quickstart
steamguard-cli is a command-line tool, and as such, it is meant to be used in a terminal. This guide will show you how to get started with steamguard-cli.
## Windows
1. Download `steamguard.exe` from the [releases page][releases].
2. Place `steamguard.exe` in a folder of your choice. For this example, we will use `%USERPROFILE%\Desktop`.
3. Open Powershell or Command Prompt. The prompt should be at `%USERPROFILE%` (eg. `C:\Users\<username>`).
4. Use `cd` to change directory into the folder where you placed `steamguard.exe`. For this example, it would be `cd Desktop`.
5. You should now be able to run `steamguard.exe` by typing `.\steamguard.exe --help` and pressing enter.
## Linux
### Ubuntu/Debian
1. Download the `.deb` from the [releases page][releases].
2. Open a terminal and run this to install it:
```bash
sudo dpkg -i ./steamguard-cli_<version>_amd64.deb
```
### Other Linux
1. Download `steamguard` from the [releases page][releases]
2. Make it executable, and move `steamguard` to `/usr/local/bin` or any other directory in your `$PATH`.
```bash
chmod +x ./steamguard
sudo mv ./steamguard /usr/local/bin
```
3. You should now be able to run `steamguard` by typing `steamguard --help` and pressing enter.
# Importing existing maFiles from Steam Desktop Authenticator
If you have used [Steam Desktop Authenticator][SDA] before, you can use your existing maFiles into steamguard-cli, and they will be automatically upgraded for use with steamguard-cli.
1. Make a backup of your `maFiles` folder.
2. Place your `maFiles` folder in the following directory:
- Linux:
- `~/.config/steamguard-cli/maFiles/`
- Windows:
- `%APPDATA%\Roaming\steamguard-cli\maFiles\`
3. Run `steamguard` from your terminal.
### Importing individual maFiles from Steam Desktop Authenticator
It's also possible to import a single maFile from Steam Desktop Authenticator and add it to your existing manifest.
```bash
steamguard import --sda <path to maFile>
```
[SDA]: https://github.com/Jessecar96/SteamDesktopAuthenticator
[releases]: http://github.com/dyc3/steamguard-cli/releases

View file

@ -1,2 +1,3 @@
tab_spaces = 4
hard_tabs = true
normalize_comments = true

View file

@ -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,14 +55,21 @@ fi
echo "Press any key to continue..."
read -n 1 -s -r
params=()
if [[ $DRY_RUN == false ]]; then
params+=(--execute)
fi
cargo smart-release --update-crates-index --no-changelog --no-tag --no-push --no-publish "${params[@]}"
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 "${params[@]}"
#echo "Verify that the publish succeeded, and Press any key to continue..."
# read -n 1 -s -r
echo "Verify that the publish succeeded, and Press any key to continue..."
read -n 1 -s -r
if ! which cross; then
echo "cross not found, installing..."
@ -90,37 +77,21 @@ if ! which cross; then
fi
BUILD_TARGET="x86_64-unknown-linux-musl"
BUILD_TARGET2="x86_64-pc-windows-gnu"
# HACK: build targets in this order to avoid a bug in cross
cross build --release "--target=$BUILD_TARGET2"
cross build --release "--target=$BUILD_TARGET"
./scripts/package-deb.sh
BIN_PATH="target/$BUILD_TARGET/release/steamguard"
BIN_PATH2="target/$BUILD_TARGET2/release/steamguard.exe"
BIN_PATH="target/$BUILD_TARGET/release/steamguard-cli"
RAW_VERSION="$("$BIN_PATH" --version | cut -d " " -f 2)"
# TODO: can't compare with the tag anymore because it doesn't exist yet. maybe get a better condition?
# TAGGED_VERSION="$(git tag | grep "^v" | tail -n 1 | tr -d v)"
# if [[ "v$RAW_VERSION" != "v$TAGGED_VERSION" ]]; then
# echo "Version mismatch: $RAW_VERSION != $TAGGED_VERSION"
# if [[ $DRY_RUN == false ]]; then
# echo "Aborting."
# exit 2
# fi
# fi
VERSION="v$RAW_VERSION"
echo "It's now safe to push tags and publish for the affected crates."
if [[ $DRY_RUN == false ]]; then
cargo smart-release --update-crates-index --no-changelog --execute
TAGGED_VERSION="$(git tag | grep "^v" | tail -n 1 | tr -d v)"
if [[ "v$RAW_VERSION" != "v$TAGGED_VERSION" ]]; then
echo "Version mismatch: $RAW_VERSION != $TAGGED_VERSION"
fi
VERSION="v$RAW_VERSION"
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" --title "$VERSION" --draft "$BIN_PATH" "./steamguard-cli_$RAW_VERSION-0.deb"
fi

View file

@ -10,7 +10,7 @@ if ! which cross; then
cargo install cross
fi
BIN_PATH="target/x86_64-unknown-linux-musl/release/steamguard"
BIN_PATH="target/x86_64-unknown-linux-musl/release/steamguard-cli"
if [[ ! -f "$BIN_PATH" ]]; then
echo "ERROR: Could not find release binaries, building them..."
cross build --release --target=x86_64-unknown-linux-musl
@ -24,6 +24,9 @@ mkdir -p "$TEMP_PKG_PATH/etc/bash_completion.d"
mkdir -p "$TEMP_PKG_PATH/DEBIAN"
cp "$BIN_PATH" "$TEMP_PKG_PATH/usr/local/bin/steamguard"
pushd "$TEMP_PKG_PATH/usr/local/bin/"
ln -s "./steamguard" "./steamguard-cli"
popd
"$BIN_PATH" completion --shell bash > "$TEMP_PKG_PATH/etc/bash_completion.d/steamguard"
cat <<EOT >> $TEMP_PKG_PATH/DEBIAN/control
@ -32,12 +35,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"

2
scripts/publish-aur.sh Executable file → Normal file
View file

@ -31,7 +31,7 @@ fi
# get version info
BIN_PATH="target/release/steamguard"
BIN_PATH="target/release/steamguard-cli"
RAW_VERSION="$("$BIN_PATH" --version | cut -d " " -f 2)"
TAGGED_VERSION="$(git tag | grep "^v" | tail -n 1 | tr -d v)"
if [[ "v$RAW_VERSION" != "v$TAGGED_VERSION" ]]; then

File diff suppressed because it is too large Load diff

View file

@ -1,185 +0,0 @@
#![allow(deprecated)]
use std::{
fs::File,
io::{BufReader, Read},
path::Path,
};
use log::debug;
use secrecy::{CloneableSecret, DebugSecret, ExposeSecret};
use serde::Deserialize;
use steamguard::{token::TwoFactorSecret, SecretString, SteamGuardAccount};
use zeroize::{Zeroize, ZeroizeOnDrop};
use crate::encryption::{EntryEncryptor, LegacySdaCompatible};
use super::{EncryptionScheme, EntryLoader, ManifestAccountLoadError, ManifestEntry, ManifestV1};
#[derive(Debug, Deserialize)]
pub struct SdaManifest {
#[serde(default)]
pub version: u32,
pub entries: Vec<SdaManifestEntry>,
/// Not really used, kept mostly for compatibility with SDA.
pub encrypted: bool,
/// Not implemented, kept for compatibility with SDA.
pub first_run: bool,
/// Not implemented, kept for compatibility with SDA.
pub periodic_checking: bool,
/// Not implemented, kept for compatibility with SDA.
pub periodic_checking_interval: i32,
/// Not implemented, kept for compatibility with SDA.
pub periodic_checking_checkall: bool,
/// Not implemented, kept for compatibility with SDA.
pub auto_confirm_market_transactions: bool,
/// Not implemented, kept for compatibility with SDA.
pub auto_confirm_trades: bool,
}
impl From<SdaManifest> for ManifestV1 {
fn from(sda: SdaManifest) -> Self {
Self {
version: 1,
entries: sda.entries.into_iter().map(|e| e.into()).collect(),
keyring_id: None,
}
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct SdaManifestEntry {
pub filename: String,
#[serde(default, rename = "steamid")]
pub steam_id: u64,
#[serde(default, flatten)]
pub encryption: Option<SdaEntryEncryptionParams>,
}
impl From<SdaManifestEntry> for ManifestEntry {
fn from(sda: SdaManifestEntry) -> Self {
Self {
filename: sda.filename,
steam_id: sda.steam_id,
account_name: Default::default(),
encryption: sda.encryption.map(|e| e.into()),
}
}
}
impl EntryLoader<SdaAccount> for SdaManifestEntry {
fn load(
&self,
path: &Path,
passkey: Option<&SecretString>,
encryption_params: Option<&EncryptionScheme>,
) -> anyhow::Result<SdaAccount, ManifestAccountLoadError> {
debug!("loading entry: {:?}", path);
let file = File::open(path)?;
let mut reader = BufReader::new(file);
let account: SdaAccount = match (&passkey, encryption_params.as_ref()) {
(Some(passkey), Some(scheme)) => {
let mut ciphertext: Vec<u8> = vec![];
reader.read_to_end(&mut ciphertext)?;
let plaintext = scheme.decrypt(passkey.expose_secret(), ciphertext)?;
if plaintext[0] != b'{' && plaintext[plaintext.len() - 1] != b'}' {
return Err(ManifestAccountLoadError::IncorrectPasskey);
}
let s = std::str::from_utf8(&plaintext).unwrap();
let mut deser = serde_json::Deserializer::from_str(s);
serde_path_to_error::deserialize(&mut deser)?
}
(None, Some(_)) => {
return Err(ManifestAccountLoadError::MissingPasskey);
}
(_, None) => {
let mut deser = serde_json::Deserializer::from_reader(reader);
serde_path_to_error::deserialize(&mut deser)?
}
};
Ok(account)
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct SdaEntryEncryptionParams {
#[serde(rename = "encryption_iv")]
pub iv: String,
#[serde(rename = "encryption_salt")]
pub salt: String,
}
impl From<SdaEntryEncryptionParams> for EncryptionScheme {
fn from(sda: SdaEntryEncryptionParams) -> Self {
EncryptionScheme::LegacySdaCompatible(LegacySdaCompatible {
iv: sda.iv,
salt: sda.salt,
})
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct SdaAccount {
pub account_name: String,
pub serial_number: String,
#[serde(with = "crate::secret_string")]
pub revocation_code: SecretString,
pub shared_secret: TwoFactorSecret,
pub token_gid: String,
#[serde(with = "crate::secret_string")]
pub identity_secret: SecretString,
#[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")]
pub secret_1: SecretString,
#[serde(default, rename = "Session")]
pub session: Option<secrecy::Secret<Session>>,
}
#[derive(Debug, Clone, Deserialize, Zeroize, ZeroizeOnDrop)]
#[deprecated(note = "this is not used anymore, the closest equivalent is `Tokens`")]
pub struct Session {
#[serde(default, rename = "SessionID")]
pub session_id: Option<String>,
#[serde(default, rename = "SteamLogin")]
pub steam_login: Option<String>,
#[serde(default, rename = "SteamLoginSecure")]
pub steam_login_secure: Option<String>,
#[serde(default, rename = "WebCookie")]
pub web_cookie: Option<String>,
#[serde(default, rename = "OAuthToken")]
pub token: Option<String>,
#[serde(rename = "SteamID")]
pub steam_id: Option<u64>,
}
impl CloneableSecret for Session {}
impl DebugSecret for Session {}
impl From<SdaAccount> for SteamGuardAccount {
fn from(value: SdaAccount) -> Self {
let steam_id = value
.session
.as_ref()
.and_then(|s| s.expose_secret().steam_id)
.unwrap_or(0);
Self {
account_name: value.account_name,
steam_id,
serial_number: value.serial_number,
revocation_code: value.revocation_code,
shared_secret: value.shared_secret,
token_gid: value.token_gid,
identity_secret: value.identity_secret,
uri: value.uri,
device_id: value.device_id,
secret_1: value.secret_1,
tokens: None,
}
}
}

View file

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

View file

@ -1,518 +0,0 @@
use std::{fs::File, io::Read, path::Path};
use log::*;
use secrecy::SecretString;
use serde::{de::Error, Deserialize};
use steamguard::SteamGuardAccount;
use thiserror::Error;
use crate::encryption::EncryptionScheme;
use super::{
legacy::{SdaAccount, SdaManifest},
manifest::ManifestV1,
steamv2::SteamMobileV2,
winauth::parse_winauth_exports,
EntryLoader, Manifest,
};
pub(crate) fn load_and_migrate(
manifest_path: &Path,
passkey: Option<&SecretString>,
) -> Result<(Manifest, Vec<SteamGuardAccount>), MigrationError> {
backup_file(manifest_path)?;
let parent = manifest_path.parent().unwrap();
parent.read_dir()?.for_each(|e| {
let entry = e.unwrap();
if entry.file_type().unwrap().is_file() {
let path = entry.path();
let Some(ext) = path.extension() else {
return;
};
if ext == "maFile" {
backup_file(&path).unwrap();
}
}
});
do_migrate(manifest_path, passkey)
}
fn do_migrate(
manifest_path: &Path,
passkey: Option<&SecretString>,
) -> Result<(Manifest, Vec<SteamGuardAccount>), MigrationError> {
let mut file = File::open(manifest_path)?;
let mut buffer = String::new();
file.read_to_string(&mut buffer)?;
let mut manifest: MigratingManifest =
deserialize_manifest(buffer).map_err(MigrationError::ManifestDeserializeFailed)?;
if manifest.is_encrypted() && passkey.is_none() {
return Err(MigrationError::MissingPasskey { keyring_id: None });
} else if !manifest.is_encrypted() && passkey.is_some() {
// no custom error because this is an edge case, mostly user error
return Err(MigrationError::UnexpectedError(anyhow::anyhow!("A passkey was provided but the manifest is not encrypted. Aborting migration because it would encrypt the maFiles, and you probably didn't mean to do that.")));
}
let folder = manifest_path.parent().unwrap();
let mut accounts = manifest.load_all_accounts(folder, passkey)?;
while !manifest.is_latest() {
manifest = manifest.upgrade();
for account in accounts.iter_mut() {
*account = account.clone().upgrade();
}
}
// HACK: force account names onto manifest entries
let mut manifest: Manifest = manifest.into();
let accounts: Vec<SteamGuardAccount> = accounts.into_iter().map(|a| a.into()).collect();
for (i, entry) in manifest.entries.iter_mut().enumerate() {
entry.account_name = accounts[i].account_name.to_lowercase();
}
Ok((manifest, accounts))
}
fn backup_file(path: &Path) -> anyhow::Result<()> {
let backup_path = Path::join(
path.parent().unwrap(),
format!("{}.bak", path.file_name().unwrap().to_str().unwrap()),
);
std::fs::copy(path, backup_path)?;
Ok(())
}
#[derive(Debug, Error)]
pub(crate) enum MigrationError {
#[error("Passkey is required to decrypt manifest")]
MissingPasskey { keyring_id: Option<String> },
#[error("Failed to deserialize manifest: {0}")]
ManifestDeserializeFailed(serde_path_to_error::Error<serde_json::Error>),
#[error("IO error when upgrading manifest: {0}")]
IoError(#[from] std::io::Error),
#[error("An unexpected error occurred during manifest migration: {0}")]
UnexpectedError(#[from] anyhow::Error),
}
#[derive(Debug)]
enum MigratingManifest {
Sda(SdaManifest),
ManifestV1(ManifestV1),
}
impl MigratingManifest {
pub fn upgrade(self) -> Self {
match self {
Self::Sda(sda) => Self::ManifestV1(sda.into()),
Self::ManifestV1(_) => self,
}
}
pub fn is_latest(&self) -> bool {
matches!(self, Self::ManifestV1(_))
}
pub fn is_encrypted(&self) -> bool {
match self {
Self::Sda(manifest) => manifest.entries.iter().any(|e| e.encryption.is_some()),
Self::ManifestV1(manifest) => manifest.entries.iter().any(|e| e.encryption.is_some()),
}
}
pub fn load_all_accounts(
&self,
folder: &Path,
passkey: Option<&SecretString>,
) -> anyhow::Result<Vec<MigratingAccount>> {
debug!("loading all accounts for migration");
let accounts = match self {
Self::Sda(sda) => {
let (accounts, errors) = sda
.entries
.iter()
.map(|e| {
let params: Option<EncryptionScheme> =
e.encryption.clone().map(|e| e.into());
e.load(&Path::join(folder, &e.filename), passkey, params.as_ref())
})
.partition::<Vec<_>, _>(Result::is_ok);
let accounts: Vec<_> = accounts.into_iter().map(Result::unwrap).collect();
let errors: Vec<_> = errors.into_iter().map(Result::unwrap_err).collect();
if !errors.is_empty() {
return Err(anyhow::anyhow!(
"Failed to load some accounts: {:?}",
errors
));
}
accounts
.into_iter()
.map(ExternalAccount::Sda)
.map(MigratingAccount::External)
.collect()
}
Self::ManifestV1(manifest) => {
let (accounts, errors) = manifest
.entries
.iter()
.map(|e| {
e.load(
&Path::join(folder, &e.filename),
passkey,
e.encryption.as_ref(),
)
})
.partition::<Vec<_>, _>(Result::is_ok);
let accounts: Vec<_> = accounts.into_iter().map(Result::unwrap).collect();
let errors: Vec<_> = errors.into_iter().map(Result::unwrap_err).collect();
if !errors.is_empty() {
return Err(anyhow::anyhow!(
"Failed to load some accounts: {:?}",
errors
));
}
accounts
.into_iter()
.map(MigratingAccount::ManifestV1)
.collect()
}
};
Ok(accounts)
}
}
impl From<MigratingManifest> for Manifest {
fn from(migrating: MigratingManifest) -> Self {
match migrating {
MigratingManifest::ManifestV1(manifest) => manifest,
_ => panic!("Manifest is not at the latest version!"),
}
}
}
#[derive(Deserialize)]
struct JustVersion {
version: Option<u32>,
}
fn deserialize_manifest(
text: String,
) -> Result<MigratingManifest, serde_path_to_error::Error<serde_json::Error>> {
let mut deser = serde_json::Deserializer::from_str(&text);
let version: JustVersion = serde_path_to_error::deserialize(&mut deser)?;
debug!("deserializing manifest: version {:?}", version.version);
let mut deser = serde_json::Deserializer::from_str(&text);
match version.version {
Some(1) => {
let manifest: ManifestV1 = serde_path_to_error::deserialize(&mut deser)?;
Ok(MigratingManifest::ManifestV1(manifest))
}
None => {
let manifest: SdaManifest = serde_path_to_error::deserialize(&mut deser)?;
Ok(MigratingManifest::Sda(manifest))
}
_ => {
// HACK: there's no way to construct the Path type, so we create it by forcing a deserialize error
#[derive(Debug)]
struct Dummy;
impl<'de> Deserialize<'de> for Dummy {
fn deserialize<D: serde::Deserializer<'de>>(_: D) -> Result<Self, D::Error> {
Err(D::Error::custom("Unknown manifest version".to_string()))
}
}
let mut deser = serde_json::Deserializer::from_str("");
let err = serde_path_to_error::deserialize::<_, Dummy>(&mut deser).unwrap_err();
Err(err)
}
}
}
#[derive(Debug, Clone)]
#[allow(clippy::large_enum_variant)]
enum MigratingAccount {
External(ExternalAccount),
ManifestV1(SteamGuardAccount),
}
impl MigratingAccount {
pub fn upgrade(self) -> Self {
match self {
Self::External(account) => Self::ManifestV1(account.into()),
Self::ManifestV1(_) => self,
}
}
pub fn is_latest(&self) -> bool {
matches!(self, Self::ManifestV1(_))
}
}
impl From<MigratingAccount> for SteamGuardAccount {
fn from(migrating: MigratingAccount) -> Self {
match migrating {
MigratingAccount::ManifestV1(account) => account,
_ => panic!("Account is not at the latest version!"),
}
}
}
pub fn load_and_upgrade_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(),
}
}
}
#[cfg(test)]
mod tests {
use tempfile::TempDir;
use crate::{accountmanager::CURRENT_MANIFEST_VERSION, AccountManager};
use super::*;
#[test]
fn should_migrate_to_latest_version() -> anyhow::Result<()> {
#[derive(Debug)]
struct Test {
manifest: &'static str,
passkey: Option<SecretString>,
}
let cases = vec![
Test {
manifest: "src/fixtures/maFiles/compat/1-account/manifest.json",
passkey: None,
},
Test {
manifest: "src/fixtures/maFiles/compat/1-account-encrypted/manifest.json",
passkey: Some(SecretString::new("password".into())),
},
Test {
manifest: "src/fixtures/maFiles/compat/2-account/manifest.json",
passkey: None,
},
Test {
manifest: "src/fixtures/maFiles/compat/missing-account-name/manifest.json",
passkey: None,
},
Test {
manifest: "src/fixtures/maFiles/compat/no-webcookie/manifest.json",
passkey: None,
},
Test {
manifest: "src/fixtures/maFiles/compat/null-oauthtoken/manifest.json",
passkey: None,
},
Test {
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);
let (manifest, accounts) = do_migrate(Path::new(case.manifest), case.passkey.as_ref())?;
assert_eq!(manifest.version, CURRENT_MANIFEST_VERSION);
assert_eq!(manifest.entries[0].account_name, "example");
assert_eq!(manifest.entries[0].steam_id, 1234);
assert_eq!(accounts[0].account_name, "example");
assert_eq!(accounts[0].steam_id, 1234);
}
Ok(())
}
#[test]
fn should_migrate_single_accounts() -> anyhow::Result<()> {
#[derive(Debug)]
struct Test {
mafile: &'static str,
account_name: &'static str,
steam_id: u64,
}
let cases = vec![
Test {
mafile: "src/fixtures/maFiles/compat/1-account/1234.maFile",
account_name: "example",
steam_id: 1234,
},
Test {
mafile: "src/fixtures/maFiles/compat/2-account/1234.maFile",
account_name: "example",
steam_id: 1234,
},
Test {
mafile: "src/fixtures/maFiles/compat/2-account/5678.maFile",
account_name: "example2",
steam_id: 5678,
},
Test {
mafile: "src/fixtures/maFiles/compat/missing-account-name/1234.maFile",
account_name: "example",
steam_id: 1234,
},
Test {
mafile: "src/fixtures/maFiles/compat/no-webcookie/nowebcookie.maFile",
account_name: "example",
steam_id: 1234,
},
Test {
mafile: "src/fixtures/maFiles/compat/null-oauthtoken/nulloauthtoken.maFile",
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();
assert_eq!(account.account_name, case.account_name);
assert_eq!(account.steam_id, case.steam_id);
}
Ok(())
}
#[test]
fn should_migrate_to_latest_version_save_and_load_again() -> anyhow::Result<()> {
#[derive(Debug)]
struct Test {
dir: &'static str,
passkey: Option<SecretString>,
}
let cases = vec![
Test {
dir: "src/fixtures/maFiles/compat/1-account/",
passkey: None,
},
Test {
dir: "src/fixtures/maFiles/compat/1-account-encrypted/",
passkey: Some(SecretString::new("password".into())),
},
Test {
dir: "src/fixtures/maFiles/compat/2-account/",
passkey: None,
},
Test {
dir: "src/fixtures/maFiles/compat/missing-account-name/",
passkey: None,
},
Test {
dir: "src/fixtures/maFiles/compat/no-webcookie/",
passkey: None,
},
Test {
dir: "src/fixtures/maFiles/compat/null-oauthtoken/",
passkey: None,
},
];
for case in cases {
eprintln!("testing: {:?}", case);
let temp = TempDir::new()?;
for file in std::fs::read_dir(case.dir)? {
let file = file?;
let path = file.path();
let dest = temp.path().join(path.file_name().unwrap());
std::fs::copy(&path, dest)?;
}
let (manifest, accounts) = do_migrate(
Path::join(temp.path(), "manifest.json").as_path(),
case.passkey.as_ref(),
)?;
assert_eq!(manifest.version, CURRENT_MANIFEST_VERSION);
assert_eq!(manifest.entries[0].account_name, "example");
assert_eq!(manifest.entries[0].steam_id, 1234);
assert_eq!(accounts[0].account_name, "example");
assert_eq!(accounts[0].steam_id, 1234);
let mut manager =
AccountManager::from_manifest(manifest, temp.path().to_str().unwrap().to_owned());
manager.submit_passkey(case.passkey.clone());
manager.register_accounts(accounts);
manager.save()?;
let path = Path::join(temp.path(), "manifest.json");
let mut manager = AccountManager::load(path.as_path())?;
manager.submit_passkey(case.passkey.clone());
manager.load_accounts()?;
let account = manager.get_or_load_account("example")?;
let account = account.lock().unwrap();
assert_eq!(account.account_name, "example");
assert_eq!(account.steam_id, 1234);
}
Ok(())
}
}

View file

@ -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")),
})
}

View file

@ -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)
}

188
src/cli.rs Normal file
View file

@ -0,0 +1,188 @@
use clap::{clap_derive::ArgEnum, Parser};
use clap_complete::Shell;
use std::str::FromStr;
#[derive(Debug, Clone, Parser)]
#[clap(name="steamguard-cli", bin_name="steamguard", author, version, about = "Generate Steam 2FA codes and confirm Steam trades from the command line.", long_about = None)]
pub(crate) struct Args {
#[clap(
short,
long,
conflicts_with = "all",
help = "Steam username, case-sensitive.",
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(
short,
long,
conflicts_with = "username",
help = "Select all accounts in the manifest."
)]
pub all: bool,
/// The path to the maFiles directory.
#[clap(
short,
long,
help = "Specify which folder your maFiles are in. This should be a path to a folder that contains manifest.json. Default: ~/.config/steamguard-cli/maFiles"
)]
pub mafiles_path: Option<String>,
#[clap(
short,
long,
env = "STEAMGUARD_CLI_PASSKEY",
help = "Specify your encryption passkey."
)]
pub passkey: Option<String>,
#[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,
#[clap(subcommand)]
pub sub: Option<Subcommands>,
#[clap(flatten)]
pub code: ArgsCode,
}
#[derive(Debug, Clone, Parser)]
pub(crate) enum Subcommands {
Debug(ArgsDebug),
Completion(ArgsCompletions),
Setup(ArgsSetup),
Import(ArgsImport),
Trade(ArgsTrade),
Remove(ArgsRemove),
Encrypt(ArgsEncrypt),
Decrypt(ArgsDecrypt),
Code(ArgsCode),
#[cfg(feature = "qr")]
Qr(ArgsQr),
}
#[derive(Debug, Clone, Copy, ArgEnum)]
pub(crate) enum Verbosity {
Error = 0,
Warn = 1,
Info = 2,
Debug = 3,
Trace = 4,
}
impl std::fmt::Display for Verbosity {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!(
"{}",
match self {
Verbosity::Error => "error",
Verbosity::Warn => "warn",
Verbosity::Info => "info",
Verbosity::Debug => "debug",
Verbosity::Trace => "trace",
}
))
}
}
impl FromStr for Verbosity {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"error" => Ok(Verbosity::Error),
"warn" => Ok(Verbosity::Warn),
"info" => Ok(Verbosity::Info),
"debug" => Ok(Verbosity::Debug),
"trace" => Ok(Verbosity::Trace),
_ => Err(anyhow!("Invalid verbosity level: {}", s)),
}
}
}
#[derive(Debug, Clone, Parser)]
#[clap(about = "Debug stuff, not useful for most users.")]
pub(crate) struct ArgsDebug {
#[clap(long, help = "Show a text prompt.")]
pub demo_prompt: bool,
#[clap(long, help = "Show a \"press any key\" prompt.")]
pub demo_pause: bool,
#[clap(long, help = "Show a character prompt.")]
pub demo_prompt_char: bool,
#[clap(long, help = "Show an example confirmation menu using dummy data.")]
pub demo_conf_menu: bool,
}
#[derive(Debug, Clone, Parser)]
#[clap(about = "Generate shell completions")]
pub(crate) struct ArgsCompletions {
#[clap(short, long, arg_enum, help = "The shell to generate completions for.")]
pub shell: Shell,
}
#[derive(Debug, Clone, Parser)]
#[clap(about = "Set up a new account with steamguard-cli")]
pub(crate) struct ArgsSetup {}
#[derive(Debug, Clone, Parser)]
#[clap(about = "Import an account with steamguard already set up")]
pub(crate) struct ArgsImport {
#[clap(long, help = "Paths to one or more maFiles, eg. \"./gaben.maFile\"")]
pub files: Vec<String>,
}
#[derive(Debug, Clone, Parser)]
#[clap(about = "Interactive interface for trade confirmations")]
pub(crate) struct ArgsTrade {
#[clap(
short,
long,
help = "Accept all open trade confirmations. Does not open interactive interface."
)]
pub accept_all: bool,
#[clap(
short,
long,
help = "If submitting a confirmation response fails, exit immediately."
)]
pub fail_fast: bool,
}
#[derive(Debug, Clone, Parser)]
#[clap(about = "Remove the authenticator from an account.")]
pub(crate) struct ArgsRemove;
#[derive(Debug, Clone, Parser)]
#[clap(about = "Encrypt all maFiles")]
pub(crate) struct ArgsEncrypt;
#[derive(Debug, Clone, Parser)]
#[clap(about = "Decrypt all maFiles")]
pub(crate) struct ArgsDecrypt;
#[derive(Debug, Clone, Parser)]
#[clap(about = "Generate 2FA codes")]
pub(crate) struct ArgsCode {
#[clap(
long,
help = "Assume the computer's time is correct. Don't ask Steam for the time when generating codes."
)]
pub offline: bool,
}
// HACK: the derive API doesn't support default subcommands, so we are going to make it so that it'll be easier to switch over when it's implemented.
// See: https://github.com/clap-rs/clap/issues/3857
impl From<Args> for ArgsCode {
fn from(args: Args) -> Self {
args.code
}
}
#[derive(Debug, Clone, Parser)]
#[clap(about = "Generate QR codes. This *will* print sensitive data to stdout.")]
#[cfg(feature = "qr")]
pub(crate) struct ArgsQr {
#[clap(
long,
help = "Force using ASCII chars to generate QR codes. Useful for terminals that don't support unicode."
)]
pub ascii: bool,
}

View file

@ -1,236 +0,0 @@
use std::sync::{Arc, Mutex};
use clap::{Parser, Subcommand, ValueEnum};
use clap_complete::Shell;
use secrecy::SecretString;
use std::str::FromStr;
use steamguard::{transport::Transport, SteamGuardAccount};
use crate::AccountManager;
pub mod code;
pub mod completions;
pub mod confirm;
pub mod debug;
pub mod decrypt;
pub mod encrypt;
pub mod import;
#[cfg(feature = "qr")]
pub mod qr;
pub mod qr_login;
pub mod remove;
pub mod setup;
pub use code::CodeCommand;
pub use completions::CompletionsCommand;
pub use confirm::ConfirmCommand;
pub use debug::DebugCommand;
pub use decrypt::DecryptCommand;
pub use encrypt::EncryptCommand;
pub use import::ImportCommand;
#[cfg(feature = "qr")]
pub use qr::QrCommand;
pub use qr_login::QrLoginCommand;
pub use remove::RemoveCommand;
pub use setup::SetupCommand;
/// A command that does not operate on the manifest or individual accounts.
pub(crate) trait ConstCommand {
fn execute(&self) -> anyhow::Result<()>;
}
/// A command that operates the manifest as a whole
pub(crate) trait ManifestCommand<T>
where
T: Transport,
{
fn execute(
&self,
transport: T,
manager: &mut AccountManager,
args: &GlobalArgs,
) -> anyhow::Result<()>;
}
/// A command that operates on individual accounts.
pub(crate) trait AccountCommand<T>
where
T: Transport,
{
fn execute(
&self,
transport: T,
manager: &mut AccountManager,
accounts: Vec<Arc<Mutex<SteamGuardAccount>>>,
args: &GlobalArgs,
) -> anyhow::Result<()>;
}
pub(crate) enum CommandType<T>
where
T: Transport,
{
Const(Box<dyn ConstCommand>),
Manifest(Box<dyn ManifestCommand<T>>),
Account(Box<dyn AccountCommand<T>>),
}
#[derive(Debug, Clone, Parser)]
#[clap(name="steamguard-cli", bin_name="steamguard", author, version, about = "Generate Steam 2FA codes and confirm Steam trades from the command line.", long_about = None)]
pub(crate) struct Args {
#[clap(flatten)]
pub global: GlobalArgs,
#[clap(subcommand)]
pub sub: Option<Subcommands>,
#[clap(flatten)]
pub code: CodeCommand,
}
#[derive(Debug, Clone, Parser)]
pub(crate) struct GlobalArgs {
#[clap(
short,
long,
conflicts_with = "all",
help = "Steam username, case-sensitive.",
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,
conflicts_with = "username",
help = "Select all accounts in the manifest."
)]
pub all: bool,
/// The path to the maFiles directory.
#[clap(
short,
long,
env = "STEAMGUARD_CLI_MAFILES",
help = "Specify which folder your maFiles are in. This should be a path to a folder that contains manifest.json. Default: ~/.config/steamguard-cli/maFiles"
)]
pub mafiles_path: Option<String>,
#[clap(
short,
long,
env = "STEAMGUARD_CLI_PASSKEY",
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.")]
pub verbosity: Verbosity,
#[cfg(feature = "updater")]
#[clap(
long,
help = "Disable checking for updates.",
long_help = "Disable checking for updates. By default, steamguard-cli will check for updates every now and then. This can be disabled with this flag."
)]
pub no_update_check: bool,
#[clap(
long,
env = "HTTP_PROXY",
help = "Use a proxy for HTTP requests.",
long_help = "Use a proxy for HTTP requests. This is useful if you are behind a firewall and need to use a proxy to access the internet."
)]
pub http_proxy: Option<String>,
#[clap(
long,
help = "Credentials to use for proxy authentication in the format username:password."
)]
pub proxy_credentials: Option<String>,
#[clap(
long,
help = "Accept invalid TLS certificates.",
long_help = "Accept invalid TLS certificates. Be warned, this is insecure and enables man-in-the-middle attacks."
)]
pub danger_accept_invalid_certs: bool,
}
#[derive(Debug, Clone, Subcommand)]
pub(crate) enum Subcommands {
Debug(DebugCommand),
Completion(CompletionsCommand),
Setup(SetupCommand),
Import(ImportCommand),
#[clap(alias = "trade")]
Confirm(ConfirmCommand),
Remove(RemoveCommand),
Encrypt(EncryptCommand),
Decrypt(DecryptCommand),
Code(CodeCommand),
#[cfg(feature = "qr")]
Qr(QrCommand),
QrLogin(QrLoginCommand),
}
#[derive(Debug, Clone, Copy, ValueEnum)]
pub(crate) enum Verbosity {
Error = 0,
Warn = 1,
Info = 2,
Debug = 3,
Trace = 4,
}
impl std::fmt::Display for Verbosity {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!(
"{}",
match self {
Verbosity::Error => "error",
Verbosity::Warn => "warn",
Verbosity::Info => "info",
Verbosity::Debug => "debug",
Verbosity::Trace => "trace",
}
))
}
}
impl FromStr for Verbosity {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"error" => Ok(Verbosity::Error),
"warn" => Ok(Verbosity::Warn),
"info" => Ok(Verbosity::Info),
"debug" => Ok(Verbosity::Debug),
"trace" => Ok(Verbosity::Trace),
_ => Err(anyhow!("Invalid verbosity level: {}", s)),
}
}
}
// HACK: the derive API doesn't support default subcommands, so we are going to make it so that it'll be easier to switch over when it's implemented.
// See: https://github.com/clap-rs/clap/issues/3857
impl From<Args> for CodeCommand {
fn from(args: Args) -> Self {
args.code
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn verify_cli() {
use clap::CommandFactory;
Args::command().debug_assert()
}
}

View file

@ -1,50 +0,0 @@
use std::{
sync::{Arc, Mutex},
time::{SystemTime, UNIX_EPOCH},
};
use log::*;
use steamguard::{steamapi, SteamGuardAccount};
use crate::AccountManager;
use super::*;
#[derive(Debug, Clone, Parser)]
#[clap(about = "Generate 2FA codes")]
pub struct CodeCommand {
#[clap(
long,
help = "Assume the computer's time is correct. Don't ask Steam for the time when generating codes."
)]
pub offline: bool,
}
impl<T> AccountCommand<T> for CodeCommand
where
T: Transport,
{
fn execute(
&self,
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()
} else {
steamapi::get_server_time(transport)?.server_time()
};
debug!("Time used to generate codes: {}", server_time);
for account in accounts {
let account = account.lock().unwrap();
info!("Generating code for {}", account.account_name);
trace!("{:?}", account);
let code = account.generate_code(server_time);
println!("{}", code);
}
Ok(())
}
}

View file

@ -1,23 +0,0 @@
use clap::CommandFactory;
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."
)]
pub shell: Shell,
}
impl ConstCommand for CompletionsCommand {
fn execute(&self) -> anyhow::Result<()> {
let mut app = Args::command_for_update();
clap_complete::generate(self.shell, &mut app, "steamguard", &mut std::io::stdout());
Ok(())
}
}

View file

@ -1,168 +0,0 @@
use std::sync::{Arc, Mutex};
use crossterm::tty::IsTty;
use log::*;
use steamguard::{Confirmation, Confirmer, ConfirmerError};
use crate::{tui, AccountManager};
use super::*;
#[derive(Debug, Clone, Parser)]
#[clap(about = "Interactive interface for steam mobile confirmations")]
pub struct ConfirmCommand {
#[clap(
short,
long,
help = "Accept all open mobile confirmations. Does not open interactive interface."
)]
pub accept_all: bool,
#[clap(
short,
long,
help = "If submitting a confirmation response fails, exit immediately."
)]
pub fail_fast: bool,
}
impl<T> AccountCommand<T> for ConfirmCommand
where
T: Transport + Clone,
{
fn execute(
&self,
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())?;
}
info!("{}: Checking for confirmations", account.account_name);
let confirmations: Vec<Confirmation>;
loop {
let confirmer = Confirmer::new(transport.clone(), &account);
match confirmer.get_confirmations() {
Ok(confs) => {
confirmations = confs;
break;
}
Err(ConfirmerError::InvalidTokens) => {
info!("obtaining new tokens");
crate::do_login(transport.clone(), &mut account, args.password.clone())?;
}
Err(err) => {
error!("Failed to get confirmations: {}", err);
return Err(err.into());
}
}
}
if confirmations.is_empty() {
info!("{}: No confirmations", account.account_name);
continue;
}
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,
) {
Ok(_) => {}
Err(err) => {
warn!("accept confirmation result: {}", err);
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) {
Ok(_) => {}
Err(err) => {
warn!("accept confirmation result: {}", err);
if self.fail_fast {
return Err(err.into());
}
any_failed = true;
}
}
match submit_loop(|| confirmer.deny_confirmations(&deny), self.fail_fast) {
Ok(_) => {}
Err(err) => {
warn!("deny confirmation result: {}", err);
if self.fail_fast {
return Err(err.into());
}
any_failed = true;
}
}
} else {
warn!("not a tty, not showing menu");
for conf in &confirmations {
println!("{}", conf.description());
}
}
if any_failed {
error!("Failed to respond to some confirmations.");
}
}
manager.save()?;
Ok(())
}
}

View file

@ -1,115 +0,0 @@
use log::*;
use steamguard::{Confirmation, ConfirmationType};
use crate::{debug::parse_json_stripped, tui};
use super::*;
#[derive(Debug, Clone, Parser, Default)]
#[clap(about = "Debug stuff, not useful for most users.")]
pub struct DebugCommand {
#[clap(long, help = "Show a text prompt.")]
pub demo_prompt: bool,
#[clap(long, help = "Show a \"press any key\" prompt.")]
pub demo_pause: bool,
#[clap(long, help = "Show a character prompt.")]
pub demo_prompt_char: bool,
#[clap(long, help = "Show an example confirmation menu using dummy data.")]
pub demo_conf_menu: bool,
#[clap(
long,
help = "Read the specified file, parse it, strip values, and print the result."
)]
pub print_stripped_json: Option<String>,
}
impl ConstCommand for DebugCommand {
fn execute(&self) -> anyhow::Result<()> {
if self.demo_prompt {
demo_prompt();
}
if self.demo_pause {
demo_pause();
}
if self.demo_prompt_char {
demo_prompt_char();
}
if self.demo_conf_menu {
demo_confirmation_menu();
}
if let Some(path) = self.print_stripped_json.as_ref() {
debug_print_json(path)?;
}
Ok(())
}
}
pub fn demo_prompt() {
print!("Prompt: ");
let result = tui::prompt();
println!("Result: {}", result);
}
pub fn demo_pause() {
let mut x = 0;
loop {
tui::pause();
x += 1;
println!("looped {} times", x);
}
}
pub fn demo_prompt_char() {
println!("Showing prompt");
let result = tui::prompt_char("Continue?", "yn");
println!("Result: {}", result);
let result = tui::prompt_char("Continue?", "Yn");
println!("Result: {}", result);
let result = tui::prompt_char("Continue?", "yN");
println!("Result: {}", result);
}
pub fn demo_confirmation_menu() {
info!("showing demo menu");
let (accept, deny) = tui::prompt_confirmation_menu(vec![
Confirmation {
id: "1234".to_owned(),
nonce: "12345".to_owned(),
conf_type: ConfirmationType::Trade,
creator_id: "09870987".to_owned(),
headline: "example confirmation".into(),
type_name: "Trade".to_owned(),
creation_time: 1687457923,
cancel: "Cancel".to_owned(),
accept: "Confirm".to_owned(),
icon: Some("".to_owned()),
multi: false,
summary: vec![],
},
Confirmation {
id: "1234".to_owned(),
nonce: "12345".to_owned(),
conf_type: ConfirmationType::MarketSell,
creator_id: "09870987".to_owned(),
headline: "example confirmation".into(),
type_name: "Market Sell".to_owned(),
creation_time: 1687457923,
cancel: "Cancel".to_owned(),
accept: "Confirm".to_owned(),
icon: Some("".to_owned()),
multi: false,
summary: vec![],
},
])
.expect("confirmation menu demo failed");
println!("accept: {}, deny: {}", accept.len(), deny.len());
}
fn debug_print_json(path: &str) -> anyhow::Result<()> {
let json = std::fs::read_to_string(path)?;
let v = parse_json_stripped(&json)?;
println!("{}", serde_json::to_string_pretty(&v)?);
Ok(())
}

View file

@ -1,62 +0,0 @@
use log::*;
use crate::{AccountManager, ManifestAccountLoadError};
use super::*;
#[derive(Debug, Clone, Parser)]
#[clap(about = "Decrypt all maFiles")]
pub struct DecryptCommand;
impl<T> ManifestCommand<T> for DecryptCommand
where
T: Transport,
{
fn execute(
&self,
_transport: T,
manager: &mut AccountManager,
_args: &GlobalArgs,
) -> anyhow::Result<()> {
load_accounts_with_prompts(manager)?;
#[cfg(feature = "keyring")]
if let Some(keyring_id) = manager.keyring_id() {
match crate::encryption::clear_passkey(keyring_id.clone()) {
Ok(_) => {
info!("Cleared passkey from keyring");
manager.clear_keyring_id();
}
Err(e) => warn!("Failed to clear passkey from keyring: {}", e),
}
}
for entry in manager.iter_mut() {
entry.encryption = None;
}
manager.submit_passkey(None);
manager.save()?;
Ok(())
}
}
fn load_accounts_with_prompts(manager: &mut AccountManager) -> anyhow::Result<()> {
loop {
match manager.load_accounts() {
Ok(_) => return Ok(()),
Err(
ManifestAccountLoadError::MissingPasskey
| ManifestAccountLoadError::IncorrectPasskey,
) => {
if manager.has_passkey() {
error!("Incorrect passkey");
}
let passkey = Some(crate::tui::prompt_passkey()?);
manager.submit_passkey(passkey);
}
Err(e) => {
error!("Could not load accounts: {}", e);
return Err(e.into());
}
}
}
}

View file

@ -1,75 +0,0 @@
use log::*;
use secrecy::ExposeSecret;
use crate::{
encryption::{EncryptionScheme, EntryEncryptor},
tui, AccountManager,
};
use super::*;
#[derive(Debug, Clone, Parser)]
#[clap(about = "Encrypt all maFiles")]
pub struct EncryptCommand;
impl<T> ManifestCommand<T> for EncryptCommand
where
T: Transport,
{
fn execute(
&self,
_transport: T,
manager: &mut AccountManager,
_args: &GlobalArgs,
) -> anyhow::Result<()> {
if !manager.has_passkey() {
let passkey: Option<SecretString>;
loop {
let passkey1 = tui::prompt_passkey()?;
if passkey1.expose_secret().is_empty() {
error!("Passkey cannot be empty, try again.");
continue;
}
let passkey_confirm = rpassword::prompt_password("Confirm encryption passkey: ")
.map(SecretString::new)?;
if passkey1.expose_secret() == passkey_confirm.expose_secret() {
passkey = Some(passkey1);
break;
}
error!("Passkeys do not match, try again.");
}
#[cfg(feature = "keyring")]
{
if tui::prompt_char(
"Would you like to store the passkey in your system keyring?",
"yn",
) == 'y'
{
let keyring_id = crate::encryption::generate_keyring_id();
match crate::encryption::store_passkey(
keyring_id.clone(),
passkey.clone().unwrap(),
) {
Ok(_) => {
info!("Stored passkey in keyring");
manager.set_keyring_id(keyring_id);
}
Err(e) => warn!(
"Failed to store passkey in keyring, continuing anyway: {}",
e
),
}
}
}
manager.submit_passkey(passkey);
}
manager.load_accounts()?;
for entry in manager.iter_mut() {
entry.encryption = Some(EncryptionScheme::generate());
}
manager.save()?;
Ok(())
}
}

View file

@ -1,71 +0,0 @@
use std::path::Path;
use log::*;
use crate::{accountmanager::ManifestAccountImportError, AccountManager};
use super::*;
#[derive(Debug, Clone, Parser, Default)]
#[clap(
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 = "Paths to one or more maFiles, eg. \"./gaben.maFile\"")]
pub files: Vec<String>,
}
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;
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);
info!("Imported account: {}", &file_path);
accounts_added += 1;
}
}
Err(err) => {
bail!("Failed to import account: {} {}", &file_path, err);
}
}
}
if accounts_added > 0 {
info!("Imported {} accounts", accounts_added);
}
manager.save()?;
Ok(())
}
}

View file

@ -1,60 +0,0 @@
use std::sync::{Arc, Mutex};
use log::*;
use qrcode::QrCode;
use secrecy::ExposeSecret;
use crate::AccountManager;
use super::*;
#[derive(Debug, Clone, Parser)]
#[clap(about = "Generate QR codes. This *will* print sensitive data to stdout.")]
pub struct QrCommand {
#[clap(
long,
help = "Force using ASCII chars to generate QR codes. Useful for terminals that don't support unicode."
)]
pub ascii: bool,
}
impl<T> AccountCommand<T> for QrCommand
where
T: Transport,
{
fn execute(
&self,
_transport: T,
_manager: &mut AccountManager,
accounts: Vec<Arc<Mutex<SteamGuardAccount>>>,
_args: &GlobalArgs,
) -> anyhow::Result<()> {
use anyhow::Context;
info!("Generating QR codes for {} accounts", accounts.len());
for account in accounts {
let account = account.lock().unwrap();
let qr = QrCode::new(account.uri.expose_secret())
.context(format!("generating qr code for {}", account.account_name))?;
info!("Printing QR code for {}", account.account_name);
let qr_string = if self.ascii {
qr.render()
.light_color(' ')
.dark_color('#')
.module_dimensions(2, 1)
.build()
} else {
use qrcode::render::unicode;
qr.render::<unicode::Dense1x2>()
.dark_color(unicode::Dense1x2::Light)
.light_color(unicode::Dense1x2::Dark)
.build()
};
println!("{}", qr_string);
}
Ok(())
}
}

View file

@ -1,128 +0,0 @@
use std::{
path::{Path, PathBuf},
sync::{Arc, Mutex},
};
use log::*;
use rqrr::PreparedImage;
use steamguard::{QrApprover, QrApproverError};
use crate::AccountManager;
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,
}
impl<T> AccountCommand<T> for QrLoginCommand
where
T: Transport + Clone,
{
fn execute(
&self,
transport: T,
_manager: &mut AccountManager,
accounts: Vec<Arc<Mutex<SteamGuardAccount>>>,
args: &GlobalArgs,
) -> anyhow::Result<()> {
ensure!(
accounts.len() == 1,
"You can only log in to one account at a time."
);
let mut account = accounts[0].lock().unwrap();
info!("Approving login to {}", account.account_name);
if account.tokens.is_none() {
crate::do_login(transport.clone(), &mut account, args.password.clone())?;
}
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
);
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()) {
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())?;
}
Err(e) => {
error!("Failed to approve login: {}", e);
break;
}
}
}
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");
}
}

View file

@ -1,102 +0,0 @@
use std::sync::{Arc, Mutex};
use log::*;
use steamguard::{accountlinker::RemoveAuthenticatorError, transport::TransportError};
use crate::{errors::UserError, tui, AccountManager};
use super::*;
#[derive(Debug, Clone, Parser)]
#[clap(about = "Remove the authenticator from an account.")]
pub struct RemoveCommand;
impl<T> AccountCommand<T> for RemoveCommand
where
T: Transport + Clone,
{
fn execute(
&self,
transport: T,
manager: &mut AccountManager,
accounts: Vec<Arc<Mutex<SteamGuardAccount>>>,
args: &GlobalArgs,
) -> anyhow::Result<()> {
eprintln!(
"This will remove the mobile authenticator from {} accounts: {}",
accounts.len(),
accounts
.iter()
.map(|a| a.lock().unwrap().account_name.clone())
.collect::<Vec<String>>()
.join(", ")
);
match tui::prompt_char("Do you want to continue?", "yN") {
'y' => {}
_ => {
info!("Aborting!");
return Err(UserError::Aborted.into());
}
}
let mut successful = vec![];
for a in accounts {
let mut account = a.lock().unwrap();
let mut revocation: Option<String> = None;
loop {
match account.remove_authenticator(transport.clone(), revocation.as_ref()) {
Ok(_) => {
info!("Removed authenticator from {}", account.account_name);
successful.push(account.account_name.clone());
break;
}
Err(RemoveAuthenticatorError::TransportError(TransportError::Unauthorized)) => {
error!("Account {} is not logged in", account.account_name);
crate::do_login(transport.clone(), &mut account, args.password.clone())?;
continue;
}
Err(RemoveAuthenticatorError::IncorrectRevocationCode {
attempts_remaining,
}) => {
error!(
"Revocation code was incorrect for {} ({} attempts remaining)",
account.account_name, attempts_remaining
);
if attempts_remaining == 0 {
error!("No attempts remaining, aborting!");
break;
}
let code = tui::prompt_non_empty(format!(
"Enter the revocation code for {}: ",
account.account_name
));
revocation = Some(code);
}
Err(RemoveAuthenticatorError::MissingRevocationCode) => {
let code = tui::prompt_non_empty(format!(
"Enter the revocation code for {}: ",
account.account_name
));
revocation = Some(code);
}
Err(err) => {
error!(
"Unexpected error when removing authenticator from {}: {}",
account.account_name, err
);
break;
}
}
}
}
for account_name in successful {
manager.remove_account(&account_name);
}
manager.save()?;
Ok(())
}
}

View file

@ -1,309 +0,0 @@
use log::*;
use phonenumber::PhoneNumber;
use secrecy::ExposeSecret;
use steamguard::{
accountlinker::{AccountLinkConfirmType, AccountLinkSuccess, RemoveAuthenticatorError},
phonelinker::PhoneLinker,
steamapi::PhoneClient,
token::Tokens,
AccountLinkError, AccountLinker, FinalizeLinkError,
};
use crate::{tui, AccountManager};
use super::*;
#[derive(Debug, Clone, Parser)]
#[clap(about = "Set up a new account with steamguard-cli")]
pub struct SetupCommand;
impl<T> ManifestCommand<T> for SetupCommand
where
T: Transport + Clone,
{
fn execute(
&self,
transport: T,
manager: &mut AccountManager,
args: &GlobalArgs,
) -> anyhow::Result<()> {
eprintln!("Log in to the account that you want to link to steamguard-cli");
eprint!("Username: ");
let username = tui::prompt().to_lowercase();
let account_name = username.clone();
if manager.account_exists(&username) {
bail!(
"Account {} already exists in manifest, remove it first",
username
);
}
info!("Logging in to {}", username);
let tokens = crate::do_login_raw(transport.clone(), username, args.password.clone())
.expect("Failed to log in. Account has not been linked.");
info!("Adding authenticator...");
let mut linker = AccountLinker::new(transport.clone(), tokens);
loop {
match linker.link() {
Ok(link) => {
return Self::add_new_account(link, manager, account_name, linker);
}
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())?;
}
Err(AccountLinkError::MustConfirmEmail) => {
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. {}",
err
);
return Err(err.into());
}
}
}
}
}
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()
);
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);
}
};
let mut tries = 0;
loop {
match linker.finalize(server_time, &mut account, confirm_code.clone()) {
Ok(_) => break,
Err(FinalizeLinkError::WantMore { server_time: s }) => {
server_time = s;
debug!("steam wants more 2fa codes (tries: {})", tries);
tries += 1;
if tries >= 30 {
error!("Failed to finalize: unable to generate valid 2fa codes");
bail!("Failed to finalize: unable to generate valid 2fa codes");
}
}
Err(err) => {
error!("Failed to finalize: {}", err);
return Err(err.into());
}
}
}
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.");
}
info!("Authenticator finalized.");
match manager.save() {
Ok(_) => {}
Err(err) => {
error!(
"Failed to save manifest, but we were able to save it before. {}",
err
);
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(())
}
}
pub fn do_add_phone_number<T: Transport>(transport: T, tokens: &Tokens) -> anyhow::Result<()> {
let client = PhoneClient::new(transport);
let linker = PhoneLinker::new(client, tokens.clone());
let phone_number: PhoneNumber;
loop {
eprintln!("Enter your phone number, including country code, in this format: +1 1234567890");
eprint!("Phone number: ");
let number = tui::prompt();
match phonenumber::parse(None, &number) {
Ok(p) => {
phone_number = p;
break;
}
Err(err) => {
error!("Failed to parse phone number: {}", err);
}
}
}
let resp = linker.set_account_phone_number(phone_number)?;
eprintln!(
"Please click the link in the email sent to {}",
resp.confirmation_email_address()
);
tui::pause();
debug!("sending phone verification code");
linker.send_phone_verification_code(0)?;
loop {
eprint!("Enter the code sent to your phone: ");
let code = tui::prompt();
match linker.verify_account_phone_with_code(code) {
Ok(_) => break,
Err(err) => {
error!("Failed to verify phone number: {}", err);
}
}
}
info!("Successfully added phone number to account");
Ok(())
}

View file

@ -1,27 +0,0 @@
/// Parses a JSON string and prints it in a readable format, with all values stripped and replaced with their types.
pub fn parse_json_stripped(json: &str) -> anyhow::Result<serde_json::Value> {
let v: serde_json::Value = serde_json::from_str(json)?;
let v = strip_json_value(v);
Ok(v)
}
pub fn strip_json_value(v: serde_json::Value) -> serde_json::Value {
match v {
serde_json::Value::Object(mut map) => {
for (_, v) in map.iter_mut() {
*v = strip_json_value(v.clone());
}
serde_json::Value::Object(map)
}
serde_json::Value::Array(mut arr) => {
for v in arr.iter_mut() {
*v = strip_json_value(v.clone());
}
serde_json::Value::Array(arr)
}
serde_json::Value::String(_) => serde_json::Value::String("string".into()),
serde_json::Value::Number(_) => serde_json::Value::Number(0.into()),
serde_json::Value::Bool(_) => serde_json::Value::Bool(false),
serde_json::Value::Null => serde_json::Value::Null,
}
}

64
src/demos.rs Normal file
View file

@ -0,0 +1,64 @@
use crate::tui;
use log::*;
use steamguard::{Confirmation, ConfirmationType};
pub fn demo_prompt() {
print!("Prompt: ");
let result = tui::prompt();
println!("Result: {}", result);
}
pub fn demo_pause() {
let mut x = 0;
loop {
tui::pause();
x += 1;
println!("looped {} times", x);
}
}
pub fn demo_prompt_char() {
println!("Showing prompt");
let result = tui::prompt_char("Continue?", "yn");
println!("Result: {}", result);
let result = tui::prompt_char("Continue?", "Yn");
println!("Result: {}", result);
let result = tui::prompt_char("Continue?", "yN");
println!("Result: {}", result);
}
pub fn demo_confirmation_menu() {
info!("showing demo menu");
let (accept, deny) = tui::prompt_confirmation_menu(vec![
Confirmation {
id: 1234,
key: 12345,
conf_type: ConfirmationType::Trade,
creator: 09870987,
description: "example confirmation".into(),
},
Confirmation {
id: 1234,
key: 12345,
conf_type: ConfirmationType::MarketSell,
creator: 09870987,
description: "example confirmation".into(),
},
Confirmation {
id: 1234,
key: 12345,
conf_type: ConfirmationType::AccountRecovery,
creator: 09870987,
description: "example confirmation".into(),
},
Confirmation {
id: 1234,
key: 12345,
conf_type: ConfirmationType::Trade,
creator: 09870987,
description: "example confirmation".into(),
},
])
.expect("confirmation menu demo failed");
println!("accept: {}, deny: {}", accept.len(), deny.len());
}

View file

@ -1,118 +1,243 @@
use aes::cipher::InvalidLength;
use rand::Rng;
use aes::Aes256;
use block_modes::block_padding::{NoPadding, Padding, Pkcs7};
use block_modes::{BlockMode, Cbc};
use ring::pbkdf2;
use ring::rand::SecureRandom;
use serde::{Deserialize, Serialize};
use thiserror::Error;
mod argon2id_aes;
#[cfg(feature = "keyring")]
mod keyring;
mod legacy;
pub use argon2id_aes::*;
pub use legacy::*;
#[cfg(feature = "keyring")]
pub use crate::encryption::keyring::*;
const SALT_LENGTH: usize = 8;
const IV_LENGTH: usize = 16;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EntryEncryptionParams {
#[serde(rename = "encryption_iv")]
pub iv: String,
#[serde(rename = "encryption_salt")]
pub salt: String,
#[serde(default, rename = "encryption_scheme")]
pub scheme: EncryptionScheme,
}
impl EntryEncryptionParams {
pub fn generate() -> EntryEncryptionParams {
let rng = ring::rand::SystemRandom::new();
let mut salt = [0u8; SALT_LENGTH];
let mut iv = [0u8; IV_LENGTH];
rng.fill(&mut salt).expect("Unable to generate salt.");
rng.fill(&mut iv).expect("Unable to generate IV.");
EntryEncryptionParams {
salt: base64::encode(salt),
iv: base64::encode(iv),
scheme: Default::default(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "scheme")]
pub enum EncryptionScheme {
Argon2idAes256(Argon2idAes256),
LegacySdaCompatible(LegacySdaCompatible),
/// Encryption scheme that is compatible with SteamDesktopAuthenticator.
LegacySdaCompatible = -1,
}
impl Default for EncryptionScheme {
fn default() -> Self {
Self::LegacySdaCompatible
}
}
pub trait EntryEncryptor {
fn generate() -> Self;
fn encrypt(
&self,
passkey: &str,
passkey: &String,
params: &EntryEncryptionParams,
plaintext: Vec<u8>,
) -> anyhow::Result<Vec<u8>, EntryEncryptionError>;
fn decrypt(
&self,
passkey: &str,
passkey: &String,
params: &EntryEncryptionParams,
ciphertext: Vec<u8>,
) -> anyhow::Result<Vec<u8>, EntryEncryptionError>;
}
impl EntryEncryptor for EncryptionScheme {
fn generate() -> Self {
EncryptionScheme::Argon2idAes256(Argon2idAes256::generate())
/// Encryption scheme that is compatible with SteamDesktopAuthenticator.
pub struct LegacySdaCompatible;
impl LegacySdaCompatible {
const PBKDF2_ITERATIONS: u32 = 50000; // This is excessive, but necessary to maintain compatibility with SteamDesktopAuthenticator.
const KEY_SIZE_BYTES: usize = 32;
fn get_encryption_key(
passkey: &String,
salt: &String,
) -> anyhow::Result<[u8; Self::KEY_SIZE_BYTES]> {
let password_bytes = passkey.as_bytes();
let salt_bytes = base64::decode(salt)?;
let mut full_key: [u8; Self::KEY_SIZE_BYTES] = [0u8; Self::KEY_SIZE_BYTES];
pbkdf2::derive(
pbkdf2::PBKDF2_HMAC_SHA1,
std::num::NonZeroU32::new(Self::PBKDF2_ITERATIONS).unwrap(),
&salt_bytes,
password_bytes,
&mut full_key,
);
return Ok(full_key);
}
}
type Aes256Cbc = Cbc<Aes256, NoPadding>;
impl EntryEncryptor for LegacySdaCompatible {
// ngl, this logic sucks ass. its kinda annoying that the logic is not completely symetric.
fn encrypt(
&self,
passkey: &str,
passkey: &String,
params: &EntryEncryptionParams,
plaintext: Vec<u8>,
) -> anyhow::Result<Vec<u8>, EntryEncryptionError> {
match self {
EncryptionScheme::Argon2idAes256(scheme) => scheme.encrypt(passkey, plaintext),
EncryptionScheme::LegacySdaCompatible(scheme) => scheme.encrypt(passkey, plaintext),
let key = Self::get_encryption_key(&passkey.into(), &params.salt)?;
let iv = base64::decode(&params.iv)?;
let cipher = Aes256Cbc::new_from_slices(&key, &iv)?;
let origsize = plaintext.len();
let buffersize: usize = (origsize / 16 + (if origsize % 16 == 0 { 0 } else { 1 })) * 16;
let mut buffer = vec![];
for chunk in plaintext.as_slice().chunks(128) {
let chunksize = chunk.len();
let buffersize = (chunksize / 16 + (if chunksize % 16 == 0 { 0 } else { 1 })) * 16;
let mut chunkbuffer = vec![0xffu8; buffersize];
chunkbuffer[..chunksize].copy_from_slice(&chunk);
if buffersize != chunksize {
// pad the last chunk
chunkbuffer = Pkcs7::pad(&mut chunkbuffer, chunksize, buffersize)
.unwrap()
.to_vec();
}
buffer.append(&mut chunkbuffer);
}
let ciphertext = cipher.encrypt(&mut buffer, buffersize)?;
let final_buffer = base64::encode(&ciphertext);
return Ok(final_buffer.as_bytes().to_vec());
}
fn decrypt(
&self,
passkey: &str,
passkey: &String,
params: &EntryEncryptionParams,
ciphertext: Vec<u8>,
) -> anyhow::Result<Vec<u8>, EntryEncryptionError> {
match self {
EncryptionScheme::Argon2idAes256(scheme) => scheme.decrypt(passkey, ciphertext),
EncryptionScheme::LegacySdaCompatible(scheme) => scheme.decrypt(passkey, ciphertext),
}
let key = Self::get_encryption_key(&passkey.into(), &params.salt)?;
let iv = base64::decode(&params.iv)?;
let cipher = Aes256Cbc::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);
let mut decrypted = cipher.decrypt(&mut buffer)?;
let unpadded = Pkcs7::unpad(&mut decrypted)?;
return Ok(unpadded.to_vec());
}
}
#[derive(Debug, Error)]
pub enum EntryEncryptionError {
#[error("Invalid ciphertext length. The ciphertext must be a multiple of 16 bytes.")]
InvalidCipherTextLength,
#[error(transparent)]
Unknown(#[from] anyhow::Error),
}
/// For some reason, these errors do not get converted to `ManifestAccountLoadError`s, even though they get converted into `anyhow::Error` just fine. I am too lazy to figure out why right now.
impl From<InvalidLength> for EntryEncryptionError {
fn from(error: InvalidLength) -> Self {
Self::Unknown(anyhow::Error::from(error))
impl From<block_modes::BlockModeError> for EntryEncryptionError {
fn from(error: block_modes::BlockModeError) -> Self {
return Self::Unknown(anyhow::Error::from(error));
}
}
impl From<inout::NotEqualError> for EntryEncryptionError {
fn from(error: inout::NotEqualError) -> Self {
Self::Unknown(anyhow::Error::from(error))
impl From<block_modes::InvalidKeyIvLength> for EntryEncryptionError {
fn from(error: block_modes::InvalidKeyIvLength) -> Self {
return Self::Unknown(anyhow::Error::from(error));
}
}
impl From<inout::PadError> for EntryEncryptionError {
fn from(error: inout::PadError) -> Self {
Self::Unknown(anyhow::Error::from(error))
impl From<block_modes::block_padding::PadError> for EntryEncryptionError {
fn from(error: block_modes::block_padding::PadError) -> Self {
return Self::Unknown(anyhow!("PadError"));
}
}
impl From<inout::block_padding::UnpadError> for EntryEncryptionError {
fn from(error: inout::block_padding::UnpadError) -> Self {
Self::Unknown(anyhow::Error::from(error))
impl From<block_modes::block_padding::UnpadError> for EntryEncryptionError {
fn from(error: block_modes::block_padding::UnpadError) -> Self {
return Self::Unknown(anyhow!("UnpadError"));
}
}
impl From<base64::DecodeError> for EntryEncryptionError {
fn from(error: base64::DecodeError) -> Self {
Self::Unknown(anyhow::Error::from(error))
return Self::Unknown(anyhow::Error::from(error));
}
}
impl From<std::io::Error> for EntryEncryptionError {
fn from(error: std::io::Error) -> Self {
Self::Unknown(anyhow::Error::from(error))
return Self::Unknown(anyhow::Error::from(error));
}
}
pub fn generate_keyring_id() -> String {
let rng = rand::thread_rng();
rng.sample_iter(rand::distributions::Alphanumeric)
.take(32)
.map(char::from)
.collect()
#[cfg(test)]
mod tests {
use super::*;
use proptest::prelude::*;
/// This test ensures compatibility with SteamDesktopAuthenticator and with previous versions of steamguard-cli
#[test]
fn test_encryption_key() {
assert_eq!(
LegacySdaCompatible::get_encryption_key(&"password".into(), &"GMhL0N2hqXg=".into())
.unwrap(),
base64::decode("KtiRa4/OxW83MlB6URf+Z8rAGj7CBY+pDlwD/NuVo6Y=")
.unwrap()
.as_slice()
);
assert_eq!(
LegacySdaCompatible::get_encryption_key(&"password".into(), &"wTzTE9A6aN8=".into())
.unwrap(),
base64::decode("Dqpej/3DqEat0roJaHmu3luYgDzRCUmzX94n4fqvWj8=")
.unwrap()
.as_slice()
);
}
#[test]
fn test_ensure_encryption_symmetric() -> anyhow::Result<()> {
let passkey = "password";
let params = EntryEncryptionParams::generate();
let orig = "tactical glizzy".as_bytes().to_vec();
let encrypted =
LegacySdaCompatible::encrypt(&passkey.clone().into(), &params, orig.clone()).unwrap();
let result = LegacySdaCompatible::decrypt(&passkey.into(), &params, encrypted).unwrap();
assert_eq!(orig, result.to_vec());
return Ok(());
}
prop_compose! {
/// An insecure but reproducible strategy for generating encryption params.
fn encryption_params()(salt in any::<[u8; SALT_LENGTH]>(), iv in any::<[u8; IV_LENGTH]>()) -> EntryEncryptionParams {
EntryEncryptionParams {
salt: base64::encode(&salt),
iv: base64::encode(&iv),
scheme: EncryptionScheme::LegacySdaCompatible,
}
}
}
// proptest! {
// #[test]
// fn ensure_encryption_symmetric(
// passkey in ".{1,}",
// params in encryption_params(),
// data in any::<Vec<u8>>(),
// ) {
// prop_assume!(data.len() >= 2);
// let mut orig = data;
// orig[0] = '{' as u8;
// let n = orig.len() - 1;
// orig[n] = '}' as u8;
// let encrypted = LegacySdaCompatible::encrypt(&passkey.clone().into(), &params, orig.clone()).unwrap();
// let result = LegacySdaCompatible::decrypt(&passkey.into(), &params, encrypted).unwrap();
// prop_assert_eq!(orig, result.to_vec());
// }
// }
}

View file

@ -1,158 +0,0 @@
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::*;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Argon2idAes256 {
pub iv: String,
pub salt: String,
}
impl Argon2idAes256 {
const KEY_SIZE_BYTES: usize = 32;
const IV_LENGTH: usize = 16;
const SALT_LENGTH: usize = 16;
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 mut full_key: [u8; Self::KEY_SIZE_BYTES] = [0u8; Self::KEY_SIZE_BYTES];
let deriver = Argon2::new(
argon2::Algorithm::Argon2id,
argon2::Version::V0x13,
Self::config(),
);
deriver.hash_password_into(password_bytes, &salt_bytes, &mut full_key)?;
Ok(full_key)
}
fn config() -> argon2::Params {
argon2::Params::new(
12 * 1024, // 12MB
3,
12,
Some(Self::KEY_SIZE_BYTES),
)
.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 {
fn generate() -> Self {
let mut rng = rand::rngs::OsRng;
let mut salt = [0u8; Self::SALT_LENGTH];
let mut iv = [0u8; Self::IV_LENGTH];
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),
}
}
fn encrypt(
&self,
passkey: &str,
plaintext: Vec<u8>,
) -> anyhow::Result<Vec<u8>, EntryEncryptionError> {
let start = std::time::Instant::now();
let key = Self::get_encryption_key(passkey, &self.salt)?;
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 ciphertext = cipher.encrypt_padded_vec_mut::<Pkcs7>(&plaintext);
let encoded = base64::engine::general_purpose::STANDARD.encode(ciphertext);
debug!("encryption took: {:?}", start.elapsed());
Ok(encoded.as_bytes().to_vec())
}
fn decrypt(
&self,
passkey: &str,
ciphertext: Vec<u8>,
) -> anyhow::Result<Vec<u8>, EntryEncryptionError> {
let start = std::time::Instant::now();
let key = Self::get_encryption_key(passkey, &self.salt)?;
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 size: usize = decoded.len() / 16 + (if decoded.len() % 16 == 0 { 0 } else { 1 });
let mut buffer = vec![0xffu8; 16 * size];
buffer[..decoded.len()].copy_from_slice(&decoded);
let decrypted = cipher.decrypt_padded_mut::<Pkcs7>(&mut buffer)?;
debug!("decryption took: {:?}", start.elapsed());
Ok(decrypted.to_vec())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_encryption_key() {
assert_eq!(
base64::engine::general_purpose::STANDARD.encode(
Argon2idAes256::get_encryption_key("password", "GMhL0N2hqXg=")
.unwrap()
.as_slice()
),
"DTm3hc95aKyAGmyVMZdLUPfcPjcXN1i1zYObYJg2GzY="
);
}
#[test]
fn test_encryption_key2() {
assert_eq!(
base64::engine::general_purpose::STANDARD.encode(
Argon2idAes256::get_encryption_key("password", "wTzTE9A6aN8=")
.unwrap()
.as_slice()
),
"zwMjXhwggpJWCvkouG/xrSPZRWn2cUUyph3PAViRONA="
);
}
#[test]
fn test_ensure_encryption_symmetric() -> anyhow::Result<()> {
let cases = [
"foo",
"tactical glizzy",
"glizzy gladiator",
"shadow wizard money gang",
"shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells",
];
let passkey = "password";
let scheme = Argon2idAes256::generate();
for case in cases {
eprintln!("testing case: {} (len {})", case, case.len());
let orig = case.as_bytes().to_vec();
let encrypted = scheme.encrypt(passkey, orig.clone()).unwrap();
let result = scheme.decrypt(passkey, encrypted).unwrap();
assert_eq!(orig, result.to_vec());
}
Ok(())
}
}

View file

@ -1,24 +0,0 @@
use keyring::Entry;
use secrecy::{ExposeSecret, SecretString};
const KEYRING_SERVICE: &str = "steamguard-cli";
pub fn init_keyring(keyring_id: String) -> keyring::Result<Entry> {
Entry::new(KEYRING_SERVICE, &keyring_id)
}
pub fn try_passkey_from_keyring(keyring_id: String) -> keyring::Result<Option<SecretString>> {
let entry = init_keyring(keyring_id)?;
let passkey = entry.get_password()?;
Ok(Some(SecretString::new(passkey)))
}
pub fn store_passkey(keyring_id: String, passkey: SecretString) -> keyring::Result<()> {
let entry = init_keyring(keyring_id)?;
entry.set_password(passkey.expose_secret())
}
pub fn clear_passkey(keyring_id: String) -> keyring::Result<()> {
let entry = init_keyring(keyring_id)?;
entry.delete_password()
}

View file

@ -1,178 +0,0 @@
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;
use super::*;
/// Encryption scheme that is compatible with SteamDesktopAuthenticator.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LegacySdaCompatible {
pub iv: String,
pub salt: String,
}
impl LegacySdaCompatible {
const PBKDF2_ITERATIONS: u32 = 50000; // This is necessary to maintain compatibility with SteamDesktopAuthenticator.
const KEY_SIZE_BYTES: usize = 32;
const SALT_LENGTH: usize = 8;
const IV_LENGTH: usize = 16;
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 mut full_key: [u8; Self::KEY_SIZE_BYTES] = [0u8; Self::KEY_SIZE_BYTES];
pbkdf2::pbkdf2_hmac::<Sha1>(
password_bytes,
&salt_bytes,
Self::PBKDF2_ITERATIONS,
&mut full_key,
);
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 {
fn generate() -> LegacySdaCompatible {
let mut rng = rand::rngs::OsRng;
let mut salt = [0u8; Self::SALT_LENGTH];
let mut iv = [0u8; Self::IV_LENGTH];
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),
}
}
fn encrypt(
&self,
passkey: &str,
plaintext: Vec<u8>,
) -> anyhow::Result<Vec<u8>, EntryEncryptionError> {
let start = std::time::Instant::now();
let key = Self::get_encryption_key(passkey, &self.salt)?;
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 ciphertext = cipher.encrypt_padded_vec_mut::<Pkcs7>(&plaintext);
let encoded = base64::engine::general_purpose::STANDARD.encode(ciphertext);
debug!("encryption took: {:?}", start.elapsed());
Ok(encoded.as_bytes().to_vec())
}
fn decrypt(
&self,
passkey: &str,
ciphertext: Vec<u8>,
) -> anyhow::Result<Vec<u8>, EntryEncryptionError> {
let start = std::time::Instant::now();
let key = Self::get_encryption_key(passkey, &self.salt)?;
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 size: usize = decoded.len() / 16 + (if decoded.len() % 16 == 0 { 0 } else { 1 });
let mut buffer = vec![0xffu8; 16 * size];
buffer[..decoded.len()].copy_from_slice(&decoded);
let decrypted = cipher.decrypt_padded_mut::<Pkcs7>(&mut buffer)?;
debug!("decryption took: {:?}", start.elapsed());
Ok(decrypted.to_vec())
}
}
#[cfg(test)]
mod tests {
use super::*;
use proptest::prelude::*;
/// This test ensures compatibility with SteamDesktopAuthenticator and with previous versions of steamguard-cli
#[test]
fn test_encryption_key() {
assert_eq!(
LegacySdaCompatible::get_encryption_key("password", "GMhL0N2hqXg=")
.unwrap()
.as_slice(),
base64::engine::general_purpose::STANDARD
.decode("KtiRa4/OxW83MlB6URf+Z8rAGj7CBY+pDlwD/NuVo6Y=")
.unwrap()
.as_slice()
);
assert_eq!(
LegacySdaCompatible::get_encryption_key("password", "wTzTE9A6aN8=")
.unwrap()
.as_slice(),
base64::engine::general_purpose::STANDARD
.decode("Dqpej/3DqEat0roJaHmu3luYgDzRCUmzX94n4fqvWj8=")
.unwrap()
.as_slice()
);
}
#[test]
fn test_ensure_encryption_symmetric() -> anyhow::Result<()> {
let cases = [
"foo",
"tactical glizzy",
"glizzy gladiator",
"shadow wizard money gang",
"shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells",
];
let passkey = "password";
let scheme = LegacySdaCompatible::generate();
for case in cases {
eprintln!("testing case: {} (len {})", case, case.len());
let orig = case.as_bytes().to_vec();
let encrypted = scheme.encrypt(passkey, orig.clone()).unwrap();
let result = scheme.decrypt(passkey, encrypted).unwrap();
assert_eq!(orig, result.to_vec());
}
Ok(())
}
prop_compose! {
/// 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),
}
}
}
// proptest! {
// #[test]
// fn ensure_encryption_symmetric(
// passkey in ".{1,}",
// params in encryption_params(),
// data in any::<Vec<u8>>(),
// ) {
// prop_assume!(data.len() >= 2);
// let mut orig = data;
// orig[0] = '{' as u8;
// let n = orig.len() - 1;
// orig[n] = '}' as u8;
// let encrypted = LegacySdaCompatible::encrypt(&passkey.clone().into(), &params, orig.clone()).unwrap();
// let result = LegacySdaCompatible::decrypt(&passkey.into(), &params, encrypted).unwrap();
// prop_assert_eq!(orig, result.to_vec());
// }
// }
}

View file

@ -4,4 +4,6 @@ use thiserror::Error;
pub(crate) enum UserError {
#[error("User aborted the operation.")]
Aborted,
#[error("Unknown subcommand. It may need to be implemented.")]
UnknownSubcommand,
}

View file

@ -1 +0,0 @@
{"shared_secret":"zvIayp3JPvtvX/QGHqsqKBk/44s=","serial_number":"kljasfhds","revocation_code":"R12345","uri":"otpauth://totp/Steam:example?secret=ASDF&issuer=Steam","server_time":1602522478,"account_name":"example","token_gid":"jkkjlhkhjgf","identity_secret":"kjsdlwowiqe=","secret_1":"sklduhfgsdlkjhf=","status":1,"device_id":"android:99d2ad0e-4bad-4247-b111-26393aae0be3","fully_enrolled":true,"Session":{"SessionID":"a;lskdjf","SteamLogin":"983498437543","SteamLoginSecure":"dlkjdsl;j%7C%32984730298","WebCookie":";lkjsed;klfjas98093","OAuthToken":"asdk;lf;dsjlkfd","SteamID":1234}}

View file

@ -1,6 +0,0 @@
#!/bin/bash
cat "1234.maFile" | jq -r '.Session | keys | .[]' | while read key; do
cat "1234.maFile" | jq ".Session[\"$key\"] = null" > "null-$key.maFile"
cat "1234.maFile" | jq ". | del(.Session.$key)" > "missing-$key.maFile"
done

View file

@ -1,83 +0,0 @@
{
"encrypted": false,
"first_run": true,
"entries": [
{
"encryption_iv": null,
"encryption_salt": null,
"filename": "missing-OAuthToken.maFile",
"steamid": 1234
},
{
"encryption_iv": null,
"encryption_salt": null,
"filename": "missing-SessionID.maFile",
"steamid": 1234
},
{
"encryption_iv": null,
"encryption_salt": null,
"filename": "missing-SteamID.maFile",
"steamid": 1234
},
{
"encryption_iv": null,
"encryption_salt": null,
"filename": "missing-SteamLogin.maFile",
"steamid": 1234
},
{
"encryption_iv": null,
"encryption_salt": null,
"filename": "missing-SteamLoginSecure.maFile",
"steamid": 1234
},
{
"encryption_iv": null,
"encryption_salt": null,
"filename": "missing-WebCookie.maFile",
"steamid": 1234
},
{
"encryption_iv": null,
"encryption_salt": null,
"filename": "null-OAuthToken.maFile",
"steamid": 1234
},
{
"encryption_iv": null,
"encryption_salt": null,
"filename": "null-SessionID.maFile",
"steamid": 1234
},
{
"encryption_iv": null,
"encryption_salt": null,
"filename": "null-SteamID.maFile",
"steamid": 1234
},
{
"encryption_iv": null,
"encryption_salt": null,
"filename": "null-SteamLogin.maFile",
"steamid": 1234
},
{
"encryption_iv": null,
"encryption_salt": null,
"filename": "null-SteamLoginSecure.maFile",
"steamid": 1234
},
{
"encryption_iv": null,
"encryption_salt": null,
"filename": "null-WebCookie.maFile",
"steamid": 1234
}
],
"periodic_checking": false,
"periodic_checking_interval": 5,
"periodic_checking_checkall": false,
"auto_confirm_market_transactions": false,
"auto_confirm_trades": false
}

View file

@ -1,21 +0,0 @@
{
"shared_secret": "zvIayp3JPvtvX/QGHqsqKBk/44s=",
"serial_number": "kljasfhds",
"revocation_code": "R12345",
"uri": "otpauth://totp/Steam:example?secret=ASDF&issuer=Steam",
"server_time": 1602522478,
"account_name": "example",
"token_gid": "jkkjlhkhjgf",
"identity_secret": "kjsdlwowiqe=",
"secret_1": "sklduhfgsdlkjhf=",
"status": 1,
"device_id": "android:99d2ad0e-4bad-4247-b111-26393aae0be3",
"fully_enrolled": true,
"Session": {
"SessionID": "a;lskdjf",
"SteamLogin": "983498437543",
"SteamLoginSecure": "dlkjdsl;j%7C%32984730298",
"WebCookie": ";lkjsed;klfjas98093",
"SteamID": 1234
}
}

View file

@ -1,21 +0,0 @@
{
"shared_secret": "zvIayp3JPvtvX/QGHqsqKBk/44s=",
"serial_number": "kljasfhds",
"revocation_code": "R12345",
"uri": "otpauth://totp/Steam:example?secret=ASDF&issuer=Steam",
"server_time": 1602522478,
"account_name": "example",
"token_gid": "jkkjlhkhjgf",
"identity_secret": "kjsdlwowiqe=",
"secret_1": "sklduhfgsdlkjhf=",
"status": 1,
"device_id": "android:99d2ad0e-4bad-4247-b111-26393aae0be3",
"fully_enrolled": true,
"Session": {
"SteamLogin": "983498437543",
"SteamLoginSecure": "dlkjdsl;j%7C%32984730298",
"WebCookie": ";lkjsed;klfjas98093",
"OAuthToken": "asdk;lf;dsjlkfd",
"SteamID": 1234
}
}

View file

@ -1,21 +0,0 @@
{
"shared_secret": "zvIayp3JPvtvX/QGHqsqKBk/44s=",
"serial_number": "kljasfhds",
"revocation_code": "R12345",
"uri": "otpauth://totp/Steam:example?secret=ASDF&issuer=Steam",
"server_time": 1602522478,
"account_name": "example",
"token_gid": "jkkjlhkhjgf",
"identity_secret": "kjsdlwowiqe=",
"secret_1": "sklduhfgsdlkjhf=",
"status": 1,
"device_id": "android:99d2ad0e-4bad-4247-b111-26393aae0be3",
"fully_enrolled": true,
"Session": {
"SessionID": "a;lskdjf",
"SteamLogin": "983498437543",
"SteamLoginSecure": "dlkjdsl;j%7C%32984730298",
"WebCookie": ";lkjsed;klfjas98093",
"OAuthToken": "asdk;lf;dsjlkfd"
}
}

View file

@ -1,21 +0,0 @@
{
"shared_secret": "zvIayp3JPvtvX/QGHqsqKBk/44s=",
"serial_number": "kljasfhds",
"revocation_code": "R12345",
"uri": "otpauth://totp/Steam:example?secret=ASDF&issuer=Steam",
"server_time": 1602522478,
"account_name": "example",
"token_gid": "jkkjlhkhjgf",
"identity_secret": "kjsdlwowiqe=",
"secret_1": "sklduhfgsdlkjhf=",
"status": 1,
"device_id": "android:99d2ad0e-4bad-4247-b111-26393aae0be3",
"fully_enrolled": true,
"Session": {
"SessionID": "a;lskdjf",
"SteamLoginSecure": "dlkjdsl;j%7C%32984730298",
"WebCookie": ";lkjsed;klfjas98093",
"OAuthToken": "asdk;lf;dsjlkfd",
"SteamID": 1234
}
}

View file

@ -1,21 +0,0 @@
{
"shared_secret": "zvIayp3JPvtvX/QGHqsqKBk/44s=",
"serial_number": "kljasfhds",
"revocation_code": "R12345",
"uri": "otpauth://totp/Steam:example?secret=ASDF&issuer=Steam",
"server_time": 1602522478,
"account_name": "example",
"token_gid": "jkkjlhkhjgf",
"identity_secret": "kjsdlwowiqe=",
"secret_1": "sklduhfgsdlkjhf=",
"status": 1,
"device_id": "android:99d2ad0e-4bad-4247-b111-26393aae0be3",
"fully_enrolled": true,
"Session": {
"SessionID": "a;lskdjf",
"SteamLogin": "983498437543",
"WebCookie": ";lkjsed;klfjas98093",
"OAuthToken": "asdk;lf;dsjlkfd",
"SteamID": 1234
}
}

View file

@ -1,21 +0,0 @@
{
"shared_secret": "zvIayp3JPvtvX/QGHqsqKBk/44s=",
"serial_number": "kljasfhds",
"revocation_code": "R12345",
"uri": "otpauth://totp/Steam:example?secret=ASDF&issuer=Steam",
"server_time": 1602522478,
"account_name": "example",
"token_gid": "jkkjlhkhjgf",
"identity_secret": "kjsdlwowiqe=",
"secret_1": "sklduhfgsdlkjhf=",
"status": 1,
"device_id": "android:99d2ad0e-4bad-4247-b111-26393aae0be3",
"fully_enrolled": true,
"Session": {
"SessionID": "a;lskdjf",
"SteamLogin": "983498437543",
"SteamLoginSecure": "dlkjdsl;j%7C%32984730298",
"OAuthToken": "asdk;lf;dsjlkfd",
"SteamID": 1234
}
}

View file

@ -1,22 +0,0 @@
{
"shared_secret": "zvIayp3JPvtvX/QGHqsqKBk/44s=",
"serial_number": "kljasfhds",
"revocation_code": "R12345",
"uri": "otpauth://totp/Steam:example?secret=ASDF&issuer=Steam",
"server_time": 1602522478,
"account_name": "example",
"token_gid": "jkkjlhkhjgf",
"identity_secret": "kjsdlwowiqe=",
"secret_1": "sklduhfgsdlkjhf=",
"status": 1,
"device_id": "android:99d2ad0e-4bad-4247-b111-26393aae0be3",
"fully_enrolled": true,
"Session": {
"SessionID": "a;lskdjf",
"SteamLogin": "983498437543",
"SteamLoginSecure": "dlkjdsl;j%7C%32984730298",
"WebCookie": ";lkjsed;klfjas98093",
"OAuthToken": null,
"SteamID": 1234
}
}

View file

@ -1,22 +0,0 @@
{
"shared_secret": "zvIayp3JPvtvX/QGHqsqKBk/44s=",
"serial_number": "kljasfhds",
"revocation_code": "R12345",
"uri": "otpauth://totp/Steam:example?secret=ASDF&issuer=Steam",
"server_time": 1602522478,
"account_name": "example",
"token_gid": "jkkjlhkhjgf",
"identity_secret": "kjsdlwowiqe=",
"secret_1": "sklduhfgsdlkjhf=",
"status": 1,
"device_id": "android:99d2ad0e-4bad-4247-b111-26393aae0be3",
"fully_enrolled": true,
"Session": {
"SessionID": null,
"SteamLogin": "983498437543",
"SteamLoginSecure": "dlkjdsl;j%7C%32984730298",
"WebCookie": ";lkjsed;klfjas98093",
"OAuthToken": "asdk;lf;dsjlkfd",
"SteamID": 1234
}
}

View file

@ -1,22 +0,0 @@
{
"shared_secret": "zvIayp3JPvtvX/QGHqsqKBk/44s=",
"serial_number": "kljasfhds",
"revocation_code": "R12345",
"uri": "otpauth://totp/Steam:example?secret=ASDF&issuer=Steam",
"server_time": 1602522478,
"account_name": "example",
"token_gid": "jkkjlhkhjgf",
"identity_secret": "kjsdlwowiqe=",
"secret_1": "sklduhfgsdlkjhf=",
"status": 1,
"device_id": "android:99d2ad0e-4bad-4247-b111-26393aae0be3",
"fully_enrolled": true,
"Session": {
"SessionID": "a;lskdjf",
"SteamLogin": "983498437543",
"SteamLoginSecure": "dlkjdsl;j%7C%32984730298",
"WebCookie": ";lkjsed;klfjas98093",
"OAuthToken": "asdk;lf;dsjlkfd",
"SteamID": null
}
}

View file

@ -1,22 +0,0 @@
{
"shared_secret": "zvIayp3JPvtvX/QGHqsqKBk/44s=",
"serial_number": "kljasfhds",
"revocation_code": "R12345",
"uri": "otpauth://totp/Steam:example?secret=ASDF&issuer=Steam",
"server_time": 1602522478,
"account_name": "example",
"token_gid": "jkkjlhkhjgf",
"identity_secret": "kjsdlwowiqe=",
"secret_1": "sklduhfgsdlkjhf=",
"status": 1,
"device_id": "android:99d2ad0e-4bad-4247-b111-26393aae0be3",
"fully_enrolled": true,
"Session": {
"SessionID": "a;lskdjf",
"SteamLogin": null,
"SteamLoginSecure": "dlkjdsl;j%7C%32984730298",
"WebCookie": ";lkjsed;klfjas98093",
"OAuthToken": "asdk;lf;dsjlkfd",
"SteamID": 1234
}
}

View file

@ -1,22 +0,0 @@
{
"shared_secret": "zvIayp3JPvtvX/QGHqsqKBk/44s=",
"serial_number": "kljasfhds",
"revocation_code": "R12345",
"uri": "otpauth://totp/Steam:example?secret=ASDF&issuer=Steam",
"server_time": 1602522478,
"account_name": "example",
"token_gid": "jkkjlhkhjgf",
"identity_secret": "kjsdlwowiqe=",
"secret_1": "sklduhfgsdlkjhf=",
"status": 1,
"device_id": "android:99d2ad0e-4bad-4247-b111-26393aae0be3",
"fully_enrolled": true,
"Session": {
"SessionID": "a;lskdjf",
"SteamLogin": "983498437543",
"SteamLoginSecure": null,
"WebCookie": ";lkjsed;klfjas98093",
"OAuthToken": "asdk;lf;dsjlkfd",
"SteamID": 1234
}
}

View file

@ -1,22 +0,0 @@
{
"shared_secret": "zvIayp3JPvtvX/QGHqsqKBk/44s=",
"serial_number": "kljasfhds",
"revocation_code": "R12345",
"uri": "otpauth://totp/Steam:example?secret=ASDF&issuer=Steam",
"server_time": 1602522478,
"account_name": "example",
"token_gid": "jkkjlhkhjgf",
"identity_secret": "kjsdlwowiqe=",
"secret_1": "sklduhfgsdlkjhf=",
"status": 1,
"device_id": "android:99d2ad0e-4bad-4247-b111-26393aae0be3",
"fully_enrolled": true,
"Session": {
"SessionID": "a;lskdjf",
"SteamLogin": "983498437543",
"SteamLoginSecure": "dlkjdsl;j%7C%32984730298",
"WebCookie": null,
"OAuthToken": "asdk;lf;dsjlkfd",
"SteamID": 1234
}
}

View file

@ -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}}

View file

@ -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}

View file

@ -1,17 +0,0 @@
{
"encrypted": false,
"first_run": true,
"entries": [
{
"encryption_iv": null,
"encryption_salt": null,
"filename": "nulloauthtoken.maFile",
"steamid": 1234
}
],
"periodic_checking": false,
"periodic_checking_interval": 5,
"periodic_checking_checkall": false,
"auto_confirm_market_transactions": false,
"auto_confirm_trades": false
}

View file

@ -1 +0,0 @@
{"shared_secret":"zvIayp3JPvtvX/QGHqsqKBk/44s=","serial_number":"kljasfhds","revocation_code":"R12345","uri":"otpauth://totp/Steam:example?secret=ASDF&issuer=Steam","server_time":1602522478,"account_name":"example","token_gid":"jkkjlhkhjgf","identity_secret":"kjsdlwowiqe=","secret_1":"sklduhfgsdlkjhf=","status":1,"device_id":"android:99d2ad0e-4bad-4247-b111-26393aae0be3","fully_enrolled":true,"Session":{"SessionID":"a;lskdjf","SteamLogin":"983498437543","SteamLoginSecure":"dlkjdsl;j%7C%32984730298","WebCookie":"asdk;lf;dsjlkfd","OAuthToken":null,"SteamID":1234}}

View file

@ -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"
}

View file

@ -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

View file

@ -1 +0,0 @@
Z0HJDSN9EuFOpKEeBzftCWxTsh0sV6QQriLTVrn37FyGNaXhGgzeHlvPfHgkXKCYbALTgx/B2fLh1CEojKO1/eqEgN+982CadR3EXk+vH1k5AMuGhMXPpsEeIh27ltxrdAEzWdlPlAyentBgOKlTCoN6iF+EZVORvp2pPaMrebyHi8/5Y+XC3HrMgfgmP7lFGpUgZK8f0mKB/pGaW+0/3oVikggBK3MIWlh4s9bC9LlMy5H+oU0n/Iu3P9dpbko1bDMKIbUKEPzS3wHXyQRg32zPIfONR0bswb7QTfAhoKixZrAenQluX3lXRL0JFafNEPzUY4r/DJ1pIMLK9cEvbzqwsPth6jrIZRd+zvgnshfNnGLCblYkPo4fGwePuhX2W2w6qgFMpo69rkSp1Zz6JKC/gH9YyL4a8N768ml9H1so5XBm7eB+fMRIL7bHof+V1CxGXX3z1RvjGRHPwKcrKLvffxTTs/dBHb9UDFtTprlymLZf6C53c5vMBQ/hk4fm

View file

@ -1 +0,0 @@
{"version":1,"entries":[{"filename":"1234.maFile","steam_id":1234,"account_name":"example","encryption":{"iv":"ifChnv66eA+/dYqGsQMIOA==","salt":"O2K8FAOWK9c=","scheme":"LegacySdaCompatible"}}]}

View file

@ -1 +0,0 @@
{"account_name":"example","steam_id":1234,"serial_number":"kljasfhds","revocation_code":"R12345","shared_secret":"zvIayp3JPvtvX/QGHqsqKBk/44s=","token_gid":"jkkjlhkhjgf","identity_secret":"kjsdlwowiqe=","uri":"otpauth://totp/Steam:example?secret=ASDF&issuer=Steam","device_id":"android:99d2ad0e-4bad-4247-b111-26393aae0be3","secret_1":"sklduhfgsdlkjhf=","tokens":null}

View file

@ -1 +0,0 @@
{"version":1,"entries":[{"filename":"1234.maFile","steam_id":1234,"account_name":"example","encryption":null}]}

View file

@ -1 +0,0 @@
{"account_name":"example","steam_id":1234,"serial_number":"kljasfhds","revocation_code":"R12345","shared_secret":"zvIayp3JPvtvX/QGHqsqKBk/44s=","token_gid":"jkkjlhkhjgf","identity_secret":"kjsdlwowiqe=","uri":"otpauth://totp/Steam:example?secret=ASDF&issuer=Steam","device_id":"android:99d2ad0e-4bad-4247-b111-26393aae0be3","secret_1":"sklduhfgsdlkjhf=","tokens":null}

View file

@ -1 +0,0 @@
{"account_name":"example2","steam_id":5678,"serial_number":"kljasfhds","revocation_code":"R56789","shared_secret":"zvIayp3JPvtvX/QGHqsqKBk/44s=","token_gid":"jkkjlhkhjgf","identity_secret":"kjsdlwowiqe=","uri":"otpauth://totp/Steam:example?secret=ASDF&issuer=Steam","device_id":"android:99d2ad0e-4bad-4247-b111-26393aae0be3","secret_1":"sklduhfgsdlkjhf=","tokens":null}

View file

@ -1 +0,0 @@
{"version":1,"entries":[{"filename":"1234.maFile","steam_id":1234,"account_name":"example","encryption":null},{"filename":"5678.maFile","steam_id":5678,"account_name":"example2","encryption":null}]}

View file

@ -1 +0,0 @@
{"account_name":"example","steam_id":1234,"serial_number":"kljasfhds","revocation_code":"R12345","shared_secret":"zvIayp3JPvtvX/QGHqsqKBk/44s=","token_gid":"jkkjlhkhjgf","identity_secret":"kjsdlwowiqe=","uri":"otpauth://totp/Steam:example?secret=ASDF&issuer=Steam","device_id":"android:99d2ad0e-4bad-4247-b111-26393aae0be3","secret_1":"sklduhfgsdlkjhf=","tokens":null}

View file

@ -1 +0,0 @@
{"version":1,"entries":[{"filename":"1234.maFile","steam_id":1234,"account_name":"example","encryption":null}]}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 KiB

View file

@ -1,219 +0,0 @@
use std::io::Write;
use log::*;
use secrecy::{ExposeSecret, SecretString};
use steamguard::{
protobufs::steammessages_auth_steamclient::{EAuthSessionGuardType, EAuthTokenPlatformType},
refresher::TokenRefresher,
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...");
let client = AuthenticationClient::new(transport.clone());
let mut refresher = TokenRefresher::new(client);
match refresher.refresh(account.steam_id, tokens) {
Ok(token) => {
info!("Successfully refreshed access token, no need to prompt to log in.");
tokens.set_access_token(token);
return Ok(());
}
Err(err) => {
warn!(
"Failed to refresh access token, prompting for login: {}",
err
);
}
}
}
if !account.account_name.is_empty() {
info!("Username: {}", account.account_name);
} else {
eprint!("Username: ");
account.account_name = tui::prompt();
}
let _ = std::io::stdout().flush();
let password = if let Some(p) = password {
p
} else {
tui::prompt_password()?
};
if !password.expose_secret().is_empty() {
debug!("password is present");
} else {
debug!("password is empty");
}
let tokens = do_login_impl(
transport,
account.account_name.clone(),
password,
Some(account),
)?;
let steam_id = tokens.access_token().decode()?.steam_id();
account.set_tokens(tokens);
account.steam_id = steam_id;
Ok(())
}
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()?
};
if !password.expose_secret().is_empty() {
debug!("password is present");
} else {
debug!("password is empty");
}
do_login_impl(transport, username, password, None)
}
fn do_login_impl<T: Transport + Clone>(
transport: T,
username: String,
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;
let confirmation_methods;
loop {
match login.begin_auth_via_credentials(&username, password.expose_secret()) {
Ok(methods) => {
confirmation_methods = methods;
break;
}
Err(LoginError::TooManyAttempts) => {
error!("Too many login attempts. Steam is rate limiting you. Please wait a while and try again later.");
return Err(LoginError::TooManyAttempts.into());
}
Err(LoginError::BadCredentials) => {
error!("Incorrect password for {username}");
password = tui::prompt_password()?;
continue;
}
Err(err) => {
error!("Unexpected error when trying to log in. If you report this as a bug, please rerun with `-v debug` or `-v trace` and include all output in your issue. {:?}", err);
return Err(err.into());
}
}
}
debug!(
"got {} confirmation methods: {:#?}",
confirmation_methods.len(),
confirmation_methods
);
for method in confirmation_methods {
match method.confirmation_type {
EAuthSessionGuardType::k_EAuthSessionGuardType_DeviceConfirmation => {
eprintln!("Please confirm this login on your other device.");
eprintln!("Press enter when you have confirmed.");
tui::pause();
}
EAuthSessionGuardType::k_EAuthSessionGuardType_EmailConfirmation => {
eprint!("Please confirm this login by clicking the link in your email.");
if !method.associated_messsage.is_empty() {
eprint!(" ({})", method.associated_messsage);
}
eprintln!();
eprintln!("Press enter when you have confirmed.");
tui::pause();
}
EAuthSessionGuardType::k_EAuthSessionGuardType_DeviceCode
| EAuthSessionGuardType::k_EAuthSessionGuardType_EmailCode => {
let prompt = if method.confirmation_type
== EAuthSessionGuardType::k_EAuthSessionGuardType_DeviceCode
{
"Enter the 2fa code from your device: "
} else {
"Enter the 2fa code sent to your email: "
};
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());
}
}
}
}
}
EAuthSessionGuardType::k_EAuthSessionGuardType_None => {
debug!("No login confirmation required. Proceeding with login.");
continue;
}
_ => {
warn!("Unknown confirmation method: {:?}", method);
continue;
}
}
break;
}
info!("Polling for tokens... -- If this takes a long time, try logging in again.");
let tokens = login.poll_until_tokens()?;
info!("Logged in successfully!");
Ok(tokens)
}
fn build_device_details() -> DeviceDetails {
DeviceDetails {
friendly_name: format!(
"{} (steamguard-cli)",
gethostname::gethostname()
.into_string()
.expect("failed to get hostname")
),
platform_type: EAuthTokenPlatformType::k_EAuthTokenPlatformType_MobileApp,
os_type: -500,
gaming_device_type: 528,
}
}

View file

@ -1,19 +1,23 @@
extern crate rpassword;
use clap::Parser;
use clap::{IntoApp, Parser};
use crossterm::tty::IsTty;
use log::*;
use secrecy::SecretString;
#[cfg(feature = "qr")]
use qrcode::QrCode;
use std::time::{SystemTime, UNIX_EPOCH};
use std::{
io::{stdout, Write},
path::Path,
sync::{Arc, Mutex},
};
use steamguard::transport::WebApiTransport;
use steamguard::SteamGuardAccount;
use steamguard::{
steamapi, AccountLinkError, AccountLinker, Confirmation, ExposeSecret, FinalizeLinkError,
LoginError, SteamGuardAccount, UserLogin,
};
use crate::accountmanager::migrate::{load_and_migrate, MigrationError};
pub use crate::accountmanager::{AccountManager, ManifestAccountLoadError, ManifestLoadError};
use crate::commands::{CommandType, Subcommands};
pub use login::*;
use crate::accountmanager::ManifestAccountLoadError;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate anyhow;
@ -21,179 +25,82 @@ extern crate base64;
extern crate dirs;
#[cfg(test)]
extern crate proptest;
extern crate ring;
mod accountmanager;
mod commands;
mod debug;
mod cli;
mod demos;
mod encryption;
mod errors;
mod login;
mod secret_string;
pub(crate) mod tui;
#[cfg(feature = "updater")]
mod updater;
fn main() {
let args = commands::Args::parse();
stderrlog::new()
.verbosity(args.global.verbosity as usize)
.module(module_path!())
.module("steamguard")
.init()
.unwrap();
debug!("{:?}", args);
#[cfg(feature = "updater")]
let should_do_update_check = !args.global.no_update_check;
let exit_code = match run(args) {
std::process::exit(match run() {
Ok(_) => 0,
Err(e) => {
error!("{:?}", e);
255
}
});
}
fn run() -> anyhow::Result<()> {
let args = cli::Args::parse();
info!("{:?}", args);
stderrlog::new()
.verbosity(args.verbosity as usize)
.module(module_path!())
.module("steamguard")
.init()
.unwrap();
match args.sub {
Some(cli::Subcommands::Debug(args)) => {
return do_subcmd_debug(args);
}
Some(cli::Subcommands::Completion(args)) => {
return do_subcmd_completion(args);
}
_ => {}
};
#[cfg(feature = "updater")]
if should_do_update_check {
match updater::check_for_update() {
Ok(Some(version)) => {
eprintln!();
info!(
"steamguard-cli {} is available. Download it here: https://github.com/dyc3/steamguard-cli/releases",
version
);
}
Ok(None) => {
debug!("No update available");
}
Err(e) => {
warn!("Failed to check for updates: {}", e);
}
}
}
std::process::exit(exit_code);
}
fn run(args: commands::Args) -> anyhow::Result<()> {
let globalargs = args.global;
let cmd: CommandType<WebApiTransport> = match args.sub.unwrap_or(Subcommands::Code(args.code)) {
Subcommands::Debug(args) => CommandType::Const(Box::new(args)),
Subcommands::Completion(args) => CommandType::Const(Box::new(args)),
Subcommands::Setup(args) => CommandType::Manifest(Box::new(args)),
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::Remove(args) => CommandType::Account(Box::new(args)),
Subcommands::Code(args) => CommandType::Account(Box::new(args)),
#[cfg(feature = "qr")]
Subcommands::Qr(args) => CommandType::Account(Box::new(args)),
Subcommands::QrLogin(args) => CommandType::Account(Box::new(args)),
};
if let CommandType::Const(cmd) = cmd {
return cmd.execute();
}
let mafiles_dir = if let Some(mafiles_path) = &globalargs.mafiles_path {
let mafiles_dir = if let Some(mafiles_path) = &args.mafiles_path {
mafiles_path.clone()
} else {
get_mafiles_dir()
};
info!("reading manifest from {}", mafiles_dir);
let path = Path::new(&mafiles_dir).join("manifest.json");
let mut passkey = globalargs.passkey.clone();
let mut manager: accountmanager::AccountManager;
let mut manifest: accountmanager::Manifest;
if !path.exists() {
error!("Did not find manifest in {}", mafiles_dir);
if tui::prompt_char(
match tui::prompt_char(
format!("Would you like to create a manifest in {} ?", mafiles_dir).as_str(),
"Yn",
) == 'n'
{
) {
'n' => {
info!("Aborting!");
return Err(errors::UserError::Aborted.into());
}
_ => {}
}
std::fs::create_dir_all(mafiles_dir)?;
manager = accountmanager::AccountManager::new(path.as_path());
manager.save()?;
manifest = accountmanager::Manifest::new(path.as_path());
manifest.save()?;
} else {
manager = match accountmanager::AccountManager::load(path.as_path()) {
Ok(m) => m,
Err(ManifestLoadError::MigrationNeeded) => {
info!("Migrating manifest");
let manifest;
let accounts;
loop {
match load_and_migrate(path.as_path(), passkey.as_ref()) {
Ok((m, a)) => {
manifest = m;
accounts = a;
break;
}
Err(MigrationError::MissingPasskey { keyring_id }) => {
if passkey.is_some() {
error!("Incorrect passkey");
manifest = accountmanager::Manifest::load(path.as_path())?;
}
#[cfg(feature = "keyring")]
if let Some(keyring_id) = keyring_id {
if passkey.is_none() {
info!("Attempting to load encryption passkey from keyring");
let entry = encryption::init_keyring(keyring_id)?;
let raw = entry.get_password()?;
passkey = Some(SecretString::new(raw));
continue;
}
}
passkey = Some(tui::prompt_passkey()?);
}
Err(e) => {
error!("Failed to migrate manifest: {}", e);
return Err(e.into());
}
}
}
let mut manager = AccountManager::from_manifest(manifest, mafiles_dir);
manager.register_accounts(accounts);
manager.submit_passkey(passkey.clone());
manager.save()?;
manager
}
Err(err) => {
error!("Failed to load manifest: {}", err);
return Err(err.into());
}
}
}
#[cfg(feature = "keyring")]
if let Some(keyring_id) = manager.keyring_id() {
if passkey.is_none() {
info!("Attempting to load encryption passkey from keyring");
match encryption::try_passkey_from_keyring(keyring_id.clone()) {
Ok(k) => passkey = k,
Err(e) => {
warn!("Failed to load encryption passkey from keyring: {}", e);
}
}
}
}
manager.submit_passkey(passkey);
let mut passkey: Option<String> = args.passkey.clone();
manifest.submit_passkey(passkey);
loop {
match manager.auto_upgrade() {
match manifest.auto_upgrade() {
Ok(upgraded) => {
if upgraded {
info!("Manifest auto-upgraded");
manager.save()?;
manifest.save()?;
} else {
debug!("Manifest is up to date");
}
@ -203,11 +110,11 @@ fn run(args: commands::Args) -> anyhow::Result<()> {
accountmanager::ManifestAccountLoadError::MissingPasskey
| accountmanager::ManifestAccountLoadError::IncorrectPasskey,
) => {
if manager.has_passkey() {
if manifest.has_passkey() {
error!("Incorrect passkey");
}
passkey = Some(tui::prompt_passkey()?);
manager.submit_passkey(passkey);
passkey = rpassword::prompt_password_stderr("Enter encryption passkey: ").ok();
manifest.submit_passkey(passkey);
}
Err(e) => {
error!("Could not load accounts: {}", e);
@ -216,42 +123,38 @@ fn run(args: commands::Args) -> anyhow::Result<()> {
}
}
let mut http_client = reqwest::blocking::Client::builder();
if let Some(proxy) = &globalargs.http_proxy {
let mut proxy = reqwest::Proxy::all(proxy)?;
if let Some(proxy_creds) = &globalargs.proxy_credentials {
let mut creds = proxy_creds.splitn(2, ':');
proxy = proxy.basic_auth(creds.next().unwrap(), creds.next().unwrap());
match args.sub {
Some(cli::Subcommands::Setup(args)) => {
return do_subcmd_setup(args, &mut manifest);
}
http_client = http_client.proxy(proxy);
Some(cli::Subcommands::Import(args)) => {
return do_subcmd_import(args, &mut manifest);
}
if globalargs.danger_accept_invalid_certs {
http_client = http_client.danger_accept_invalid_certs(true);
Some(cli::Subcommands::Encrypt(args)) => {
return do_subcmd_encrypt(args, &mut manifest);
}
let http_client = http_client.build()?;
let transport = WebApiTransport::new(http_client);
if let CommandType::Manifest(cmd) = cmd {
cmd.execute(transport, &mut manager, &globalargs)?;
return Ok(());
Some(cli::Subcommands::Decrypt(args)) => {
return do_subcmd_decrypt(args, &mut manifest);
}
_ => {}
}
let selected_accounts: Vec<Arc<Mutex<SteamGuardAccount>>>;
loop {
match get_selected_accounts(&globalargs, &mut manager) {
match get_selected_accounts(&args, &mut manifest) {
Ok(accounts) => {
selected_accounts = accounts;
break;
}
Err(
accountmanager::ManifestAccountLoadError::MissingPasskey { .. }
accountmanager::ManifestAccountLoadError::MissingPasskey
| accountmanager::ManifestAccountLoadError::IncorrectPasskey,
) => {
if manager.has_passkey() {
if manifest.has_passkey() {
error!("Incorrect passkey");
}
passkey = Some(tui::prompt_passkey()?);
manager.submit_passkey(passkey);
passkey = rpassword::prompt_password_stdout("Enter encryption passkey: ").ok();
manifest.submit_passkey(passkey);
}
Err(e) => {
error!("Could not load accounts: {}", e);
@ -268,31 +171,45 @@ fn run(args: commands::Args) -> anyhow::Result<()> {
.collect::<Vec<String>>()
);
if let CommandType::Account(cmd) = cmd {
return cmd.execute(transport, &mut manager, selected_accounts, &globalargs);
match args.sub.unwrap_or(cli::Subcommands::Code(args.code)) {
cli::Subcommands::Trade(args) => {
return do_subcmd_trade(args, &mut manifest, selected_accounts);
}
cli::Subcommands::Remove(args) => {
return do_subcmd_remove(args, &mut manifest, selected_accounts);
}
cli::Subcommands::Code(args) => {
return do_subcmd_code(args, selected_accounts);
}
#[cfg(feature = "qr")]
cli::Subcommands::Qr(args) => {
return do_subcmd_qr(args, selected_accounts);
}
s => {
error!("Unknown subcommand: {:?}", s);
return Err(errors::UserError::UnknownSubcommand.into());
}
}
Ok(())
}
fn get_selected_accounts(
args: &commands::GlobalArgs,
manifest: &mut accountmanager::AccountManager,
args: &cli::Args,
manifest: &mut accountmanager::Manifest,
) -> anyhow::Result<Vec<Arc<Mutex<SteamGuardAccount>>>, ManifestAccountLoadError> {
let mut selected_accounts: Vec<Arc<Mutex<SteamGuardAccount>>> = vec![];
if args.all {
manifest.load_accounts()?;
for entry in manifest.iter() {
for entry in &manifest.entries {
selected_accounts.push(manifest.get_account(&entry.account_name).unwrap().clone());
}
} else {
let entry = if let Some(username) = &args.username {
manifest.get_entry(username)
manifest.get_entry(&username)
} else {
manifest
.iter()
.next()
.entries
.first()
.ok_or(ManifestAccountLoadError::MissingManifestEntry)
}?;
@ -300,17 +217,92 @@ fn get_selected_accounts(
let account = manifest.get_or_load_account(&account_name)?;
selected_accounts.push(account);
}
Ok(selected_accounts)
return Ok(selected_accounts);
}
fn do_login(account: &mut SteamGuardAccount) -> anyhow::Result<()> {
if account.account_name.len() > 0 {
info!("Username: {}", account.account_name);
} else {
eprint!("Username: ");
account.account_name = tui::prompt();
}
let _ = std::io::stdout().flush();
let password = rpassword::prompt_password_stdout("Password: ").unwrap();
if password.len() > 0 {
debug!("password is present");
} else {
debug!("password is empty");
}
account.set_session(do_login_impl(
account.account_name.clone(),
password,
Some(account),
)?);
return Ok(());
}
fn do_login_raw(username: String) -> anyhow::Result<steamapi::Session> {
let _ = std::io::stdout().flush();
let password = rpassword::prompt_password_stdout("Password: ").unwrap();
if password.len() > 0 {
debug!("password is present");
} else {
debug!("password is empty");
}
return do_login_impl(username, password, None);
}
fn do_login_impl(
username: String,
password: String,
account: Option<&SteamGuardAccount>,
) -> anyhow::Result<steamapi::Session> {
// TODO: reprompt if password is empty
let mut login = UserLogin::new(username, password);
let mut loops = 0;
loop {
match login.login() {
Ok(s) => {
return Ok(s);
}
Err(LoginError::Need2FA) => match account {
Some(a) => {
let server_time = steamapi::get_server_time()?.server_time;
login.twofactor_code = a.generate_code(server_time);
}
None => {
print!("Enter 2fa code: ");
login.twofactor_code = tui::prompt();
}
},
Err(LoginError::NeedCaptcha { captcha_gid }) => {
debug!("need captcha to log in");
login.captcha_text = tui::prompt_captcha_text(&captcha_gid);
}
Err(LoginError::NeedEmail) => {
println!("You should have received an email with a code. If you did not, check your spam folder, or abort and try again.");
print!("Enter code: ");
login.email_code = tui::prompt();
}
Err(r) => {
error!("Fatal login result: {:?}", r);
bail!(r);
}
}
loops += 1;
if loops > 2 {
error!("Too many loops. Aborting login process, to avoid getting rate limited.");
bail!("Too many loops. Login process aborted to avoid getting rate limited.");
}
}
}
fn get_mafiles_dir() -> String {
let mut paths = vec![
let paths = vec![
Path::new(&dirs::config_dir().unwrap()).join("steamguard-cli/maFiles"),
Path::new(&dirs::home_dir().unwrap()).join("maFiles"),
];
if let Ok(current_exe) = std::env::current_exe() {
paths.push(current_exe.parent().unwrap().join("maFiles"));
}
for path in &paths {
if path.join("manifest.json").is_file() {
@ -320,3 +312,429 @@ fn get_mafiles_dir() -> String {
return paths[0].to_str().unwrap().into();
}
fn load_accounts_with_prompts(manifest: &mut accountmanager::Manifest) -> anyhow::Result<()> {
loop {
match manifest.load_accounts() {
Ok(_) => return Ok(()),
Err(
accountmanager::ManifestAccountLoadError::MissingPasskey
| accountmanager::ManifestAccountLoadError::IncorrectPasskey,
) => {
if manifest.has_passkey() {
error!("Incorrect passkey");
}
let passkey = rpassword::prompt_password_stdout("Enter encryption passkey: ").ok();
manifest.submit_passkey(passkey);
}
Err(e) => {
error!("Could not load accounts: {}", e);
return Err(e.into());
}
}
}
}
fn do_subcmd_debug(args: cli::ArgsDebug) -> anyhow::Result<()> {
if args.demo_prompt {
demos::demo_prompt();
}
if args.demo_pause {
demos::demo_pause();
}
if args.demo_prompt_char {
demos::demo_prompt_char();
}
if args.demo_conf_menu {
demos::demo_confirmation_menu();
}
return Ok(());
}
fn do_subcmd_completion(args: cli::ArgsCompletions) -> Result<(), anyhow::Error> {
let mut app = cli::Args::command_for_update();
clap_complete::generate(args.shell, &mut app, "steamguard", &mut std::io::stdout());
return Ok(());
}
fn do_subcmd_setup(
_args: cli::ArgsSetup,
manifest: &mut accountmanager::Manifest,
) -> anyhow::Result<()> {
eprintln!("Log in to the account that you want to link to steamguard-cli");
eprint!("Username: ");
let username = tui::prompt().to_lowercase();
let account_name = username.clone();
if manifest.account_exists(&username) {
bail!(
"Account {} already exists in manifest, remove it first",
username
);
}
info!("Logging in to {}", username);
let session = do_login_raw(username).expect("Failed to log in. Account has not been linked.");
info!("Adding authenticator...");
let mut linker = AccountLinker::new(session);
let account: SteamGuardAccount;
loop {
match linker.link() {
Ok(a) => {
account = a;
break;
}
Err(AccountLinkError::MustRemovePhoneNumber) => {
println!("There is already a phone number on this account, please remove it and try again.");
bail!("There is already a phone number on this account, please remove it and try again.");
}
Err(AccountLinkError::MustProvidePhoneNumber) => {
println!("Enter your phone number in the following format: +1 123-456-7890");
print!("Phone number: ");
linker.phone_number = tui::prompt().replace(&['(', ')', '-'][..], "");
}
Err(AccountLinkError::AuthenticatorPresent) => {
println!("An authenticator is already present on this account.");
bail!("An authenticator is already present on this account.");
}
Err(AccountLinkError::MustConfirmEmail) => {
println!("Check your email and click the link.");
tui::pause();
}
Err(err) => {
error!(
"Failed to link authenticator. Account has not been linked. {}",
err
);
return Err(err.into());
}
}
}
manifest.add_account(account);
match manifest.save() {
Ok(_) => {}
Err(err) => {
error!("Aborting the account linking process because we failed to save the manifest. This is really bad. Here is the error: {}", err);
println!(
"Just in case, here is the account info. Save it somewhere just in case!\n{:?}",
manifest.get_account(&account_name).unwrap().lock().unwrap()
);
return Err(err.into());
}
}
let account_arc = manifest.get_account(&account_name).unwrap();
let mut account = account_arc.lock().unwrap();
println!("Authenticator has not yet been linked. Before continuing with finalization, please take the time to write down your revocation code: {}", account.revocation_code.expose_secret());
tui::pause();
debug!("attempting link finalization");
print!("Enter SMS code: ");
let sms_code = tui::prompt();
let mut tries = 0;
loop {
match linker.finalize(&mut account, sms_code.clone()) {
Ok(_) => break,
Err(FinalizeLinkError::WantMore) => {
debug!("steam wants more 2fa codes (tries: {})", tries);
tries += 1;
if tries >= 30 {
error!("Failed to finalize: unable to generate valid 2fa codes");
bail!("Failed to finalize: unable to generate valid 2fa codes");
}
}
Err(err) => {
error!("Failed to finalize: {}", err);
return Err(err.into());
}
}
}
println!("Authenticator finalized.");
match manifest.save() {
Ok(_) => {}
Err(err) => {
println!(
"Failed to save manifest, but we were able to save it before. {}",
err
);
return Err(err);
}
}
println!(
"Authenticator has been finalized. Please actually write down your revocation code: {}",
account.revocation_code.expose_secret()
);
return Ok(());
}
fn do_subcmd_import(
args: cli::ArgsImport,
manifest: &mut accountmanager::Manifest,
) -> anyhow::Result<()> {
for file_path in args.files {
match manifest.import_account(&file_path) {
Ok(_) => {
info!("Imported account: {}", &file_path);
}
Err(err) => {
bail!("Failed to import account: {} {}", &file_path, err);
}
}
}
manifest.save()?;
return Ok(());
}
fn do_subcmd_trade(
args: cli::ArgsTrade,
manifest: &mut accountmanager::Manifest,
mut selected_accounts: Vec<Arc<Mutex<SteamGuardAccount>>>,
) -> anyhow::Result<()> {
for a in selected_accounts.iter_mut() {
let mut account = a.lock().unwrap();
info!("Checking for trade confirmations");
let confirmations: Vec<Confirmation>;
loop {
match account.get_trade_confirmations() {
Ok(confs) => {
confirmations = confs;
break;
}
Err(_) => {
info!("failed to get trade confirmations, asking user to log in");
do_login(&mut account)?;
}
}
}
let mut any_failed = false;
if args.accept_all {
info!("accepting all confirmations");
for conf in &confirmations {
let result = account.accept_confirmation(conf);
if result.is_err() {
warn!("accept confirmation result: {:?}", result);
any_failed = true;
if args.fail_fast {
return result;
}
} else {
debug!("accept confirmation result: {:?}", result);
}
}
} else {
if stdout().is_tty() {
let (accept, deny) = tui::prompt_confirmation_menu(confirmations)?;
for conf in &accept {
let result = account.accept_confirmation(conf);
if result.is_err() {
warn!("accept confirmation result: {:?}", result);
any_failed = true;
if args.fail_fast {
return result;
}
} else {
debug!("accept confirmation result: {:?}", result);
}
}
for conf in &deny {
let result = account.deny_confirmation(conf);
debug!("deny confirmation result: {:?}", result);
if result.is_err() {
warn!("deny confirmation result: {:?}", result);
any_failed = true;
if args.fail_fast {
return result;
}
} else {
debug!("deny confirmation result: {:?}", result);
}
}
} else {
warn!("not a tty, not showing menu");
for conf in &confirmations {
println!("{}", conf.description());
}
}
}
if any_failed {
error!("Failed to respond to some confirmations.");
}
}
manifest.save()?;
return Ok(());
}
fn do_subcmd_remove(
_args: cli::ArgsRemove,
manifest: &mut accountmanager::Manifest,
selected_accounts: Vec<Arc<Mutex<SteamGuardAccount>>>,
) -> anyhow::Result<()> {
println!(
"This will remove the mobile authenticator from {} accounts: {}",
selected_accounts.len(),
selected_accounts
.iter()
.map(|a| a.lock().unwrap().account_name.clone())
.collect::<Vec<String>>()
.join(", ")
);
match tui::prompt_char("Do you want to continue?", "yN") {
'y' => {}
_ => {
info!("Aborting!");
return Err(errors::UserError::Aborted.into());
}
}
let mut successful = vec![];
for a in selected_accounts {
let account = a.lock().unwrap();
match account.remove_authenticator(None) {
Ok(success) => {
if success {
println!("Removed authenticator from {}", account.account_name);
successful.push(account.account_name.clone());
} else {
println!(
"Failed to remove authenticator from {}",
account.account_name
);
match tui::prompt_char(
"Would you like to remove it from the manifest anyway?",
"yN",
) {
'y' => {
successful.push(account.account_name.clone());
}
_ => {}
}
}
}
Err(err) => {
error!(
"Unexpected error when removing authenticator from {}: {}",
account.account_name, err
);
}
}
}
for account_name in successful {
manifest.remove_account(account_name);
}
manifest.save()?;
return Ok(());
}
fn do_subcmd_encrypt(
_args: cli::ArgsEncrypt,
manifest: &mut accountmanager::Manifest,
) -> anyhow::Result<()> {
if !manifest.has_passkey() {
let mut passkey;
loop {
passkey = rpassword::prompt_password_stdout("Enter encryption passkey: ").ok();
if let Some(p) = passkey.as_ref() {
if p.is_empty() {
error!("Passkey cannot be empty, try again.");
continue;
}
}
let passkey_confirm =
rpassword::prompt_password_stdout("Confirm encryption passkey: ").ok();
if passkey == passkey_confirm {
break;
}
error!("Passkeys do not match, try again.");
}
manifest.submit_passkey(passkey);
}
manifest.load_accounts()?;
for entry in &mut manifest.entries {
entry.encryption = Some(accountmanager::EntryEncryptionParams::generate());
}
manifest.save()?;
return Ok(());
}
fn do_subcmd_decrypt(
_args: cli::ArgsDecrypt,
manifest: &mut accountmanager::Manifest,
) -> anyhow::Result<()> {
load_accounts_with_prompts(manifest)?;
for entry in &mut manifest.entries {
entry.encryption = None;
}
manifest.submit_passkey(None);
manifest.save()?;
return Ok(());
}
fn do_subcmd_code(
args: cli::ArgsCode,
selected_accounts: Vec<Arc<Mutex<SteamGuardAccount>>>,
) -> anyhow::Result<()> {
let server_time = if args.offline {
SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs()
} else {
steamapi::get_server_time()?.server_time
};
debug!("Time used to generate codes: {}", server_time);
for account in selected_accounts {
info!(
"Generating code for {}",
account.lock().unwrap().account_name
);
trace!("{:?}", account);
let code = account.lock().unwrap().generate_code(server_time);
println!("{}", code);
}
return Ok(());
}
#[cfg(feature = "qr")]
fn do_subcmd_qr(
args: cli::ArgsQr,
selected_accounts: Vec<Arc<Mutex<SteamGuardAccount>>>,
) -> anyhow::Result<()> {
use anyhow::Context;
info!(
"Generating QR codes for {} accounts",
selected_accounts.len()
);
for account in selected_accounts {
let account = account.lock().unwrap();
let qr = QrCode::new(account.uri.expose_secret())
.context(format!("generating qr code for {}", account.account_name))?;
info!("Printing QR code for {}", account.account_name);
let qr_string = if args.ascii {
qr.render()
.light_color(' ')
.dark_color('#')
.module_dimensions(2, 1)
.build()
} else {
use qrcode::render::unicode;
qr.render::<unicode::Dense1x2>()
.dark_color(unicode::Dense1x2::Light)
.light_color(unicode::Dense1x2::Dark)
.build()
};
println!("{}", qr_string);
}
return Ok(());
}

View file

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

View file

@ -1,4 +1,3 @@
use anyhow::Context;
use crossterm::{
cursor,
event::{Event, KeyCode, KeyEvent, KeyModifiers},
@ -7,12 +6,39 @@ use crossterm::{
terminal::{Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen},
QueueableCommand,
};
use log::debug;
use secrecy::SecretString;
use log::*;
use regex::Regex;
use std::collections::HashSet;
use std::io::{stderr, stdout, Write};
use steamguard::Confirmation;
lazy_static! {
static ref CAPTCHA_VALID_CHARS: Regex =
Regex::new("^([A-H]|[J-N]|[P-R]|[T-Z]|[2-4]|[7-9]|[@%&])+$").unwrap();
}
pub fn validate_captcha_text(text: &String) -> bool {
return CAPTCHA_VALID_CHARS.is_match(text);
}
#[test]
fn test_validate_captcha_text() {
assert!(validate_captcha_text(&String::from("2WWUA@")));
assert!(validate_captcha_text(&String::from("3G8HT2")));
assert!(validate_captcha_text(&String::from("3J%@X3")));
assert!(validate_captcha_text(&String::from("2GCZ4A")));
assert!(validate_captcha_text(&String::from("3G8HT2")));
assert!(!validate_captcha_text(&String::from("asd823")));
assert!(!validate_captcha_text(&String::from("!PQ4RD")));
assert!(!validate_captcha_text(&String::from("1GQ4XZ")));
assert!(!validate_captcha_text(&String::from("8GO4XZ")));
assert!(!validate_captcha_text(&String::from("IPQ4RD")));
assert!(!validate_captcha_text(&String::from("0PT4RD")));
assert!(!validate_captcha_text(&String::from("APTSRD")));
assert!(!validate_captcha_text(&String::from("AP5TRD")));
assert!(!validate_captcha_text(&String::from("AP6TRD")));
}
/// Prompt the user for text input.
pub(crate) fn prompt() -> String {
stdout().flush().expect("failed to flush stdout");
@ -34,20 +60,23 @@ pub(crate) fn prompt() -> String {
line
}
pub(crate) fn prompt_non_empty(prompt_text: impl AsRef<str>) -> String {
pub(crate) fn prompt_captcha_text(captcha_gid: &String) -> String {
eprintln!("Captcha required. Open this link in your web browser: https://steamcommunity.com/public/captcha.php?gid={}", captcha_gid);
let mut captcha_text;
loop {
eprint!("{}", prompt_text.as_ref());
let input = prompt();
if !input.is_empty() {
return input;
eprint!("Enter captcha text: ");
captcha_text = prompt();
if captcha_text.len() > 0 && validate_captcha_text(&captcha_text) {
break;
}
warn!("Invalid chars for captcha text found in user's input. Prompting again...");
}
return captcha_text;
}
/// 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 +88,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.");
@ -72,7 +104,7 @@ fn prompt_char_impl(input: impl Into<String>, chars: &str) -> anyhow::Result<cha
let answer: String = input.into().to_ascii_lowercase();
if answer.is_empty() {
if answer.len() == 0 {
if let Some(a) = default_answer {
return Ok(a);
} else {
@ -94,8 +126,8 @@ fn prompt_char_impl(input: impl Into<String>, chars: &str) -> anyhow::Result<cha
pub(crate) fn prompt_confirmation_menu(
confirmations: Vec<Confirmation>,
) -> anyhow::Result<(Vec<Confirmation>, Vec<Confirmation>)> {
if confirmations.is_empty() {
return Ok((vec![], vec![]));
if confirmations.len() == 0 {
bail!("no confirmations")
}
let mut to_accept_idx: HashSet<usize> = HashSet::new();
@ -117,7 +149,7 @@ pub(crate) fn prompt_confirmation_menu(
),
)?;
for (i, conf) in confirmations.iter().enumerate() {
for i in 0..confirmations.len() {
stdout().queue(Print("\r"))?;
if selected_idx == i {
stdout().queue(SetForegroundColor(Color::Yellow))?;
@ -141,7 +173,7 @@ pub(crate) fn prompt_confirmation_menu(
stdout().queue(SetForegroundColor(Color::Yellow))?;
}
stdout().queue(Print(format!(" {}\n", conf.description())))?;
stdout().queue(Print(format!(" {}\n", confirmations[i].description())))?;
}
stdout().flush()?;
@ -255,27 +287,6 @@ pub(crate) fn pause() {
}
}
pub(crate) fn prompt_passkey() -> anyhow::Result<SecretString> {
debug!("prompting for passkey");
loop {
let raw = rpassword::prompt_password("Enter encryption passkey: ")
.context("prompting for passkey")?;
if !raw.is_empty() {
return Ok(SecretString::new(raw));
}
}
}
pub(crate) fn prompt_password() -> anyhow::Result<SecretString> {
debug!("prompting for password");
loop {
let raw = rpassword::prompt_password("Password: ").context("prompting for password")?;
if !raw.is_empty() {
return Ok(SecretString::new(raw));
}
}
}
#[cfg(test)]
mod prompt_char_tests {
use super::*;
@ -301,7 +312,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 +320,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(_)));
}
}

View file

@ -1,46 +0,0 @@
use std::time::Duration;
use serde::de::DeserializeOwned;
use update_informer::{
http_client::{HeaderMap, HttpClient},
registry, Check, Version,
};
use crate::debug;
pub fn check_for_update() -> update_informer::Result<Option<Version>> {
let name = "dyc3/steamguard-cli";
let version = env!("CARGO_PKG_VERSION");
debug!("Checking for updates to {} v{}", name, version);
let informer = update_informer::new(registry::GitHub, name, version)
.http_client(ReqwestHttpClient)
.interval(Duration::from_secs(60 * 60 * 24 * 2));
informer.check_version()
}
struct ReqwestHttpClient;
impl HttpClient for ReqwestHttpClient {
fn get<T: DeserializeOwned>(
url: &str,
timeout: Duration,
headers: HeaderMap,
) -> update_informer::Result<T> {
let mut req = reqwest::blocking::Client::builder()
.timeout(timeout)
.build()?
.get(url)
.header(reqwest::header::USER_AGENT, "steamguard-cli");
for (key, value) in headers {
req = req.header(key, value);
}
let resp = req.send()?;
debug!("Update check response status: {:?}", resp.status());
let json = resp.json()?;
Ok(json)
}
}

View file

@ -1,47 +1,32 @@
[package]
name = "steamguard"
version = "0.14.0"
version = "0.7.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"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
rsa = "0.9.2"
rsa = "0.5.0"
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"] }
log = "0.4.19"
uuid = { version = "0.8", features = ["v4"] }
log = "0.4.14"
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"
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"
protobuf = "3.2.0"
protobuf-codegen = "3.2.0"
zeroize = "^1.4.3"

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,50 +0,0 @@
message CPhone_AddPhoneToAccount_Response {
optional bool success = 1;
optional int32 phone_number_type = 2;
}
message CPhone_ConfirmAddPhoneToAccount_Request {
optional fixed64 steamid = 1;
optional string stoken = 2;
}
message CPhone_IsAccountWaitingForEmailConfirmation_Request {
}
message CPhone_IsAccountWaitingForEmailConfirmation_Response {
optional bool awaiting_email_confirmation = 1;
optional uint32 seconds_to_wait = 2;
}
message CPhone_SendPhoneVerificationCode_Request {
optional uint32 language = 1;
}
message CPhone_SendPhoneVerificationCode_Response {
}
message CPhone_SetAccountPhoneNumber_Request {
optional string phone_number = 1;
optional string phone_country_code = 2;
}
message CPhone_SetAccountPhoneNumber_Response {
optional string confirmation_email_address = 1;
optional string phone_number_formatted = 2;
}
message CPhone_VerifyAccountPhoneWithCode_Request {
optional string code = 1;
}
message CPhone_VerifyAccountPhoneWithCode_Response {
}
service Phone {
rpc ConfirmAddPhoneToAccount (.CPhone_ConfirmAddPhoneToAccount_Request) returns (.CPhone_AddPhoneToAccount_Response);
rpc IsAccountWaitingForEmailConfirmation (.CPhone_IsAccountWaitingForEmailConfirmation_Request) returns (.CPhone_IsAccountWaitingForEmailConfirmation_Response);
rpc SendPhoneVerificationCode (.CPhone_SendPhoneVerificationCode_Request) returns (.CPhone_SendPhoneVerificationCode_Response);
rpc SetAccountPhoneNumber (.CPhone_SetAccountPhoneNumber_Request) returns (.CPhone_SetAccountPhoneNumber_Response);
rpc VerifyAccountPhoneWithCode (.CPhone_VerifyAccountPhoneWithCode_Request) returns (.CPhone_VerifyAccountPhoneWithCode_Response);
}

View file

@ -1,170 +0,0 @@
import "common_base.proto";
message CRemoveAuthenticatorViaChallengeContinue_Replacement_Token {
optional bytes shared_secret = 1;
optional fixed64 serial_number = 2;
optional string revocation_code = 3;
optional string uri = 4;
optional uint64 server_time = 5;
optional string account_name = 6;
optional string token_gid = 7;
optional bytes identity_secret = 8;
optional bytes secret_1 = 9;
optional int32 status = 10;
optional uint32 steamguard_scheme = 11;
optional fixed64 steamid = 12;
}
message CTwoFactor_AddAuthenticator_Request {
optional fixed64 steamid = 1;
optional uint64 authenticator_time = 2;
optional fixed64 serial_number = 3;
optional uint32 authenticator_type = 4;
optional string device_identifier = 5;
optional string sms_phone_id = 6;
repeated string http_headers = 7;
optional uint32 version = 8 [default = 1];
}
message CTwoFactor_AddAuthenticator_Response {
optional bytes shared_secret = 1;
optional fixed64 serial_number = 2;
optional string revocation_code = 3;
optional string uri = 4;
optional uint64 server_time = 5;
optional string account_name = 6;
optional string token_gid = 7;
optional bytes identity_secret = 8;
optional bytes secret_1 = 9;
optional int32 status = 10;
optional string phone_number_hint = 11;
optional int32 confirm_type = 12;
}
message CTwoFactor_CreateEmergencyCodes_Response {
repeated string codes = 1;
}
message CTwoFactor_DestroyEmergencyCodes_Response {
}
message CTwoFactor_FinalizeAddAuthenticator_Request {
optional fixed64 steamid = 1;
optional string authenticator_code = 2;
optional uint64 authenticator_time = 3;
optional string activation_code = 4;
repeated string http_headers = 5;
optional bool validate_sms_code = 6;
}
message CTwoFactor_FinalizeAddAuthenticator_Response {
optional bool success = 1;
optional bool want_more = 2;
optional uint64 server_time = 3;
optional int32 status = 4;
}
message CTwoFactor_RemoveAuthenticator_Request {
optional string revocation_code = 2;
optional uint32 revocation_reason = 5;
optional uint32 steamguard_scheme = 6;
optional bool remove_all_steamguard_cookies = 7;
}
message CTwoFactor_RemoveAuthenticator_Response {
optional bool success = 1;
optional uint64 server_time = 3;
optional uint32 revocation_attempts_remaining = 5;
}
message CTwoFactor_RemoveAuthenticatorViaChallengeContinue_Request {
optional string sms_code = 1;
optional bool generate_new_token = 2;
optional uint32 version = 3 [default = 1];
}
message CTwoFactor_RemoveAuthenticatorViaChallengeContinue_Response {
optional bool success = 1;
optional .CRemoveAuthenticatorViaChallengeContinue_Replacement_Token replacement_token = 2;
}
message CTwoFactor_RemoveAuthenticatorViaChallengeStart_Request {
}
message CTwoFactor_RemoveAuthenticatorViaChallengeStart_Response {
optional bool success = 1;
}
message CTwoFactor_SendEmail_Request {
optional fixed64 steamid = 1;
optional uint32 email_type = 2;
optional bool include_activation_code = 3;
}
message CTwoFactor_SendEmail_Response {
}
message CTwoFactor_Status_Request {
optional fixed64 steamid = 1;
}
message CTwoFactor_Status_Response {
optional uint32 state = 1;
optional uint32 inactivation_reason = 2;
optional uint32 authenticator_type = 3;
optional bool authenticator_allowed = 4;
optional uint32 steamguard_scheme = 5;
optional string token_gid = 6;
optional bool email_validated = 7;
optional string device_identifier = 8;
optional uint32 time_created = 9;
optional uint32 revocation_attempts_remaining = 10;
optional string classified_agent = 11;
optional bool allow_external_authenticator = 12;
optional uint32 time_transferred = 13;
optional uint32 version = 14;
}
message CTwoFactor_Time_Request {
optional uint64 sender_time = 1;
}
message CTwoFactor_Time_Response {
optional uint64 server_time = 1;
optional uint64 skew_tolerance_seconds = 2;
optional uint64 large_time_jink = 3;
optional uint32 probe_frequency_seconds = 4;
optional uint32 adjusted_time_probe_frequency_seconds = 5;
optional uint32 hint_probe_frequency_seconds = 6;
optional uint32 sync_timeout = 7;
optional uint32 try_again_seconds = 8;
optional uint32 max_attempts = 9;
}
message CTwoFactor_UpdateTokenVersion_Request {
optional fixed64 steamid = 1;
optional uint32 version = 2;
optional bytes signature = 3;
}
message CTwoFactor_UpdateTokenVersion_Response {
}
message CTwoFactor_ValidateToken_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 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 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);
}

View file

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

View file

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

View file

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

View file

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

View file

@ -1,285 +1,121 @@
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::{
api_responses::{AddAuthenticatorResponse, FinalizeAddAuthenticatorResponse},
steamapi::{Session, SteamApiClient},
SteamGuardAccount,
};
use crate::steamapi::twofactor::TwoFactorClient;
use crate::token::TwoFactorSecret;
use crate::transport::{Transport, TransportError};
use crate::{steamapi::EResult, token::Tokens, SteamGuardAccount};
use anyhow::Context;
use base64::Engine;
use log::*;
use thiserror::Error;
#[derive(Debug)]
pub struct AccountLinker<T>
where
T: Transport,
{
pub struct AccountLinker {
device_id: String,
pub phone_number: String,
pub account: Option<SteamGuardAccount>,
pub finalized: bool,
tokens: Tokens,
client: TwoFactorClient<T>,
sent_confirmation_email: bool,
session: Session,
client: SteamApiClient,
}
impl<T> AccountLinker<T>
where
T: Transport,
{
pub fn new(transport: T, tokens: Tokens) -> Self {
Self {
impl AccountLinker {
pub fn new(session: Session) -> AccountLinker {
return AccountLinker {
device_id: generate_device_id(),
phone_number: "".into(),
account: None,
finalized: false,
tokens,
client: TwoFactorClient::new(transport),
}
}
pub fn tokens(&self) -> &Tokens {
&self.tokens
}
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 mut req = CTwoFactor_AddAuthenticator_Request::new();
req.set_authenticator_type(1);
req.set_steamid(steam_id);
req.set_sms_phone_id("1".to_owned());
req.set_device_identifier(self.device_id.clone());
let resp = self
.client
.add_authenticator(req, access_token)
.context("add authenticator request")?;
if resp.result != EResult::OK {
return Err(resp.result.into());
}
let mut resp = resp.into_response_data();
let account = SteamGuardAccount {
account_name: resp.take_account_name(),
steam_id,
serial_number: resp.serial_number().to_string(),
revocation_code: resp.take_revocation_code().into(),
uri: resp.take_uri().into(),
shared_secret: TwoFactorSecret::from_bytes(resp.take_shared_secret()),
token_gid: resp.take_token_gid(),
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()),
sent_confirmation_email: false,
session: session.clone(),
client: SteamApiClient::new(Some(secrecy::Secret::new(session))),
};
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)
}
pub fn link(&mut self) -> anyhow::Result<SteamGuardAccount, AccountLinkError> {
// let has_phone = self.client.has_phone()?;
// if has_phone && !self.phone_number.is_empty() {
// return Err(AccountLinkError::MustRemovePhoneNumber);
// }
// if !has_phone && self.phone_number.is_empty() {
// return Err(AccountLinkError::MustProvidePhoneNumber);
// }
// if !has_phone {
// if self.sent_confirmation_email {
// if !self.client.check_email_confirmation()? {
// return Err(anyhow!("Failed email confirmation check"))?;
// }
// } else if !self.client.add_phone_number(self.phone_number.clone())? {
// return Err(anyhow!("Failed to add phone number"))?;
// } else {
// self.sent_confirmation_email = true;
// return Err(AccountLinkError::MustConfirmEmail);
// }
// }
let resp: AddAuthenticatorResponse =
self.client.add_authenticator(self.device_id.clone())?;
match resp.status {
29 => {
return Err(AccountLinkError::AuthenticatorPresent);
}
2 => {
// If the user has no phone number on their account, it will always return this status code.
// However, this does not mean that this status just means "no phone number". It can also
// be literally anything else, so that's why we return GenericFailure here.
return Err(AccountLinkError::GenericFailure);
}
1 => {
let mut account = resp.to_steam_guard_account();
account.device_id = self.device_id.clone();
account.session = self.client.session.clone();
return Ok(account);
}
status => {
return Err(anyhow!("Unknown add authenticator status code: {}", status))?;
}
}
}
/// You may have to call this multiple times. If you have to call it a bunch of times, then you can assume that you are unable to generate correct 2fa codes.
pub fn finalize(
&mut self,
time: u64,
account: &mut SteamGuardAccount,
confirm_code: String,
sms_code: String,
) -> anyhow::Result<(), FinalizeLinkError> {
let time = crate::steamapi::get_server_time()?.server_time;
let code = account.generate_code(time);
let resp: FinalizeAddAuthenticatorResponse =
self.client
.finalize_authenticator(sms_code.clone(), code, time)?;
info!("finalize response status: {}", resp.status);
let token = self.tokens.access_token();
let steam_id = account.steam_id;
let mut req = CTwoFactor_FinalizeAddAuthenticator_Request::new();
req.set_steamid(steam_id);
req.set_authenticator_code(code);
req.set_authenticator_time(time);
req.set_activation_code(confirm_code);
req.set_validate_sms_code(true);
let resp = self.client.finalize_authenticator(req, token)?;
if resp.result != EResult::OK {
return Err(resp.result.into());
match resp.status {
89 => {
return Err(FinalizeLinkError::BadSmsCode);
}
_ => {}
}
let resp = resp.into_response_data();
if !resp.success {
return Err(FinalizeLinkError::Failure {
status: resp.status,
})?;
}
if resp.want_more() {
return Err(FinalizeLinkError::WantMore {
server_time: resp.server_time(),
});
if resp.want_more {
return Err(FinalizeLinkError::WantMore);
}
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)]
pub struct AccountLinkSuccess {
account: SteamGuardAccount,
server_time: u64,
phone_number_hint: String,
confirm_type: AccountLinkConfirmType,
}
impl AccountLinkSuccess {
pub fn account(&self) -> &SteamGuardAccount {
&self.account
}
pub fn into_account(self) -> SteamGuardAccount {
self.account
}
pub fn server_time(&self) -> u64 {
self.server_time
}
pub fn phone_number_hint(&self) -> &str {
&self.phone_number_hint
}
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),
}
account.fully_enrolled = true;
return Ok(());
}
}
fn generate_device_id() -> String {
format!("android:{}", uuid::Uuid::new_v4())
return format!("android:{}", uuid::Uuid::new_v4().to_string());
}
#[derive(Error, Debug)]
@ -287,96 +123,29 @@ pub enum AccountLinkError {
/// No phone number on the account
#[error("A phone number is needed, but not already present on the account.")]
MustProvidePhoneNumber,
/// A phone number is already on the account
#[error("A phone number was provided, but one is already present on the account.")]
MustRemovePhoneNumber,
/// User need to click link from confirmation email
#[error("An email has been sent to the user's email, click the link in that email.")]
MustConfirmEmail,
#[error("Authenticator is already present on this account.")]
#[error("Authenticator is already present.")]
AuthenticatorPresent,
#[error("You are sending too many requests to Steam, and we got rate limited. Wait at least a couple hours and try again.")]
RateLimitExceeded,
#[error("Steam was unable to link the authenticator to the account. No additional information about this error is available. This is a Steam error, not a steamguard-cli error. Try adding a phone number to your Steam account (which you can do here: https://store.steampowered.com/phone/add), or try again later.")]
GenericFailure,
#[error("Steam returned an unexpected error code: {0:?}")]
UnknownEResult(EResult),
#[error(transparent)]
Unknown(#[from] anyhow::Error),
}
impl From<EResult> for AccountLinkError {
fn from(result: EResult) -> Self {
match result {
EResult::RateLimitExceeded => AccountLinkError::RateLimitExceeded,
EResult::NoVerifiedPhone => AccountLinkError::MustProvidePhoneNumber,
EResult::DuplicateRequest => AccountLinkError::AuthenticatorPresent,
// If the user has no phone number on their account, it will always return this status code.
// However, this does not mean that this status just means "no phone number". It can also
// be literally anything else, so that's why we return GenericFailure here.
// update 2023: This may be no longer true, now it seems to return NoVerifiedPhone if there is no phone number. We'll see.
EResult::Fail => AccountLinkError::GenericFailure,
r => AccountLinkError::UnknownEResult(r),
}
}
}
#[derive(Error, Debug)]
pub enum FinalizeLinkError {
#[error("Provided SMS code was incorrect.")]
BadSmsCode,
/// Steam wants more 2fa codes to verify that we can generate valid codes. Call finalize again.
#[error("Steam wants more 2fa codes for verification.")]
WantMore { server_time: u64 },
#[error("Steam returned an unexpected error code: {0:?}")]
UnknownEResult(EResult),
WantMore,
#[error("Finalization was not successful. Status code {status:?}")]
Failure { status: i32 },
#[error(transparent)]
Unknown(#[from] anyhow::Error),
}
impl From<EResult> for FinalizeLinkError {
fn from(result: EResult) -> Self {
match result {
EResult::TwoFactorActivationCodeMismatch => FinalizeLinkError::BadSmsCode,
r => FinalizeLinkError::UnknownEResult(r),
}
}
}
#[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),
}
}
}

View file

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

View file

@ -0,0 +1,130 @@
use crate::{token::TwoFactorSecret, SteamGuardAccount};
use super::parse_json_string_as_number;
use serde::{Deserialize, Serialize};
/// Represents the response from `/ITwoFactorService/QueryTime/v0001`
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueryTimeResponse {
/// The time that the server will use to check your two factor code.
#[serde(deserialize_with = "parse_json_string_as_number")]
pub server_time: u64,
#[serde(deserialize_with = "parse_json_string_as_number")]
pub skew_tolerance_seconds: u64,
#[serde(deserialize_with = "parse_json_string_as_number")]
pub large_time_jink: u64,
pub probe_frequency_seconds: u64,
pub adjusted_time_probe_frequency_seconds: u64,
pub hint_probe_frequency_seconds: u64,
pub sync_timeout: u64,
pub try_again_seconds: u64,
pub max_attempts: u64,
}
#[derive(Debug, Clone, Deserialize)]
pub struct AddAuthenticatorResponse {
/// Shared secret between server and authenticator
#[serde(default)]
pub shared_secret: String,
/// Authenticator serial number (unique per token)
#[serde(default)]
pub serial_number: String,
/// code used to revoke authenticator
#[serde(default)]
pub revocation_code: String,
/// URI for QR code generation
#[serde(default)]
pub uri: String,
/// Current server time
#[serde(default, deserialize_with = "parse_json_string_as_number")]
pub server_time: u64,
/// Account name to display on token client
#[serde(default)]
pub account_name: String,
/// Token GID assigned by server
#[serde(default)]
pub token_gid: String,
/// Secret used for identity attestation (e.g., for eventing)
#[serde(default)]
pub identity_secret: String,
/// Spare shared secret
#[serde(default)]
pub secret_1: String,
/// Result code
pub status: i32,
#[serde(default)]
pub phone_number_hint: Option<String>,
}
impl AddAuthenticatorResponse {
pub fn to_steam_guard_account(self) -> SteamGuardAccount {
SteamGuardAccount {
shared_secret: TwoFactorSecret::parse_shared_secret(self.shared_secret).unwrap(),
serial_number: self.serial_number.clone(),
revocation_code: self.revocation_code.into(),
uri: self.uri.into(),
server_time: self.server_time,
account_name: self.account_name.clone(),
token_gid: self.token_gid.clone(),
identity_secret: self.identity_secret.into(),
secret_1: self.secret_1.into(),
fully_enrolled: false,
device_id: "".into(),
session: None,
}
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct FinalizeAddAuthenticatorResponse {
pub status: i32,
#[serde(deserialize_with = "parse_json_string_as_number")]
pub server_time: u64,
pub want_more: bool,
pub success: bool,
}
#[derive(Debug, Clone, Deserialize)]
pub struct RemoveAuthenticatorResponse {
pub success: bool,
}
#[cfg(test)]
mod test {
use super::*;
use crate::api_responses::SteamApiResponse;
#[test]
fn test_parse_add_auth_response() {
let result = serde_json::from_str::<SteamApiResponse<AddAuthenticatorResponse>>(
include_str!("../fixtures/api-responses/add-authenticator-1.json"),
);
assert!(
matches!(result, Ok(_)),
"got error: {}",
result.unwrap_err()
);
let resp = result.unwrap().response;
assert_eq!(resp.server_time, 1628559846);
assert_eq!(resp.shared_secret, "wGwZx=sX5MmTxi6QgA3Gi");
assert_eq!(resp.revocation_code, "R123456");
}
#[test]
fn test_parse_add_auth_response2() {
let result = serde_json::from_str::<SteamApiResponse<AddAuthenticatorResponse>>(
include_str!("../fixtures/api-responses/add-authenticator-2.json"),
);
assert!(
matches!(result, Ok(_)),
"got error: {}",
result.unwrap_err()
);
let resp = result.unwrap().response;
assert_eq!(resp.status, 29);
}
}

View file

@ -1,7 +1,17 @@
use serde::Deserialize;
use serde::{Deserialize, Deserializer, Serialize};
use super::parse_json_string_as_number;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoginTransferParameters {
pub steamid: String,
pub token_secure: String,
pub auth: String,
pub remember_login: bool,
pub webcookie: String,
}
#[derive(Debug, Clone, Deserialize)]
#[allow(dead_code)]
pub struct OAuthData {
pub oauth_token: String,
pub steamid: String,
@ -11,6 +21,56 @@ pub struct OAuthData {
pub webcookie: String,
}
#[derive(Debug, Clone, Deserialize)]
pub struct RsaResponse {
pub success: bool,
pub publickey_exp: String,
pub publickey_mod: String,
pub timestamp: String,
pub token_gid: String,
}
#[derive(Debug, Clone, Deserialize)]
pub struct LoginResponse {
pub success: bool,
#[serde(default)]
pub login_complete: bool,
#[serde(default)]
pub captcha_needed: bool,
#[serde(default)]
pub captcha_gid: String,
#[serde(default, deserialize_with = "parse_json_string_as_number")]
pub emailsteamid: u64,
#[serde(default)]
pub emailauth_needed: bool,
#[serde(default)]
pub requires_twofactor: bool,
#[serde(default)]
pub message: String,
#[serde(default, deserialize_with = "oauth_data_from_string")]
pub oauth: Option<OAuthData>,
pub transfer_urls: Option<Vec<String>>,
pub transfer_parameters: Option<LoginTransferParameters>,
}
/// For some reason, the `oauth` field in the login response is a string of JSON, not a JSON object.
/// Deserializes to `Option` because the `oauth` field is not always there.
fn oauth_data_from_string<'de, D>(deserializer: D) -> Result<Option<OAuthData>, D::Error>
where
D: Deserializer<'de>,
{
// for some reason, deserializing to &str doesn't work but this does.
let s: String = Deserialize::deserialize(deserializer)?;
let data: OAuthData = serde_json::from_str(s.as_str()).map_err(serde::de::Error::custom)?;
Ok(Some(data))
}
impl LoginResponse {
pub fn needs_transfer_login(&self) -> bool {
self.transfer_urls.is_some() || self.transfer_parameters.is_some()
}
}
#[cfg(test)]
mod test {
use super::*;
@ -29,4 +89,49 @@ mod test {
);
assert_eq!(oauth.webcookie, "6298070A226E5DAD49938D78BCF36F7A7118FDD5");
}
#[test]
fn test_login_response_parse() {
let result = serde_json::from_str::<LoginResponse>(include_str!(
"../fixtures/api-responses/login-response1.json"
));
assert!(
matches!(result, Ok(_)),
"got error: {}",
result.unwrap_err()
);
let resp = result.unwrap();
let oauth = resp.oauth.unwrap();
assert_eq!(oauth.steamid, "78562647129469312");
assert_eq!(oauth.oauth_token, "fd2fdb3d0717bad2220d98c7ec61c7bd");
assert_eq!(oauth.wgtoken, "72E7013D598A4F68C7E268F6FA3767D89D763732");
assert_eq!(
oauth.wgtoken_secure,
"21061EA13C36D7C29812CAED900A215171AD13A2"
);
assert_eq!(oauth.webcookie, "6298070A226E5DAD49938D78BCF36F7A7118FDD5");
}
#[test]
fn test_login_response_parse_missing_webcookie() {
let result = serde_json::from_str::<LoginResponse>(include_str!(
"../fixtures/api-responses/login-response-missing-webcookie.json"
));
assert!(
matches!(result, Ok(_)),
"got error: {}",
result.unwrap_err()
);
let resp = result.unwrap();
let oauth = resp.oauth.unwrap();
assert_eq!(oauth.steamid, "92591609556178617");
assert_eq!(oauth.oauth_token, "1cc83205dab2979e558534dab29f6f3aa");
assert_eq!(oauth.wgtoken, "3EDA9DEF07D7B39361D95203525D8AFE82A");
assert_eq!(oauth.wgtoken_secure, "F31641B9AFC2F8B0EE7B6F44D7E73EA3FA48");
assert_eq!(oauth.webcookie, "");
}
}

View file

@ -1,5 +1,23 @@
mod i_authentication_service;
mod i_two_factor_service;
mod login;
mod phone_ajax;
pub use i_authentication_service::*;
pub use i_two_factor_service::*;
pub use login::*;
pub use phone_ajax::*;
use serde::{Deserialize, Deserializer};
pub(crate) fn parse_json_string_as_number<'de, D>(deserializer: D) -> Result<u64, D::Error>
where
D: Deserializer<'de>,
{
// for some reason, deserializing to &str doesn't work but this does.
let s: String = Deserialize::deserialize(deserializer)?;
Ok(s.parse().unwrap())
}
#[derive(Debug, Clone, Deserialize)]
pub struct SteamApiResponse<T> {
pub response: T,
}

View file

@ -1,489 +1,38 @@
use std::borrow::Cow;
use base64::Engine;
use hmac::{Hmac, Mac};
use log::*;
use reqwest::{
cookie::CookieStore,
header::{CONTENT_TYPE, COOKIE, USER_AGENT},
Url,
};
use secrecy::ExposeSecret;
use serde::Deserialize;
use sha1::Sha1;
use crate::{
steamapi::{self},
transport::Transport,
SteamGuardAccount,
};
lazy_static! {
static ref STEAM_COOKIE_URL: Url = "https://steamcommunity.com".parse::<Url>().unwrap();
}
/// Provides an interface that wraps the Steam mobile confirmation API.
///
/// Only compatible with WebApiTransport.
pub struct Confirmer<'a, T> {
account: &'a SteamGuardAccount,
transport: T,
}
impl<'a, T> Confirmer<'a, T>
where
T: Transport + Clone,
{
pub fn new(transport: T, account: &'a SteamGuardAccount) -> Self {
Self { account, transport }
}
fn get_confirmation_query_params<'q>(
&'q self,
tag: &'q str,
time: u64,
) -> Vec<(&'static str, Cow<'q, str>)> {
[
("p", self.account.device_id.as_str().into()),
("a", self.account.steam_id.to_string().into()),
(
"k",
generate_confirmation_hash_for_time(
time,
tag,
self.account.identity_secret.expose_secret(),
)
.into(),
),
("t", time.to_string().into()),
("m", "react".into()),
("tag", tag.into()),
]
.into()
}
fn build_cookie_jar(&self) -> reqwest::cookie::Jar {
let cookies = reqwest::cookie::Jar::default();
let tokens = self.account.tokens.as_ref().unwrap();
cookies.add_cookie_str("dob=", &STEAM_COOKIE_URL);
cookies.add_cookie_str(
format!("steamid={}", self.account.steam_id).as_str(),
&STEAM_COOKIE_URL,
);
cookies.add_cookie_str(
format!(
"steamLoginSecure={}||{}",
self.account.steam_id,
tokens.access_token().expose_secret()
)
.as_str(),
&STEAM_COOKIE_URL,
);
cookies
}
pub fn get_confirmations(&self) -> Result<Vec<Confirmation>, ConfirmerError> {
let cookies = self.build_cookie_jar();
let client = self.transport.innner_http_client()?;
let time = steamapi::get_server_time(self.transport.clone())?.server_time();
let resp = client
.get(
"https://steamcommunity.com/mobileconf/getlist"
.parse::<Url>()
.unwrap(),
)
.header(USER_AGENT, "steamguard-cli")
.header(COOKIE, cookies.cookies(&STEAM_COOKIE_URL).unwrap())
.query(&self.get_confirmation_query_params("conf", time))
.send()?;
trace!("{:?}", resp);
let text = resp.text().unwrap();
debug!("Confirmations response: {}", text);
let mut deser = serde_json::Deserializer::from_str(text.as_str());
let body: ConfirmationListResponse = serde_path_to_error::deserialize(&mut deser)?;
if body.needauth.unwrap_or(false) {
return Err(ConfirmerError::InvalidTokens);
}
if !body.success {
if let Some(msg) = body.message {
return Err(ConfirmerError::RemoteFailureWithMessage(msg));
} else {
return Err(ConfirmerError::RemoteFailure);
}
}
Ok(body.conf)
}
/// Respond to a confirmation.
///
/// Host: https://steamcommunity.com
/// Steam Endpoint: `GET /mobileconf/ajaxop`
fn send_confirmation_ajax(
&self,
conf: &Confirmation,
action: ConfirmationAction,
) -> Result<(), ConfirmerError> {
debug!("responding to a single confirmation: send_confirmation_ajax()");
let operation = action.to_operation();
let cookies = self.build_cookie_jar();
let client = self.transport.innner_http_client()?;
let time = steamapi::get_server_time(self.transport.clone())?.server_time();
let mut query_params = self.get_confirmation_query_params("conf", time);
query_params.push(("op", operation.into()));
query_params.push(("cid", Cow::Borrowed(&conf.id)));
query_params.push(("ck", Cow::Borrowed(&conf.nonce)));
let resp = client
.get(
"https://steamcommunity.com/mobileconf/ajaxop"
.parse::<Url>()
.unwrap(),
)
.header(USER_AGENT, "steamguard-cli")
.header(COOKIE, cookies.cookies(&STEAM_COOKIE_URL).unwrap())
.query(&query_params)
.send()?;
trace!("send_confirmation_ajax() response: {:?}", &resp);
debug!(
"send_confirmation_ajax() response status code: {}",
&resp.status()
);
let raw = resp.text()?;
debug!("send_confirmation_ajax() response body: {:?}", &raw);
let mut deser = serde_json::Deserializer::from_str(raw.as_str());
let body: SendConfirmationResponse = serde_path_to_error::deserialize(&mut deser)?;
if body.needsauth.unwrap_or(false) {
return Err(ConfirmerError::InvalidTokens);
}
if !body.success {
if let Some(msg) = body.message {
return Err(ConfirmerError::RemoteFailureWithMessage(msg));
} else {
return Err(ConfirmerError::RemoteFailure);
}
}
Ok(())
}
pub fn accept_confirmation(&self, conf: &Confirmation) -> Result<(), ConfirmerError> {
self.send_confirmation_ajax(conf, ConfirmationAction::Accept)
}
pub fn deny_confirmation(&self, conf: &Confirmation) -> Result<(), ConfirmerError> {
self.send_confirmation_ajax(conf, ConfirmationAction::Deny)
}
/// Respond to more than 1 confirmation.
///
/// Host: https://steamcommunity.com
/// Steam Endpoint: `GET /mobileconf/multiajaxop`
fn send_multi_confirmation_ajax(
&self,
confs: &[Confirmation],
action: ConfirmationAction,
) -> Result<(), ConfirmerError> {
debug!("responding to bulk confirmations: send_multi_confirmation_ajax()");
if confs.is_empty() {
debug!("confs is empty, nothing to do.");
return Ok(());
}
let operation = action.to_operation();
let cookies = self.build_cookie_jar();
let client = self.transport.innner_http_client()?;
let time = steamapi::get_server_time(self.transport.clone())?.server_time();
let mut query_params = self.get_confirmation_query_params("conf", time);
query_params.push(("op", operation.into()));
for conf in confs.iter() {
query_params.push(("cid[]", Cow::Borrowed(&conf.id)));
query_params.push(("ck[]", Cow::Borrowed(&conf.nonce)));
}
let query_params = self.build_multi_conf_query_string(&query_params);
// despite being called query parameters, they will actually go in the body
debug!("query_params: {}", &query_params);
let resp = client
.post(
"https://steamcommunity.com/mobileconf/multiajaxop"
.parse::<Url>()
.unwrap(),
)
.header(USER_AGENT, "steamguard-cli")
.header(COOKIE, cookies.cookies(&STEAM_COOKIE_URL).unwrap())
.header(
CONTENT_TYPE,
"application/x-www-form-urlencoded; charset=UTF-8",
)
.body(query_params)
.send()?;
trace!("send_multi_confirmation_ajax() response: {:?}", &resp);
debug!(
"send_multi_confirmation_ajax() response status code: {}",
&resp.status()
);
let raw = resp.text()?;
debug!("send_multi_confirmation_ajax() response body: {:?}", &raw);
let mut deser = serde_json::Deserializer::from_str(raw.as_str());
let body: SendConfirmationResponse = serde_path_to_error::deserialize(&mut deser)?;
if body.needsauth.unwrap_or(false) {
return Err(ConfirmerError::InvalidTokens);
}
if !body.success {
if let Some(msg) = body.message {
return Err(ConfirmerError::RemoteFailureWithMessage(msg));
} else {
return Err(ConfirmerError::RemoteFailure);
}
}
Ok(())
}
pub fn accept_confirmations(&self, confs: &[Confirmation]) -> Result<(), ConfirmerError> {
self.send_multi_confirmation_ajax(confs, ConfirmationAction::Accept)
}
pub fn deny_confirmations(&self, confs: &[Confirmation]) -> Result<(), ConfirmerError> {
self.send_multi_confirmation_ajax(confs, ConfirmationAction::Deny)
}
fn build_multi_conf_query_string(&self, params: &[(&str, Cow<str>)]) -> String {
params
.iter()
.map(|(k, v)| format!("{}={}", k, v))
.collect::<Vec<_>>()
.join("&")
}
/// Steam Endpoint: `GET /mobileconf/details/:id`
pub fn get_confirmation_details(&self, conf: &Confirmation) -> anyhow::Result<String> {
#[derive(Debug, Clone, Deserialize)]
struct ConfirmationDetailsResponse {
pub success: bool,
pub html: String,
}
let cookies = self.build_cookie_jar();
let client = self.transport.innner_http_client()?;
let time = steamapi::get_server_time(self.transport.clone())?.server_time();
let query_params = self.get_confirmation_query_params("details", time);
let resp = client
.get(
format!("https://steamcommunity.com/mobileconf/details/{}", conf.id)
.parse::<Url>()
.unwrap(),
)
.header(USER_AGENT, "steamguard-cli")
.header(COOKIE, cookies.cookies(&STEAM_COOKIE_URL).unwrap())
.query(&query_params)
.send()?;
let text = resp.text()?;
let mut deser = serde_json::Deserializer::from_str(text.as_str());
let body: ConfirmationDetailsResponse = serde_path_to_error::deserialize(&mut deser)?;
ensure!(body.success);
Ok(body.html)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConfirmationAction {
Accept,
Deny,
}
impl ConfirmationAction {
fn to_operation(self) -> &'static str {
match self {
ConfirmationAction::Accept => "allow",
ConfirmationAction::Deny => "cancel",
}
}
}
#[derive(Debug, thiserror::Error)]
pub enum ConfirmerError {
#[error("Invalid tokens, login or token refresh required.")]
InvalidTokens,
#[error("Network failure: {0}")]
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),
}
/// A mobile confirmation. There are multiple things that can be confirmed, like trade offers.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[derive(Debug, Clone, PartialEq)]
pub struct Confirmation {
#[serde(rename = "type")]
pub conf_type: ConfirmationType,
pub type_name: String,
pub id: String,
pub id: u64,
pub key: u64,
/// Trade offer ID or market transaction ID
pub creator_id: String,
pub nonce: String,
pub creation_time: u64,
pub cancel: String,
pub accept: String,
pub icon: Option<String>,
pub multi: bool,
pub headline: String,
pub summary: Vec<String>,
pub creator: u64,
pub conf_type: ConfirmationType,
pub description: String,
}
impl Confirmation {
/// Human readable representation of this confirmation.
pub fn description(&self) -> String {
format!(
"{:?} - {} - {}",
self.conf_type,
self.headline,
self.summary.join(", ")
)
format!("{:?} - {}", self.conf_type, self.description)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, num_enum::FromPrimitive)]
#[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.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
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
Generic = 1,
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),
Unknown,
}
#[derive(Debug, Deserialize)]
pub struct ConfirmationListResponse {
pub success: bool,
#[serde(default)]
pub needauth: Option<bool>,
#[serde(default)]
pub conf: Vec<Confirmation>,
#[serde(default)]
pub message: Option<String>,
}
#[derive(Debug, Clone, 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] {
time.to_be_bytes()
}
fn generate_confirmation_hash_for_time(
time: u64,
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)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_confirmations() -> anyhow::Result<()> {
struct Test {
text: &'static str,
confirmation_type: ConfirmationType,
}
let cases = [
Test {
text: include_str!("fixtures/confirmations/email-change.json"),
confirmation_type: ConfirmationType::AccountRecovery,
},
Test {
text: include_str!("fixtures/confirmations/phone-number-change.json"),
confirmation_type: ConfirmationType::PhoneNumberChange,
},
];
for case in cases.iter() {
let confirmations = serde_json::from_str::<ConfirmationListResponse>(case.text)?;
assert_eq!(confirmations.conf.len(), 1);
let confirmation = &confirmations.conf[0];
assert_eq!(confirmation.conf_type, case.confirmation_type);
}
Ok(())
}
#[test]
fn test_parse_confirmations_2() -> anyhow::Result<()> {
struct Test {
text: &'static str,
}
let cases = [Test {
text: include_str!("fixtures/confirmations/need-auth.json"),
}];
for case in cases.iter() {
let confirmations = serde_json::from_str::<ConfirmationListResponse>(case.text)?;
assert_eq!(confirmations.conf.len(), 0);
assert_eq!(confirmations.needauth, Some(true));
}
Ok(())
}
#[test]
fn test_generate_confirmation_hash_for_time() {
assert_eq!(
generate_confirmation_hash_for_time(1617591917, "conf", "GQP46b73Ws7gr8GmZFR0sDuau5c="),
String::from("NaL8EIMhfy/7vBounJ0CvpKbrPk=")
);
impl From<&str> for ConfirmationType {
fn from(text: &str) -> Self {
match text {
"1" => ConfirmationType::Generic,
"2" => ConfirmationType::Trade,
"3" => ConfirmationType::MarketSell,
"6" => ConfirmationType::AccountRecovery,
_ => ConfirmationType::Unknown,
}
}
}

View file

@ -0,0 +1 @@
{"success":true,"requires_twofactor":false,"redirect_uri":"steammobile:\/\/mobileloginsucceeded","login_complete":true,"oauth":"{\"steamid\":\"92591609556178617\",\"account_name\":\"hydrastar2\",\"oauth_token\":\"1cc83205dab2979e558534dab29f6f3aa\",\"wgtoken\":\"3EDA9DEF07D7B39361D95203525D8AFE82A\",\"wgtoken_secure\":\"F31641B9AFC2F8B0EE7B6F44D7E73EA3FA48\"}"}

View file

@ -0,0 +1 @@
{"success":true,"requires_twofactor":false,"redirect_uri":"steammobile://mobileloginsucceeded","login_complete":true,"oauth":"{\"steamid\":\"78562647129469312\",\"account_name\":\"feuarus\",\"oauth_token\":\"fd2fdb3d0717bad2220d98c7ec61c7bd\",\"wgtoken\":\"72E7013D598A4F68C7E268F6FA3767D89D763732\",\"wgtoken_secure\":\"21061EA13C36D7C29812CAED900A215171AD13A2\",\"webcookie\":\"6298070A226E5DAD49938D78BCF36F7A7118FDD5\"}"}

View file

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

View file

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

Some files were not shown because too many files have changed in this diff Show more