Compare commits
160 commits
Author | SHA1 | Date | |
---|---|---|---|
|
96a30c6150 | ||
|
dd153a617c | ||
|
28c7a797cf | ||
|
c2a72fee6c | ||
|
602acc6641 | ||
|
b4564b7d5e | ||
|
d30ba017c9 | ||
|
37ae7c76a6 | ||
|
ef72bd898c | ||
|
52044c95bb | ||
|
b24a7415f6 | ||
|
8d54a1254a | ||
|
ab5cb00ee3 | ||
|
c7fefc1452 | ||
|
a64f7d4134 | ||
|
0a41e8b042 | ||
|
d3c1dfb3d5 | ||
|
a8d3f3fc99 | ||
|
5e24031719 | ||
|
d67e925a47 | ||
|
4c9f494ed3 | ||
|
46a1c2ed04 | ||
|
ad146c97c9 | ||
|
d96b6e65a6 | ||
|
84da432b2d | ||
|
2629b0b715 | ||
|
f7a4ce6133 | ||
|
c5d51b5174 | ||
|
8394baa157 | ||
|
25280abc62 | ||
|
bdc8d3c526 | ||
|
bcac6fa7a3 | ||
|
225b53d719 | ||
|
4ea44151b9 | ||
|
68dcedaeb7 | ||
|
9358fb60c9 | ||
|
9795453a04 | ||
|
8f7ca33e8a | ||
|
fca7e53a0d | ||
|
166b7a908c | ||
|
63805293ff | ||
|
d18dd378c3 | ||
|
41bf8a45ec | ||
|
37b7b75077 | ||
|
8bfab8d2a2 | ||
|
a9e39b4215 | ||
|
a50109ad63 | ||
|
7eb62cfa7b | ||
|
94a3210f09 | ||
|
6d4915a39c | ||
|
e529b76c97 | ||
|
47894cc217 | ||
|
c809d1e725 | ||
|
0c256a0e05 | ||
|
04295dc742 | ||
|
4fb0e4cfcd | ||
|
e032008fdb | ||
|
5178238f8d | ||
|
90ba3b64b5 | ||
|
14589e70d5 | ||
|
a9af82da13 | ||
|
f952ed5b1b | ||
|
97a9040eb8 | ||
|
544608a330 | ||
|
9f26e6b241 | ||
|
2c63350bcf | ||
|
29aca56067 | ||
|
f2821d2837 | ||
|
84993dedae | ||
|
4348529ffd | ||
|
40d81f360b | ||
|
84f488a7bd | ||
|
34d17a2462 | ||
|
e960b7cedc | ||
|
3957177709 | ||
|
f0e66a4651 | ||
|
94a7ca8bc8 | ||
|
8bd0079ffc | ||
|
aa5168e663 | ||
|
28733e029d | ||
|
2114d0a98d | ||
|
fff3427d8d | ||
|
d7173b4efb | ||
|
96f342137a | ||
|
d1ff150cbf | ||
|
9c6d10dc1f | ||
|
d31a1435c2 | ||
|
e5b76fe4a4 | ||
|
942ac6f35f | ||
|
e1a27e8b23 | ||
|
eb51a7a2a7 | ||
|
17d19c53c0 | ||
|
7c985f62ff | ||
|
df47ff1823 | ||
|
d9261d0ac8 | ||
|
b98cd2d4c7 | ||
|
3fdf2fdbc9 | ||
|
7635e5ca10 | ||
|
a2b3f18d76 | ||
|
d3b9471e95 | ||
|
391371002b | ||
|
06af8c2219 | ||
|
8f4ec79144 | ||
|
969baeed4c | ||
|
d5218d770e | ||
|
26c6916e79 | ||
|
11b36c566e | ||
|
7e94f76653 | ||
|
fe663cf43f | ||
|
1d99bae469 | ||
|
e25ab17fd6 | ||
|
6f4064ff58 | ||
|
3146d4824c | ||
|
55a8bee695 | ||
|
b9d9179537 | ||
|
f05f423d23 | ||
|
4cc4d2370c | ||
|
b3c6639146 | ||
|
71d399f645 | ||
|
4990d23c32 | ||
|
6c4af1c9de | ||
|
f7f9c916ba | ||
|
b30eb050de | ||
|
3cb0869597 | ||
|
06ea485e55 | ||
|
dc591212bb | ||
|
9bfd07c6b4 | ||
|
39fa6bb4a1 | ||
|
0341db0046 | ||
|
201288952a | ||
|
4b92d46049 | ||
|
0b8de57e3a | ||
|
6af4374da3 | ||
|
0d24d12c55 | ||
|
09fd78a5a5 | ||
|
79c01833e8 | ||
|
ad5a9b3131 | ||
|
7d39da8213 | ||
|
4fed9486de | ||
|
f8ae7d4e0e | ||
|
da44f49c56 | ||
|
46ddaad281 | ||
|
fdf54e6498 | ||
|
a062e718d7 | ||
|
ac7717bde8 | ||
|
d2ba7d8f1d | ||
|
93a5fe643c | ||
|
1632e2f10e | ||
|
d87caa06f6 | ||
|
f1855ba7c0 | ||
|
a5be7b26bb | ||
|
bff16bd341 | ||
|
64697b6808 | ||
|
7e04a4240a | ||
|
2dc6376533 | ||
|
f080e35971 | ||
|
2d180f0209 | ||
|
2934dd3927 | ||
|
6a5b8d5573 | ||
|
a72126ffcd |
100 changed files with 7051 additions and 2615 deletions
2
.github/ISSUE_TEMPLATE/bug.yml
vendored
2
.github/ISSUE_TEMPLATE/bug.yml
vendored
|
@ -10,7 +10,7 @@ body:
|
||||||
id: version
|
id: version
|
||||||
attributes:
|
attributes:
|
||||||
label: Version
|
label: Version
|
||||||
description: What version of steamguard-cli are you running? You can find this by running `steamguard --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:
|
validations:
|
||||||
required: true
|
required: true
|
||||||
- type: textarea
|
- type: textarea
|
||||||
|
|
3
.github/workflows/aur-checker.yml
vendored
3
.github/workflows/aur-checker.yml
vendored
|
@ -5,12 +5,13 @@ on:
|
||||||
- cron: "32 5 */3 * *"
|
- cron: "32 5 */3 * *"
|
||||||
push:
|
push:
|
||||||
branches: [ master, main ]
|
branches: [ master, main ]
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
test-install:
|
test-install:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v4
|
||||||
- name: Install AUR package
|
- name: Install AUR package
|
||||||
run: ./scripts/check-aur.sh
|
run: ./scripts/check-aur.sh
|
25
.github/workflows/rust.yml
vendored
25
.github/workflows/rust.yml
vendored
|
@ -10,14 +10,14 @@ env:
|
||||||
CARGO_TERM_COLOR: always
|
CARGO_TERM_COLOR: always
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
test:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- run: rustup component add clippy rustfmt
|
- run: rustup component add clippy rustfmt
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v4
|
||||||
- name: Rust Cache
|
- name: Rust Cache
|
||||||
uses: Swatinem/rust-cache@v2.2.1
|
uses: Swatinem/rust-cache@v2
|
||||||
- name: Check format
|
- name: Check format
|
||||||
run: cargo fmt --all -- --check
|
run: cargo fmt --all -- --check
|
||||||
- name: Check
|
- name: Check
|
||||||
|
@ -27,4 +27,21 @@ jobs:
|
||||||
- name: Validate documentation
|
- name: Validate documentation
|
||||||
run: cargo doc --workspace --no-deps --all-features
|
run: cargo doc --workspace --no-deps --all-features
|
||||||
- name: Run tests
|
- name: Run tests
|
||||||
run: cargo test --verbose
|
run: cargo test --verbose --all-features --all-targets --workspace
|
||||||
|
check:
|
||||||
|
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
|
||||||
|
with:
|
||||||
|
prefix-key: v0-rust-${{ matrix.target }}
|
||||||
|
- name: Install Cross
|
||||||
|
uses: baptiste0928/cargo-install@v2
|
||||||
|
with:
|
||||||
|
crate: cross
|
||||||
|
- name: Check
|
||||||
|
run: cross check --verbose --all-targets --all-features --target ${{ matrix.target }}
|
||||||
|
|
8
.vscode/launch.json
vendored
8
.vscode/launch.json
vendored
|
@ -30,11 +30,11 @@
|
||||||
"cargo": {
|
"cargo": {
|
||||||
"args": [
|
"args": [
|
||||||
"build",
|
"build",
|
||||||
"--bin=steamguard-cli",
|
"--bin=steamguard",
|
||||||
"--package=steamguard-cli"
|
"--package=steamguard-cli"
|
||||||
],
|
],
|
||||||
"filter": {
|
"filter": {
|
||||||
"name": "steamguard-cli",
|
"name": "steamguard",
|
||||||
"kind": "bin"
|
"kind": "bin"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
@ -49,11 +49,11 @@
|
||||||
"args": [
|
"args": [
|
||||||
"test",
|
"test",
|
||||||
"--no-run",
|
"--no-run",
|
||||||
"--bin=steamguard-cli",
|
"--bin=steamguard",
|
||||||
"--package=steamguard-cli"
|
"--package=steamguard-cli"
|
||||||
],
|
],
|
||||||
"filter": {
|
"filter": {
|
||||||
"name": "steamguard-cli",
|
"name": "steamguard",
|
||||||
"kind": "bin"
|
"kind": "bin"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
3511
Cargo.lock
generated
3511
Cargo.lock
generated
File diff suppressed because it is too large
Load diff
76
Cargo.toml
76
Cargo.toml
|
@ -1,14 +1,12 @@
|
||||||
[workspace]
|
[workspace]
|
||||||
|
|
||||||
members = [
|
members = ["steamguard"]
|
||||||
"steamguard"
|
|
||||||
]
|
|
||||||
|
|
||||||
[package]
|
[package]
|
||||||
name = "steamguard-cli"
|
name = "steamguard-cli"
|
||||||
version = "0.8.1"
|
version = "0.14.0"
|
||||||
authors = ["dyc3 (Carson McManus) <carson.mcmanus1@gmail.com>"]
|
authors = ["dyc3 (Carson McManus) <carson.mcmanus1@gmail.com>"]
|
||||||
edition = "2018"
|
edition = "2021"
|
||||||
description = "A command line utility to generate Steam 2FA codes and respond to confirmations."
|
description = "A command line utility to generate Steam 2FA codes and respond to confirmations."
|
||||||
keywords = ["steam", "2fa", "steamguard", "authentication", "cli"]
|
keywords = ["steam", "2fa", "steamguard", "authentication", "cli"]
|
||||||
categories = ["command-line-utilities"]
|
categories = ["command-line-utilities"]
|
||||||
|
@ -16,8 +14,10 @@ repository = "https://github.com/dyc3/steamguard-cli"
|
||||||
license = "GPL-3.0-or-later"
|
license = "GPL-3.0-or-later"
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = ["qr"]
|
default = ["qr", "updater", "keyring"]
|
||||||
qr = ["qrcode"]
|
qr = ["dep:qrcode"]
|
||||||
|
updater = ["dep:update-informer"]
|
||||||
|
keyring = ["dep:keyring"]
|
||||||
|
|
||||||
# [[bin]]
|
# [[bin]]
|
||||||
# name = "steamguard-cli"
|
# name = "steamguard-cli"
|
||||||
|
@ -27,42 +27,56 @@ qr = ["qrcode"]
|
||||||
name = "steamguard"
|
name = "steamguard"
|
||||||
path = "src/main.rs"
|
path = "src/main.rs"
|
||||||
|
|
||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
anyhow = "^1.0"
|
anyhow = "^1.0"
|
||||||
hmac-sha1 = "^0.1"
|
base64 = "0.22.1"
|
||||||
base64 = "0.13.0"
|
|
||||||
text_io = "0.1.8"
|
text_io = "0.1.8"
|
||||||
rpassword = "5.0"
|
rpassword = "7.2.0"
|
||||||
reqwest = { version = "0.11", default-features = false, features = ["blocking", "json", "cookies", "gzip", "rustls-tls"] }
|
reqwest = { version = "0.12", default-features = false, features = [
|
||||||
|
"blocking",
|
||||||
|
"json",
|
||||||
|
"cookies",
|
||||||
|
"gzip",
|
||||||
|
"rustls-tls",
|
||||||
|
] }
|
||||||
serde = { version = "1.0", features = ["derive"] }
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
rsa = "0.5.0"
|
rsa = "0.9.2"
|
||||||
rand = "0.8.4"
|
rand = "0.8.5"
|
||||||
standback = "0.2.17" # required to fix a compilation error on a transient dependency
|
clap = { version = "4.5.4", features = ["derive", "cargo", "env"] }
|
||||||
clap = { version = "3.1.18", features = ["derive", "cargo", "env"] }
|
clap_complete = "4.5.2"
|
||||||
clap_complete = "3.2.1"
|
log = "0.4.19"
|
||||||
log = "0.4.14"
|
stderrlog = "0.6"
|
||||||
stderrlog = "0.4"
|
cookie = "0.18"
|
||||||
cookie = "0.14"
|
|
||||||
regex = "1"
|
regex = "1"
|
||||||
lazy_static = "1.4.0"
|
lazy_static = "1.4.0"
|
||||||
uuid = { version = "0.8", features = ["v4"] }
|
uuid = { version = "1.8", features = ["v4"] }
|
||||||
steamguard = { version = "^0.8.1", path = "./steamguard" }
|
steamguard = { version = "^0.14.0", path = "./steamguard" }
|
||||||
dirs = "3.0.2"
|
dirs = "5.0.1"
|
||||||
ring = "0.16.20"
|
aes = { version = "0.8.3", features = ["zeroize"] }
|
||||||
aes = "0.7.4"
|
thiserror = "1.0.61"
|
||||||
block-modes = "0.8.1"
|
|
||||||
thiserror = "1.0.26"
|
|
||||||
crossterm = { version = "0.23.2", features = ["event-stream"] }
|
crossterm = { version = "0.23.2", features = ["event-stream"] }
|
||||||
qrcode = { version = "0.12.0", optional = true }
|
qrcode = { version = "0.14.0", optional = true }
|
||||||
gethostname = "0.4.3"
|
gethostname = "0.4.3"
|
||||||
secrecy = { version = "0.8", features = ["serde"] }
|
secrecy = { version = "0.8", features = ["serde"] }
|
||||||
zeroize = "^1.4.3"
|
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"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
tempdir = "0.3"
|
tempfile = "3"
|
||||||
proptest = "1"
|
proptest = "1"
|
||||||
|
|
||||||
[profile.release]
|
[profile.release]
|
||||||
|
|
6
PKGBUILD
6
PKGBUILD
|
@ -3,7 +3,7 @@
|
||||||
|
|
||||||
_pkgname=steamguard-cli
|
_pkgname=steamguard-cli
|
||||||
pkgname=${_pkgname}-git
|
pkgname=${_pkgname}-git
|
||||||
pkgver=0.4.3.r1.145c03e9
|
pkgver=0.14.0.r1.602acc66
|
||||||
pkgrel=1
|
pkgrel=1
|
||||||
pkgdesc="A command line utility to generate Steam 2FA codes and respond to confirmations."
|
pkgdesc="A command line utility to generate Steam 2FA codes and respond to confirmations."
|
||||||
arch=('i686' 'x86_64' 'armv6h' 'armv7h')
|
arch=('i686' 'x86_64' 'armv6h' 'armv7h')
|
||||||
|
@ -12,6 +12,7 @@ license=('GPL3')
|
||||||
makedepends=('rust' 'cargo' 'git')
|
makedepends=('rust' 'cargo' 'git')
|
||||||
source=("git+https://github.com/dyc3/steamguard-cli.git")
|
source=("git+https://github.com/dyc3/steamguard-cli.git")
|
||||||
sha256sums=('SKIP')
|
sha256sums=('SKIP')
|
||||||
|
options=(!lto)
|
||||||
|
|
||||||
pkgver() {
|
pkgver() {
|
||||||
cd "${srcdir}/${_pkgname}"
|
cd "${srcdir}/${_pkgname}"
|
||||||
|
@ -24,5 +25,6 @@ build() {
|
||||||
}
|
}
|
||||||
|
|
||||||
package() {
|
package() {
|
||||||
install -Dm755 "${srcdir}/${_pkgname}/target/release/${_pkgname}" "${pkgdir}/usr/bin/${_pkgname}"
|
install -Dm755 "${srcdir}/${_pkgname}/target/release/steamguard" "${pkgdir}/usr/bin/steamguard"
|
||||||
|
ln -s "${pkgdir}/usr/bin/steamguard" "${pkgdir}/usr/bin/${_pkgname}"
|
||||||
}
|
}
|
||||||
|
|
22
README.md
22
README.md
|
@ -3,13 +3,29 @@
|
||||||
[](https://github.com/dyc3/steamguard-cli/actions/workflows/rust.yml)
|
[](https://github.com/dyc3/steamguard-cli/actions/workflows/rust.yml)
|
||||||
[](https://github.com/dyc3/steamguard-cli/actions/workflows/aur-checker.yml)
|
[](https://github.com/dyc3/steamguard-cli/actions/workflows/aur-checker.yml)
|
||||||
|
|
||||||
A command line utility for setting up and using Steam Mobile Authenticator (AKA Steam 2FA). It can also be used to respond to trade and market confirmations.
|
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.
|
||||||
|
|
||||||
**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.**
|
**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
|
# 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.**
|
**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
|
# Install
|
||||||
|
|
||||||
If you have the Rust toolchain installed:
|
If you have the Rust toolchain installed:
|
||||||
|
@ -19,8 +35,8 @@ cargo install steamguard-cli
|
||||||
|
|
||||||
Arch-based systems can install from the AUR:
|
Arch-based systems can install from the AUR:
|
||||||
|
|
||||||
- For [steamguard-cli-git](https://aur.archlinux.org/packages/steamguard-cli-git/)
|
- [steamguard-cli](https://aur.archlinux.org/packages/steamguard-cli/) tracks the latest release
|
||||||
- *Non-git release is not officially provided. Please open an issue if you would like to help set that up.*
|
- [steamguard-cli-git](https://aur.archlinux.org/packages/steamguard-cli-git/) tracks the latest git commit
|
||||||
|
|
||||||
Otherwise, you can download binaries from the releases.
|
Otherwise, you can download binaries from the releases.
|
||||||
|
|
||||||
|
|
55
docs/quickstart.md
Normal file
55
docs/quickstart.md
Normal file
|
@ -0,0 +1,55 @@
|
||||||
|
# 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
|
|
@ -1,3 +1,2 @@
|
||||||
tab_spaces = 4
|
tab_spaces = 4
|
||||||
hard_tabs = true
|
hard_tabs = true
|
||||||
normalize_comments = true
|
|
||||||
|
|
|
@ -4,6 +4,7 @@ set -e
|
||||||
|
|
||||||
DRY_RUN=true
|
DRY_RUN=true
|
||||||
SKIP_CRATE_PUBLISH=false
|
SKIP_CRATE_PUBLISH=false
|
||||||
|
ALLOW_DIRTY=false
|
||||||
|
|
||||||
POSITIONAL=()
|
POSITIONAL=()
|
||||||
while [[ $# -gt 0 ]]; do
|
while [[ $# -gt 0 ]]; do
|
||||||
|
@ -23,6 +24,10 @@ while [[ $# -gt 0 ]]; do
|
||||||
SKIP_CRATE_PUBLISH=true
|
SKIP_CRATE_PUBLISH=true
|
||||||
shift # past argument
|
shift # past argument
|
||||||
;;
|
;;
|
||||||
|
--allow-dirty)
|
||||||
|
ALLOW_DIRTY=true
|
||||||
|
shift # past argument
|
||||||
|
;;
|
||||||
*) # unknown option
|
*) # unknown option
|
||||||
POSITIONAL+=("$1") # save it in an array for later
|
POSITIONAL+=("$1") # save it in an array for later
|
||||||
shift # past argument
|
shift # past argument
|
||||||
|
@ -47,6 +52,21 @@ This will do everything needed to release a new version:
|
||||||
- publish crates on crates.io
|
- publish crates on crates.io
|
||||||
- upload artifacts to a new release on github
|
- 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
|
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."
|
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
|
else
|
||||||
|
@ -55,21 +75,14 @@ fi
|
||||||
echo "Press any key to continue..."
|
echo "Press any key to continue..."
|
||||||
read -n 1 -s -r
|
read -n 1 -s -r
|
||||||
|
|
||||||
params=()
|
|
||||||
if [[ $DRY_RUN == false ]]; then
|
if [[ $DRY_RUN == false ]]; then
|
||||||
params+=(--execute)
|
params+=(--execute)
|
||||||
fi
|
fi
|
||||||
if [[ $BUMP != "" ]]; then
|
cargo smart-release --update-crates-index --no-changelog --no-tag --no-push --no-publish "${params[@]}"
|
||||||
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..."
|
#echo "Verify that the publish succeeded, and Press any key to continue..."
|
||||||
read -n 1 -s -r
|
# read -n 1 -s -r
|
||||||
|
|
||||||
if ! which cross; then
|
if ! which cross; then
|
||||||
echo "cross not found, installing..."
|
echo "cross not found, installing..."
|
||||||
|
@ -78,23 +91,36 @@ fi
|
||||||
|
|
||||||
BUILD_TARGET="x86_64-unknown-linux-musl"
|
BUILD_TARGET="x86_64-unknown-linux-musl"
|
||||||
BUILD_TARGET2="x86_64-pc-windows-gnu"
|
BUILD_TARGET2="x86_64-pc-windows-gnu"
|
||||||
cross build --release "--target=$BUILD_TARGET"
|
# HACK: build targets in this order to avoid a bug in cross
|
||||||
cross build --release "--target=$BUILD_TARGET2"
|
cross build --release "--target=$BUILD_TARGET2"
|
||||||
|
cross build --release "--target=$BUILD_TARGET"
|
||||||
|
|
||||||
./scripts/package-deb.sh
|
./scripts/package-deb.sh
|
||||||
|
|
||||||
BIN_PATH="target/$BUILD_TARGET/release/steamguard"
|
BIN_PATH="target/$BUILD_TARGET/release/steamguard"
|
||||||
BIN_PATH2="target/$BUILD_TARGET2/release/steamguard.exe"
|
BIN_PATH2="target/$BUILD_TARGET2/release/steamguard.exe"
|
||||||
RAW_VERSION="$("$BIN_PATH" --version | cut -d " " -f 2)"
|
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
|
# TODO: can't compare with the tag anymore because it doesn't exist yet. maybe get a better condition?
|
||||||
echo "Version mismatch: $RAW_VERSION != $TAGGED_VERSION"
|
# TAGGED_VERSION="$(git tag | grep "^v" | tail -n 1 | tr -d v)"
|
||||||
fi
|
# 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"
|
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
|
||||||
|
fi
|
||||||
|
|
||||||
if [[ $DRY_RUN == false ]]; then
|
if [[ $DRY_RUN == false ]]; then
|
||||||
if [[ $(gh release list | grep -i "Draft" | grep -i "$VERSION" && echo "true" || echo "false") == "true" ]]; then
|
if [[ $(gh release list | grep -i "Draft" | grep -i "$VERSION" && echo "true" || echo "false") == "true" ]]; then
|
||||||
gh release delete --yes "$VERSION"
|
gh release delete --yes "$VERSION"
|
||||||
fi
|
fi
|
||||||
gh release create "$VERSION" --title "$VERSION" --draft "$BIN_PATH" "$BIN_PATH2" "./steamguard-cli_$RAW_VERSION-0.deb"
|
gh release create "$VERSION" --discussion-category "General" --title "$VERSION" "$BIN_PATH" "$BIN_PATH2" "./steamguard-cli_$RAW_VERSION-0.deb"
|
||||||
fi
|
fi
|
||||||
|
|
|
@ -32,12 +32,12 @@ Depends:
|
||||||
Version: $VERSION
|
Version: $VERSION
|
||||||
Section: base
|
Section: base
|
||||||
Priority: optional
|
Priority: optional
|
||||||
Architecture: x86-64
|
Architecture: amd64
|
||||||
Maintainer: Carson McManus <carson.mcmanus1@gmail.com>
|
Maintainer: Carson McManus <carson.mcmanus1@gmail.com>
|
||||||
Description: steamguard-cli
|
Description: steamguard-cli
|
||||||
A command line utility to generate Steam 2FA codes and respond to confirmations.
|
A command line utility to generate Steam 2FA codes and respond to confirmations.
|
||||||
EOT
|
EOT
|
||||||
|
|
||||||
dpkg-deb --build "$TEMP_PKG_PATH" "steamguard-cli_$VERSION-0.deb"
|
dpkg-deb -Zxz --build "$TEMP_PKG_PATH" "steamguard-cli_$VERSION-0.deb"
|
||||||
|
|
||||||
rm -rf "$TEMP_PKG_PATH"
|
rm -rf "$TEMP_PKG_PATH"
|
||||||
|
|
2
scripts/publish-aur.sh
Normal file → Executable file
2
scripts/publish-aur.sh
Normal file → Executable file
|
@ -31,7 +31,7 @@ fi
|
||||||
|
|
||||||
|
|
||||||
# get version info
|
# get version info
|
||||||
BIN_PATH="target/release/steamguard-cli"
|
BIN_PATH="target/release/steamguard"
|
||||||
RAW_VERSION="$("$BIN_PATH" --version | cut -d " " -f 2)"
|
RAW_VERSION="$("$BIN_PATH" --version | cut -d " " -f 2)"
|
||||||
TAGGED_VERSION="$(git tag | grep "^v" | tail -n 1 | tr -d v)"
|
TAGGED_VERSION="$(git tag | grep "^v" | tail -n 1 | tr -d v)"
|
||||||
if [[ "v$RAW_VERSION" != "v$TAGGED_VERSION" ]]; then
|
if [[ "v$RAW_VERSION" != "v$TAGGED_VERSION" ]]; then
|
||||||
|
|
|
@ -1,7 +1,9 @@
|
||||||
use crate::accountmanager::legacy::SdaManifest;
|
use crate::accountmanager::legacy::SdaManifest;
|
||||||
pub use crate::encryption::EntryEncryptionParams;
|
pub use crate::encryption::EncryptionScheme;
|
||||||
use crate::encryption::EntryEncryptor;
|
use crate::encryption::EntryEncryptor;
|
||||||
use log::*;
|
use log::*;
|
||||||
|
use rayon::prelude::*;
|
||||||
|
use secrecy::{ExposeSecret, SecretString};
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::fs::File;
|
use std::fs::File;
|
||||||
use std::io::{BufReader, Read, Write};
|
use std::io::{BufReader, Read, Write};
|
||||||
|
@ -13,6 +15,8 @@ use thiserror::Error;
|
||||||
mod legacy;
|
mod legacy;
|
||||||
pub mod manifest;
|
pub mod manifest;
|
||||||
pub mod migrate;
|
pub mod migrate;
|
||||||
|
mod steamv2;
|
||||||
|
mod winauth;
|
||||||
|
|
||||||
pub use manifest::*;
|
pub use manifest::*;
|
||||||
|
|
||||||
|
@ -21,7 +25,7 @@ pub struct AccountManager {
|
||||||
manifest: Manifest,
|
manifest: Manifest,
|
||||||
accounts: HashMap<String, Arc<Mutex<SteamGuardAccount>>>,
|
accounts: HashMap<String, Arc<Mutex<SteamGuardAccount>>>,
|
||||||
folder: String,
|
folder: String,
|
||||||
passkey: Option<String>,
|
passkey: Option<SecretString>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AccountManager {
|
impl AccountManager {
|
||||||
|
@ -53,7 +57,8 @@ impl AccountManager {
|
||||||
let mut reader = BufReader::new(file);
|
let mut reader = BufReader::new(file);
|
||||||
let mut buffer = String::new();
|
let mut buffer = String::new();
|
||||||
reader.read_to_string(&mut buffer)?;
|
reader.read_to_string(&mut buffer)?;
|
||||||
let manifest: Manifest = match serde_json::from_str(&buffer) {
|
let mut deser = serde_json::Deserializer::from_str(&buffer);
|
||||||
|
let manifest: Manifest = match serde_path_to_error::deserialize(&mut deser) {
|
||||||
Ok(m) => m,
|
Ok(m) => m,
|
||||||
Err(orig_err) => match serde_json::from_str::<SdaManifest>(&buffer) {
|
Err(orig_err) => match serde_json::from_str::<SdaManifest>(&buffer) {
|
||||||
Ok(_) => return Err(ManifestLoadError::MigrationNeeded)?,
|
Ok(_) => return Err(ManifestLoadError::MigrationNeeded)?,
|
||||||
|
@ -72,9 +77,9 @@ impl AccountManager {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Tells the manager to keep track of the encryption passkey, and use it for encryption when loading or saving accounts.
|
/// Tells the manager to keep track of the encryption passkey, and use it for encryption when loading or saving accounts.
|
||||||
pub fn submit_passkey(&mut self, passkey: Option<String>) {
|
pub fn submit_passkey(&mut self, passkey: Option<SecretString>) {
|
||||||
if let Some(p) = passkey.as_ref() {
|
if let Some(p) = passkey.as_ref() {
|
||||||
if p.is_empty() {
|
if p.expose_secret().is_empty() {
|
||||||
panic!("Encryption passkey cannot be empty");
|
panic!("Encryption passkey cannot be empty");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -86,15 +91,28 @@ impl AccountManager {
|
||||||
self.passkey = passkey;
|
self.passkey = passkey;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn keyring_id(&self) -> Option<&String> {
|
||||||
|
self.manifest.keyring_id.as_ref()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_keyring_id(&mut self, keyring_id: String) {
|
||||||
|
self.manifest.keyring_id = Some(keyring_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn clear_keyring_id(&mut self) {
|
||||||
|
self.manifest.keyring_id = None;
|
||||||
|
}
|
||||||
|
|
||||||
/// Loads all accounts, and registers them.
|
/// Loads all accounts, and registers them.
|
||||||
pub fn load_accounts(&mut self) -> anyhow::Result<(), ManifestAccountLoadError> {
|
pub fn load_accounts(&mut self) -> anyhow::Result<(), ManifestAccountLoadError> {
|
||||||
let mut accounts = vec![];
|
let accounts = self
|
||||||
for entry in &self.manifest.entries {
|
.manifest
|
||||||
let account = self.load_account_by_entry(entry)?;
|
.entries
|
||||||
accounts.push(account);
|
.par_iter()
|
||||||
}
|
.map(|entry| self.load_account_by_entry(entry))
|
||||||
|
.collect::<Vec<_>>();
|
||||||
for account in accounts {
|
for account in accounts {
|
||||||
self.register_loaded_account(account);
|
self.register_loaded_account(account?);
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -103,7 +121,7 @@ impl AccountManager {
|
||||||
/// Must call `register_loaded_account` after loading the account.
|
/// Must call `register_loaded_account` after loading the account.
|
||||||
fn load_account(
|
fn load_account(
|
||||||
&self,
|
&self,
|
||||||
account_name: &String,
|
account_name: impl AsRef<str>,
|
||||||
) -> anyhow::Result<Arc<Mutex<SteamGuardAccount>>, ManifestAccountLoadError> {
|
) -> anyhow::Result<Arc<Mutex<SteamGuardAccount>>, ManifestAccountLoadError> {
|
||||||
let entry = self.get_entry(account_name)?;
|
let entry = self.get_entry(account_name)?;
|
||||||
self.load_account_by_entry(entry)
|
self.load_account_by_entry(entry)
|
||||||
|
@ -152,64 +170,80 @@ impl AccountManager {
|
||||||
.insert(account.account_name.clone(), Arc::new(Mutex::new(account)));
|
.insert(account.account_name.clone(), Arc::new(Mutex::new(account)));
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn import_account(&mut self, import_path: &String) -> anyhow::Result<()> {
|
pub fn import_account(
|
||||||
|
&mut self,
|
||||||
|
import_path: &String,
|
||||||
|
) -> anyhow::Result<(), ManifestAccountImportError> {
|
||||||
let path = Path::new(import_path);
|
let path = Path::new(import_path);
|
||||||
ensure!(path.exists(), "{} does not exist.", import_path);
|
if !path.exists() {
|
||||||
ensure!(path.is_file(), "{} is not a file.", import_path);
|
return Err(ManifestAccountImportError::FileNotFound);
|
||||||
|
}
|
||||||
|
if !path.is_file() {
|
||||||
|
return Err(ManifestAccountImportError::NotAFile);
|
||||||
|
}
|
||||||
|
|
||||||
let file = File::open(path)?;
|
let file = File::open(path)?;
|
||||||
let reader = BufReader::new(file);
|
let reader = BufReader::new(file);
|
||||||
let account: SteamGuardAccount = serde_json::from_reader(reader)?;
|
let mut deser = serde_json::Deserializer::from_reader(reader);
|
||||||
ensure!(
|
let account: SteamGuardAccount = serde_path_to_error::deserialize(&mut deser)?;
|
||||||
!self.account_exists(&account.account_name),
|
if self.account_exists(&account.account_name) {
|
||||||
"Account already exists in manifest, please remove it first."
|
return Err(ManifestAccountImportError::AlreadyExists {
|
||||||
);
|
account_name: account.account_name,
|
||||||
|
});
|
||||||
|
}
|
||||||
self.add_account(account);
|
self.add_account(account);
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn remove_account(&mut self, account_name: String) {
|
pub fn remove_account(&mut self, account_name: &String) {
|
||||||
let index = self
|
let index = self
|
||||||
.manifest
|
.manifest
|
||||||
.entries
|
.entries
|
||||||
.iter()
|
.iter()
|
||||||
.position(|a| a.account_name == account_name)
|
.position(|a| &a.account_name == account_name)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
self.accounts.remove(&account_name);
|
self.accounts.remove(account_name);
|
||||||
self.manifest.entries.remove(index);
|
self.manifest.entries.remove(index);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Saves the manifest and all loaded accounts.
|
/// Saves the manifest and all loaded accounts.
|
||||||
pub fn save(&self) -> anyhow::Result<()> {
|
pub fn save(&self) -> anyhow::Result<()> {
|
||||||
info!("Saving manifest and accounts...");
|
info!("Saving manifest and accounts...");
|
||||||
for account in self
|
let save_results: Vec<_> = self
|
||||||
.accounts
|
.accounts
|
||||||
.values()
|
.values()
|
||||||
.map(|a| a.clone().lock().unwrap().clone())
|
.par_bridge()
|
||||||
{
|
.map(|account| -> anyhow::Result<()> {
|
||||||
let entry = self.get_entry(&account.account_name)?.clone();
|
let account = account.lock().unwrap();
|
||||||
debug!("saving {}", entry.filename);
|
let entry = self.get_entry(&account.account_name)?.clone();
|
||||||
let serialized = serde_json::to_vec(&account)?;
|
debug!("saving {}", entry.filename);
|
||||||
ensure!(
|
let serialized = serde_json::to_vec(&account.clone())?;
|
||||||
serialized.len() > 2,
|
ensure!(
|
||||||
"Something extra weird happened and the account was serialized into nothing."
|
serialized.len() > 2,
|
||||||
);
|
"Something extra weird happened and the account was serialized into nothing."
|
||||||
|
);
|
||||||
|
|
||||||
let final_buffer: Vec<u8> = match (&self.passkey, entry.encryption.as_ref()) {
|
let final_buffer: Vec<u8> = match (&self.passkey, entry.encryption.as_ref()) {
|
||||||
(Some(passkey), Some(params)) => {
|
(Some(passkey), Some(scheme)) => {
|
||||||
crate::encryption::LegacySdaCompatible::encrypt(passkey, params, serialized)?
|
scheme.encrypt(passkey.expose_secret(), serialized)?
|
||||||
}
|
}
|
||||||
(None, Some(_)) => {
|
(None, Some(_)) => {
|
||||||
bail!("maFiles are encrypted, but no passkey was provided.");
|
bail!("maFiles are encrypted, but no passkey was provided.");
|
||||||
}
|
}
|
||||||
(_, None) => serialized,
|
(_, None) => serialized,
|
||||||
};
|
};
|
||||||
|
|
||||||
let path = Path::new(&self.folder).join(&entry.filename);
|
let path = Path::new(&self.folder).join(&entry.filename);
|
||||||
let mut file = File::create(path)?;
|
let mut file = File::create(path)?;
|
||||||
file.write_all(final_buffer.as_slice())?;
|
file.write_all(final_buffer.as_slice())?;
|
||||||
file.sync_data()?;
|
file.sync_data()?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
for result in save_results {
|
||||||
|
result?;
|
||||||
}
|
}
|
||||||
debug!("saving manifest");
|
debug!("saving manifest");
|
||||||
let manifest_serialized = serde_json::to_string(&self.manifest)?;
|
let manifest_serialized = serde_json::to_string(&self.manifest)?;
|
||||||
|
@ -229,24 +263,24 @@ impl AccountManager {
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub fn get_entry(
|
pub fn get_entry(
|
||||||
&self,
|
&self,
|
||||||
account_name: &String,
|
account_name: impl AsRef<str>,
|
||||||
) -> anyhow::Result<&ManifestEntry, ManifestAccountLoadError> {
|
) -> anyhow::Result<&ManifestEntry, ManifestAccountLoadError> {
|
||||||
self.manifest
|
self.manifest
|
||||||
.entries
|
.entries
|
||||||
.iter()
|
.iter()
|
||||||
.find(|e| &e.account_name == account_name)
|
.find(|e| e.account_name == account_name.as_ref())
|
||||||
.ok_or(ManifestAccountLoadError::MissingManifestEntry)
|
.ok_or(ManifestAccountLoadError::MissingManifestEntry)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub fn get_entry_mut(
|
pub fn get_entry_mut(
|
||||||
&mut self,
|
&mut self,
|
||||||
account_name: &String,
|
account_name: impl AsRef<str>,
|
||||||
) -> anyhow::Result<&mut ManifestEntry, ManifestAccountLoadError> {
|
) -> anyhow::Result<&mut ManifestEntry, ManifestAccountLoadError> {
|
||||||
self.manifest
|
self.manifest
|
||||||
.entries
|
.entries
|
||||||
.iter_mut()
|
.iter_mut()
|
||||||
.find(|e| &e.account_name == account_name)
|
.find(|e| e.account_name == account_name.as_ref())
|
||||||
.ok_or(ManifestAccountLoadError::MissingManifestEntry)
|
.ok_or(ManifestAccountLoadError::MissingManifestEntry)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -258,11 +292,11 @@ impl AccountManager {
|
||||||
/// Fails if the account does not exist in the manifest entries.
|
/// Fails if the account does not exist in the manifest entries.
|
||||||
pub fn get_account(
|
pub fn get_account(
|
||||||
&self,
|
&self,
|
||||||
account_name: &String,
|
account_name: impl AsRef<str>,
|
||||||
) -> anyhow::Result<Arc<Mutex<SteamGuardAccount>>> {
|
) -> anyhow::Result<Arc<Mutex<SteamGuardAccount>>> {
|
||||||
let account = self
|
let account = self
|
||||||
.accounts
|
.accounts
|
||||||
.get(account_name)
|
.get(account_name.as_ref())
|
||||||
.cloned()
|
.cloned()
|
||||||
.ok_or(anyhow!("Account not loaded"));
|
.ok_or(anyhow!("Account not loaded"));
|
||||||
account
|
account
|
||||||
|
@ -271,13 +305,13 @@ impl AccountManager {
|
||||||
/// Get or load the spcified account.
|
/// Get or load the spcified account.
|
||||||
pub fn get_or_load_account(
|
pub fn get_or_load_account(
|
||||||
&mut self,
|
&mut self,
|
||||||
account_name: &String,
|
account_name: impl AsRef<str>,
|
||||||
) -> anyhow::Result<Arc<Mutex<SteamGuardAccount>>, ManifestAccountLoadError> {
|
) -> anyhow::Result<Arc<Mutex<SteamGuardAccount>>, ManifestAccountLoadError> {
|
||||||
let account = self.get_account(account_name);
|
let account = self.get_account(account_name.as_ref());
|
||||||
if let Ok(account) = account {
|
if let Ok(account) = account {
|
||||||
return Ok(account);
|
return Ok(account);
|
||||||
}
|
}
|
||||||
let account = self.load_account(account_name)?;
|
let account = self.load_account(account_name.as_ref())?;
|
||||||
self.register_loaded_account(account.clone());
|
self.register_loaded_account(account.clone());
|
||||||
Ok(account)
|
Ok(account)
|
||||||
}
|
}
|
||||||
|
@ -305,8 +339,9 @@ impl AccountManager {
|
||||||
debug!("Adding missing account names");
|
debug!("Adding missing account names");
|
||||||
for i in 0..self.manifest.entries.len() {
|
for i in 0..self.manifest.entries.len() {
|
||||||
let account = self.load_account_by_entry(&self.manifest.entries[i].clone())?;
|
let account = self.load_account_by_entry(&self.manifest.entries[i].clone())?;
|
||||||
self.manifest.entries[i].account_name =
|
self.manifest.entries[i]
|
||||||
account.lock().unwrap().account_name.clone();
|
.account_name
|
||||||
|
.clone_from(&account.lock().unwrap().account_name);
|
||||||
}
|
}
|
||||||
upgraded = true;
|
upgraded = true;
|
||||||
}
|
}
|
||||||
|
@ -336,8 +371,8 @@ trait EntryLoader<T> {
|
||||||
fn load(
|
fn load(
|
||||||
&self,
|
&self,
|
||||||
path: &Path,
|
path: &Path,
|
||||||
passkey: Option<&String>,
|
passkey: Option<&SecretString>,
|
||||||
encryption_params: Option<&EntryEncryptionParams>,
|
encryption_params: Option<&EncryptionScheme>,
|
||||||
) -> anyhow::Result<T, ManifestAccountLoadError>;
|
) -> anyhow::Result<T, ManifestAccountLoadError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -345,28 +380,31 @@ impl EntryLoader<SteamGuardAccount> for ManifestEntry {
|
||||||
fn load(
|
fn load(
|
||||||
&self,
|
&self,
|
||||||
path: &Path,
|
path: &Path,
|
||||||
passkey: Option<&String>,
|
passkey: Option<&SecretString>,
|
||||||
encryption_params: Option<&EntryEncryptionParams>,
|
encryption_params: Option<&EncryptionScheme>,
|
||||||
) -> anyhow::Result<SteamGuardAccount, ManifestAccountLoadError> {
|
) -> anyhow::Result<SteamGuardAccount, ManifestAccountLoadError> {
|
||||||
debug!("loading entry: {:?}", path);
|
debug!("loading entry: {:?}", path);
|
||||||
let file = File::open(path)?;
|
let file = File::open(path)?;
|
||||||
let mut reader = BufReader::new(file);
|
let mut reader = BufReader::new(file);
|
||||||
let account: SteamGuardAccount = match (&passkey, encryption_params.as_ref()) {
|
let account: SteamGuardAccount = match (&passkey, encryption_params.as_ref()) {
|
||||||
(Some(passkey), Some(params)) => {
|
(Some(passkey), Some(scheme)) => {
|
||||||
let mut ciphertext: Vec<u8> = vec![];
|
let mut ciphertext: Vec<u8> = vec![];
|
||||||
reader.read_to_end(&mut ciphertext)?;
|
reader.read_to_end(&mut ciphertext)?;
|
||||||
let plaintext =
|
let plaintext = scheme.decrypt(passkey.expose_secret(), ciphertext)?;
|
||||||
crate::encryption::LegacySdaCompatible::decrypt(passkey, params, ciphertext)?;
|
|
||||||
if plaintext[0] != b'{' && plaintext[plaintext.len() - 1] != b'}' {
|
if plaintext[0] != b'{' && plaintext[plaintext.len() - 1] != b'}' {
|
||||||
return Err(ManifestAccountLoadError::IncorrectPasskey);
|
return Err(ManifestAccountLoadError::IncorrectPasskey);
|
||||||
}
|
}
|
||||||
let s = std::str::from_utf8(&plaintext).unwrap();
|
let s = std::str::from_utf8(&plaintext).unwrap();
|
||||||
serde_json::from_str(s)?
|
let mut deser = serde_json::Deserializer::from_str(s);
|
||||||
|
serde_path_to_error::deserialize(&mut deser)?
|
||||||
}
|
}
|
||||||
(None, Some(_)) => {
|
(None, Some(_)) => {
|
||||||
return Err(ManifestAccountLoadError::MissingPasskey);
|
return Err(ManifestAccountLoadError::MissingPasskey);
|
||||||
}
|
}
|
||||||
(_, None) => serde_json::from_reader(reader)?,
|
(_, None) => {
|
||||||
|
let mut deser = serde_json::Deserializer::from_reader(reader);
|
||||||
|
serde_path_to_error::deserialize(&mut deser)?
|
||||||
|
}
|
||||||
};
|
};
|
||||||
Ok(account)
|
Ok(account)
|
||||||
}
|
}
|
||||||
|
@ -378,8 +416,8 @@ pub enum ManifestLoadError {
|
||||||
Missing(#[from] std::io::Error),
|
Missing(#[from] std::io::Error),
|
||||||
#[error("Manifest needs to be migrated to the latest format.")]
|
#[error("Manifest needs to be migrated to the latest format.")]
|
||||||
MigrationNeeded,
|
MigrationNeeded,
|
||||||
#[error("Failed to deserialize the manifest.")]
|
#[error("Failed to deserialize the manifest. {self:?}")]
|
||||||
DeserializationFailed(#[from] serde_json::Error),
|
DeserializationFailed(#[from] serde_path_to_error::Error<serde_json::Error>),
|
||||||
#[error(transparent)]
|
#[error(transparent)]
|
||||||
Unknown(#[from] anyhow::Error),
|
Unknown(#[from] anyhow::Error),
|
||||||
}
|
}
|
||||||
|
@ -394,50 +432,58 @@ pub enum ManifestAccountLoadError {
|
||||||
IncorrectPasskey,
|
IncorrectPasskey,
|
||||||
#[error("Failed to decrypt account. {self:?}")]
|
#[error("Failed to decrypt account. {self:?}")]
|
||||||
DecryptionFailed(#[from] crate::encryption::EntryEncryptionError),
|
DecryptionFailed(#[from] crate::encryption::EntryEncryptionError),
|
||||||
#[error("Failed to deserialize the account.")]
|
#[error("Failed to deserialize the account. {self:?}")]
|
||||||
DeserializationFailed(#[from] serde_json::Error),
|
DeserializationFailed(#[from] serde_path_to_error::Error<serde_json::Error>),
|
||||||
#[error(transparent)]
|
#[error(transparent)]
|
||||||
Unknown(#[from] anyhow::Error),
|
Unknown(#[from] anyhow::Error),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<block_modes::BlockModeError> for ManifestAccountLoadError {
|
|
||||||
fn from(error: block_modes::BlockModeError) -> Self {
|
|
||||||
Self::Unknown(anyhow::Error::from(error))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl From<base64::DecodeError> for ManifestAccountLoadError {
|
impl From<base64::DecodeError> for ManifestAccountLoadError {
|
||||||
fn from(error: base64::DecodeError) -> Self {
|
fn from(error: base64::DecodeError) -> Self {
|
||||||
Self::Unknown(anyhow::Error::from(error))
|
Self::Unknown(anyhow::Error::from(error))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl From<block_modes::InvalidKeyIvLength> for ManifestAccountLoadError {
|
|
||||||
fn from(error: block_modes::InvalidKeyIvLength) -> Self {
|
|
||||||
Self::Unknown(anyhow::Error::from(error))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl From<std::io::Error> for ManifestAccountLoadError {
|
impl From<std::io::Error> for ManifestAccountLoadError {
|
||||||
fn from(error: std::io::Error) -> Self {
|
fn from(error: std::io::Error) -> Self {
|
||||||
Self::Unknown(anyhow::Error::from(error))
|
Self::Unknown(anyhow::Error::from(error))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Error)]
|
||||||
|
pub enum ManifestAccountImportError {
|
||||||
|
#[error("Could not find the specified file.")]
|
||||||
|
FileNotFound,
|
||||||
|
#[error("The specified path is not a file.")]
|
||||||
|
NotAFile,
|
||||||
|
#[error(
|
||||||
|
"The account you are trying to import, \"{account_name}\", already exists in the manifest."
|
||||||
|
)]
|
||||||
|
AlreadyExists { account_name: String },
|
||||||
|
#[error(transparent)]
|
||||||
|
IOError(#[from] std::io::Error),
|
||||||
|
#[error("Failed to deserialize the account. {self:?}")]
|
||||||
|
DeserializationFailed(#[from] serde_path_to_error::Error<serde_json::Error>),
|
||||||
|
#[error(transparent)]
|
||||||
|
Unknown(#[from] anyhow::Error),
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use steamguard::ExposeSecret;
|
use steamguard::ExposeSecret;
|
||||||
use tempdir::TempDir;
|
use tempfile::TempDir;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_should_save_new_manifest() {
|
fn test_should_save_new_manifest() {
|
||||||
let tmp_dir = TempDir::new("steamguard-cli-test").unwrap();
|
let tmp_dir = TempDir::new().unwrap();
|
||||||
let manifest_path = tmp_dir.path().join("manifest.json");
|
let manifest_path = tmp_dir.path().join("manifest.json");
|
||||||
let manager = AccountManager::new(manifest_path.as_path());
|
let manager = AccountManager::new(manifest_path.as_path());
|
||||||
assert!(matches!(manager.save(), Ok(_)));
|
assert!(manager.save().is_ok());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_should_save_and_load_manifest() -> anyhow::Result<()> {
|
fn test_should_save_and_load_manifest() -> anyhow::Result<()> {
|
||||||
let tmp_dir = TempDir::new("steamguard-cli-test")?;
|
let tmp_dir = TempDir::new()?;
|
||||||
let manifest_path = tmp_dir.path().join("manifest.json");
|
let manifest_path = tmp_dir.path().join("manifest.json");
|
||||||
println!("tempdir: {}", manifest_path.display());
|
println!("tempdir: {}", manifest_path.display());
|
||||||
let mut manager = AccountManager::new(manifest_path.as_path());
|
let mut manager = AccountManager::new(manifest_path.as_path());
|
||||||
|
@ -455,41 +501,25 @@ mod tests {
|
||||||
assert_eq!(manager.manifest.entries[0].filename, "asdf1234.maFile");
|
assert_eq!(manager.manifest.entries[0].filename, "asdf1234.maFile");
|
||||||
manager.load_accounts()?;
|
manager.load_accounts()?;
|
||||||
assert_eq!(manager.manifest.entries.len(), manager.accounts.len());
|
assert_eq!(manager.manifest.entries.len(), manager.accounts.len());
|
||||||
let account_name = "asdf1234".into();
|
let account_name = "asdf1234";
|
||||||
|
let account = manager.get_account(account_name)?;
|
||||||
|
let account = account.lock().unwrap();
|
||||||
|
assert_eq!(account.account_name, "asdf1234");
|
||||||
|
assert_eq!(account.revocation_code.expose_secret(), "R12345");
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
manager
|
account.shared_secret,
|
||||||
.get_account(&account_name)?
|
|
||||||
.lock()
|
|
||||||
.unwrap()
|
|
||||||
.account_name,
|
|
||||||
"asdf1234"
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
manager
|
|
||||||
.get_account(&account_name)?
|
|
||||||
.lock()
|
|
||||||
.unwrap()
|
|
||||||
.revocation_code
|
|
||||||
.expose_secret(),
|
|
||||||
"R12345"
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
manager
|
|
||||||
.get_account(&account_name)?
|
|
||||||
.lock()
|
|
||||||
.unwrap()
|
|
||||||
.shared_secret,
|
|
||||||
steamguard::token::TwoFactorSecret::parse_shared_secret(
|
steamguard::token::TwoFactorSecret::parse_shared_secret(
|
||||||
"zvIayp3JPvtvX/QGHqsqKBk/44s=".into()
|
"zvIayp3JPvtvX/QGHqsqKBk/44s=".into()
|
||||||
)?,
|
)
|
||||||
|
.unwrap(),
|
||||||
);
|
);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_should_save_and_load_manifest_encrypted() -> anyhow::Result<()> {
|
fn test_should_save_and_load_manifest_encrypted() -> anyhow::Result<()> {
|
||||||
let passkey = Some("password".into());
|
let passkey = Some(SecretString::new("password".into()));
|
||||||
let tmp_dir = TempDir::new("steamguard-cli-test")?;
|
let tmp_dir = TempDir::new()?;
|
||||||
let manifest_path = tmp_dir.path().join("manifest.json");
|
let manifest_path = tmp_dir.path().join("manifest.json");
|
||||||
let mut manager = AccountManager::new(manifest_path.as_path());
|
let mut manager = AccountManager::new(manifest_path.as_path());
|
||||||
let mut account = SteamGuardAccount::new();
|
let mut account = SteamGuardAccount::new();
|
||||||
|
@ -499,9 +529,9 @@ mod tests {
|
||||||
"zvIayp3JPvtvX/QGHqsqKBk/44s=".into(),
|
"zvIayp3JPvtvX/QGHqsqKBk/44s=".into(),
|
||||||
)?;
|
)?;
|
||||||
manager.add_account(account);
|
manager.add_account(account);
|
||||||
manager.manifest.entries[0].encryption = Some(EntryEncryptionParams::generate());
|
manager.manifest.entries[0].encryption = Some(EncryptionScheme::generate());
|
||||||
manager.submit_passkey(passkey.clone());
|
manager.submit_passkey(passkey.clone());
|
||||||
assert!(matches!(manager.save(), Ok(_)));
|
assert!(manager.save().is_ok());
|
||||||
|
|
||||||
let mut loaded_manager = AccountManager::load(manifest_path.as_path()).unwrap();
|
let mut loaded_manager = AccountManager::load(manifest_path.as_path()).unwrap();
|
||||||
loaded_manager.submit_passkey(passkey);
|
loaded_manager.submit_passkey(passkey);
|
||||||
|
@ -514,47 +544,31 @@ mod tests {
|
||||||
if _r.is_err() {
|
if _r.is_err() {
|
||||||
eprintln!("{:?}", _r);
|
eprintln!("{:?}", _r);
|
||||||
}
|
}
|
||||||
assert!(matches!(_r, Ok(_)));
|
assert!(_r.is_ok());
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
loaded_manager.manifest.entries.len(),
|
loaded_manager.manifest.entries.len(),
|
||||||
loaded_manager.accounts.len()
|
loaded_manager.accounts.len()
|
||||||
);
|
);
|
||||||
let account_name = "asdf1234".into();
|
let account_name = "asdf1234";
|
||||||
|
let account = loaded_manager.get_account(account_name)?;
|
||||||
|
let account = account.lock().unwrap();
|
||||||
|
assert_eq!(account.account_name, "asdf1234");
|
||||||
|
assert_eq!(account.revocation_code.expose_secret(), "R12345");
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
loaded_manager
|
account.shared_secret,
|
||||||
.get_account(&account_name)?
|
|
||||||
.lock()
|
|
||||||
.unwrap()
|
|
||||||
.account_name,
|
|
||||||
"asdf1234"
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
loaded_manager
|
|
||||||
.get_account(&account_name)?
|
|
||||||
.lock()
|
|
||||||
.unwrap()
|
|
||||||
.revocation_code
|
|
||||||
.expose_secret(),
|
|
||||||
"R12345"
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
loaded_manager
|
|
||||||
.get_account(&account_name)?
|
|
||||||
.lock()
|
|
||||||
.unwrap()
|
|
||||||
.shared_secret,
|
|
||||||
steamguard::token::TwoFactorSecret::parse_shared_secret(
|
steamguard::token::TwoFactorSecret::parse_shared_secret(
|
||||||
"zvIayp3JPvtvX/QGHqsqKBk/44s=".into()
|
"zvIayp3JPvtvX/QGHqsqKBk/44s=".into()
|
||||||
)
|
)
|
||||||
.unwrap(),
|
.unwrap(),
|
||||||
);
|
);
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_should_save_and_load_manifest_encrypted_longer() -> anyhow::Result<()> {
|
fn test_should_save_and_load_manifest_encrypted_longer() -> anyhow::Result<()> {
|
||||||
let passkey = Some("password".into());
|
let passkey = Some(SecretString::new("password".into()));
|
||||||
let tmp_dir = TempDir::new("steamguard-cli-test")?;
|
let tmp_dir = TempDir::new()?;
|
||||||
let manifest_path = tmp_dir.path().join("manifest.json");
|
let manifest_path = tmp_dir.path().join("manifest.json");
|
||||||
let mut manager = AccountManager::new(manifest_path.as_path());
|
let mut manager = AccountManager::new(manifest_path.as_path());
|
||||||
let mut account = SteamGuardAccount::new();
|
let mut account = SteamGuardAccount::new();
|
||||||
|
@ -568,7 +582,7 @@ mod tests {
|
||||||
account.token_gid = "asdf1234".into();
|
account.token_gid = "asdf1234".into();
|
||||||
manager.add_account(account);
|
manager.add_account(account);
|
||||||
manager.submit_passkey(passkey.clone());
|
manager.submit_passkey(passkey.clone());
|
||||||
manager.manifest.entries[0].encryption = Some(EntryEncryptionParams::generate());
|
manager.manifest.entries[0].encryption = Some(EncryptionScheme::generate());
|
||||||
manager.save()?;
|
manager.save()?;
|
||||||
|
|
||||||
let mut loaded_manager = AccountManager::load(manifest_path.as_path())?;
|
let mut loaded_manager = AccountManager::load(manifest_path.as_path())?;
|
||||||
|
@ -583,30 +597,13 @@ mod tests {
|
||||||
loaded_manager.manifest.entries.len(),
|
loaded_manager.manifest.entries.len(),
|
||||||
loaded_manager.accounts.len()
|
loaded_manager.accounts.len()
|
||||||
);
|
);
|
||||||
let account_name = "asdf1234".into();
|
let account_name = "asdf1234";
|
||||||
|
let account = loaded_manager.get_account(account_name)?;
|
||||||
|
let account = account.lock().unwrap();
|
||||||
|
assert_eq!(account.account_name, "asdf1234");
|
||||||
|
assert_eq!(account.revocation_code.expose_secret(), "R12345");
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
loaded_manager
|
account.shared_secret,
|
||||||
.get_account(&account_name)?
|
|
||||||
.lock()
|
|
||||||
.unwrap()
|
|
||||||
.account_name,
|
|
||||||
"asdf1234"
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
loaded_manager
|
|
||||||
.get_account(&account_name)?
|
|
||||||
.lock()
|
|
||||||
.unwrap()
|
|
||||||
.revocation_code
|
|
||||||
.expose_secret(),
|
|
||||||
"R12345"
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
loaded_manager
|
|
||||||
.get_account(&account_name)?
|
|
||||||
.lock()
|
|
||||||
.unwrap()
|
|
||||||
.shared_secret,
|
|
||||||
steamguard::token::TwoFactorSecret::parse_shared_secret(
|
steamguard::token::TwoFactorSecret::parse_shared_secret(
|
||||||
"zvIayp3JPvtvX/QGHqsqKBk/44s=".into()
|
"zvIayp3JPvtvX/QGHqsqKBk/44s=".into()
|
||||||
)
|
)
|
||||||
|
@ -618,7 +615,7 @@ mod tests {
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_should_import() -> anyhow::Result<()> {
|
fn test_should_import() -> anyhow::Result<()> {
|
||||||
let tmp_dir = TempDir::new("steamguard-cli-test")?;
|
let tmp_dir = TempDir::new()?;
|
||||||
let manifest_path = tmp_dir.path().join("manifest.json");
|
let manifest_path = tmp_dir.path().join("manifest.json");
|
||||||
let mut manager = AccountManager::new(manifest_path.as_path());
|
let mut manager = AccountManager::new(manifest_path.as_path());
|
||||||
let mut account = SteamGuardAccount::new();
|
let mut account = SteamGuardAccount::new();
|
||||||
|
@ -633,45 +630,27 @@ mod tests {
|
||||||
std::fs::remove_file(&manifest_path)?;
|
std::fs::remove_file(&manifest_path)?;
|
||||||
|
|
||||||
let mut loaded_manager = AccountManager::new(manifest_path.as_path());
|
let mut loaded_manager = AccountManager::new(manifest_path.as_path());
|
||||||
assert!(matches!(
|
assert!(loaded_manager
|
||||||
loaded_manager.import_account(
|
.import_account(
|
||||||
&tmp_dir
|
&tmp_dir
|
||||||
.path()
|
.path()
|
||||||
.join("asdf1234.maFile")
|
.join("asdf1234.maFile")
|
||||||
.into_os_string()
|
.into_os_string()
|
||||||
.into_string()
|
.into_string()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
),
|
)
|
||||||
Ok(_)
|
.is_ok());
|
||||||
));
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
loaded_manager.manifest.entries.len(),
|
loaded_manager.manifest.entries.len(),
|
||||||
loaded_manager.accounts.len()
|
loaded_manager.accounts.len()
|
||||||
);
|
);
|
||||||
let account_name = "asdf1234".into();
|
let account_name = "asdf1234";
|
||||||
|
let account = loaded_manager.get_account(account_name)?;
|
||||||
|
let account = account.lock().unwrap();
|
||||||
|
assert_eq!(account.account_name, "asdf1234");
|
||||||
|
assert_eq!(account.revocation_code.expose_secret(), "R12345");
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
loaded_manager
|
account.shared_secret,
|
||||||
.get_account(&account_name)?
|
|
||||||
.lock()
|
|
||||||
.unwrap()
|
|
||||||
.account_name,
|
|
||||||
"asdf1234"
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
loaded_manager
|
|
||||||
.get_account(&account_name)?
|
|
||||||
.lock()
|
|
||||||
.unwrap()
|
|
||||||
.revocation_code
|
|
||||||
.expose_secret(),
|
|
||||||
"R12345"
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
loaded_manager
|
|
||||||
.get_account(&account_name)?
|
|
||||||
.lock()
|
|
||||||
.unwrap()
|
|
||||||
.shared_secret,
|
|
||||||
steamguard::token::TwoFactorSecret::parse_shared_secret(
|
steamguard::token::TwoFactorSecret::parse_shared_secret(
|
||||||
"zvIayp3JPvtvX/QGHqsqKBk/44s=".into()
|
"zvIayp3JPvtvX/QGHqsqKBk/44s=".into()
|
||||||
)
|
)
|
||||||
|
@ -681,134 +660,44 @@ mod tests {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
// #[test]
|
#[test]
|
||||||
// fn test_sda_compatibility_1() -> anyhow::Result<()> {
|
fn should_load_manifest_v1() -> anyhow::Result<()> {
|
||||||
// let path = Path::new("src/fixtures/maFiles/compat/1-account/manifest.json");
|
#[derive(Debug)]
|
||||||
// assert!(path.is_file());
|
struct Test {
|
||||||
// let mut manager = AccountManager::load(path)?;
|
manifest: &'static str,
|
||||||
// assert!(matches!(manager.entries.last().unwrap().encryption, None));
|
passkey: Option<SecretString>,
|
||||||
// manager.load_accounts()?;
|
}
|
||||||
// let account_name = manager.entries.last().unwrap().account_name.clone();
|
let cases = vec![
|
||||||
// assert_eq!(
|
Test {
|
||||||
// account_name,
|
manifest: "src/fixtures/maFiles/manifest-v1/1-account/manifest.json",
|
||||||
// manager
|
passkey: None,
|
||||||
// .get_account(&account_name)?
|
},
|
||||||
// .lock()
|
Test {
|
||||||
// .unwrap()
|
manifest: "src/fixtures/maFiles/manifest-v1/1-account-encrypted/manifest.json",
|
||||||
// .account_name
|
passkey: Some(SecretString::new("password".into())),
|
||||||
// );
|
},
|
||||||
// Ok(())
|
Test {
|
||||||
// }
|
manifest: "src/fixtures/maFiles/manifest-v1/2-account/manifest.json",
|
||||||
|
passkey: None,
|
||||||
// #[test]
|
},
|
||||||
// fn test_sda_compatibility_1_encrypted() -> anyhow::Result<()> {
|
Test {
|
||||||
// let path = Path::new("src/fixtures/maFiles/compat/1-account-encrypted/manifest.json");
|
manifest: "src/fixtures/maFiles/manifest-v1/missing-account-name/manifest.json",
|
||||||
// assert!(path.is_file());
|
passkey: None,
|
||||||
// let mut manifest = Manifest::load(path)?;
|
},
|
||||||
// assert!(matches!(
|
];
|
||||||
// manifest.entries.last().unwrap().encryption,
|
for case in cases {
|
||||||
// Some(_)
|
eprintln!("testing: {:?}", case);
|
||||||
// ));
|
let mut manager = AccountManager::load(Path::new(case.manifest))?;
|
||||||
// manifest.submit_passkey(Some("password".into()));
|
manager.submit_passkey(case.passkey.clone());
|
||||||
// manifest.load_accounts()?;
|
manager.load_accounts()?;
|
||||||
// let account_name = manifest.entries.last().unwrap().account_name.clone();
|
assert_eq!(manager.manifest.version, CURRENT_MANIFEST_VERSION);
|
||||||
// assert_eq!(
|
assert_eq!(manager.manifest.entries[0].account_name, "example");
|
||||||
// account_name,
|
assert_eq!(manager.manifest.entries[0].steam_id, 1234);
|
||||||
// manifest
|
let account = manager.get_account("example").unwrap();
|
||||||
// .get_account(&account_name)?
|
let account = account.lock().unwrap();
|
||||||
// .lock()
|
assert_eq!(account.account_name, "example");
|
||||||
// .unwrap()
|
assert_eq!(account.steam_id, 1234);
|
||||||
// .account_name
|
}
|
||||||
// );
|
Ok(())
|
||||||
// Ok(())
|
}
|
||||||
// }
|
|
||||||
|
|
||||||
// #[test]
|
|
||||||
// fn test_sda_compatibility_no_webcookie() -> anyhow::Result<()> {
|
|
||||||
// let path = Path::new("src/fixtures/maFiles/compat/no-webcookie/manifest.json");
|
|
||||||
// assert!(path.is_file());
|
|
||||||
// let mut manifest = Manifest::load(path)?;
|
|
||||||
// assert!(matches!(manifest.entries.last().unwrap().encryption, None));
|
|
||||||
// assert!(matches!(manifest.load_accounts(), Ok(_)));
|
|
||||||
// let account_name = manifest.entries.last().unwrap().account_name.clone();
|
|
||||||
// let account = manifest.get_account(&account_name)?;
|
|
||||||
// assert_eq!(account_name, account.lock().unwrap().account_name);
|
|
||||||
// assert_eq!(
|
|
||||||
// account
|
|
||||||
// .lock()
|
|
||||||
// .unwrap()
|
|
||||||
// .session
|
|
||||||
// .as_ref()
|
|
||||||
// .unwrap()
|
|
||||||
// .expose_secret()
|
|
||||||
// .web_cookie,
|
|
||||||
// None
|
|
||||||
// );
|
|
||||||
// Ok(())
|
|
||||||
// }
|
|
||||||
|
|
||||||
// #[test]
|
|
||||||
// fn test_sda_compatibility_2() -> anyhow::Result<()> {
|
|
||||||
// let path = Path::new("src/fixtures/maFiles/compat/2-account/manifest.json");
|
|
||||||
// assert!(path.is_file());
|
|
||||||
// let mut manifest = Manifest::load(path)?;
|
|
||||||
// assert!(matches!(manifest.entries.last().unwrap().encryption, None));
|
|
||||||
// manifest.load_accounts()?;
|
|
||||||
// let account_name = manifest.entries[0].account_name.clone();
|
|
||||||
// let account = manifest.get_account(&account_name)?;
|
|
||||||
// assert_eq!(account_name, account.lock().unwrap().account_name);
|
|
||||||
// assert_eq!(
|
|
||||||
// account.lock().unwrap().revocation_code.expose_secret(),
|
|
||||||
// "R12345"
|
|
||||||
// );
|
|
||||||
// assert_eq!(
|
|
||||||
// account
|
|
||||||
// .lock()
|
|
||||||
// .unwrap()
|
|
||||||
// .session
|
|
||||||
// .as_ref()
|
|
||||||
// .unwrap()
|
|
||||||
// .expose_secret()
|
|
||||||
// .steam_id,
|
|
||||||
// 1234
|
|
||||||
// );
|
|
||||||
|
|
||||||
// let account_name = manifest.entries[1].account_name.clone();
|
|
||||||
// let account = manifest.get_account(&account_name)?;
|
|
||||||
// assert_eq!(account_name, account.lock().unwrap().account_name);
|
|
||||||
// assert_eq!(
|
|
||||||
// account.lock().unwrap().revocation_code.expose_secret(),
|
|
||||||
// "R56789"
|
|
||||||
// );
|
|
||||||
// assert_eq!(
|
|
||||||
// account
|
|
||||||
// .lock()
|
|
||||||
// .unwrap()
|
|
||||||
// .session
|
|
||||||
// .as_ref()
|
|
||||||
// .unwrap()
|
|
||||||
// .expose_secret()
|
|
||||||
// .steam_id,
|
|
||||||
// 5678
|
|
||||||
// );
|
|
||||||
// Ok(())
|
|
||||||
// }
|
|
||||||
|
|
||||||
// #[cfg(test)]
|
|
||||||
// mod manifest_upgrades {
|
|
||||||
// use super::*;
|
|
||||||
|
|
||||||
// #[test]
|
|
||||||
// fn test_missing_account_name() {
|
|
||||||
// let path = Path::new("src/fixtures/maFiles/compat/missing-account-name/manifest.json");
|
|
||||||
// assert!(path.is_file());
|
|
||||||
// let mut manager = AccountManager::load(path).unwrap();
|
|
||||||
// assert_eq!(manager.entries.len(), 1);
|
|
||||||
// assert_eq!(manager.entries[0].account_name, "".to_string());
|
|
||||||
// assert!(manager.is_missing_account_name());
|
|
||||||
|
|
||||||
// manager.auto_upgrade().unwrap();
|
|
||||||
// assert_eq!(manager.entries[0].account_name, "example".to_string());
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -10,13 +10,11 @@ use log::debug;
|
||||||
use secrecy::{CloneableSecret, DebugSecret, ExposeSecret};
|
use secrecy::{CloneableSecret, DebugSecret, ExposeSecret};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use steamguard::{token::TwoFactorSecret, SecretString, SteamGuardAccount};
|
use steamguard::{token::TwoFactorSecret, SecretString, SteamGuardAccount};
|
||||||
use zeroize::Zeroize;
|
use zeroize::{Zeroize, ZeroizeOnDrop};
|
||||||
|
|
||||||
use crate::encryption::{EncryptionScheme, EntryEncryptor};
|
use crate::encryption::{EntryEncryptor, LegacySdaCompatible};
|
||||||
|
|
||||||
use super::{
|
use super::{EncryptionScheme, EntryLoader, ManifestAccountLoadError, ManifestEntry, ManifestV1};
|
||||||
EntryEncryptionParams, EntryLoader, ManifestAccountLoadError, ManifestEntry, ManifestV1,
|
|
||||||
};
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize)]
|
||||||
pub struct SdaManifest {
|
pub struct SdaManifest {
|
||||||
|
@ -44,6 +42,7 @@ impl From<SdaManifest> for ManifestV1 {
|
||||||
Self {
|
Self {
|
||||||
version: 1,
|
version: 1,
|
||||||
entries: sda.entries.into_iter().map(|e| e.into()).collect(),
|
entries: sda.entries.into_iter().map(|e| e.into()).collect(),
|
||||||
|
keyring_id: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -72,28 +71,31 @@ impl EntryLoader<SdaAccount> for SdaManifestEntry {
|
||||||
fn load(
|
fn load(
|
||||||
&self,
|
&self,
|
||||||
path: &Path,
|
path: &Path,
|
||||||
passkey: Option<&String>,
|
passkey: Option<&SecretString>,
|
||||||
encryption_params: Option<&EntryEncryptionParams>,
|
encryption_params: Option<&EncryptionScheme>,
|
||||||
) -> anyhow::Result<SdaAccount, ManifestAccountLoadError> {
|
) -> anyhow::Result<SdaAccount, ManifestAccountLoadError> {
|
||||||
debug!("loading entry: {:?}", path);
|
debug!("loading entry: {:?}", path);
|
||||||
let file = File::open(path)?;
|
let file = File::open(path)?;
|
||||||
let mut reader = BufReader::new(file);
|
let mut reader = BufReader::new(file);
|
||||||
let account: SdaAccount = match (&passkey, encryption_params.as_ref()) {
|
let account: SdaAccount = match (&passkey, encryption_params.as_ref()) {
|
||||||
(Some(passkey), Some(params)) => {
|
(Some(passkey), Some(scheme)) => {
|
||||||
let mut ciphertext: Vec<u8> = vec![];
|
let mut ciphertext: Vec<u8> = vec![];
|
||||||
reader.read_to_end(&mut ciphertext)?;
|
reader.read_to_end(&mut ciphertext)?;
|
||||||
let plaintext =
|
let plaintext = scheme.decrypt(passkey.expose_secret(), ciphertext)?;
|
||||||
crate::encryption::LegacySdaCompatible::decrypt(passkey, params, ciphertext)?;
|
|
||||||
if plaintext[0] != b'{' && plaintext[plaintext.len() - 1] != b'}' {
|
if plaintext[0] != b'{' && plaintext[plaintext.len() - 1] != b'}' {
|
||||||
return Err(ManifestAccountLoadError::IncorrectPasskey);
|
return Err(ManifestAccountLoadError::IncorrectPasskey);
|
||||||
}
|
}
|
||||||
let s = std::str::from_utf8(&plaintext).unwrap();
|
let s = std::str::from_utf8(&plaintext).unwrap();
|
||||||
serde_json::from_str(s)?
|
let mut deser = serde_json::Deserializer::from_str(s);
|
||||||
|
serde_path_to_error::deserialize(&mut deser)?
|
||||||
}
|
}
|
||||||
(None, Some(_)) => {
|
(None, Some(_)) => {
|
||||||
return Err(ManifestAccountLoadError::MissingPasskey);
|
return Err(ManifestAccountLoadError::MissingPasskey);
|
||||||
}
|
}
|
||||||
(_, None) => serde_json::from_reader(reader)?,
|
(_, None) => {
|
||||||
|
let mut deser = serde_json::Deserializer::from_reader(reader);
|
||||||
|
serde_path_to_error::deserialize(&mut deser)?
|
||||||
|
}
|
||||||
};
|
};
|
||||||
Ok(account)
|
Ok(account)
|
||||||
}
|
}
|
||||||
|
@ -107,13 +109,12 @@ pub struct SdaEntryEncryptionParams {
|
||||||
pub salt: String,
|
pub salt: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<SdaEntryEncryptionParams> for EntryEncryptionParams {
|
impl From<SdaEntryEncryptionParams> for EncryptionScheme {
|
||||||
fn from(sda: SdaEntryEncryptionParams) -> Self {
|
fn from(sda: SdaEntryEncryptionParams) -> Self {
|
||||||
Self {
|
EncryptionScheme::LegacySdaCompatible(LegacySdaCompatible {
|
||||||
iv: sda.iv,
|
iv: sda.iv,
|
||||||
salt: sda.salt,
|
salt: sda.salt,
|
||||||
scheme: EncryptionScheme::LegacySdaCompatible,
|
})
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -127,9 +128,11 @@ pub struct SdaAccount {
|
||||||
pub token_gid: String,
|
pub token_gid: String,
|
||||||
#[serde(with = "crate::secret_string")]
|
#[serde(with = "crate::secret_string")]
|
||||||
pub identity_secret: SecretString,
|
pub identity_secret: SecretString,
|
||||||
|
#[serde(default)]
|
||||||
pub server_time: u64,
|
pub server_time: u64,
|
||||||
#[serde(with = "crate::secret_string")]
|
#[serde(with = "crate::secret_string")]
|
||||||
pub uri: SecretString,
|
pub uri: SecretString,
|
||||||
|
#[serde(default)]
|
||||||
pub fully_enrolled: bool,
|
pub fully_enrolled: bool,
|
||||||
pub device_id: String,
|
pub device_id: String,
|
||||||
#[serde(with = "crate::secret_string")]
|
#[serde(with = "crate::secret_string")]
|
||||||
|
@ -138,22 +141,21 @@ pub struct SdaAccount {
|
||||||
pub session: Option<secrecy::Secret<Session>>,
|
pub session: Option<secrecy::Secret<Session>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize, Zeroize)]
|
#[derive(Debug, Clone, Deserialize, Zeroize, ZeroizeOnDrop)]
|
||||||
#[zeroize(drop)]
|
|
||||||
#[deprecated(note = "this is not used anymore, the closest equivalent is `Tokens`")]
|
#[deprecated(note = "this is not used anymore, the closest equivalent is `Tokens`")]
|
||||||
pub struct Session {
|
pub struct Session {
|
||||||
#[serde(rename = "SessionID")]
|
#[serde(default, rename = "SessionID")]
|
||||||
pub session_id: String,
|
pub session_id: Option<String>,
|
||||||
#[serde(rename = "SteamLogin")]
|
#[serde(default, rename = "SteamLogin")]
|
||||||
pub steam_login: String,
|
pub steam_login: Option<String>,
|
||||||
#[serde(rename = "SteamLoginSecure")]
|
#[serde(default, rename = "SteamLoginSecure")]
|
||||||
pub steam_login_secure: String,
|
pub steam_login_secure: Option<String>,
|
||||||
#[serde(default, rename = "WebCookie")]
|
#[serde(default, rename = "WebCookie")]
|
||||||
pub web_cookie: Option<String>,
|
pub web_cookie: Option<String>,
|
||||||
#[serde(rename = "OAuthToken")]
|
#[serde(default, rename = "OAuthToken")]
|
||||||
pub token: String,
|
pub token: Option<String>,
|
||||||
#[serde(rename = "SteamID")]
|
#[serde(rename = "SteamID")]
|
||||||
pub steam_id: u64,
|
pub steam_id: Option<u64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CloneableSecret for Session {}
|
impl CloneableSecret for Session {}
|
||||||
|
@ -164,7 +166,7 @@ impl From<SdaAccount> for SteamGuardAccount {
|
||||||
let steam_id = value
|
let steam_id = value
|
||||||
.session
|
.session
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.map(|s| s.expose_secret().steam_id)
|
.and_then(|s| s.expose_secret().steam_id)
|
||||||
.unwrap_or(0);
|
.unwrap_or(0);
|
||||||
Self {
|
Self {
|
||||||
account_name: value.account_name,
|
account_name: value.account_name,
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use super::EntryEncryptionParams;
|
use super::EncryptionScheme;
|
||||||
|
|
||||||
pub const CURRENT_MANIFEST_VERSION: u32 = 1;
|
pub const CURRENT_MANIFEST_VERSION: u32 = 1;
|
||||||
pub type Manifest = ManifestV1;
|
pub type Manifest = ManifestV1;
|
||||||
|
@ -10,6 +10,8 @@ pub type ManifestEntry = ManifestEntryV1;
|
||||||
pub struct ManifestV1 {
|
pub struct ManifestV1 {
|
||||||
pub version: u32,
|
pub version: u32,
|
||||||
pub entries: Vec<ManifestEntry>,
|
pub entries: Vec<ManifestEntry>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub keyring_id: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
@ -17,7 +19,7 @@ pub struct ManifestEntryV1 {
|
||||||
pub filename: String,
|
pub filename: String,
|
||||||
pub steam_id: u64,
|
pub steam_id: u64,
|
||||||
pub account_name: String,
|
pub account_name: String,
|
||||||
pub encryption: Option<EntryEncryptionParams>,
|
pub encryption: Option<EncryptionScheme>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for ManifestV1 {
|
impl Default for ManifestV1 {
|
||||||
|
@ -25,6 +27,7 @@ impl Default for ManifestV1 {
|
||||||
Self {
|
Self {
|
||||||
version: 1,
|
version: 1,
|
||||||
entries: vec![],
|
entries: vec![],
|
||||||
|
keyring_id: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,22 +1,24 @@
|
||||||
// notes for migration:
|
|
||||||
// account names must be made lowercase
|
|
||||||
|
|
||||||
use std::{fs::File, io::Read, path::Path};
|
use std::{fs::File, io::Read, path::Path};
|
||||||
|
|
||||||
use log::debug;
|
use log::*;
|
||||||
use serde::de::Error;
|
use secrecy::SecretString;
|
||||||
|
use serde::{de::Error, Deserialize};
|
||||||
use steamguard::SteamGuardAccount;
|
use steamguard::SteamGuardAccount;
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
|
|
||||||
|
use crate::encryption::EncryptionScheme;
|
||||||
|
|
||||||
use super::{
|
use super::{
|
||||||
legacy::{SdaAccount, SdaManifest},
|
legacy::{SdaAccount, SdaManifest},
|
||||||
manifest::ManifestV1,
|
manifest::ManifestV1,
|
||||||
EntryEncryptionParams, EntryLoader, Manifest,
|
steamv2::SteamMobileV2,
|
||||||
|
winauth::parse_winauth_exports,
|
||||||
|
EntryLoader, Manifest,
|
||||||
};
|
};
|
||||||
|
|
||||||
pub(crate) fn load_and_migrate(
|
pub(crate) fn load_and_migrate(
|
||||||
manifest_path: &Path,
|
manifest_path: &Path,
|
||||||
passkey: Option<&String>,
|
passkey: Option<&SecretString>,
|
||||||
) -> Result<(Manifest, Vec<SteamGuardAccount>), MigrationError> {
|
) -> Result<(Manifest, Vec<SteamGuardAccount>), MigrationError> {
|
||||||
backup_file(manifest_path)?;
|
backup_file(manifest_path)?;
|
||||||
let parent = manifest_path.parent().unwrap();
|
let parent = manifest_path.parent().unwrap();
|
||||||
|
@ -24,7 +26,10 @@ pub(crate) fn load_and_migrate(
|
||||||
let entry = e.unwrap();
|
let entry = e.unwrap();
|
||||||
if entry.file_type().unwrap().is_file() {
|
if entry.file_type().unwrap().is_file() {
|
||||||
let path = entry.path();
|
let path = entry.path();
|
||||||
if path.extension().unwrap() == "maFile" {
|
let Some(ext) = path.extension() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
if ext == "maFile" {
|
||||||
backup_file(&path).unwrap();
|
backup_file(&path).unwrap();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -35,7 +40,7 @@ pub(crate) fn load_and_migrate(
|
||||||
|
|
||||||
fn do_migrate(
|
fn do_migrate(
|
||||||
manifest_path: &Path,
|
manifest_path: &Path,
|
||||||
passkey: Option<&String>,
|
passkey: Option<&SecretString>,
|
||||||
) -> Result<(Manifest, Vec<SteamGuardAccount>), MigrationError> {
|
) -> Result<(Manifest, Vec<SteamGuardAccount>), MigrationError> {
|
||||||
let mut file = File::open(manifest_path)?;
|
let mut file = File::open(manifest_path)?;
|
||||||
let mut buffer = String::new();
|
let mut buffer = String::new();
|
||||||
|
@ -44,7 +49,7 @@ fn do_migrate(
|
||||||
deserialize_manifest(buffer).map_err(MigrationError::ManifestDeserializeFailed)?;
|
deserialize_manifest(buffer).map_err(MigrationError::ManifestDeserializeFailed)?;
|
||||||
|
|
||||||
if manifest.is_encrypted() && passkey.is_none() {
|
if manifest.is_encrypted() && passkey.is_none() {
|
||||||
return Err(MigrationError::MissingPasskey);
|
return Err(MigrationError::MissingPasskey { keyring_id: None });
|
||||||
} else if !manifest.is_encrypted() && passkey.is_some() {
|
} else if !manifest.is_encrypted() && passkey.is_some() {
|
||||||
// no custom error because this is an edge case, mostly user error
|
// 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.")));
|
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.")));
|
||||||
|
@ -83,9 +88,9 @@ fn backup_file(path: &Path) -> anyhow::Result<()> {
|
||||||
#[derive(Debug, Error)]
|
#[derive(Debug, Error)]
|
||||||
pub(crate) enum MigrationError {
|
pub(crate) enum MigrationError {
|
||||||
#[error("Passkey is required to decrypt manifest")]
|
#[error("Passkey is required to decrypt manifest")]
|
||||||
MissingPasskey,
|
MissingPasskey { keyring_id: Option<String> },
|
||||||
#[error("Failed to deserialize manifest: {0}")]
|
#[error("Failed to deserialize manifest: {0}")]
|
||||||
ManifestDeserializeFailed(serde_json::Error),
|
ManifestDeserializeFailed(serde_path_to_error::Error<serde_json::Error>),
|
||||||
#[error("IO error when upgrading manifest: {0}")]
|
#[error("IO error when upgrading manifest: {0}")]
|
||||||
IoError(#[from] std::io::Error),
|
IoError(#[from] std::io::Error),
|
||||||
#[error("An unexpected error occurred during manifest migration: {0}")]
|
#[error("An unexpected error occurred during manifest migration: {0}")]
|
||||||
|
@ -120,7 +125,7 @@ impl MigratingManifest {
|
||||||
pub fn load_all_accounts(
|
pub fn load_all_accounts(
|
||||||
&self,
|
&self,
|
||||||
folder: &Path,
|
folder: &Path,
|
||||||
passkey: Option<&String>,
|
passkey: Option<&SecretString>,
|
||||||
) -> anyhow::Result<Vec<MigratingAccount>> {
|
) -> anyhow::Result<Vec<MigratingAccount>> {
|
||||||
debug!("loading all accounts for migration");
|
debug!("loading all accounts for migration");
|
||||||
let accounts = match self {
|
let accounts = match self {
|
||||||
|
@ -129,7 +134,7 @@ impl MigratingManifest {
|
||||||
.entries
|
.entries
|
||||||
.iter()
|
.iter()
|
||||||
.map(|e| {
|
.map(|e| {
|
||||||
let params: Option<EntryEncryptionParams> =
|
let params: Option<EncryptionScheme> =
|
||||||
e.encryption.clone().map(|e| e.into());
|
e.encryption.clone().map(|e| e.into());
|
||||||
e.load(&Path::join(folder, &e.filename), passkey, params.as_ref())
|
e.load(&Path::join(folder, &e.filename), passkey, params.as_ref())
|
||||||
})
|
})
|
||||||
|
@ -142,7 +147,11 @@ impl MigratingManifest {
|
||||||
errors
|
errors
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
accounts.into_iter().map(MigratingAccount::Sda).collect()
|
accounts
|
||||||
|
.into_iter()
|
||||||
|
.map(ExternalAccount::Sda)
|
||||||
|
.map(MigratingAccount::External)
|
||||||
|
.collect()
|
||||||
}
|
}
|
||||||
Self::ManifestV1(manifest) => {
|
Self::ManifestV1(manifest) => {
|
||||||
let (accounts, errors) = manifest
|
let (accounts, errors) = manifest
|
||||||
|
@ -183,33 +192,58 @@ impl From<MigratingManifest> for Manifest {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn deserialize_manifest(text: String) -> Result<MigratingManifest, serde_json::Error> {
|
#[derive(Deserialize)]
|
||||||
let json: serde_json::Value = serde_json::from_str(&text)?;
|
struct JustVersion {
|
||||||
debug!("deserializing manifest: version {}", json["version"]);
|
version: Option<u32>,
|
||||||
if json["version"] == 1 {
|
}
|
||||||
let manifest: ManifestV1 = serde_json::from_str(&text)?;
|
|
||||||
Ok(MigratingManifest::ManifestV1(manifest))
|
fn deserialize_manifest(
|
||||||
} else if json["version"] == serde_json::Value::Null {
|
text: String,
|
||||||
let manifest: SdaManifest = serde_json::from_str(&text)?;
|
) -> Result<MigratingManifest, serde_path_to_error::Error<serde_json::Error>> {
|
||||||
Ok(MigratingManifest::Sda(manifest))
|
let mut deser = serde_json::Deserializer::from_str(&text);
|
||||||
} else {
|
let version: JustVersion = serde_path_to_error::deserialize(&mut deser)?;
|
||||||
Err(serde_json::Error::custom(format!(
|
|
||||||
"Unknown manifest version: {}",
|
debug!("deserializing manifest: version {:?}", version.version);
|
||||||
json["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)]
|
#[derive(Debug, Clone)]
|
||||||
|
#[allow(clippy::large_enum_variant)]
|
||||||
enum MigratingAccount {
|
enum MigratingAccount {
|
||||||
Sda(SdaAccount),
|
External(ExternalAccount),
|
||||||
ManifestV1(SteamGuardAccount),
|
ManifestV1(SteamGuardAccount),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl MigratingAccount {
|
impl MigratingAccount {
|
||||||
pub fn upgrade(self) -> Self {
|
pub fn upgrade(self) -> Self {
|
||||||
match self {
|
match self {
|
||||||
Self::Sda(sda) => Self::ManifestV1(sda.into()),
|
Self::External(account) => Self::ManifestV1(account.into()),
|
||||||
Self::ManifestV1(_) => self,
|
Self::ManifestV1(_) => self,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -228,20 +262,66 @@ impl From<MigratingAccount> for SteamGuardAccount {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn load_and_upgrade_sda_account(path: &Path) -> anyhow::Result<SteamGuardAccount> {
|
pub fn load_and_upgrade_external_accounts(path: &Path) -> anyhow::Result<Vec<SteamGuardAccount>> {
|
||||||
let file = File::open(path)?;
|
let mut file = File::open(path)?;
|
||||||
let account: SdaAccount = serde_json::from_reader(file)?;
|
let mut buf = vec![];
|
||||||
let mut account = MigratingAccount::Sda(account);
|
file.read_to_end(&mut buf)?;
|
||||||
while !account.is_latest() {
|
let mut deser = serde_json::Deserializer::from_slice(&buf);
|
||||||
account = account.upgrade();
|
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(account.into())
|
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)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use crate::accountmanager::CURRENT_MANIFEST_VERSION;
|
use tempfile::TempDir;
|
||||||
|
|
||||||
|
use crate::{accountmanager::CURRENT_MANIFEST_VERSION, AccountManager};
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
@ -250,7 +330,7 @@ mod tests {
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
struct Test {
|
struct Test {
|
||||||
manifest: &'static str,
|
manifest: &'static str,
|
||||||
passkey: Option<String>,
|
passkey: Option<SecretString>,
|
||||||
}
|
}
|
||||||
let cases = vec![
|
let cases = vec![
|
||||||
Test {
|
Test {
|
||||||
|
@ -259,7 +339,7 @@ mod tests {
|
||||||
},
|
},
|
||||||
Test {
|
Test {
|
||||||
manifest: "src/fixtures/maFiles/compat/1-account-encrypted/manifest.json",
|
manifest: "src/fixtures/maFiles/compat/1-account-encrypted/manifest.json",
|
||||||
passkey: Some("password".into()),
|
passkey: Some(SecretString::new("password".into())),
|
||||||
},
|
},
|
||||||
Test {
|
Test {
|
||||||
manifest: "src/fixtures/maFiles/compat/2-account/manifest.json",
|
manifest: "src/fixtures/maFiles/compat/2-account/manifest.json",
|
||||||
|
@ -273,6 +353,18 @@ mod tests {
|
||||||
manifest: "src/fixtures/maFiles/compat/no-webcookie/manifest.json",
|
manifest: "src/fixtures/maFiles/compat/no-webcookie/manifest.json",
|
||||||
passkey: None,
|
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 {
|
for case in cases {
|
||||||
eprintln!("testing: {:?}", case);
|
eprintln!("testing: {:?}", case);
|
||||||
|
@ -285,4 +377,142 @@ mod tests {
|
||||||
}
|
}
|
||||||
Ok(())
|
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(())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
73
src/accountmanager/steamv2.rs
Normal file
73
src/accountmanager/steamv2.rs
Normal file
|
@ -0,0 +1,73 @@
|
||||||
|
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")),
|
||||||
|
})
|
||||||
|
}
|
50
src/accountmanager/winauth.rs
Normal file
50
src/accountmanager/winauth.rs
Normal file
|
@ -0,0 +1,50 @@
|
||||||
|
//! 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)
|
||||||
|
}
|
107
src/commands.rs
107
src/commands.rs
|
@ -1,35 +1,38 @@
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
use clap::{clap_derive::ArgEnum, Parser};
|
use clap::{Parser, Subcommand, ValueEnum};
|
||||||
use clap_complete::Shell;
|
use clap_complete::Shell;
|
||||||
|
use secrecy::SecretString;
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
use steamguard::SteamGuardAccount;
|
use steamguard::{transport::Transport, SteamGuardAccount};
|
||||||
|
|
||||||
use crate::AccountManager;
|
use crate::AccountManager;
|
||||||
|
|
||||||
pub mod code;
|
pub mod code;
|
||||||
pub mod completions;
|
pub mod completions;
|
||||||
|
pub mod confirm;
|
||||||
pub mod debug;
|
pub mod debug;
|
||||||
pub mod decrypt;
|
pub mod decrypt;
|
||||||
pub mod encrypt;
|
pub mod encrypt;
|
||||||
pub mod import;
|
pub mod import;
|
||||||
#[cfg(feature = "qr")]
|
#[cfg(feature = "qr")]
|
||||||
pub mod qr;
|
pub mod qr;
|
||||||
|
pub mod qr_login;
|
||||||
pub mod remove;
|
pub mod remove;
|
||||||
pub mod setup;
|
pub mod setup;
|
||||||
pub mod trade;
|
|
||||||
|
|
||||||
pub use code::CodeCommand;
|
pub use code::CodeCommand;
|
||||||
pub use completions::CompletionsCommand;
|
pub use completions::CompletionsCommand;
|
||||||
|
pub use confirm::ConfirmCommand;
|
||||||
pub use debug::DebugCommand;
|
pub use debug::DebugCommand;
|
||||||
pub use decrypt::DecryptCommand;
|
pub use decrypt::DecryptCommand;
|
||||||
pub use encrypt::EncryptCommand;
|
pub use encrypt::EncryptCommand;
|
||||||
pub use import::ImportCommand;
|
pub use import::ImportCommand;
|
||||||
#[cfg(feature = "qr")]
|
#[cfg(feature = "qr")]
|
||||||
pub use qr::QrCommand;
|
pub use qr::QrCommand;
|
||||||
|
pub use qr_login::QrLoginCommand;
|
||||||
pub use remove::RemoveCommand;
|
pub use remove::RemoveCommand;
|
||||||
pub use setup::SetupCommand;
|
pub use setup::SetupCommand;
|
||||||
pub use trade::TradeCommand;
|
|
||||||
|
|
||||||
/// A command that does not operate on the manifest or individual accounts.
|
/// A command that does not operate on the manifest or individual accounts.
|
||||||
pub(crate) trait ConstCommand {
|
pub(crate) trait ConstCommand {
|
||||||
|
@ -37,23 +40,39 @@ pub(crate) trait ConstCommand {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A command that operates the manifest as a whole
|
/// A command that operates the manifest as a whole
|
||||||
pub(crate) trait ManifestCommand {
|
pub(crate) trait ManifestCommand<T>
|
||||||
fn execute(&self, manager: &mut AccountManager) -> anyhow::Result<()>;
|
where
|
||||||
}
|
T: Transport,
|
||||||
|
{
|
||||||
/// A command that operates on individual accounts.
|
|
||||||
pub(crate) trait AccountCommand {
|
|
||||||
fn execute(
|
fn execute(
|
||||||
&self,
|
&self,
|
||||||
|
transport: T,
|
||||||
manager: &mut AccountManager,
|
manager: &mut AccountManager,
|
||||||
accounts: Vec<Arc<Mutex<SteamGuardAccount>>>,
|
args: &GlobalArgs,
|
||||||
) -> anyhow::Result<()>;
|
) -> anyhow::Result<()>;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) enum CommandType {
|
/// 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>),
|
Const(Box<dyn ConstCommand>),
|
||||||
Manifest(Box<dyn ManifestCommand>),
|
Manifest(Box<dyn ManifestCommand<T>>),
|
||||||
Account(Box<dyn AccountCommand>),
|
Account(Box<dyn AccountCommand<T>>),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Parser)]
|
#[derive(Debug, Clone, Parser)]
|
||||||
|
@ -79,6 +98,13 @@ pub(crate) struct GlobalArgs {
|
||||||
long_help = "Select the account you want by steam username. Case-sensitive. By default, the first account in the manifest is selected."
|
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>,
|
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(
|
#[clap(
|
||||||
short,
|
short,
|
||||||
long,
|
long,
|
||||||
|
@ -90,6 +116,7 @@ pub(crate) struct GlobalArgs {
|
||||||
#[clap(
|
#[clap(
|
||||||
short,
|
short,
|
||||||
long,
|
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"
|
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>,
|
pub mafiles_path: Option<String>,
|
||||||
|
@ -99,27 +126,58 @@ pub(crate) struct GlobalArgs {
|
||||||
env = "STEAMGUARD_CLI_PASSKEY",
|
env = "STEAMGUARD_CLI_PASSKEY",
|
||||||
help = "Specify your encryption passkey."
|
help = "Specify your encryption passkey."
|
||||||
)]
|
)]
|
||||||
pub passkey: Option<String>,
|
pub passkey: Option<SecretString>,
|
||||||
#[clap(short, long, arg_enum, default_value_t=Verbosity::Info, help = "Set the log level. Be warned, trace is capable of printing sensitive data.")]
|
#[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,
|
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, Parser)]
|
#[derive(Debug, Clone, Subcommand)]
|
||||||
pub(crate) enum Subcommands {
|
pub(crate) enum Subcommands {
|
||||||
Debug(DebugCommand),
|
Debug(DebugCommand),
|
||||||
Completion(CompletionsCommand),
|
Completion(CompletionsCommand),
|
||||||
Setup(SetupCommand),
|
Setup(SetupCommand),
|
||||||
Import(ImportCommand),
|
Import(ImportCommand),
|
||||||
Trade(TradeCommand),
|
#[clap(alias = "trade")]
|
||||||
|
Confirm(ConfirmCommand),
|
||||||
Remove(RemoveCommand),
|
Remove(RemoveCommand),
|
||||||
Encrypt(EncryptCommand),
|
Encrypt(EncryptCommand),
|
||||||
Decrypt(DecryptCommand),
|
Decrypt(DecryptCommand),
|
||||||
Code(CodeCommand),
|
Code(CodeCommand),
|
||||||
#[cfg(feature = "qr")]
|
#[cfg(feature = "qr")]
|
||||||
Qr(QrCommand),
|
Qr(QrCommand),
|
||||||
|
QrLogin(QrLoginCommand),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, ArgEnum)]
|
#[derive(Debug, Clone, Copy, ValueEnum)]
|
||||||
pub(crate) enum Verbosity {
|
pub(crate) enum Verbosity {
|
||||||
Error = 0,
|
Error = 0,
|
||||||
Warn = 1,
|
Warn = 1,
|
||||||
|
@ -165,3 +223,14 @@ impl From<Args> for CodeCommand {
|
||||||
args.code
|
args.code
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn verify_cli() {
|
||||||
|
use clap::CommandFactory;
|
||||||
|
Args::command().debug_assert()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -20,16 +20,21 @@ pub struct CodeCommand {
|
||||||
pub offline: bool,
|
pub offline: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AccountCommand for CodeCommand {
|
impl<T> AccountCommand<T> for CodeCommand
|
||||||
|
where
|
||||||
|
T: Transport,
|
||||||
|
{
|
||||||
fn execute(
|
fn execute(
|
||||||
&self,
|
&self,
|
||||||
|
transport: T,
|
||||||
_manager: &mut AccountManager,
|
_manager: &mut AccountManager,
|
||||||
accounts: Vec<Arc<Mutex<SteamGuardAccount>>>,
|
accounts: Vec<Arc<Mutex<SteamGuardAccount>>>,
|
||||||
|
_args: &GlobalArgs,
|
||||||
) -> anyhow::Result<()> {
|
) -> anyhow::Result<()> {
|
||||||
let server_time = if self.offline {
|
let server_time = if self.offline {
|
||||||
SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs()
|
SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs()
|
||||||
} else {
|
} else {
|
||||||
steamapi::get_server_time()?.server_time()
|
steamapi::get_server_time(transport)?.server_time()
|
||||||
};
|
};
|
||||||
debug!("Time used to generate codes: {}", server_time);
|
debug!("Time used to generate codes: {}", server_time);
|
||||||
|
|
||||||
|
|
|
@ -5,7 +5,12 @@ use super::*;
|
||||||
#[derive(Debug, Clone, Parser)]
|
#[derive(Debug, Clone, Parser)]
|
||||||
#[clap(about = "Generate shell completions")]
|
#[clap(about = "Generate shell completions")]
|
||||||
pub struct CompletionsCommand {
|
pub struct CompletionsCommand {
|
||||||
#[clap(short, long, arg_enum, help = "The shell to generate completions for.")]
|
#[clap(
|
||||||
|
short,
|
||||||
|
long,
|
||||||
|
value_enum,
|
||||||
|
help = "The shell to generate completions for."
|
||||||
|
)]
|
||||||
pub shell: Shell,
|
pub shell: Shell,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
168
src/commands/confirm.rs
Normal file
168
src/commands/confirm.rs
Normal file
|
@ -0,0 +1,168 @@
|
||||||
|
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(())
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,7 +1,7 @@
|
||||||
use log::*;
|
use log::*;
|
||||||
use steamguard::{Confirmation, ConfirmationType};
|
use steamguard::{Confirmation, ConfirmationType};
|
||||||
|
|
||||||
use crate::tui;
|
use crate::{debug::parse_json_stripped, tui};
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
@ -16,6 +16,12 @@ pub struct DebugCommand {
|
||||||
pub demo_prompt_char: bool,
|
pub demo_prompt_char: bool,
|
||||||
#[clap(long, help = "Show an example confirmation menu using dummy data.")]
|
#[clap(long, help = "Show an example confirmation menu using dummy data.")]
|
||||||
pub demo_conf_menu: bool,
|
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 {
|
impl ConstCommand for DebugCommand {
|
||||||
|
@ -32,6 +38,9 @@ impl ConstCommand for DebugCommand {
|
||||||
if self.demo_conf_menu {
|
if self.demo_conf_menu {
|
||||||
demo_confirmation_menu();
|
demo_confirmation_menu();
|
||||||
}
|
}
|
||||||
|
if let Some(path) = self.print_stripped_json.as_ref() {
|
||||||
|
debug_print_json(path)?;
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -74,7 +83,7 @@ pub fn demo_confirmation_menu() {
|
||||||
creation_time: 1687457923,
|
creation_time: 1687457923,
|
||||||
cancel: "Cancel".to_owned(),
|
cancel: "Cancel".to_owned(),
|
||||||
accept: "Confirm".to_owned(),
|
accept: "Confirm".to_owned(),
|
||||||
icon: "".to_owned(),
|
icon: Some("".to_owned()),
|
||||||
multi: false,
|
multi: false,
|
||||||
summary: vec![],
|
summary: vec![],
|
||||||
},
|
},
|
||||||
|
@ -88,7 +97,7 @@ pub fn demo_confirmation_menu() {
|
||||||
creation_time: 1687457923,
|
creation_time: 1687457923,
|
||||||
cancel: "Cancel".to_owned(),
|
cancel: "Cancel".to_owned(),
|
||||||
accept: "Confirm".to_owned(),
|
accept: "Confirm".to_owned(),
|
||||||
icon: "".to_owned(),
|
icon: Some("".to_owned()),
|
||||||
multi: false,
|
multi: false,
|
||||||
summary: vec![],
|
summary: vec![],
|
||||||
},
|
},
|
||||||
|
@ -96,3 +105,11 @@ pub fn demo_confirmation_menu() {
|
||||||
.expect("confirmation menu demo failed");
|
.expect("confirmation menu demo failed");
|
||||||
println!("accept: {}, deny: {}", accept.len(), deny.len());
|
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(())
|
||||||
|
}
|
||||||
|
|
|
@ -8,10 +8,29 @@ use super::*;
|
||||||
#[clap(about = "Decrypt all maFiles")]
|
#[clap(about = "Decrypt all maFiles")]
|
||||||
pub struct DecryptCommand;
|
pub struct DecryptCommand;
|
||||||
|
|
||||||
impl ManifestCommand for DecryptCommand {
|
impl<T> ManifestCommand<T> for DecryptCommand
|
||||||
fn execute(&self, manager: &mut AccountManager) -> anyhow::Result<()> {
|
where
|
||||||
|
T: Transport,
|
||||||
|
{
|
||||||
|
fn execute(
|
||||||
|
&self,
|
||||||
|
_transport: T,
|
||||||
|
manager: &mut AccountManager,
|
||||||
|
_args: &GlobalArgs,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
load_accounts_with_prompts(manager)?;
|
load_accounts_with_prompts(manager)?;
|
||||||
for mut entry in manager.iter_mut() {
|
|
||||||
|
#[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;
|
entry.encryption = None;
|
||||||
}
|
}
|
||||||
manager.submit_passkey(None);
|
manager.submit_passkey(None);
|
||||||
|
@ -31,7 +50,7 @@ fn load_accounts_with_prompts(manager: &mut AccountManager) -> anyhow::Result<()
|
||||||
if manager.has_passkey() {
|
if manager.has_passkey() {
|
||||||
error!("Incorrect passkey");
|
error!("Incorrect passkey");
|
||||||
}
|
}
|
||||||
let passkey = rpassword::prompt_password_stdout("Enter encryption passkey: ").ok();
|
let passkey = Some(crate::tui::prompt_passkey()?);
|
||||||
manager.submit_passkey(passkey);
|
manager.submit_passkey(passkey);
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
|
|
|
@ -1,6 +1,10 @@
|
||||||
use log::*;
|
use log::*;
|
||||||
|
use secrecy::ExposeSecret;
|
||||||
|
|
||||||
use crate::AccountManager;
|
use crate::{
|
||||||
|
encryption::{EncryptionScheme, EntryEncryptor},
|
||||||
|
tui, AccountManager,
|
||||||
|
};
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
@ -8,30 +12,62 @@ use super::*;
|
||||||
#[clap(about = "Encrypt all maFiles")]
|
#[clap(about = "Encrypt all maFiles")]
|
||||||
pub struct EncryptCommand;
|
pub struct EncryptCommand;
|
||||||
|
|
||||||
impl ManifestCommand for EncryptCommand {
|
impl<T> ManifestCommand<T> for EncryptCommand
|
||||||
fn execute(&self, manager: &mut AccountManager) -> anyhow::Result<()> {
|
where
|
||||||
|
T: Transport,
|
||||||
|
{
|
||||||
|
fn execute(
|
||||||
|
&self,
|
||||||
|
_transport: T,
|
||||||
|
manager: &mut AccountManager,
|
||||||
|
_args: &GlobalArgs,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
if !manager.has_passkey() {
|
if !manager.has_passkey() {
|
||||||
let mut passkey;
|
let passkey: Option<SecretString>;
|
||||||
loop {
|
loop {
|
||||||
passkey = rpassword::prompt_password_stdout("Enter encryption passkey: ").ok();
|
let passkey1 = tui::prompt_passkey()?;
|
||||||
if let Some(p) = passkey.as_ref() {
|
if passkey1.expose_secret().is_empty() {
|
||||||
if p.is_empty() {
|
error!("Passkey cannot be empty, try again.");
|
||||||
error!("Passkey cannot be empty, try again.");
|
continue;
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
let passkey_confirm =
|
let passkey_confirm = rpassword::prompt_password("Confirm encryption passkey: ")
|
||||||
rpassword::prompt_password_stdout("Confirm encryption passkey: ").ok();
|
.map(SecretString::new)?;
|
||||||
if passkey == passkey_confirm {
|
if passkey1.expose_secret() == passkey_confirm.expose_secret() {
|
||||||
|
passkey = Some(passkey1);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
error!("Passkeys do not match, try again.");
|
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.submit_passkey(passkey);
|
||||||
}
|
}
|
||||||
manager.load_accounts()?;
|
manager.load_accounts()?;
|
||||||
for entry in manager.iter_mut() {
|
for entry in manager.iter_mut() {
|
||||||
entry.encryption = Some(crate::accountmanager::EntryEncryptionParams::generate());
|
entry.encryption = Some(EncryptionScheme::generate());
|
||||||
}
|
}
|
||||||
manager.save()?;
|
manager.save()?;
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|
|
@ -2,39 +2,68 @@ use std::path::Path;
|
||||||
|
|
||||||
use log::*;
|
use log::*;
|
||||||
|
|
||||||
use crate::AccountManager;
|
use crate::{accountmanager::ManifestAccountImportError, AccountManager};
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
#[derive(Debug, Clone, Parser, Default)]
|
#[derive(Debug, Clone, Parser, Default)]
|
||||||
#[clap(about = "Import an account with steamguard already set up")]
|
#[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 {
|
pub struct ImportCommand {
|
||||||
#[clap(long, help = "Whether or not the provided maFiles are from SDA.")]
|
|
||||||
pub sda: bool,
|
|
||||||
|
|
||||||
#[clap(long, help = "Paths to one or more maFiles, eg. \"./gaben.maFile\"")]
|
#[clap(long, help = "Paths to one or more maFiles, eg. \"./gaben.maFile\"")]
|
||||||
pub files: Vec<String>,
|
pub files: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ManifestCommand for ImportCommand {
|
impl<T> ManifestCommand<T> for ImportCommand
|
||||||
fn execute(&self, manager: &mut AccountManager) -> anyhow::Result<()> {
|
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() {
|
for file_path in self.files.iter() {
|
||||||
if self.sda {
|
debug!("loading entry: {:?}", file_path);
|
||||||
let path = Path::new(&file_path);
|
match manager.import_account(file_path) {
|
||||||
let account = crate::accountmanager::migrate::load_and_upgrade_sda_account(path)?;
|
Ok(_) => {
|
||||||
manager.add_account(account);
|
info!("Imported account: {}", &file_path);
|
||||||
info!("Imported account: {}", &file_path);
|
}
|
||||||
} else {
|
Err(ManifestAccountImportError::AlreadyExists { .. }) => {
|
||||||
match manager.import_account(file_path) {
|
warn!("Account already exists: {} -- Ignoring", &file_path);
|
||||||
Ok(_) => {
|
}
|
||||||
|
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);
|
info!("Imported account: {}", &file_path);
|
||||||
}
|
accounts_added += 1;
|
||||||
Err(err) => {
|
|
||||||
bail!("Failed to import account: {} {}", &file_path, err);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Err(err) => {
|
||||||
|
bail!("Failed to import account: {} {}", &file_path, err);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if accounts_added > 0 {
|
||||||
|
info!("Imported {} accounts", accounts_added);
|
||||||
|
}
|
||||||
|
|
||||||
manager.save()?;
|
manager.save()?;
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|
|
@ -18,11 +18,16 @@ pub struct QrCommand {
|
||||||
pub ascii: bool,
|
pub ascii: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AccountCommand for QrCommand {
|
impl<T> AccountCommand<T> for QrCommand
|
||||||
|
where
|
||||||
|
T: Transport,
|
||||||
|
{
|
||||||
fn execute(
|
fn execute(
|
||||||
&self,
|
&self,
|
||||||
|
_transport: T,
|
||||||
_manager: &mut AccountManager,
|
_manager: &mut AccountManager,
|
||||||
accounts: Vec<Arc<Mutex<SteamGuardAccount>>>,
|
accounts: Vec<Arc<Mutex<SteamGuardAccount>>>,
|
||||||
|
_args: &GlobalArgs,
|
||||||
) -> anyhow::Result<()> {
|
) -> anyhow::Result<()> {
|
||||||
use anyhow::Context;
|
use anyhow::Context;
|
||||||
|
|
||||||
|
|
128
src/commands/qr_login.rs
Normal file
128
src/commands/qr_login.rs
Normal file
|
@ -0,0 +1,128 @@
|
||||||
|
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");
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,6 +1,7 @@
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
use log::*;
|
use log::*;
|
||||||
|
use steamguard::{accountlinker::RemoveAuthenticatorError, transport::TransportError};
|
||||||
|
|
||||||
use crate::{errors::UserError, tui, AccountManager};
|
use crate::{errors::UserError, tui, AccountManager};
|
||||||
|
|
||||||
|
@ -10,11 +11,16 @@ use super::*;
|
||||||
#[clap(about = "Remove the authenticator from an account.")]
|
#[clap(about = "Remove the authenticator from an account.")]
|
||||||
pub struct RemoveCommand;
|
pub struct RemoveCommand;
|
||||||
|
|
||||||
impl AccountCommand for RemoveCommand {
|
impl<T> AccountCommand<T> for RemoveCommand
|
||||||
|
where
|
||||||
|
T: Transport + Clone,
|
||||||
|
{
|
||||||
fn execute(
|
fn execute(
|
||||||
&self,
|
&self,
|
||||||
|
transport: T,
|
||||||
manager: &mut AccountManager,
|
manager: &mut AccountManager,
|
||||||
accounts: Vec<Arc<Mutex<SteamGuardAccount>>>,
|
accounts: Vec<Arc<Mutex<SteamGuardAccount>>>,
|
||||||
|
args: &GlobalArgs,
|
||||||
) -> anyhow::Result<()> {
|
) -> anyhow::Result<()> {
|
||||||
eprintln!(
|
eprintln!(
|
||||||
"This will remove the mobile authenticator from {} accounts: {}",
|
"This will remove the mobile authenticator from {} accounts: {}",
|
||||||
|
@ -37,41 +43,57 @@ impl AccountCommand for RemoveCommand {
|
||||||
let mut successful = vec![];
|
let mut successful = vec![];
|
||||||
for a in accounts {
|
for a in accounts {
|
||||||
let mut account = a.lock().unwrap();
|
let mut account = a.lock().unwrap();
|
||||||
if !account.is_logged_in() {
|
|
||||||
info!("Account does not have tokens, logging in");
|
|
||||||
crate::do_login(&mut account)?;
|
|
||||||
}
|
|
||||||
|
|
||||||
match account.remove_authenticator(None) {
|
let mut revocation: Option<String> = None;
|
||||||
Ok(success) => {
|
loop {
|
||||||
if success {
|
match account.remove_authenticator(transport.clone(), revocation.as_ref()) {
|
||||||
println!("Removed authenticator from {}", account.account_name);
|
Ok(_) => {
|
||||||
|
info!("Removed authenticator from {}", account.account_name);
|
||||||
successful.push(account.account_name.clone());
|
successful.push(account.account_name.clone());
|
||||||
} else {
|
break;
|
||||||
println!(
|
}
|
||||||
"Failed to remove authenticator from {}",
|
Err(RemoveAuthenticatorError::TransportError(TransportError::Unauthorized)) => {
|
||||||
account.account_name
|
error!("Account {} is not logged in", account.account_name);
|
||||||
);
|
crate::do_login(transport.clone(), &mut account, args.password.clone())?;
|
||||||
if tui::prompt_char(
|
continue;
|
||||||
"Would you like to remove it from the manifest anyway?",
|
}
|
||||||
"yN",
|
Err(RemoveAuthenticatorError::IncorrectRevocationCode {
|
||||||
) == 'y'
|
attempts_remaining,
|
||||||
{
|
}) => {
|
||||||
successful.push(account.account_name.clone());
|
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;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
Err(err) => {
|
|
||||||
error!(
|
|
||||||
"Unexpected error when removing authenticator from {}: {}",
|
|
||||||
account.account_name, err
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for account_name in successful {
|
for account_name in successful {
|
||||||
manager.remove_account(account_name);
|
manager.remove_account(&account_name);
|
||||||
}
|
}
|
||||||
|
|
||||||
manager.save()?;
|
manager.save()?;
|
||||||
|
|
|
@ -1,7 +1,12 @@
|
||||||
use log::*;
|
use log::*;
|
||||||
|
use phonenumber::PhoneNumber;
|
||||||
use secrecy::ExposeSecret;
|
use secrecy::ExposeSecret;
|
||||||
use steamguard::{
|
use steamguard::{
|
||||||
accountlinker::AccountLinkSuccess, AccountLinkError, AccountLinker, FinalizeLinkError,
|
accountlinker::{AccountLinkConfirmType, AccountLinkSuccess, RemoveAuthenticatorError},
|
||||||
|
phonelinker::PhoneLinker,
|
||||||
|
steamapi::PhoneClient,
|
||||||
|
token::Tokens,
|
||||||
|
AccountLinkError, AccountLinker, FinalizeLinkError,
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::{tui, AccountManager};
|
use crate::{tui, AccountManager};
|
||||||
|
@ -12,8 +17,16 @@ use super::*;
|
||||||
#[clap(about = "Set up a new account with steamguard-cli")]
|
#[clap(about = "Set up a new account with steamguard-cli")]
|
||||||
pub struct SetupCommand;
|
pub struct SetupCommand;
|
||||||
|
|
||||||
impl ManifestCommand for SetupCommand {
|
impl<T> ManifestCommand<T> for SetupCommand
|
||||||
fn execute(&self, manager: &mut AccountManager) -> anyhow::Result<()> {
|
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");
|
eprintln!("Log in to the account that you want to link to steamguard-cli");
|
||||||
eprint!("Username: ");
|
eprint!("Username: ");
|
||||||
let username = tui::prompt().to_lowercase();
|
let username = tui::prompt().to_lowercase();
|
||||||
|
@ -25,35 +38,68 @@ impl ManifestCommand for SetupCommand {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
info!("Logging in to {}", username);
|
info!("Logging in to {}", username);
|
||||||
let session =
|
let tokens = crate::do_login_raw(transport.clone(), username, args.password.clone())
|
||||||
crate::do_login_raw(username).expect("Failed to log in. Account has not been linked.");
|
.expect("Failed to log in. Account has not been linked.");
|
||||||
|
|
||||||
info!("Adding authenticator...");
|
info!("Adding authenticator...");
|
||||||
let mut linker = AccountLinker::new(session);
|
let mut linker = AccountLinker::new(transport.clone(), tokens);
|
||||||
let link: AccountLinkSuccess;
|
|
||||||
loop {
|
loop {
|
||||||
match linker.link() {
|
match linker.link() {
|
||||||
Ok(a) => {
|
Ok(link) => {
|
||||||
link = a;
|
return Self::add_new_account(link, manager, account_name, linker);
|
||||||
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) => {
|
Err(AccountLinkError::MustProvidePhoneNumber) => {
|
||||||
println!("Enter your phone number in the following format: +1 123-456-7890");
|
// 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.
|
||||||
print!("Phone number: ");
|
eprintln!("Looks like you don't have a phone number on this account.");
|
||||||
linker.phone_number = tui::prompt().replace(&['(', ')', '-'][..], "");
|
do_add_phone_number(transport.clone(), linker.tokens())?;
|
||||||
}
|
|
||||||
Err(AccountLinkError::AuthenticatorPresent) => {
|
|
||||||
println!("An authenticator is already present on this account.");
|
|
||||||
bail!("An authenticator is already present on this account.");
|
|
||||||
}
|
}
|
||||||
Err(AccountLinkError::MustConfirmEmail) => {
|
Err(AccountLinkError::MustConfirmEmail) => {
|
||||||
println!("Check your email and click the link.");
|
println!("Check your email and click the link.");
|
||||||
tui::pause();
|
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) => {
|
Err(err) => {
|
||||||
error!(
|
error!(
|
||||||
"Failed to link authenticator. Account has not been linked. {}",
|
"Failed to link authenticator. Account has not been linked. {}",
|
||||||
|
@ -63,39 +109,64 @@ impl ManifestCommand for SetupCommand {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 mut server_time = link.server_time();
|
||||||
let phone_number_hint = link.phone_number_hint().to_owned();
|
let phone_number_hint = link.phone_number_hint().to_owned();
|
||||||
|
let confirm_type = link.confirm_type();
|
||||||
manager.add_account(link.into_account());
|
manager.add_account(link.into_account());
|
||||||
match manager.save() {
|
match manager.save() {
|
||||||
Ok(_) => {}
|
Ok(_) => {}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
error!("Aborting the account linking process because we failed to save the manifest. This is really bad. Here is the error: {}", err);
|
error!("Aborting the account linking process because we failed to save the manifest. This is really bad. Here is the error: {}", err);
|
||||||
println!(
|
eprintln!(
|
||||||
"Just in case, here is the account info. Save it somewhere just in case!\n{:#?}",
|
"Just in case, here is the account info. Save it somewhere just in case!\n{:#?}",
|
||||||
manager.get_account(&account_name).unwrap().lock().unwrap()
|
manager.get_account(&account_name).unwrap().lock().unwrap()
|
||||||
);
|
);
|
||||||
return Err(err);
|
return Err(err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let account_arc = manager
|
let account_arc = manager
|
||||||
.get_account(&account_name)
|
.get_account(&account_name)
|
||||||
.expect("account was not present in manifest");
|
.expect("account was not present in manifest");
|
||||||
let mut account = account_arc.lock().unwrap();
|
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());
|
||||||
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();
|
tui::pause();
|
||||||
|
|
||||||
debug!("attempting link finalization");
|
debug!("attempting link finalization");
|
||||||
println!(
|
let confirm_code = match confirm_type {
|
||||||
"A code has been sent to your phone number ending in {}.",
|
AccountLinkConfirmType::Email => {
|
||||||
phone_number_hint
|
eprintln!(
|
||||||
);
|
"A code has been sent to the email address associated with this account."
|
||||||
print!("Enter SMS code: ");
|
);
|
||||||
let sms_code = tui::prompt();
|
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;
|
let mut tries = 0;
|
||||||
loop {
|
loop {
|
||||||
match linker.finalize(server_time, &mut account, sms_code.clone()) {
|
match linker.finalize(server_time, &mut account, confirm_code.clone()) {
|
||||||
Ok(_) => break,
|
Ok(_) => break,
|
||||||
Err(FinalizeLinkError::WantMore { server_time: s }) => {
|
Err(FinalizeLinkError::WantMore { server_time: s }) => {
|
||||||
server_time = s;
|
server_time = s;
|
||||||
|
@ -113,25 +184,126 @@ impl ManifestCommand for SetupCommand {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let revocation_code = account.revocation_code.clone();
|
let revocation_code = account.revocation_code.clone();
|
||||||
drop(account); // explicitly drop the lock so we don't hang on the mutex
|
drop(account);
|
||||||
|
info!("Verifying authenticator status...");
|
||||||
println!("Authenticator finalized.");
|
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() {
|
match manager.save() {
|
||||||
Ok(_) => {}
|
Ok(_) => {}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
println!(
|
error!(
|
||||||
"Failed to save manifest, but we were able to save it before. {}",
|
"Failed to save manifest, but we were able to save it before. {}",
|
||||||
err
|
err
|
||||||
);
|
);
|
||||||
return Err(err);
|
return Err(err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
eprintln!(
|
||||||
println!(
|
|
||||||
"Authenticator has been finalized. Please actually write down your revocation code: {}",
|
"Authenticator has been finalized. Please actually write down your revocation code: {}",
|
||||||
revocation_code.expose_secret()
|
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(())
|
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(())
|
||||||
|
}
|
||||||
|
|
|
@ -1,115 +0,0 @@
|
||||||
use std::sync::{Arc, Mutex};
|
|
||||||
|
|
||||||
use crossterm::tty::IsTty;
|
|
||||||
use log::*;
|
|
||||||
use steamguard::Confirmation;
|
|
||||||
|
|
||||||
use crate::{tui, AccountManager};
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Parser)]
|
|
||||||
#[clap(about = "Interactive interface for trade confirmations")]
|
|
||||||
pub struct TradeCommand {
|
|
||||||
#[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,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AccountCommand for TradeCommand {
|
|
||||||
fn execute(
|
|
||||||
&self,
|
|
||||||
manager: &mut AccountManager,
|
|
||||||
accounts: Vec<Arc<Mutex<SteamGuardAccount>>>,
|
|
||||||
) -> 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(&mut account)?;
|
|
||||||
}
|
|
||||||
|
|
||||||
info!("Checking for trade confirmations");
|
|
||||||
let confirmations: Vec<Confirmation>;
|
|
||||||
loop {
|
|
||||||
match account.get_trade_confirmations() {
|
|
||||||
Ok(confs) => {
|
|
||||||
confirmations = confs;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
Err(err) => {
|
|
||||||
error!("Failed to get trade confirmations: {:#?}", err);
|
|
||||||
info!("failed to get trade confirmations, asking user to log in");
|
|
||||||
crate::do_login(&mut account)?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut any_failed = false;
|
|
||||||
if self.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 self.fail_fast {
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
debug!("accept confirmation result: {:?}", result);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else if std::io::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 self.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 self.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.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
manager.save()?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
27
src/debug.rs
Normal file
27
src/debug.rs
Normal file
|
@ -0,0 +1,27 @@
|
||||||
|
/// 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,
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,163 +1,103 @@
|
||||||
use aes::Aes256;
|
use aes::cipher::InvalidLength;
|
||||||
use block_modes::block_padding::{NoPadding, Padding, Pkcs7};
|
|
||||||
use block_modes::{BlockMode, Cbc};
|
use rand::Rng;
|
||||||
use ring::pbkdf2;
|
|
||||||
use ring::rand::SecureRandom;
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
|
|
||||||
const SALT_LENGTH: usize = 8;
|
mod argon2id_aes;
|
||||||
const IV_LENGTH: usize = 16;
|
#[cfg(feature = "keyring")]
|
||||||
|
mod keyring;
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
mod legacy;
|
||||||
pub struct EntryEncryptionParams {
|
|
||||||
pub iv: String,
|
pub use argon2id_aes::*;
|
||||||
pub salt: String,
|
pub use legacy::*;
|
||||||
pub scheme: EncryptionScheme,
|
|
||||||
}
|
#[cfg(feature = "keyring")]
|
||||||
|
pub use crate::encryption::keyring::*;
|
||||||
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)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
#[serde(tag = "scheme")]
|
||||||
pub enum EncryptionScheme {
|
pub enum EncryptionScheme {
|
||||||
/// Encryption scheme that is compatible with SteamDesktopAuthenticator.
|
Argon2idAes256(Argon2idAes256),
|
||||||
LegacySdaCompatible = -1,
|
LegacySdaCompatible(LegacySdaCompatible),
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for EncryptionScheme {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self::LegacySdaCompatible
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait EntryEncryptor {
|
pub trait EntryEncryptor {
|
||||||
|
fn generate() -> Self;
|
||||||
fn encrypt(
|
fn encrypt(
|
||||||
|
&self,
|
||||||
passkey: &str,
|
passkey: &str,
|
||||||
params: &EntryEncryptionParams,
|
|
||||||
plaintext: Vec<u8>,
|
plaintext: Vec<u8>,
|
||||||
) -> anyhow::Result<Vec<u8>, EntryEncryptionError>;
|
) -> anyhow::Result<Vec<u8>, EntryEncryptionError>;
|
||||||
fn decrypt(
|
fn decrypt(
|
||||||
|
&self,
|
||||||
passkey: &str,
|
passkey: &str,
|
||||||
params: &EntryEncryptionParams,
|
|
||||||
ciphertext: Vec<u8>,
|
ciphertext: Vec<u8>,
|
||||||
) -> anyhow::Result<Vec<u8>, EntryEncryptionError>;
|
) -> anyhow::Result<Vec<u8>, EntryEncryptionError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Encryption scheme that is compatible with SteamDesktopAuthenticator.
|
impl EntryEncryptor for EncryptionScheme {
|
||||||
pub struct LegacySdaCompatible;
|
fn generate() -> Self {
|
||||||
|
EncryptionScheme::Argon2idAes256(Argon2idAes256::generate())
|
||||||
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: &str, salt: &str) -> 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,
|
|
||||||
);
|
|
||||||
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(
|
fn encrypt(
|
||||||
|
&self,
|
||||||
passkey: &str,
|
passkey: &str,
|
||||||
params: &EntryEncryptionParams,
|
|
||||||
plaintext: Vec<u8>,
|
plaintext: Vec<u8>,
|
||||||
) -> anyhow::Result<Vec<u8>, EntryEncryptionError> {
|
) -> anyhow::Result<Vec<u8>, EntryEncryptionError> {
|
||||||
let key = Self::get_encryption_key(passkey, ¶ms.salt)?;
|
match self {
|
||||||
let iv = base64::decode(¶ms.iv)?;
|
EncryptionScheme::Argon2idAes256(scheme) => scheme.encrypt(passkey, plaintext),
|
||||||
let cipher = Aes256Cbc::new_from_slices(&key, &iv)?;
|
EncryptionScheme::LegacySdaCompatible(scheme) => scheme.encrypt(passkey, plaintext),
|
||||||
|
|
||||||
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(
|
fn decrypt(
|
||||||
|
&self,
|
||||||
passkey: &str,
|
passkey: &str,
|
||||||
params: &EntryEncryptionParams,
|
|
||||||
ciphertext: Vec<u8>,
|
ciphertext: Vec<u8>,
|
||||||
) -> anyhow::Result<Vec<u8>, EntryEncryptionError> {
|
) -> anyhow::Result<Vec<u8>, EntryEncryptionError> {
|
||||||
let key = Self::get_encryption_key(passkey, ¶ms.salt)?;
|
match self {
|
||||||
let iv = base64::decode(¶ms.iv)?;
|
EncryptionScheme::Argon2idAes256(scheme) => scheme.decrypt(passkey, ciphertext),
|
||||||
let cipher = Aes256Cbc::new_from_slices(&key, &iv)?;
|
EncryptionScheme::LegacySdaCompatible(scheme) => scheme.decrypt(passkey, ciphertext),
|
||||||
|
}
|
||||||
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 decrypted = cipher.decrypt(&mut buffer)?;
|
|
||||||
let unpadded = Pkcs7::unpad(decrypted)?;
|
|
||||||
Ok(unpadded.to_vec())
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Error)]
|
#[derive(Debug, Error)]
|
||||||
pub enum EntryEncryptionError {
|
pub enum EntryEncryptionError {
|
||||||
|
#[error("Invalid ciphertext length. The ciphertext must be a multiple of 16 bytes.")]
|
||||||
|
InvalidCipherTextLength,
|
||||||
#[error(transparent)]
|
#[error(transparent)]
|
||||||
Unknown(#[from] anyhow::Error),
|
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.
|
/// For some reason, these errors do not get converted to `ManifestAccountLoadError`s, even though they get converted into `anyhow::Error` just fine. I am too lazy to figure out why right now.
|
||||||
impl From<block_modes::BlockModeError> for EntryEncryptionError {
|
impl From<InvalidLength> for EntryEncryptionError {
|
||||||
fn from(error: block_modes::BlockModeError) -> Self {
|
fn from(error: InvalidLength) -> Self {
|
||||||
Self::Unknown(anyhow::Error::from(error))
|
Self::Unknown(anyhow::Error::from(error))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl From<block_modes::InvalidKeyIvLength> for EntryEncryptionError {
|
|
||||||
fn from(error: block_modes::InvalidKeyIvLength) -> Self {
|
impl From<inout::NotEqualError> for EntryEncryptionError {
|
||||||
|
fn from(error: inout::NotEqualError) -> Self {
|
||||||
Self::Unknown(anyhow::Error::from(error))
|
Self::Unknown(anyhow::Error::from(error))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl From<block_modes::block_padding::PadError> for EntryEncryptionError {
|
|
||||||
fn from(_error: block_modes::block_padding::PadError) -> Self {
|
impl From<inout::PadError> for EntryEncryptionError {
|
||||||
Self::Unknown(anyhow!("PadError"))
|
fn from(error: inout::PadError) -> 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 {
|
impl From<inout::block_padding::UnpadError> for EntryEncryptionError {
|
||||||
Self::Unknown(anyhow!("UnpadError"))
|
fn from(error: inout::block_padding::UnpadError) -> Self {
|
||||||
|
Self::Unknown(anyhow::Error::from(error))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<base64::DecodeError> for EntryEncryptionError {
|
impl From<base64::DecodeError> for EntryEncryptionError {
|
||||||
fn from(error: base64::DecodeError) -> Self {
|
fn from(error: base64::DecodeError) -> Self {
|
||||||
Self::Unknown(anyhow::Error::from(error))
|
Self::Unknown(anyhow::Error::from(error))
|
||||||
|
@ -169,66 +109,10 @@ impl From<std::io::Error> for EntryEncryptionError {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
pub fn generate_keyring_id() -> String {
|
||||||
mod tests {
|
let rng = rand::thread_rng();
|
||||||
use super::*;
|
rng.sample_iter(rand::distributions::Alphanumeric)
|
||||||
use proptest::prelude::*;
|
.take(32)
|
||||||
|
.map(char::from)
|
||||||
/// This test ensures compatibility with SteamDesktopAuthenticator and with previous versions of steamguard-cli
|
.collect()
|
||||||
#[test]
|
|
||||||
fn test_encryption_key() {
|
|
||||||
assert_eq!(
|
|
||||||
LegacySdaCompatible::get_encryption_key("password", "GMhL0N2hqXg=").unwrap(),
|
|
||||||
base64::decode("KtiRa4/OxW83MlB6URf+Z8rAGj7CBY+pDlwD/NuVo6Y=")
|
|
||||||
.unwrap()
|
|
||||||
.as_slice()
|
|
||||||
);
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
LegacySdaCompatible::get_encryption_key("password", "wTzTE9A6aN8=").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, ¶ms, orig.clone()).unwrap();
|
|
||||||
let result = LegacySdaCompatible::decrypt(passkey, ¶ms, 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; 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(), ¶ms, orig.clone()).unwrap();
|
|
||||||
// let result = LegacySdaCompatible::decrypt(&passkey.into(), ¶ms, encrypted).unwrap();
|
|
||||||
// prop_assert_eq!(orig, result.to_vec());
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
}
|
}
|
||||||
|
|
158
src/encryption/argon2id_aes.rs
Normal file
158
src/encryption/argon2id_aes.rs
Normal file
|
@ -0,0 +1,158 @@
|
||||||
|
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(())
|
||||||
|
}
|
||||||
|
}
|
24
src/encryption/keyring.rs
Normal file
24
src/encryption/keyring.rs
Normal file
|
@ -0,0 +1,24 @@
|
||||||
|
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()
|
||||||
|
}
|
178
src/encryption/legacy.rs
Normal file
178
src/encryption/legacy.rs
Normal file
|
@ -0,0 +1,178 @@
|
||||||
|
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(), ¶ms, orig.clone()).unwrap();
|
||||||
|
// let result = LegacySdaCompatible::decrypt(&passkey.into(), ¶ms, encrypted).unwrap();
|
||||||
|
// prop_assert_eq!(orig, result.to_vec());
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
}
|
|
@ -0,0 +1 @@
|
||||||
|
{"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}}
|
6
src/fixtures/maFiles/compat/difficult-migration/generate.sh
Executable file
6
src/fixtures/maFiles/compat/difficult-migration/generate.sh
Executable file
|
@ -0,0 +1,6 @@
|
||||||
|
#!/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
|
|
@ -0,0 +1,83 @@
|
||||||
|
{
|
||||||
|
"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
|
||||||
|
}
|
|
@ -0,0 +1,21 @@
|
||||||
|
{
|
||||||
|
"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
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,21 @@
|
||||||
|
{
|
||||||
|
"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
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,21 @@
|
||||||
|
{
|
||||||
|
"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"
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,21 @@
|
||||||
|
{
|
||||||
|
"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
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,21 @@
|
||||||
|
{
|
||||||
|
"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
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,21 @@
|
||||||
|
{
|
||||||
|
"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
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,22 @@
|
||||||
|
{
|
||||||
|
"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
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,22 @@
|
||||||
|
{
|
||||||
|
"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
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,22 @@
|
||||||
|
{
|
||||||
|
"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
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,22 @@
|
||||||
|
{
|
||||||
|
"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
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,22 @@
|
||||||
|
{
|
||||||
|
"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
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,22 @@
|
||||||
|
{
|
||||||
|
"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
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1 @@
|
||||||
|
{"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}}
|
|
@ -0,0 +1 @@
|
||||||
|
{"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}
|
17
src/fixtures/maFiles/compat/null-oauthtoken/manifest.json
Normal file
17
src/fixtures/maFiles/compat/null-oauthtoken/manifest.json
Normal file
|
@ -0,0 +1,17 @@
|
||||||
|
{
|
||||||
|
"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
|
||||||
|
}
|
|
@ -0,0 +1 @@
|
||||||
|
{"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}}
|
14
src/fixtures/maFiles/compat/steamv2/sample.maFile
Normal file
14
src/fixtures/maFiles/compat/steamv2/sample.maFile
Normal file
|
@ -0,0 +1,14 @@
|
||||||
|
{
|
||||||
|
"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"
|
||||||
|
}
|
2
src/fixtures/maFiles/compat/winauth/exports.txt
Normal file
2
src/fixtures/maFiles/compat/winauth/exports.txt
Normal file
|
@ -0,0 +1,2 @@
|
||||||
|
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
|
|
@ -0,0 +1 @@
|
||||||
|
Z0HJDSN9EuFOpKEeBzftCWxTsh0sV6QQriLTVrn37FyGNaXhGgzeHlvPfHgkXKCYbALTgx/B2fLh1CEojKO1/eqEgN+982CadR3EXk+vH1k5AMuGhMXPpsEeIh27ltxrdAEzWdlPlAyentBgOKlTCoN6iF+EZVORvp2pPaMrebyHi8/5Y+XC3HrMgfgmP7lFGpUgZK8f0mKB/pGaW+0/3oVikggBK3MIWlh4s9bC9LlMy5H+oU0n/Iu3P9dpbko1bDMKIbUKEPzS3wHXyQRg32zPIfONR0bswb7QTfAhoKixZrAenQluX3lXRL0JFafNEPzUY4r/DJ1pIMLK9cEvbzqwsPth6jrIZRd+zvgnshfNnGLCblYkPo4fGwePuhX2W2w6qgFMpo69rkSp1Zz6JKC/gH9YyL4a8N768ml9H1so5XBm7eB+fMRIL7bHof+V1CxGXX3z1RvjGRHPwKcrKLvffxTTs/dBHb9UDFtTprlymLZf6C53c5vMBQ/hk4fm
|
|
@ -0,0 +1 @@
|
||||||
|
{"version":1,"entries":[{"filename":"1234.maFile","steam_id":1234,"account_name":"example","encryption":{"iv":"ifChnv66eA+/dYqGsQMIOA==","salt":"O2K8FAOWK9c=","scheme":"LegacySdaCompatible"}}]}
|
1
src/fixtures/maFiles/manifest-v1/1-account/1234.maFile
Normal file
1
src/fixtures/maFiles/manifest-v1/1-account/1234.maFile
Normal file
|
@ -0,0 +1 @@
|
||||||
|
{"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}
|
1
src/fixtures/maFiles/manifest-v1/1-account/manifest.json
Normal file
1
src/fixtures/maFiles/manifest-v1/1-account/manifest.json
Normal file
|
@ -0,0 +1 @@
|
||||||
|
{"version":1,"entries":[{"filename":"1234.maFile","steam_id":1234,"account_name":"example","encryption":null}]}
|
1
src/fixtures/maFiles/manifest-v1/2-account/1234.maFile
Normal file
1
src/fixtures/maFiles/manifest-v1/2-account/1234.maFile
Normal file
|
@ -0,0 +1 @@
|
||||||
|
{"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}
|
1
src/fixtures/maFiles/manifest-v1/2-account/5678.maFile
Normal file
1
src/fixtures/maFiles/manifest-v1/2-account/5678.maFile
Normal file
|
@ -0,0 +1 @@
|
||||||
|
{"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}
|
1
src/fixtures/maFiles/manifest-v1/2-account/manifest.json
Normal file
1
src/fixtures/maFiles/manifest-v1/2-account/manifest.json
Normal file
|
@ -0,0 +1 @@
|
||||||
|
{"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}]}
|
|
@ -0,0 +1 @@
|
||||||
|
{"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}
|
|
@ -0,0 +1 @@
|
||||||
|
{"version":1,"entries":[{"filename":"1234.maFile","steam_id":1234,"account_name":"example","encryption":null}]}
|
BIN
src/fixtures/qr-codes/login-qr.png
Normal file
BIN
src/fixtures/qr-codes/login-qr.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 1.3 KiB |
219
src/login.rs
Normal file
219
src/login.rs
Normal file
|
@ -0,0 +1,219 @@
|
||||||
|
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,
|
||||||
|
}
|
||||||
|
}
|
282
src/main.rs
282
src/main.rs
|
@ -1,20 +1,18 @@
|
||||||
extern crate rpassword;
|
extern crate rpassword;
|
||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use log::*;
|
use log::*;
|
||||||
|
use secrecy::SecretString;
|
||||||
use std::{
|
use std::{
|
||||||
io::Write,
|
|
||||||
path::Path,
|
path::Path,
|
||||||
sync::{Arc, Mutex},
|
sync::{Arc, Mutex},
|
||||||
};
|
};
|
||||||
use steamguard::protobufs::steammessages_auth_steamclient::{
|
use steamguard::transport::WebApiTransport;
|
||||||
EAuthSessionGuardType, EAuthTokenPlatformType,
|
use steamguard::SteamGuardAccount;
|
||||||
};
|
|
||||||
use steamguard::token::Tokens;
|
|
||||||
use steamguard::{steamapi, DeviceDetails, LoginError, SteamGuardAccount, UserLogin};
|
|
||||||
|
|
||||||
use crate::accountmanager::migrate::load_and_migrate;
|
use crate::accountmanager::migrate::{load_and_migrate, MigrationError};
|
||||||
pub use crate::accountmanager::{AccountManager, ManifestAccountLoadError, ManifestLoadError};
|
pub use crate::accountmanager::{AccountManager, ManifestAccountLoadError, ManifestLoadError};
|
||||||
use crate::commands::{CommandType, Subcommands};
|
use crate::commands::{CommandType, Subcommands};
|
||||||
|
pub use login::*;
|
||||||
|
|
||||||
extern crate lazy_static;
|
extern crate lazy_static;
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
|
@ -23,49 +21,77 @@ extern crate base64;
|
||||||
extern crate dirs;
|
extern crate dirs;
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
extern crate proptest;
|
extern crate proptest;
|
||||||
extern crate ring;
|
|
||||||
mod accountmanager;
|
mod accountmanager;
|
||||||
mod commands;
|
mod commands;
|
||||||
|
mod debug;
|
||||||
mod encryption;
|
mod encryption;
|
||||||
mod errors;
|
mod errors;
|
||||||
|
mod login;
|
||||||
mod secret_string;
|
mod secret_string;
|
||||||
pub(crate) mod tui;
|
pub(crate) mod tui;
|
||||||
|
|
||||||
|
#[cfg(feature = "updater")]
|
||||||
|
mod updater;
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
std::process::exit(match run() {
|
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) {
|
||||||
Ok(_) => 0,
|
Ok(_) => 0,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
error!("{:?}", e);
|
error!("{:?}", e);
|
||||||
255
|
255
|
||||||
}
|
}
|
||||||
});
|
};
|
||||||
|
|
||||||
|
#[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() -> anyhow::Result<()> {
|
fn run(args: commands::Args) -> anyhow::Result<()> {
|
||||||
let args = commands::Args::parse();
|
|
||||||
info!("{:?}", args);
|
|
||||||
|
|
||||||
let globalargs = args.global;
|
let globalargs = args.global;
|
||||||
|
|
||||||
stderrlog::new()
|
let cmd: CommandType<WebApiTransport> = match args.sub.unwrap_or(Subcommands::Code(args.code)) {
|
||||||
.verbosity(globalargs.verbosity as usize)
|
|
||||||
.module(module_path!())
|
|
||||||
.module("steamguard")
|
|
||||||
.init()
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
let cmd: CommandType = match args.sub.unwrap_or(Subcommands::Code(args.code)) {
|
|
||||||
Subcommands::Debug(args) => CommandType::Const(Box::new(args)),
|
Subcommands::Debug(args) => CommandType::Const(Box::new(args)),
|
||||||
Subcommands::Completion(args) => CommandType::Const(Box::new(args)),
|
Subcommands::Completion(args) => CommandType::Const(Box::new(args)),
|
||||||
Subcommands::Setup(args) => CommandType::Manifest(Box::new(args)),
|
Subcommands::Setup(args) => CommandType::Manifest(Box::new(args)),
|
||||||
Subcommands::Import(args) => CommandType::Manifest(Box::new(args)),
|
Subcommands::Import(args) => CommandType::Manifest(Box::new(args)),
|
||||||
Subcommands::Encrypt(args) => CommandType::Manifest(Box::new(args)),
|
Subcommands::Encrypt(args) => CommandType::Manifest(Box::new(args)),
|
||||||
Subcommands::Decrypt(args) => CommandType::Manifest(Box::new(args)),
|
Subcommands::Decrypt(args) => CommandType::Manifest(Box::new(args)),
|
||||||
Subcommands::Trade(args) => CommandType::Account(Box::new(args)),
|
Subcommands::Confirm(args) => CommandType::Account(Box::new(args)),
|
||||||
Subcommands::Remove(args) => CommandType::Account(Box::new(args)),
|
Subcommands::Remove(args) => CommandType::Account(Box::new(args)),
|
||||||
Subcommands::Code(args) => CommandType::Account(Box::new(args)),
|
Subcommands::Code(args) => CommandType::Account(Box::new(args)),
|
||||||
#[cfg(feature = "qr")]
|
#[cfg(feature = "qr")]
|
||||||
Subcommands::Qr(args) => CommandType::Account(Box::new(args)),
|
Subcommands::Qr(args) => CommandType::Account(Box::new(args)),
|
||||||
|
Subcommands::QrLogin(args) => CommandType::Account(Box::new(args)),
|
||||||
};
|
};
|
||||||
|
|
||||||
if let CommandType::Const(cmd) = cmd {
|
if let CommandType::Const(cmd) = cmd {
|
||||||
|
@ -79,6 +105,8 @@ fn run() -> anyhow::Result<()> {
|
||||||
};
|
};
|
||||||
info!("reading manifest from {}", mafiles_dir);
|
info!("reading manifest from {}", mafiles_dir);
|
||||||
let path = Path::new(&mafiles_dir).join("manifest.json");
|
let path = Path::new(&mafiles_dir).join("manifest.json");
|
||||||
|
let mut passkey = globalargs.passkey.clone();
|
||||||
|
|
||||||
let mut manager: accountmanager::AccountManager;
|
let mut manager: accountmanager::AccountManager;
|
||||||
if !path.exists() {
|
if !path.exists() {
|
||||||
error!("Did not find manifest in {}", mafiles_dir);
|
error!("Did not find manifest in {}", mafiles_dir);
|
||||||
|
@ -99,11 +127,42 @@ fn run() -> anyhow::Result<()> {
|
||||||
Ok(m) => m,
|
Ok(m) => m,
|
||||||
Err(ManifestLoadError::MigrationNeeded) => {
|
Err(ManifestLoadError::MigrationNeeded) => {
|
||||||
info!("Migrating manifest");
|
info!("Migrating manifest");
|
||||||
let (manifest, accounts) =
|
let manifest;
|
||||||
load_and_migrate(path.as_path(), globalargs.passkey.as_ref())?;
|
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");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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);
|
let mut manager = AccountManager::from_manifest(manifest, mafiles_dir);
|
||||||
manager.register_accounts(accounts);
|
manager.register_accounts(accounts);
|
||||||
manager.submit_passkey(globalargs.passkey.clone());
|
manager.submit_passkey(passkey.clone());
|
||||||
manager.save()?;
|
manager.save()?;
|
||||||
manager
|
manager
|
||||||
}
|
}
|
||||||
|
@ -114,7 +173,19 @@ fn run() -> anyhow::Result<()> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut passkey = globalargs.passkey.clone();
|
#[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);
|
manager.submit_passkey(passkey);
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
|
@ -135,7 +206,7 @@ fn run() -> anyhow::Result<()> {
|
||||||
if manager.has_passkey() {
|
if manager.has_passkey() {
|
||||||
error!("Incorrect passkey");
|
error!("Incorrect passkey");
|
||||||
}
|
}
|
||||||
passkey = rpassword::prompt_password_stderr("Enter encryption passkey: ").ok();
|
passkey = Some(tui::prompt_passkey()?);
|
||||||
manager.submit_passkey(passkey);
|
manager.submit_passkey(passkey);
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
|
@ -145,8 +216,23 @@ fn run() -> 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());
|
||||||
|
}
|
||||||
|
http_client = http_client.proxy(proxy);
|
||||||
|
}
|
||||||
|
if globalargs.danger_accept_invalid_certs {
|
||||||
|
http_client = http_client.danger_accept_invalid_certs(true);
|
||||||
|
}
|
||||||
|
let http_client = http_client.build()?;
|
||||||
|
let transport = WebApiTransport::new(http_client);
|
||||||
|
|
||||||
if let CommandType::Manifest(cmd) = cmd {
|
if let CommandType::Manifest(cmd) = cmd {
|
||||||
cmd.execute(&mut manager)?;
|
cmd.execute(transport, &mut manager, &globalargs)?;
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -158,13 +244,13 @@ fn run() -> anyhow::Result<()> {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
Err(
|
Err(
|
||||||
accountmanager::ManifestAccountLoadError::MissingPasskey
|
accountmanager::ManifestAccountLoadError::MissingPasskey { .. }
|
||||||
| accountmanager::ManifestAccountLoadError::IncorrectPasskey,
|
| accountmanager::ManifestAccountLoadError::IncorrectPasskey,
|
||||||
) => {
|
) => {
|
||||||
if manager.has_passkey() {
|
if manager.has_passkey() {
|
||||||
error!("Incorrect passkey");
|
error!("Incorrect passkey");
|
||||||
}
|
}
|
||||||
passkey = rpassword::prompt_password_stdout("Enter encryption passkey: ").ok();
|
passkey = Some(tui::prompt_passkey()?);
|
||||||
manager.submit_passkey(passkey);
|
manager.submit_passkey(passkey);
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
|
@ -183,7 +269,7 @@ fn run() -> anyhow::Result<()> {
|
||||||
);
|
);
|
||||||
|
|
||||||
if let CommandType::Account(cmd) = cmd {
|
if let CommandType::Account(cmd) = cmd {
|
||||||
return cmd.execute(&mut manager, selected_accounts);
|
return cmd.execute(transport, &mut manager, selected_accounts, &globalargs);
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
|
@ -217,138 +303,14 @@ fn get_selected_accounts(
|
||||||
Ok(selected_accounts)
|
Ok(selected_accounts)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn do_login(account: &mut SteamGuardAccount) -> anyhow::Result<()> {
|
|
||||||
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 = rpassword::prompt_password_stdout("Password: ").unwrap();
|
|
||||||
if !password.is_empty() {
|
|
||||||
debug!("password is present");
|
|
||||||
} else {
|
|
||||||
debug!("password is empty");
|
|
||||||
}
|
|
||||||
let tokens = do_login_impl(account.account_name.clone(), password, Some(account))?;
|
|
||||||
let steam_id = tokens.access_token().decode()?.steam_id();
|
|
||||||
account.set_tokens(tokens);
|
|
||||||
account.steam_id = steam_id;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn do_login_raw(username: String) -> anyhow::Result<Tokens> {
|
|
||||||
let _ = std::io::stdout().flush();
|
|
||||||
let password = rpassword::prompt_password_stdout("Password: ").unwrap();
|
|
||||||
if !password.is_empty() {
|
|
||||||
debug!("password is present");
|
|
||||||
} else {
|
|
||||||
debug!("password is empty");
|
|
||||||
}
|
|
||||||
do_login_impl(username, password, None)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn do_login_impl(
|
|
||||||
username: String,
|
|
||||||
password: String,
|
|
||||||
account: Option<&SteamGuardAccount>,
|
|
||||||
) -> anyhow::Result<Tokens> {
|
|
||||||
let mut login = UserLogin::new(build_device_details());
|
|
||||||
|
|
||||||
let mut password = password;
|
|
||||||
let confirmation_methods;
|
|
||||||
loop {
|
|
||||||
match login.begin_auth_via_credentials(&username, &password) {
|
|
||||||
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.");
|
|
||||||
password = rpassword::prompt_password_stdout("Password: ")
|
|
||||||
.unwrap()
|
|
||||||
.trim()
|
|
||||||
.to_owned();
|
|
||||||
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());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for method in confirmation_methods {
|
|
||||||
match method.confirmation_type {
|
|
||||||
EAuthSessionGuardType::k_EAuthSessionGuardType_DeviceConfirmation => {
|
|
||||||
eprintln!("Please confirm this login on your other device.");
|
|
||||||
eprintln!("Press enter when you have confirmed.");
|
|
||||||
tui::pause();
|
|
||||||
}
|
|
||||||
EAuthSessionGuardType::k_EAuthSessionGuardType_EmailConfirmation => {
|
|
||||||
eprint!("Please confirm this login by clicking the link in your email.");
|
|
||||||
if !method.associated_messsage.is_empty() {
|
|
||||||
eprint!(" ({})", method.associated_messsage);
|
|
||||||
}
|
|
||||||
eprintln!();
|
|
||||||
eprintln!("Press enter when you have confirmed.");
|
|
||||||
tui::pause();
|
|
||||||
}
|
|
||||||
EAuthSessionGuardType::k_EAuthSessionGuardType_DeviceCode => {
|
|
||||||
let code = if let Some(account) = account {
|
|
||||||
debug!("Generating 2fa code...");
|
|
||||||
let time = steamapi::get_server_time()?.server_time();
|
|
||||||
account.generate_code(time)
|
|
||||||
} else {
|
|
||||||
eprint!("Enter the 2fa code from your device: ");
|
|
||||||
tui::prompt().trim().to_owned()
|
|
||||||
};
|
|
||||||
login.submit_steam_guard_code(method.confirmation_type, code)?;
|
|
||||||
}
|
|
||||||
EAuthSessionGuardType::k_EAuthSessionGuardType_EmailCode => {
|
|
||||||
eprint!("Enter the 2fa code sent to your email: ");
|
|
||||||
let code = tui::prompt().trim().to_owned();
|
|
||||||
login.submit_steam_guard_code(method.confirmation_type, code)?;
|
|
||||||
}
|
|
||||||
_ => {
|
|
||||||
warn!("Unknown confirmation method: {:?}", method);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
info!("Polling for tokens... -- If this takes a long time, try logging in again.");
|
|
||||||
let tokens = login.poll_until_tokens()?;
|
|
||||||
|
|
||||||
info!("Logged in successfully!");
|
|
||||||
Ok(tokens)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn build_device_details() -> DeviceDetails {
|
|
||||||
DeviceDetails {
|
|
||||||
friendly_name: format!(
|
|
||||||
"{} (steamguard-cli)",
|
|
||||||
gethostname::gethostname()
|
|
||||||
.into_string()
|
|
||||||
.expect("failed to get hostname")
|
|
||||||
),
|
|
||||||
platform_type: EAuthTokenPlatformType::k_EAuthTokenPlatformType_MobileApp,
|
|
||||||
os_type: -500,
|
|
||||||
gaming_device_type: 528,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_mafiles_dir() -> String {
|
fn get_mafiles_dir() -> String {
|
||||||
let paths = vec![
|
let mut paths = vec![
|
||||||
Path::new(&dirs::config_dir().unwrap()).join("steamguard-cli/maFiles"),
|
Path::new(&dirs::config_dir().unwrap()).join("steamguard-cli/maFiles"),
|
||||||
Path::new(&dirs::home_dir().unwrap()).join("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 {
|
for path in &paths {
|
||||||
if path.join("manifest.json").is_file() {
|
if path.join("manifest.json").is_file() {
|
||||||
|
|
46
src/tui.rs
46
src/tui.rs
|
@ -1,3 +1,4 @@
|
||||||
|
use anyhow::Context;
|
||||||
use crossterm::{
|
use crossterm::{
|
||||||
cursor,
|
cursor,
|
||||||
event::{Event, KeyCode, KeyEvent, KeyModifiers},
|
event::{Event, KeyCode, KeyEvent, KeyModifiers},
|
||||||
|
@ -6,6 +7,8 @@ use crossterm::{
|
||||||
terminal::{Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen},
|
terminal::{Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen},
|
||||||
QueueableCommand,
|
QueueableCommand,
|
||||||
};
|
};
|
||||||
|
use log::debug;
|
||||||
|
use secrecy::SecretString;
|
||||||
use std::collections::HashSet;
|
use std::collections::HashSet;
|
||||||
use std::io::{stderr, stdout, Write};
|
use std::io::{stderr, stdout, Write};
|
||||||
use steamguard::Confirmation;
|
use steamguard::Confirmation;
|
||||||
|
@ -31,9 +34,20 @@ pub(crate) fn prompt() -> String {
|
||||||
line
|
line
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn prompt_non_empty(prompt_text: impl AsRef<str>) -> String {
|
||||||
|
loop {
|
||||||
|
eprint!("{}", prompt_text.as_ref());
|
||||||
|
let input = prompt();
|
||||||
|
if !input.is_empty() {
|
||||||
|
return input;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Prompt the user for a single character response. Useful for asking yes or no questions.
|
/// 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.
|
/// `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 {
|
pub(crate) fn prompt_char(text: &str, chars: &str) -> char {
|
||||||
loop {
|
loop {
|
||||||
let _ = stderr().queue(Print(format!("{} [{}] ", text, chars)));
|
let _ = stderr().queue(Print(format!("{} [{}] ", text, chars)));
|
||||||
|
@ -45,10 +59,7 @@ pub(crate) fn prompt_char(text: &str, chars: &str) -> char {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn prompt_char_impl<T>(input: T, chars: &str) -> anyhow::Result<char>
|
fn prompt_char_impl(input: impl Into<String>, chars: &str) -> anyhow::Result<char> {
|
||||||
where
|
|
||||||
T: Into<String>,
|
|
||||||
{
|
|
||||||
let uppers = chars.replace(char::is_lowercase, "");
|
let uppers = chars.replace(char::is_lowercase, "");
|
||||||
if uppers.len() > 1 {
|
if uppers.len() > 1 {
|
||||||
panic!("Invalid chars for prompt_char. Maximum 1 uppercase letter is allowed.");
|
panic!("Invalid chars for prompt_char. Maximum 1 uppercase letter is allowed.");
|
||||||
|
@ -84,7 +95,7 @@ pub(crate) fn prompt_confirmation_menu(
|
||||||
confirmations: Vec<Confirmation>,
|
confirmations: Vec<Confirmation>,
|
||||||
) -> anyhow::Result<(Vec<Confirmation>, Vec<Confirmation>)> {
|
) -> anyhow::Result<(Vec<Confirmation>, Vec<Confirmation>)> {
|
||||||
if confirmations.is_empty() {
|
if confirmations.is_empty() {
|
||||||
bail!("no confirmations")
|
return Ok((vec![], vec![]));
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut to_accept_idx: HashSet<usize> = HashSet::new();
|
let mut to_accept_idx: HashSet<usize> = HashSet::new();
|
||||||
|
@ -244,6 +255,27 @@ 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)]
|
#[cfg(test)]
|
||||||
mod prompt_char_tests {
|
mod prompt_char_tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
@ -269,7 +301,7 @@ mod prompt_char_tests {
|
||||||
#[test]
|
#[test]
|
||||||
fn test_should_not_give_invalid() {
|
fn test_should_not_give_invalid() {
|
||||||
let answer = prompt_char_impl("g", "yn");
|
let answer = prompt_char_impl("g", "yn");
|
||||||
assert!(matches!(answer, Err(_)));
|
assert!(answer.is_err());
|
||||||
let answer = prompt_char_impl("n", "yn").unwrap();
|
let answer = prompt_char_impl("n", "yn").unwrap();
|
||||||
assert_eq!(answer, 'n');
|
assert_eq!(answer, 'n');
|
||||||
}
|
}
|
||||||
|
@ -277,6 +309,6 @@ mod prompt_char_tests {
|
||||||
#[test]
|
#[test]
|
||||||
fn test_should_not_give_multichar() {
|
fn test_should_not_give_multichar() {
|
||||||
let answer = prompt_char_impl("yy", "yn");
|
let answer = prompt_char_impl("yy", "yn");
|
||||||
assert!(matches!(answer, Err(_)));
|
assert!(answer.is_err());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
46
src/updater.rs
Normal file
46
src/updater.rs
Normal file
|
@ -0,0 +1,46 @@
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,37 +1,45 @@
|
||||||
[package]
|
[package]
|
||||||
name = "steamguard"
|
name = "steamguard"
|
||||||
version = "0.8.1"
|
version = "0.14.0"
|
||||||
authors = ["Carson McManus <carson.mcmanus1@gmail.com>"]
|
authors = ["Carson McManus <carson.mcmanus1@gmail.com>"]
|
||||||
edition = "2018"
|
edition = "2021"
|
||||||
description = "Library for generating 2fa codes for Steam and responding to mobile confirmations."
|
description = "Library for generating 2fa codes for Steam and responding to mobile confirmations."
|
||||||
keywords = ["steam", "2fa", "steamguard", "authentication"]
|
keywords = ["steam", "2fa", "steamguard", "authentication"]
|
||||||
repository = "https://github.com/dyc3/steamguard-cli/tree/master/steamguard"
|
repository = "https://github.com/dyc3/steamguard-cli/tree/master/steamguard"
|
||||||
license = "MIT OR Apache-2.0"
|
license = "MIT OR Apache-2.0"
|
||||||
|
|
||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
anyhow = "^1.0"
|
anyhow = "^1.0"
|
||||||
hmac-sha1 = "^0.1"
|
sha1 = "^0.10"
|
||||||
base64 = "0.13.0"
|
base64 = "^0.22.1"
|
||||||
reqwest = { version = "0.11", default-features = false, features = ["blocking", "json", "cookies", "gzip", "rustls-tls", "multipart"] }
|
reqwest = { version = "0.12", default-features = false, features = [
|
||||||
|
"blocking",
|
||||||
|
"json",
|
||||||
|
"cookies",
|
||||||
|
"gzip",
|
||||||
|
"rustls-tls",
|
||||||
|
"multipart",
|
||||||
|
] }
|
||||||
serde = { version = "1.0", features = ["derive"] }
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
rsa = "0.5.0"
|
rsa = "0.9.2"
|
||||||
rand = "0.8.4"
|
rand = "0.8.4"
|
||||||
standback = "0.2.17" # required to fix a compilation error on a transient dependency
|
cookie = "0.18"
|
||||||
cookie = "0.14"
|
|
||||||
regex = "1"
|
regex = "1"
|
||||||
lazy_static = "1.4.0"
|
lazy_static = "1.4.0"
|
||||||
uuid = { version = "0.8", features = ["v4"] }
|
uuid = { version = "1.8", features = ["v4"] }
|
||||||
log = "0.4.14"
|
log = "0.4.19"
|
||||||
scraper = "0.12.0"
|
|
||||||
maplit = "1.0.2"
|
maplit = "1.0.2"
|
||||||
thiserror = "1.0.26"
|
thiserror = "1.0.26"
|
||||||
secrecy = { version = "0.8", features = ["serde"] }
|
secrecy = { version = "0.8", features = ["serde"] }
|
||||||
zeroize = "^1.4.3"
|
zeroize = { version = "^1.6.0", features = ["std", "zeroize_derive"] }
|
||||||
protobuf = "3.2.0"
|
protobuf = "3.2.0"
|
||||||
protobuf-json-mapping = "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]
|
[build-dependencies]
|
||||||
anyhow = "^1.0"
|
anyhow = "^1.0"
|
||||||
|
|
|
@ -1,6 +1,8 @@
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
use protobuf::descriptor::field_descriptor_proto::Type;
|
||||||
|
use protobuf::reflect::FieldDescriptor;
|
||||||
use protobuf::reflect::MessageDescriptor;
|
use protobuf::reflect::MessageDescriptor;
|
||||||
use protobuf_codegen::Codegen;
|
use protobuf_codegen::Codegen;
|
||||||
use protobuf_codegen::Customize;
|
use protobuf_codegen::Customize;
|
||||||
|
@ -44,32 +46,29 @@ struct GenSerde;
|
||||||
|
|
||||||
impl CustomizeCallback for GenSerde {
|
impl CustomizeCallback for GenSerde {
|
||||||
fn message(&self, _message: &MessageDescriptor) -> Customize {
|
fn message(&self, _message: &MessageDescriptor) -> Customize {
|
||||||
// Customize::default().before("#[derive(::serde::Serialize, ::serde::Deserialize)]")
|
Customize::default().before("#[derive(::zeroize::Zeroize, ::zeroize::ZeroizeOnDrop)]")
|
||||||
Customize::default()
|
// Customize::default()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn enumeration(&self, _enum_type: &protobuf::reflect::EnumDescriptor) -> Customize {
|
fn enumeration(&self, _enum_type: &protobuf::reflect::EnumDescriptor) -> Customize {
|
||||||
Customize::default().before("#[derive(::serde::Serialize, ::serde::Deserialize)]")
|
Customize::default()
|
||||||
|
.before("#[derive(::serde::Serialize, ::serde::Deserialize, ::zeroize::Zeroize)]")
|
||||||
}
|
}
|
||||||
|
|
||||||
// fn field(&self, field: &FieldDescriptor) -> Customize {
|
fn field(&self, field: &FieldDescriptor) -> Customize {
|
||||||
// // if field.name() == "public_ip" {
|
// if field.name() == "public_ip" {
|
||||||
// // eprintln!("type_name: {:?}", field.proto().type_name());
|
// eprintln!("type_name: {:?}", field.proto().type_name());
|
||||||
// // eprintln!("type_: {:?}", field.proto().type_());
|
// eprintln!("type_: {:?}", field.proto().type_());
|
||||||
// // eprintln!("{:?}", field.proto());
|
// eprintln!("{:?}", field.proto());
|
||||||
// // }
|
// }
|
||||||
// if field.proto().type_() == Type::TYPE_ENUM {
|
if field.proto().type_() == Type::TYPE_ENUM || field.proto().type_() == Type::TYPE_MESSAGE {
|
||||||
// // `EnumOrUnknown` is not a part of rust-protobuf, so external serializer is needed.
|
Customize::default().before("#[zeroize(skip)]")
|
||||||
// Customize::default().before(
|
} else {
|
||||||
// "#[serde(serialize_with = \"crate::protobufs::serialize_enum_or_unknown\", deserialize_with = \"crate::protobufs::deserialize_enum_or_unknown\")]")
|
Customize::default()
|
||||||
// // } else if field.name() == "public_ip" {
|
}
|
||||||
// // Customize::default().before("#[serde(with = \"crate::protobufs::MessageFieldDef\")]")
|
}
|
||||||
// } else {
|
|
||||||
// Customize::default()
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
// fn special_field(&self, _message: &MessageDescriptor, _field: &str) -> Customize {
|
fn special_field(&self, _message: &MessageDescriptor, _field: &str) -> Customize {
|
||||||
// Customize::default().before("#[serde(skip)]")
|
Customize::default().before("#[zeroize(skip)]")
|
||||||
// }
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -19,5 +19,3 @@ message CAuthentication_BeginAuthSessionViaCredentials_Request_BinaryGuardData {
|
||||||
optional uint32 language = 11;
|
optional uint32 language = 11;
|
||||||
optional int32 qos_level = 12 [default = 2, (description) = "[ENetQOSLevel] client-specified priority for this auth attempt"];
|
optional int32 qos_level = 12 [default = 2, (description) = "[ENetQOSLevel] client-specified priority for this auth attempt"];
|
||||||
}
|
}
|
||||||
|
|
||||||
message CTwoFactor_Time_Request {}
|
|
||||||
|
|
|
@ -59,9 +59,10 @@ enum EPersonaStateFlag {
|
||||||
|
|
||||||
enum EContentCheckProvider {
|
enum EContentCheckProvider {
|
||||||
k_EContentCheckProvider_Invalid = 0;
|
k_EContentCheckProvider_Invalid = 0;
|
||||||
k_EContentCheckProvider_Google = 1;
|
k_EContentCheckProvider_Google_DEPRECATED = 1;
|
||||||
k_EContentCheckProvider_Amazon = 2;
|
k_EContentCheckProvider_Amazon = 2;
|
||||||
k_EContentCheckProvider_Local = 3;
|
k_EContentCheckProvider_Local = 3;
|
||||||
|
k_EContentCheckProvider_GoogleVertexAI = 4;
|
||||||
}
|
}
|
||||||
|
|
||||||
enum EProfileCustomizationType {
|
enum EProfileCustomizationType {
|
||||||
|
@ -89,6 +90,7 @@ enum EProfileCustomizationType {
|
||||||
k_EProfileCustomizationTypeLoyaltyRewardReactions = 21;
|
k_EProfileCustomizationTypeLoyaltyRewardReactions = 21;
|
||||||
k_EProfileCustomizationTypeSingleArtworkShowcase = 22;
|
k_EProfileCustomizationTypeSingleArtworkShowcase = 22;
|
||||||
k_EProfileCustomizationTypeAchievementsCompletionist = 23;
|
k_EProfileCustomizationTypeAchievementsCompletionist = 23;
|
||||||
|
k_EProfileCustomizationTypeReplay = 24;
|
||||||
}
|
}
|
||||||
|
|
||||||
enum EPublishedFileStorageSystem {
|
enum EPublishedFileStorageSystem {
|
||||||
|
@ -113,17 +115,32 @@ enum ESDCardFormatStage {
|
||||||
k_ESDCardFormatStage_Finalizing = 5;
|
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 {
|
enum ESystemFanControlMode {
|
||||||
k_SystemFanControlMode_Invalid = 0;
|
k_SystemFanControlMode_Invalid = 0;
|
||||||
k_SystemFanControlMode_Disabled = 1;
|
k_SystemFanControlMode_Disabled = 1;
|
||||||
k_SystemFanControlMode_Default = 2;
|
k_SystemFanControlMode_Default = 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
enum EColorProfile {
|
enum EStartupMovieVariant {
|
||||||
k_EColorProfile_Invalid = 0;
|
k_EStartupMovieVariant_Invalid = 0;
|
||||||
k_EColorProfile_Native = 1;
|
k_EStartupMovieVariant_Default = 1;
|
||||||
k_EColorProfile_Standard = 2;
|
k_EStartupMovieVariant_Orange = 2;
|
||||||
k_EColorProfile_Vivid = 3;
|
}
|
||||||
|
|
||||||
|
enum EColorGamutLabelSet {
|
||||||
|
k_ColorGamutLabelSet_Default = 0;
|
||||||
|
k_ColorGamutLabelSet_sRGB_Native = 1;
|
||||||
|
k_ColorGamutLabelSet_Native_sRGB_Boosted = 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
enum EBluetoothDeviceType {
|
enum EBluetoothDeviceType {
|
||||||
|
@ -206,6 +223,52 @@ enum EScalingFilter {
|
||||||
k_EScalingFilter_NIS = 5;
|
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 {
|
enum ECPUGovernor {
|
||||||
k_ECPUGovernor_Invalid = 0;
|
k_ECPUGovernor_Invalid = 0;
|
||||||
k_ECPUGovernor_Perf = 1;
|
k_ECPUGovernor_Perf = 1;
|
||||||
|
@ -249,6 +312,20 @@ enum EStorageBlockFileSystemType {
|
||||||
k_EStorageBlockFileSystemType_Ext4 = 3;
|
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 {
|
enum ESteamDeckCompatibilityCategory {
|
||||||
k_ESteamDeckCompatibilityCategory_Unknown = 0;
|
k_ESteamDeckCompatibilityCategory_Unknown = 0;
|
||||||
k_ESteamDeckCompatibilityCategory_Unsupported = 1;
|
k_ESteamDeckCompatibilityCategory_Unsupported = 1;
|
||||||
|
@ -285,6 +362,7 @@ enum EOSBranch {
|
||||||
k_EOSBranch_Beta = 3;
|
k_EOSBranch_Beta = 3;
|
||||||
k_EOSBranch_BetaCandidate = 4;
|
k_EOSBranch_BetaCandidate = 4;
|
||||||
k_EOSBranch_Main = 5;
|
k_EOSBranch_Main = 5;
|
||||||
|
k_EOSBranch_Staging = 6;
|
||||||
}
|
}
|
||||||
|
|
||||||
enum ECommunityItemClass {
|
enum ECommunityItemClass {
|
||||||
|
@ -305,6 +383,7 @@ enum ECommunityItemClass {
|
||||||
k_ECommunityItemClass_AvatarFrame = 14;
|
k_ECommunityItemClass_AvatarFrame = 14;
|
||||||
k_ECommunityItemClass_AnimatedAvatar = 15;
|
k_ECommunityItemClass_AnimatedAvatar = 15;
|
||||||
k_ECommunityItemClass_SteamDeckKeyboardSkin = 16;
|
k_ECommunityItemClass_SteamDeckKeyboardSkin = 16;
|
||||||
|
k_ECommunityItemClass_SteamDeckStartupMovie = 17;
|
||||||
}
|
}
|
||||||
|
|
||||||
enum ESteamDeckCompatibilityFeedback {
|
enum ESteamDeckCompatibilityFeedback {
|
||||||
|
@ -342,3 +421,54 @@ enum ESessionPersistence {
|
||||||
k_ESessionPersistence_Ephemeral = 0;
|
k_ESessionPersistence_Ephemeral = 0;
|
||||||
k_ESessionPersistence_Persistent = 1;
|
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;
|
||||||
|
}
|
50
steamguard/protobufs/service_phone.proto
Normal file
50
steamguard/protobufs/service_phone.proto
Normal file
|
@ -0,0 +1,50 @@
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
|
@ -38,20 +38,13 @@ message CTwoFactor_AddAuthenticator_Response {
|
||||||
optional bytes secret_1 = 9;
|
optional bytes secret_1 = 9;
|
||||||
optional int32 status = 10;
|
optional int32 status = 10;
|
||||||
optional string phone_number_hint = 11;
|
optional string phone_number_hint = 11;
|
||||||
}
|
optional int32 confirm_type = 12;
|
||||||
|
|
||||||
message CTwoFactor_CreateEmergencyCodes_Request {
|
|
||||||
optional string code = 1;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
message CTwoFactor_CreateEmergencyCodes_Response {
|
message CTwoFactor_CreateEmergencyCodes_Response {
|
||||||
repeated string codes = 1;
|
repeated string codes = 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
message CTwoFactor_DestroyEmergencyCodes_Request {
|
|
||||||
optional fixed64 steamid = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
message CTwoFactor_DestroyEmergencyCodes_Response {
|
message CTwoFactor_DestroyEmergencyCodes_Response {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -132,6 +125,10 @@ message CTwoFactor_Status_Response {
|
||||||
optional uint32 version = 14;
|
optional uint32 version = 14;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
message CTwoFactor_Time_Request {
|
||||||
|
optional uint64 sender_time = 1;
|
||||||
|
}
|
||||||
|
|
||||||
message CTwoFactor_Time_Response {
|
message CTwoFactor_Time_Response {
|
||||||
optional uint64 server_time = 1;
|
optional uint64 server_time = 1;
|
||||||
optional uint64 skew_tolerance_seconds = 2;
|
optional uint64 skew_tolerance_seconds = 2;
|
||||||
|
@ -153,25 +150,21 @@ message CTwoFactor_UpdateTokenVersion_Request {
|
||||||
message CTwoFactor_UpdateTokenVersion_Response {
|
message CTwoFactor_UpdateTokenVersion_Response {
|
||||||
}
|
}
|
||||||
|
|
||||||
message CTwoFactor_ValidateToken_Request {
|
|
||||||
optional string code = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
message CTwoFactor_ValidateToken_Response {
|
message CTwoFactor_ValidateToken_Response {
|
||||||
optional bool valid = 1;
|
optional bool valid = 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
service TwoFactor {
|
service TwoFactor {
|
||||||
rpc AddAuthenticator (.CTwoFactor_AddAuthenticator_Request) returns (.CTwoFactor_AddAuthenticator_Response);
|
rpc AddAuthenticator (.CTwoFactor_AddAuthenticator_Request) returns (.CTwoFactor_AddAuthenticator_Response);
|
||||||
rpc CreateEmergencyCodes (.CTwoFactor_CreateEmergencyCodes_Request) returns (.CTwoFactor_CreateEmergencyCodes_Response);
|
rpc CreateEmergencyCodes (.NotImplemented) returns (.CTwoFactor_CreateEmergencyCodes_Response);
|
||||||
rpc DestroyEmergencyCodes (.CTwoFactor_DestroyEmergencyCodes_Request) returns (.CTwoFactor_DestroyEmergencyCodes_Response);
|
rpc DestroyEmergencyCodes (.NotImplemented) returns (.CTwoFactor_DestroyEmergencyCodes_Response);
|
||||||
rpc FinalizeAddAuthenticator (.CTwoFactor_FinalizeAddAuthenticator_Request) returns (.CTwoFactor_FinalizeAddAuthenticator_Response);
|
rpc FinalizeAddAuthenticator (.CTwoFactor_FinalizeAddAuthenticator_Request) returns (.CTwoFactor_FinalizeAddAuthenticator_Response);
|
||||||
rpc QueryStatus (.CTwoFactor_Status_Request) returns (.CTwoFactor_Status_Response);
|
rpc QueryStatus (.CTwoFactor_Status_Request) returns (.CTwoFactor_Status_Response);
|
||||||
rpc QueryTime (.NotImplemented) returns (.CTwoFactor_Time_Response);
|
rpc QueryTime (.CTwoFactor_Time_Request) returns (.CTwoFactor_Time_Response);
|
||||||
rpc RemoveAuthenticator (.CTwoFactor_RemoveAuthenticator_Request) returns (.CTwoFactor_RemoveAuthenticator_Response);
|
rpc RemoveAuthenticator (.CTwoFactor_RemoveAuthenticator_Request) returns (.CTwoFactor_RemoveAuthenticator_Response);
|
||||||
rpc RemoveAuthenticatorViaChallengeContinue (.CTwoFactor_RemoveAuthenticatorViaChallengeContinue_Request) returns (.CTwoFactor_RemoveAuthenticatorViaChallengeContinue_Response);
|
rpc RemoveAuthenticatorViaChallengeContinue (.CTwoFactor_RemoveAuthenticatorViaChallengeContinue_Request) returns (.CTwoFactor_RemoveAuthenticatorViaChallengeContinue_Response);
|
||||||
rpc RemoveAuthenticatorViaChallengeStart (.CTwoFactor_RemoveAuthenticatorViaChallengeStart_Request) returns (.CTwoFactor_RemoveAuthenticatorViaChallengeStart_Response);
|
rpc RemoveAuthenticatorViaChallengeStart (.CTwoFactor_RemoveAuthenticatorViaChallengeStart_Request) returns (.CTwoFactor_RemoveAuthenticatorViaChallengeStart_Response);
|
||||||
rpc SendEmail (.CTwoFactor_SendEmail_Request) returns (.CTwoFactor_SendEmail_Response);
|
rpc SendEmail (.CTwoFactor_SendEmail_Request) returns (.CTwoFactor_SendEmail_Response);
|
||||||
rpc UpdateTokenVersion (.CTwoFactor_UpdateTokenVersion_Request) returns (.CTwoFactor_UpdateTokenVersion_Response);
|
rpc UpdateTokenVersion (.CTwoFactor_UpdateTokenVersion_Request) returns (.CTwoFactor_UpdateTokenVersion_Response);
|
||||||
rpc ValidateToken (.CTwoFactor_ValidateToken_Request) returns (.CTwoFactor_ValidateToken_Response);
|
rpc ValidateToken (.NotImplemented) returns (.CTwoFactor_ValidateToken_Response);
|
||||||
}
|
}
|
||||||
|
|
|
@ -28,12 +28,20 @@ enum EAuthSessionSecurityHistory {
|
||||||
k_EAuthSessionSecurityHistory_NoPriorHistory = 2;
|
k_EAuthSessionSecurityHistory_NoPriorHistory = 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
enum ETokenRenewalType {
|
||||||
|
k_ETokenRenewalType_None = 0;
|
||||||
|
k_ETokenRenewalType_Allow = 1;
|
||||||
|
}
|
||||||
|
|
||||||
enum EAuthTokenRevokeAction {
|
enum EAuthTokenRevokeAction {
|
||||||
k_EAuthTokenRevokeLogout = 0;
|
k_EAuthTokenRevokeLogout = 0;
|
||||||
k_EAuthTokenRevokePermanent = 1;
|
k_EAuthTokenRevokePermanent = 1;
|
||||||
k_EAuthTokenRevokeReplaced = 2;
|
k_EAuthTokenRevokeReplaced = 2;
|
||||||
k_EAuthTokenRevokeSupport = 3;
|
k_EAuthTokenRevokeSupport = 3;
|
||||||
k_EAuthTokenRevokeConsume = 4;
|
k_EAuthTokenRevokeConsume = 4;
|
||||||
|
k_EAuthTokenRevokeNonRememberedLogout = 5;
|
||||||
|
k_EAuthTokenRevokeNonRememberedPermanent = 6;
|
||||||
|
k_EAuthTokenRevokeAutomatic = 7;
|
||||||
}
|
}
|
||||||
|
|
||||||
enum EAuthTokenState {
|
enum EAuthTokenState {
|
||||||
|
@ -62,6 +70,8 @@ message CAuthentication_DeviceDetails {
|
||||||
optional .EAuthTokenPlatformType platform_type = 2 [default = k_EAuthTokenPlatformType_Unknown, (description) = "EAuthTokenPlatformType, claimed, 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 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 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 {
|
message CAuthentication_BeginAuthSessionViaQR_Request {
|
||||||
|
@ -173,10 +183,12 @@ message CAuthentication_UpdateAuthSessionWithSteamGuardCode_Response {
|
||||||
message CAuthentication_AccessToken_GenerateForApp_Request {
|
message CAuthentication_AccessToken_GenerateForApp_Request {
|
||||||
optional string refresh_token = 1;
|
optional string refresh_token = 1;
|
||||||
optional fixed64 steamid = 2;
|
optional fixed64 steamid = 2;
|
||||||
|
optional .ETokenRenewalType renewal_type = 3 [default = k_ETokenRenewalType_None];
|
||||||
}
|
}
|
||||||
|
|
||||||
message CAuthentication_AccessToken_GenerateForApp_Response {
|
message CAuthentication_AccessToken_GenerateForApp_Response {
|
||||||
optional string access_token = 1;
|
optional string access_token = 1;
|
||||||
|
optional string refresh_token = 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
message CAuthentication_RefreshToken_Enumerate_Request {
|
message CAuthentication_RefreshToken_Enumerate_Request {
|
||||||
|
@ -228,6 +240,14 @@ message CAuthentication_MigrateMobileSession_Response {
|
||||||
optional string access_token = 2;
|
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 {
|
message CAuthentication_RefreshToken_Revoke_Request {
|
||||||
optional fixed64 token_id = 1;
|
optional fixed64 token_id = 1;
|
||||||
optional fixed64 steamid = 2 [(description) = "Token holder if an admin action on behalf of another user"];
|
optional fixed64 steamid = 2 [(description) = "Token holder if an admin action on behalf of another user"];
|
||||||
|
@ -373,6 +393,10 @@ service Authentication {
|
||||||
option (method_description) = "Migrates a WG token to an access and refresh token using a signature generated with the user's 2FA secret";
|
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) {
|
rpc RevokeRefreshToken (.CAuthentication_RefreshToken_Revoke_Request) returns (.CAuthentication_RefreshToken_Revoke_Response) {
|
||||||
option (method_description) = "Mark the given refresh token as revoked";
|
option (method_description) = "Mark the given refresh token as revoked";
|
||||||
}
|
}
|
||||||
|
|
|
@ -92,6 +92,11 @@ message CMsgGCRoutingProtoBufHeader {
|
||||||
}
|
}
|
||||||
|
|
||||||
message CMsgProtoBufHeader {
|
message CMsgProtoBufHeader {
|
||||||
|
enum ESessionDisposition {
|
||||||
|
k_ESessionDispositionNormal = 0;
|
||||||
|
k_ESessionDispositionDisconnect = 1;
|
||||||
|
}
|
||||||
|
|
||||||
optional fixed64 steamid = 1;
|
optional fixed64 steamid = 1;
|
||||||
optional int32 client_sessionid = 2;
|
optional int32 client_sessionid = 2;
|
||||||
optional uint32 routing_appid = 3;
|
optional uint32 routing_appid = 3;
|
||||||
|
@ -120,6 +125,10 @@ message CMsgProtoBufHeader {
|
||||||
optional uint32 debug_source_string_index = 35;
|
optional uint32 debug_source_string_index = 35;
|
||||||
optional uint64 token_id = 36;
|
optional uint64 token_id = 36;
|
||||||
optional .CMsgGCRoutingProtoBufHeader routing_gc = 37;
|
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 {
|
oneof ip_addr {
|
||||||
uint32 ip = 15;
|
uint32 ip = 15;
|
||||||
|
@ -145,6 +154,7 @@ message CMsgAuthTicket {
|
||||||
optional uint32 ticket_crc = 6;
|
optional uint32 ticket_crc = 6;
|
||||||
optional bytes ticket = 7;
|
optional bytes ticket = 7;
|
||||||
optional bytes server_secret = 8;
|
optional bytes server_secret = 8;
|
||||||
|
optional uint32 ticket_type = 9;
|
||||||
}
|
}
|
||||||
|
|
||||||
message CCDDBAppDetailCommon {
|
message CCDDBAppDetailCommon {
|
||||||
|
@ -302,6 +312,8 @@ message CPackageReservationStatus {
|
||||||
optional bool expired = 6;
|
optional bool expired = 6;
|
||||||
optional uint32 time_expires = 7;
|
optional uint32 time_expires = 7;
|
||||||
optional uint32 time_reserved = 8;
|
optional uint32 time_reserved = 8;
|
||||||
|
optional uint32 rtime_estimated_notification = 9;
|
||||||
|
optional string notificaton_token = 10;
|
||||||
}
|
}
|
||||||
|
|
||||||
message CMsgKeyValuePair {
|
message CMsgKeyValuePair {
|
||||||
|
@ -312,3 +324,12 @@ message CMsgKeyValuePair {
|
||||||
message CMsgKeyValueSet {
|
message CMsgKeyValueSet {
|
||||||
repeated .CMsgKeyValuePair pairs = 1;
|
repeated .CMsgKeyValuePair pairs = 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
message UserContentDescriptorPreferences {
|
||||||
|
message ContentDescriptor {
|
||||||
|
optional uint32 content_descriptorid = 1;
|
||||||
|
optional uint32 timestamp_added = 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
repeated .UserContentDescriptorPreferences.ContentDescriptor content_descriptors_to_exclude = 1;
|
||||||
|
}
|
||||||
|
|
|
@ -99,11 +99,11 @@ message CMsgClientLogonResponse {
|
||||||
optional string email_domain = 8;
|
optional string email_domain = 8;
|
||||||
optional bytes steam2_ticket = 9;
|
optional bytes steam2_ticket = 9;
|
||||||
optional int32 eresult_extended = 10;
|
optional int32 eresult_extended = 10;
|
||||||
optional string webapi_authenticate_user_nonce = 11;
|
|
||||||
optional uint32 cell_id_ping_threshold = 12;
|
optional uint32 cell_id_ping_threshold = 12;
|
||||||
optional bool deprecated_use_pics = 13;
|
optional bool deprecated_use_pics = 13;
|
||||||
optional string vanity_url = 14;
|
optional string vanity_url = 14;
|
||||||
optional .CMsgIPAddress public_ip = 15;
|
optional .CMsgIPAddress public_ip = 15;
|
||||||
|
optional string user_country = 16;
|
||||||
optional fixed64 client_supplied_steamid = 20;
|
optional fixed64 client_supplied_steamid = 20;
|
||||||
optional string ip_country_code = 21;
|
optional string ip_country_code = 21;
|
||||||
optional bytes parental_settings = 22;
|
optional bytes parental_settings = 22;
|
||||||
|
|
|
@ -1,60 +1,54 @@
|
||||||
use crate::protobufs::service_twofactor::{
|
use crate::protobufs::service_twofactor::{
|
||||||
CTwoFactor_AddAuthenticator_Request, CTwoFactor_FinalizeAddAuthenticator_Request,
|
CTwoFactor_AddAuthenticator_Request, CTwoFactor_FinalizeAddAuthenticator_Request,
|
||||||
|
CTwoFactor_RemoveAuthenticatorViaChallengeContinue_Request,
|
||||||
|
CTwoFactor_RemoveAuthenticatorViaChallengeStart_Request,
|
||||||
|
CTwoFactor_RemoveAuthenticator_Request, CTwoFactor_Status_Request, CTwoFactor_Status_Response,
|
||||||
};
|
};
|
||||||
use crate::steamapi::twofactor::TwoFactorClient;
|
use crate::steamapi::twofactor::TwoFactorClient;
|
||||||
use crate::token::TwoFactorSecret;
|
use crate::token::TwoFactorSecret;
|
||||||
use crate::transport::WebApiTransport;
|
use crate::transport::{Transport, TransportError};
|
||||||
use crate::{steamapi::EResult, token::Tokens, SteamGuardAccount};
|
use crate::{steamapi::EResult, token::Tokens, SteamGuardAccount};
|
||||||
|
use anyhow::Context;
|
||||||
|
use base64::Engine;
|
||||||
use log::*;
|
use log::*;
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct AccountLinker {
|
pub struct AccountLinker<T>
|
||||||
|
where
|
||||||
|
T: Transport,
|
||||||
|
{
|
||||||
device_id: String,
|
device_id: String,
|
||||||
pub phone_number: String,
|
|
||||||
pub account: Option<SteamGuardAccount>,
|
pub account: Option<SteamGuardAccount>,
|
||||||
pub finalized: bool,
|
pub finalized: bool,
|
||||||
tokens: Tokens,
|
tokens: Tokens,
|
||||||
client: TwoFactorClient<WebApiTransport>,
|
client: TwoFactorClient<T>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AccountLinker {
|
impl<T> AccountLinker<T>
|
||||||
pub fn new(tokens: Tokens) -> AccountLinker {
|
where
|
||||||
|
T: Transport,
|
||||||
|
{
|
||||||
|
pub fn new(transport: T, tokens: Tokens) -> Self {
|
||||||
Self {
|
Self {
|
||||||
device_id: generate_device_id(),
|
device_id: generate_device_id(),
|
||||||
phone_number: "".into(),
|
|
||||||
account: None,
|
account: None,
|
||||||
finalized: false,
|
finalized: false,
|
||||||
tokens,
|
tokens,
|
||||||
client: TwoFactorClient::new(WebApiTransport::new()),
|
client: TwoFactorClient::new(transport),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn tokens(&self) -> &Tokens {
|
||||||
|
&self.tokens
|
||||||
|
}
|
||||||
|
|
||||||
pub fn link(&mut self) -> anyhow::Result<AccountLinkSuccess, AccountLinkError> {
|
pub fn link(&mut self) -> anyhow::Result<AccountLinkSuccess, AccountLinkError> {
|
||||||
// let has_phone = self.client.has_phone()?;
|
|
||||||
|
|
||||||
// if has_phone && !self.phone_number.is_empty() {
|
|
||||||
// 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 access_token = self.tokens.access_token();
|
let access_token = self.tokens.access_token();
|
||||||
let steam_id = access_token.decode()?.steam_id();
|
let steam_id = access_token
|
||||||
|
.decode()
|
||||||
|
.context("decoding access token")?
|
||||||
|
.steam_id();
|
||||||
|
|
||||||
let mut req = CTwoFactor_AddAuthenticator_Request::new();
|
let mut req = CTwoFactor_AddAuthenticator_Request::new();
|
||||||
req.set_authenticator_type(1);
|
req.set_authenticator_type(1);
|
||||||
|
@ -62,7 +56,10 @@ impl AccountLinker {
|
||||||
req.set_sms_phone_id("1".to_owned());
|
req.set_sms_phone_id("1".to_owned());
|
||||||
req.set_device_identifier(self.device_id.clone());
|
req.set_device_identifier(self.device_id.clone());
|
||||||
|
|
||||||
let resp = self.client.add_authenticator(req, access_token)?;
|
let resp = self
|
||||||
|
.client
|
||||||
|
.add_authenticator(req, access_token)
|
||||||
|
.context("add authenticator request")?;
|
||||||
|
|
||||||
if resp.result != EResult::OK {
|
if resp.result != EResult::OK {
|
||||||
return Err(resp.result.into());
|
return Err(resp.result.into());
|
||||||
|
@ -78,15 +75,20 @@ impl AccountLinker {
|
||||||
uri: resp.take_uri().into(),
|
uri: resp.take_uri().into(),
|
||||||
shared_secret: TwoFactorSecret::from_bytes(resp.take_shared_secret()),
|
shared_secret: TwoFactorSecret::from_bytes(resp.take_shared_secret()),
|
||||||
token_gid: resp.take_token_gid(),
|
token_gid: resp.take_token_gid(),
|
||||||
identity_secret: base64::encode(resp.take_identity_secret()).into(),
|
identity_secret: base64::engine::general_purpose::STANDARD
|
||||||
|
.encode(resp.take_identity_secret())
|
||||||
|
.into(),
|
||||||
device_id: self.device_id.clone(),
|
device_id: self.device_id.clone(),
|
||||||
secret_1: base64::encode(resp.take_secret_1()).into(),
|
secret_1: base64::engine::general_purpose::STANDARD
|
||||||
|
.encode(resp.take_secret_1())
|
||||||
|
.into(),
|
||||||
tokens: Some(self.tokens.clone()),
|
tokens: Some(self.tokens.clone()),
|
||||||
};
|
};
|
||||||
let success = AccountLinkSuccess {
|
let success = AccountLinkSuccess {
|
||||||
account,
|
account,
|
||||||
server_time: resp.server_time(),
|
server_time: resp.server_time(),
|
||||||
phone_number_hint: resp.take_phone_number_hint(),
|
phone_number_hint: resp.take_phone_number_hint(),
|
||||||
|
confirm_type: resp.confirm_type().into(),
|
||||||
};
|
};
|
||||||
Ok(success)
|
Ok(success)
|
||||||
}
|
}
|
||||||
|
@ -96,7 +98,7 @@ impl AccountLinker {
|
||||||
&mut self,
|
&mut self,
|
||||||
time: u64,
|
time: u64,
|
||||||
account: &mut SteamGuardAccount,
|
account: &mut SteamGuardAccount,
|
||||||
sms_code: String,
|
confirm_code: String,
|
||||||
) -> anyhow::Result<(), FinalizeLinkError> {
|
) -> anyhow::Result<(), FinalizeLinkError> {
|
||||||
let code = account.generate_code(time);
|
let code = account.generate_code(time);
|
||||||
|
|
||||||
|
@ -107,7 +109,8 @@ impl AccountLinker {
|
||||||
req.set_steamid(steam_id);
|
req.set_steamid(steam_id);
|
||||||
req.set_authenticator_code(code);
|
req.set_authenticator_code(code);
|
||||||
req.set_authenticator_time(time);
|
req.set_authenticator_time(time);
|
||||||
req.set_activation_code(sms_code);
|
req.set_activation_code(confirm_code);
|
||||||
|
req.set_validate_sms_code(true);
|
||||||
|
|
||||||
let resp = self.client.finalize_authenticator(req, token)?;
|
let resp = self.client.finalize_authenticator(req, token)?;
|
||||||
|
|
||||||
|
@ -126,6 +129,105 @@ impl AccountLinker {
|
||||||
self.finalized = true;
|
self.finalized = true;
|
||||||
Ok(())
|
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)]
|
#[derive(Debug)]
|
||||||
|
@ -133,6 +235,7 @@ pub struct AccountLinkSuccess {
|
||||||
account: SteamGuardAccount,
|
account: SteamGuardAccount,
|
||||||
server_time: u64,
|
server_time: u64,
|
||||||
phone_number_hint: String,
|
phone_number_hint: String,
|
||||||
|
confirm_type: AccountLinkConfirmType,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AccountLinkSuccess {
|
impl AccountLinkSuccess {
|
||||||
|
@ -151,6 +254,28 @@ impl AccountLinkSuccess {
|
||||||
pub fn phone_number_hint(&self) -> &str {
|
pub fn phone_number_hint(&self) -> &str {
|
||||||
&self.phone_number_hint
|
&self.phone_number_hint
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn confirm_type(&self) -> AccountLinkConfirmType {
|
||||||
|
self.confirm_type
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
#[repr(i32)]
|
||||||
|
pub enum AccountLinkConfirmType {
|
||||||
|
SMS = 1,
|
||||||
|
Email = 3,
|
||||||
|
Unknown(i32),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<i32> for AccountLinkConfirmType {
|
||||||
|
fn from(i: i32) -> Self {
|
||||||
|
match i {
|
||||||
|
1 => AccountLinkConfirmType::SMS,
|
||||||
|
3 => AccountLinkConfirmType::Email,
|
||||||
|
_ => AccountLinkConfirmType::Unknown(i),
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn generate_device_id() -> String {
|
fn generate_device_id() -> String {
|
||||||
|
@ -162,14 +287,13 @@ pub enum AccountLinkError {
|
||||||
/// No phone number on the account
|
/// No phone number on the account
|
||||||
#[error("A phone number is needed, but not already present on the account.")]
|
#[error("A phone number is needed, but not already present on the account.")]
|
||||||
MustProvidePhoneNumber,
|
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
|
/// 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.")]
|
#[error("An email has been sent to the user's email, click the link in that email.")]
|
||||||
MustConfirmEmail,
|
MustConfirmEmail,
|
||||||
#[error("Authenticator is already present.")]
|
#[error("Authenticator is already present on this account.")]
|
||||||
AuthenticatorPresent,
|
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.")]
|
#[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,
|
GenericFailure,
|
||||||
#[error("Steam returned an unexpected error code: {0:?}")]
|
#[error("Steam returned an unexpected error code: {0:?}")]
|
||||||
|
@ -181,10 +305,13 @@ pub enum AccountLinkError {
|
||||||
impl From<EResult> for AccountLinkError {
|
impl From<EResult> for AccountLinkError {
|
||||||
fn from(result: EResult) -> Self {
|
fn from(result: EResult) -> Self {
|
||||||
match result {
|
match result {
|
||||||
|
EResult::RateLimitExceeded => AccountLinkError::RateLimitExceeded,
|
||||||
|
EResult::NoVerifiedPhone => AccountLinkError::MustProvidePhoneNumber,
|
||||||
EResult::DuplicateRequest => AccountLinkError::AuthenticatorPresent,
|
EResult::DuplicateRequest => AccountLinkError::AuthenticatorPresent,
|
||||||
// If the user has no phone number on their account, it will always return this status code.
|
// 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
|
// 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.
|
// 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,
|
EResult::Fail => AccountLinkError::GenericFailure,
|
||||||
r => AccountLinkError::UnknownEResult(r),
|
r => AccountLinkError::UnknownEResult(r),
|
||||||
}
|
}
|
||||||
|
@ -212,3 +339,44 @@ impl From<EResult> for FinalizeLinkError {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum RemoveAuthenticatorError {
|
||||||
|
#[error("Missing revocation code")]
|
||||||
|
MissingRevocationCode,
|
||||||
|
#[error("Incorrect revocation code, {attempts_remaining} attempts remaining")]
|
||||||
|
IncorrectRevocationCode { attempts_remaining: u32 },
|
||||||
|
#[error("Transport error: {0}")]
|
||||||
|
TransportError(#[from] TransportError),
|
||||||
|
#[error("Steam returned an enexpected result: {0:?}")]
|
||||||
|
UnknownEResult(EResult),
|
||||||
|
#[error("Unexpected error: {0}")]
|
||||||
|
Unknown(#[from] anyhow::Error),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<EResult> for RemoveAuthenticatorError {
|
||||||
|
fn from(e: EResult) -> Self {
|
||||||
|
Self::UnknownEResult(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Error, Debug)]
|
||||||
|
pub enum TransferError {
|
||||||
|
#[error("Provided SMS code was incorrect.")]
|
||||||
|
BadSmsCode,
|
||||||
|
#[error("Failed to send request to Steam: {0:?}")]
|
||||||
|
Transport(#[from] crate::transport::TransportError),
|
||||||
|
#[error("Steam returned an unexpected error code: {0:?}")]
|
||||||
|
UnknownEResult(EResult),
|
||||||
|
#[error(transparent)]
|
||||||
|
Unknown(#[from] anyhow::Error),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<EResult> for TransferError {
|
||||||
|
fn from(result: EResult) -> Self {
|
||||||
|
match result {
|
||||||
|
EResult::SMSCodeFailed => TransferError::BadSmsCode,
|
||||||
|
r => TransferError::UnknownEResult(r),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize)]
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
#[allow(dead_code)]
|
||||||
pub struct OAuthData {
|
pub struct OAuthData {
|
||||||
pub oauth_token: String,
|
pub oauth_token: String,
|
||||||
pub steamid: String,
|
pub steamid: String,
|
||||||
|
|
|
@ -3,5 +3,3 @@ mod login;
|
||||||
mod phone_ajax;
|
mod phone_ajax;
|
||||||
|
|
||||||
pub use i_authentication_service::*;
|
pub use i_authentication_service::*;
|
||||||
pub use login::*;
|
|
||||||
pub use phone_ajax::*;
|
|
||||||
|
|
|
@ -1,4 +1,340 @@
|
||||||
|
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 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.
|
/// A mobile confirmation. There are multiple things that can be confirmed, like trade offers.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||||
|
@ -13,7 +349,7 @@ pub struct Confirmation {
|
||||||
pub creation_time: u64,
|
pub creation_time: u64,
|
||||||
pub cancel: String,
|
pub cancel: String,
|
||||||
pub accept: String,
|
pub accept: String,
|
||||||
pub icon: String,
|
pub icon: Option<String>,
|
||||||
pub multi: bool,
|
pub multi: bool,
|
||||||
pub headline: String,
|
pub headline: String,
|
||||||
pub summary: Vec<String>,
|
pub summary: Vec<String>,
|
||||||
|
@ -31,38 +367,65 @@ impl Confirmation {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, num_enum::FromPrimitive)]
|
||||||
#[repr(u32)]
|
#[repr(u32)]
|
||||||
#[serde(from = "u32")]
|
#[serde(from = "u32")]
|
||||||
|
/// Source: https://github.com/SteamDatabase/SteamTracking/blob/6e7797e69b714c59f4b5784780b24753c17732ba/Structs/enums.steamd#L1607-L1616
|
||||||
|
/// There are also some additional undocumented types.
|
||||||
pub enum ConfirmationType {
|
pub enum ConfirmationType {
|
||||||
Generic = 1,
|
Test = 1,
|
||||||
|
/// Occurs when sending a trade offer or accepting a received trade offer, only when there is items on the user's side
|
||||||
Trade = 2,
|
Trade = 2,
|
||||||
|
/// Occurs when selling an item on the Steam community market
|
||||||
MarketSell = 3,
|
MarketSell = 3,
|
||||||
|
FeatureOptOut = 4,
|
||||||
|
/// Occurs when changing the phone number associated with the account
|
||||||
|
PhoneNumberChange = 5,
|
||||||
AccountRecovery = 6,
|
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(u32),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<u32> for ConfirmationType {
|
|
||||||
fn from(text: u32) -> Self {
|
|
||||||
match text {
|
|
||||||
1 => ConfirmationType::Generic,
|
|
||||||
2 => ConfirmationType::Trade,
|
|
||||||
3 => ConfirmationType::MarketSell,
|
|
||||||
6 => ConfirmationType::AccountRecovery,
|
|
||||||
v => ConfirmationType::Unknown(v),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize)]
|
||||||
pub struct ConfirmationListResponse {
|
pub struct ConfirmationListResponse {
|
||||||
pub success: bool,
|
pub success: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
pub needauth: Option<bool>,
|
||||||
|
#[serde(default)]
|
||||||
pub conf: Vec<Confirmation>,
|
pub conf: Vec<Confirmation>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub message: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, Deserialize)]
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
pub struct SendConfirmationResponse {
|
pub struct SendConfirmationResponse {
|
||||||
pub success: bool,
|
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)]
|
#[cfg(test)]
|
||||||
|
@ -70,16 +433,57 @@ mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_parse_email_change() -> anyhow::Result<()> {
|
fn test_parse_confirmations() -> anyhow::Result<()> {
|
||||||
let text = include_str!("fixtures/confirmations/email-change.json");
|
struct Test {
|
||||||
let confirmations = serde_json::from_str::<ConfirmationListResponse>(text)?;
|
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);
|
assert_eq!(confirmations.conf.len(), 1);
|
||||||
|
|
||||||
let confirmation = &confirmations.conf[0];
|
let confirmation = &confirmations.conf[0];
|
||||||
|
|
||||||
assert_eq!(confirmation.conf_type, ConfirmationType::AccountRecovery);
|
assert_eq!(confirmation.conf_type, case.confirmation_type);
|
||||||
|
}
|
||||||
|
|
||||||
Ok(())
|
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=")
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
4
steamguard/src/fixtures/confirmations/need-auth.json
Normal file
4
steamguard/src/fixtures/confirmations/need-auth.json
Normal file
|
@ -0,0 +1,4 @@
|
||||||
|
{
|
||||||
|
"success": false,
|
||||||
|
"needauth": true
|
||||||
|
}
|
|
@ -0,0 +1,22 @@
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"conf": [
|
||||||
|
{
|
||||||
|
"type": 5,
|
||||||
|
"type_name": "Account details",
|
||||||
|
"id": "13831364158",
|
||||||
|
"creator_id": "4486196268090979848",
|
||||||
|
"nonce": "11118003665658287603",
|
||||||
|
"creation_time": 1687821676,
|
||||||
|
"cancel": "Cancel",
|
||||||
|
"accept": "Confirm",
|
||||||
|
"icon": null,
|
||||||
|
"multi": false,
|
||||||
|
"headline": "Change phone number",
|
||||||
|
"summary": [
|
||||||
|
""
|
||||||
|
],
|
||||||
|
"warn": null
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
|
@ -1,23 +1,13 @@
|
||||||
use crate::confirmation::{ConfirmationListResponse, SendConfirmationResponse};
|
use crate::token::TwoFactorSecret;
|
||||||
use crate::protobufs::service_twofactor::CTwoFactor_RemoveAuthenticator_Request;
|
use accountlinker::RemoveAuthenticatorError;
|
||||||
use crate::steamapi::EResult;
|
|
||||||
use crate::{
|
|
||||||
steamapi::twofactor::TwoFactorClient, token::TwoFactorSecret, transport::WebApiTransport,
|
|
||||||
};
|
|
||||||
pub use accountlinker::{AccountLinkError, AccountLinker, FinalizeLinkError};
|
pub use accountlinker::{AccountLinkError, AccountLinker, FinalizeLinkError};
|
||||||
use anyhow::Result;
|
pub use confirmation::*;
|
||||||
pub use confirmation::{Confirmation, ConfirmationType};
|
pub use qrapprover::{QrApprover, QrApproverError};
|
||||||
use hmacsha1::hmac_sha1;
|
|
||||||
use log::*;
|
|
||||||
use reqwest::{
|
|
||||||
cookie::CookieStore,
|
|
||||||
header::{COOKIE, USER_AGENT},
|
|
||||||
Url,
|
|
||||||
};
|
|
||||||
pub use secrecy::{ExposeSecret, SecretString};
|
pub use secrecy::{ExposeSecret, SecretString};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::{collections::HashMap, io::Read};
|
use std::io::Read;
|
||||||
use token::Tokens;
|
use token::Tokens;
|
||||||
|
use transport::{Transport, TransportError};
|
||||||
pub use userlogin::{DeviceDetails, LoginError, UserLogin};
|
pub use userlogin::{DeviceDetails, LoginError, UserLogin};
|
||||||
|
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
|
@ -29,7 +19,10 @@ extern crate maplit;
|
||||||
pub mod accountlinker;
|
pub mod accountlinker;
|
||||||
mod api_responses;
|
mod api_responses;
|
||||||
mod confirmation;
|
mod confirmation;
|
||||||
|
pub mod phonelinker;
|
||||||
pub mod protobufs;
|
pub mod protobufs;
|
||||||
|
mod qrapprover;
|
||||||
|
pub mod refresher;
|
||||||
mod secret_string;
|
mod secret_string;
|
||||||
pub mod steamapi;
|
pub mod steamapi;
|
||||||
pub mod token;
|
pub mod token;
|
||||||
|
@ -38,7 +31,6 @@ pub mod userlogin;
|
||||||
|
|
||||||
extern crate base64;
|
extern crate base64;
|
||||||
extern crate cookie;
|
extern crate cookie;
|
||||||
extern crate hmacsha1;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct SteamGuardAccount {
|
pub struct SteamGuardAccount {
|
||||||
|
@ -59,23 +51,6 @@ pub struct SteamGuardAccount {
|
||||||
pub tokens: Option<Tokens>,
|
pub tokens: Option<Tokens>,
|
||||||
}
|
}
|
||||||
|
|
||||||
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::decode(identity_secret).unwrap();
|
|
||||||
let time_bytes = build_time_bytes(time);
|
|
||||||
let tag_bytes = tag.as_bytes();
|
|
||||||
let array = [&time_bytes, tag_bytes].concat();
|
|
||||||
let hash = hmac_sha1(decode, &array);
|
|
||||||
base64::encode(hash)
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for SteamGuardAccount {
|
impl Default for SteamGuardAccount {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
|
@ -118,185 +93,23 @@ impl SteamGuardAccount {
|
||||||
self.shared_secret.generate_code(time)
|
self.shared_secret.generate_code(time)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_confirmation_query_params(&self, tag: &str, time: u64) -> HashMap<&str, String> {
|
|
||||||
let mut params = HashMap::new();
|
|
||||||
params.insert("p", self.device_id.clone());
|
|
||||||
params.insert("a", self.steam_id.to_string());
|
|
||||||
params.insert(
|
|
||||||
"k",
|
|
||||||
generate_confirmation_hash_for_time(time, tag, self.identity_secret.expose_secret()),
|
|
||||||
);
|
|
||||||
params.insert("t", time.to_string());
|
|
||||||
params.insert("m", String::from("android"));
|
|
||||||
params.insert("tag", String::from(tag));
|
|
||||||
params
|
|
||||||
}
|
|
||||||
|
|
||||||
fn build_cookie_jar(&self) -> reqwest::cookie::Jar {
|
|
||||||
let url = "https://steamcommunity.com".parse::<Url>().unwrap();
|
|
||||||
let cookies = reqwest::cookie::Jar::default();
|
|
||||||
// let session = self.session.as_ref().unwrap().expose_secret();
|
|
||||||
let tokens = self.tokens.as_ref().unwrap();
|
|
||||||
cookies.add_cookie_str("mobileClientVersion=0 (2.1.3)", &url);
|
|
||||||
cookies.add_cookie_str("mobileClient=android", &url);
|
|
||||||
cookies.add_cookie_str("Steam_Language=english", &url);
|
|
||||||
cookies.add_cookie_str("dob=", &url);
|
|
||||||
// cookies.add_cookie_str(format!("sessionid={}", session.session_id).as_str(), &url);
|
|
||||||
cookies.add_cookie_str(format!("steamid={}", self.steam_id).as_str(), &url);
|
|
||||||
cookies.add_cookie_str(
|
|
||||||
format!(
|
|
||||||
"steamLoginSecure={}||{}",
|
|
||||||
self.steam_id,
|
|
||||||
tokens.access_token().expose_secret()
|
|
||||||
)
|
|
||||||
.as_str(),
|
|
||||||
&url,
|
|
||||||
);
|
|
||||||
cookies
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_trade_confirmations(&self) -> Result<Vec<Confirmation>, anyhow::Error> {
|
|
||||||
// uri: "https://steamcommunity.com/mobileconf/conf"
|
|
||||||
// confirmation details:
|
|
||||||
let url = "https://steamcommunity.com".parse::<Url>().unwrap();
|
|
||||||
let cookies = self.build_cookie_jar();
|
|
||||||
let client = reqwest::blocking::ClientBuilder::new()
|
|
||||||
.cookie_store(true)
|
|
||||||
.build()?;
|
|
||||||
|
|
||||||
let time = steamapi::get_server_time()?.server_time();
|
|
||||||
let resp = client
|
|
||||||
.get("https://steamcommunity.com/mobileconf/getlist".parse::<Url>().unwrap())
|
|
||||||
.header("X-Requested-With", "com.valvesoftware.android.steam.community")
|
|
||||||
.header(USER_AGENT, "Mozilla/5.0 (Linux; U; Android 4.1.1; en-us; Google Nexus 4 - 4.1.1 - API 16 - 768x1280 Build/JRO03S) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30")
|
|
||||||
.header(COOKIE, cookies.cookies(&url).unwrap())
|
|
||||||
.query(&self.get_confirmation_query_params("conf", time))
|
|
||||||
.send()?;
|
|
||||||
|
|
||||||
trace!("{:?}", resp);
|
|
||||||
let text = resp.text().unwrap();
|
|
||||||
trace!("text: {:?}", text);
|
|
||||||
trace!("{}", text);
|
|
||||||
|
|
||||||
let body: ConfirmationListResponse = serde_json::from_str(text.as_str())?;
|
|
||||||
ensure!(body.success);
|
|
||||||
Ok(body.conf)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Respond to a confirmation.
|
|
||||||
///
|
|
||||||
/// Host: https://steamcommunity.com
|
|
||||||
/// Steam Endpoint: `GET /mobileconf/ajaxop`
|
|
||||||
fn send_confirmation_ajax(&self, conf: &Confirmation, operation: String) -> anyhow::Result<()> {
|
|
||||||
ensure!(operation == "allow" || operation == "cancel");
|
|
||||||
|
|
||||||
let url = "https://steamcommunity.com".parse::<Url>().unwrap();
|
|
||||||
let cookies = self.build_cookie_jar();
|
|
||||||
let client = reqwest::blocking::ClientBuilder::new()
|
|
||||||
.cookie_store(true)
|
|
||||||
.build()?;
|
|
||||||
|
|
||||||
let time = steamapi::get_server_time()?.server_time();
|
|
||||||
let mut query_params = self.get_confirmation_query_params("conf", time);
|
|
||||||
query_params.insert("op", operation);
|
|
||||||
query_params.insert("cid", conf.id.to_string());
|
|
||||||
query_params.insert("ck", conf.nonce.to_string());
|
|
||||||
|
|
||||||
let resp = client.get("https://steamcommunity.com/mobileconf/ajaxop".parse::<Url>().unwrap())
|
|
||||||
.header("X-Requested-With", "com.valvesoftware.android.steam.community")
|
|
||||||
.header(USER_AGENT, "Mozilla/5.0 (Linux; U; Android 4.1.1; en-us; Google Nexus 4 - 4.1.1 - API 16 - 768x1280 Build/JRO03S) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30")
|
|
||||||
.header(COOKIE, cookies.cookies(&url).unwrap())
|
|
||||||
.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 body: SendConfirmationResponse = serde_json::from_str(raw.as_str())?;
|
|
||||||
|
|
||||||
if !body.success {
|
|
||||||
return Err(anyhow!("Server responded with failure."));
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn accept_confirmation(&self, conf: &Confirmation) -> anyhow::Result<()> {
|
|
||||||
self.send_confirmation_ajax(conf, "allow".into())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn deny_confirmation(&self, conf: &Confirmation) -> anyhow::Result<()> {
|
|
||||||
self.send_confirmation_ajax(conf, "cancel".into())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 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 url = "https://steamcommunity.com".parse::<Url>().unwrap();
|
|
||||||
let cookies = self.build_cookie_jar();
|
|
||||||
let client = reqwest::blocking::ClientBuilder::new()
|
|
||||||
.cookie_store(true)
|
|
||||||
.build()?;
|
|
||||||
|
|
||||||
let time = steamapi::get_server_time()?.server_time();
|
|
||||||
let query_params = self.get_confirmation_query_params("details", time);
|
|
||||||
|
|
||||||
let resp: ConfirmationDetailsResponse = client.get(format!("https://steamcommunity.com/mobileconf/details/{}", conf.id).parse::<Url>().unwrap())
|
|
||||||
.header("X-Requested-With", "com.valvesoftware.android.steam.community")
|
|
||||||
.header(USER_AGENT, "Mozilla/5.0 (Linux; U; Android 4.1.1; en-us; Google Nexus 4 - 4.1.1 - API 16 - 768x1280 Build/JRO03S) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30")
|
|
||||||
.header(COOKIE, cookies.cookies(&url).unwrap())
|
|
||||||
.query(&query_params)
|
|
||||||
.send()?
|
|
||||||
.json()?;
|
|
||||||
|
|
||||||
ensure!(resp.success);
|
|
||||||
Ok(resp.html)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Removes the mobile authenticator from the steam account. If this operation succeeds, this object can no longer be considered valid.
|
/// Removes the mobile authenticator from the steam account. If this operation succeeds, this object can no longer be considered valid.
|
||||||
/// Returns whether or not the operation was successful.
|
/// Returns whether or not the operation was successful.
|
||||||
pub fn remove_authenticator(&self, revocation_code: Option<String>) -> anyhow::Result<bool> {
|
///
|
||||||
ensure!(
|
/// A convenience method for [`AccountLinker::remove_authenticator`].
|
||||||
matches!(revocation_code, Some(_)) || !self.revocation_code.expose_secret().is_empty(),
|
pub fn remove_authenticator(
|
||||||
"Revocation code not provided."
|
&self,
|
||||||
);
|
transport: impl Transport,
|
||||||
|
revocation_code: Option<&String>,
|
||||||
|
) -> Result<(), RemoveAuthenticatorError> {
|
||||||
let Some(tokens) = &self.tokens else {
|
let Some(tokens) = &self.tokens else {
|
||||||
return Err(anyhow!("Tokens not set, login required"));
|
return Err(RemoveAuthenticatorError::TransportError(
|
||||||
|
TransportError::Unauthorized,
|
||||||
|
));
|
||||||
};
|
};
|
||||||
let mut client = TwoFactorClient::new(WebApiTransport::new());
|
let revocation_code =
|
||||||
let mut req = CTwoFactor_RemoveAuthenticator_Request::new();
|
Some(revocation_code.unwrap_or_else(|| self.revocation_code.expose_secret()));
|
||||||
req.set_revocation_code(
|
let linker = AccountLinker::new(transport, tokens.clone());
|
||||||
revocation_code.unwrap_or(self.revocation_code.expose_secret().to_owned()),
|
linker.remove_authenticator(revocation_code)
|
||||||
);
|
|
||||||
let resp = client.remove_authenticator(req, tokens.access_token())?;
|
|
||||||
if resp.result != EResult::OK {
|
|
||||||
Err(anyhow!("Failed to remove authenticator: {:?}", resp.result))
|
|
||||||
} else {
|
|
||||||
Ok(true)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_generate_confirmation_hash_for_time() {
|
|
||||||
assert_eq!(
|
|
||||||
generate_confirmation_hash_for_time(1617591917, "conf", "GQP46b73Ws7gr8GmZFR0sDuau5c="),
|
|
||||||
String::from("NaL8EIMhfy/7vBounJ0CvpKbrPk=")
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
171
steamguard/src/phonelinker.rs
Normal file
171
steamguard/src/phonelinker.rs
Normal file
|
@ -0,0 +1,171 @@
|
||||||
|
use crate::protobufs::service_phone::*;
|
||||||
|
use crate::transport::{Transport, TransportError};
|
||||||
|
use crate::{
|
||||||
|
steamapi::{EResult, PhoneClient},
|
||||||
|
token::Tokens,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub use phonenumber::PhoneNumber;
|
||||||
|
|
||||||
|
pub struct PhoneLinker<T>
|
||||||
|
where
|
||||||
|
T: Transport,
|
||||||
|
{
|
||||||
|
client: PhoneClient<T>,
|
||||||
|
tokens: Tokens,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> PhoneLinker<T>
|
||||||
|
where
|
||||||
|
T: Transport,
|
||||||
|
{
|
||||||
|
pub fn new(client: PhoneClient<T>, tokens: Tokens) -> Self {
|
||||||
|
Self { client, tokens }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// If successful, wait for the user to click the link in the email, then immediately call [`send_phone_verification_code`].
|
||||||
|
pub fn set_account_phone_number(
|
||||||
|
&self,
|
||||||
|
phone_number: PhoneNumber,
|
||||||
|
) -> Result<SetAccountPhoneNumberResponse, SetPhoneNumberError> {
|
||||||
|
// This results in an email being sent to the account's email address with a link to click on to confirm the phone number.
|
||||||
|
// This endpoint also does almost no validation of the phone number. It only validates it after the user clicks the link.
|
||||||
|
|
||||||
|
// `phone_number` needs to include the country code in the format `11234567890`
|
||||||
|
|
||||||
|
let mut req = CPhone_SetAccountPhoneNumber_Request::new();
|
||||||
|
req.set_phone_number(
|
||||||
|
phone_number
|
||||||
|
.format()
|
||||||
|
.mode(phonenumber::Mode::E164)
|
||||||
|
.to_string(),
|
||||||
|
);
|
||||||
|
req.set_phone_country_code(phone_number.code().value().to_string());
|
||||||
|
|
||||||
|
let resp = self
|
||||||
|
.client
|
||||||
|
.set_account_phone_number(req, self.tokens.access_token())?;
|
||||||
|
|
||||||
|
if resp.result != EResult::Pending {
|
||||||
|
return Err(SetPhoneNumberError::UnknownEResult(resp.result));
|
||||||
|
}
|
||||||
|
|
||||||
|
let resp = resp.into_response_data();
|
||||||
|
Ok(resp.into())
|
||||||
|
}
|
||||||
|
|
||||||
|
// confirm_add_phone_to_account is actually not needed, because it's performed by the user clicking the link in the email.
|
||||||
|
|
||||||
|
/// language 0 is english
|
||||||
|
pub fn send_phone_verification_code(&self, language: u32) -> anyhow::Result<()> {
|
||||||
|
let mut req = CPhone_SendPhoneVerificationCode_Request::new();
|
||||||
|
req.set_language(language);
|
||||||
|
|
||||||
|
let resp = self
|
||||||
|
.client
|
||||||
|
.send_phone_verification_code(req, self.tokens.access_token())?;
|
||||||
|
|
||||||
|
if resp.result != EResult::OK {
|
||||||
|
return Err(anyhow::anyhow!(
|
||||||
|
"Failed to send phone verification code: {:?}",
|
||||||
|
resp.result
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn verify_account_phone_with_code(
|
||||||
|
&self,
|
||||||
|
code: String,
|
||||||
|
) -> anyhow::Result<(), VerifyPhoneError> {
|
||||||
|
let mut req = CPhone_VerifyAccountPhoneWithCode_Request::new();
|
||||||
|
req.set_code(code);
|
||||||
|
|
||||||
|
let resp = self
|
||||||
|
.client
|
||||||
|
.verify_account_phone_with_code(req, self.tokens.access_token())?;
|
||||||
|
|
||||||
|
if resp.result != EResult::OK {
|
||||||
|
return Err(resp.result.into());
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// If true, returns `Some` with the value inside being the time in seconds until the email expires.
|
||||||
|
pub fn is_account_waiting_for_email_confirmation(&self) -> anyhow::Result<Option<u32>> {
|
||||||
|
let req = CPhone_IsAccountWaitingForEmailConfirmation_Request::new();
|
||||||
|
|
||||||
|
let resp = self
|
||||||
|
.client
|
||||||
|
.is_account_waiting_for_email_confirmation(req, self.tokens.access_token())?;
|
||||||
|
|
||||||
|
if resp.result != EResult::OK {
|
||||||
|
return Err(anyhow::anyhow!(
|
||||||
|
"Failed to check if account is waiting for email confirmation: {:?}",
|
||||||
|
resp.result
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
let resp = resp.into_response_data();
|
||||||
|
if !resp.awaiting_email_confirmation() {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(resp.seconds_to_wait)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum SetPhoneNumberError {
|
||||||
|
#[error("Transport error: {0}")]
|
||||||
|
TransportError(#[from] TransportError),
|
||||||
|
#[error("Steam says: {0:?}")]
|
||||||
|
UnknownEResult(EResult),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<EResult> for SetPhoneNumberError {
|
||||||
|
fn from(result: EResult) -> Self {
|
||||||
|
SetPhoneNumberError::UnknownEResult(result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct SetAccountPhoneNumberResponse {
|
||||||
|
confirmation_email_address: String,
|
||||||
|
phone_number_formatted: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SetAccountPhoneNumberResponse {
|
||||||
|
pub fn confirmation_email_address(&self) -> &str {
|
||||||
|
&self.confirmation_email_address
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn phone_number_formatted(&self) -> &str {
|
||||||
|
&self.phone_number_formatted
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<CPhone_SetAccountPhoneNumber_Response> for SetAccountPhoneNumberResponse {
|
||||||
|
fn from(mut resp: CPhone_SetAccountPhoneNumber_Response) -> Self {
|
||||||
|
Self {
|
||||||
|
confirmation_email_address: resp.take_confirmation_email_address(),
|
||||||
|
phone_number_formatted: resp.take_phone_number_formatted(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum VerifyPhoneError {
|
||||||
|
#[error("Transport error: {0}")]
|
||||||
|
TransportError(#[from] TransportError),
|
||||||
|
#[error("Steam says: {0:?}")]
|
||||||
|
UnknownEResult(EResult),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<EResult> for VerifyPhoneError {
|
||||||
|
fn from(result: EResult) -> Self {
|
||||||
|
VerifyPhoneError::UnknownEResult(result)
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,7 +1,30 @@
|
||||||
|
use zeroize::Zeroize;
|
||||||
|
|
||||||
|
use self::steammessages_base::{cmsg_ipaddress::Ip, cmsg_proto_buf_header::Ip_addr};
|
||||||
|
|
||||||
include!(concat!(env!("OUT_DIR"), "/protobufs/mod.rs"));
|
include!(concat!(env!("OUT_DIR"), "/protobufs/mod.rs"));
|
||||||
|
|
||||||
|
impl Zeroize for Ip {
|
||||||
|
fn zeroize(&mut self) {
|
||||||
|
match self {
|
||||||
|
Ip::V4(ip) => ip.zeroize(),
|
||||||
|
Ip::V6(ip) => ip.zeroize(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Zeroize for Ip_addr {
|
||||||
|
fn zeroize(&mut self) {
|
||||||
|
match self {
|
||||||
|
Ip_addr::Ip(ip) => ip.zeroize(),
|
||||||
|
Ip_addr::IpV6(ip) => ip.zeroize(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod parse_tests {
|
mod parse_tests {
|
||||||
|
use base64::Engine;
|
||||||
use protobuf::Message;
|
use protobuf::Message;
|
||||||
|
|
||||||
use super::steammessages_auth_steamclient::CAuthentication_GetPasswordRSAPublicKey_Request;
|
use super::steammessages_auth_steamclient::CAuthentication_GetPasswordRSAPublicKey_Request;
|
||||||
|
@ -12,7 +35,7 @@ mod parse_tests {
|
||||||
req.set_account_name("hydrastar2".to_owned());
|
req.set_account_name("hydrastar2".to_owned());
|
||||||
|
|
||||||
let bytes = req.write_to_bytes().unwrap();
|
let bytes = req.write_to_bytes().unwrap();
|
||||||
let s = base64::encode_config(bytes, base64::URL_SAFE);
|
let s = base64::engine::general_purpose::URL_SAFE.encode(bytes);
|
||||||
assert_eq!(s, "CgpoeWRyYXN0YXIy");
|
assert_eq!(s, "CgpoeWRyYXN0YXIy");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
191
steamguard/src/qrapprover.rs
Normal file
191
steamguard/src/qrapprover.rs
Normal file
|
@ -0,0 +1,191 @@
|
||||||
|
use hmac::{Hmac, Mac};
|
||||||
|
use log::debug;
|
||||||
|
use reqwest::IntoUrl;
|
||||||
|
use sha2::Sha256;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
protobufs::steammessages_auth_steamclient::CAuthentication_UpdateAuthSessionWithMobileConfirmation_Request,
|
||||||
|
steamapi::{AuthenticationClient, EResult},
|
||||||
|
token::{Tokens, TwoFactorSecret},
|
||||||
|
transport::Transport,
|
||||||
|
SteamGuardAccount,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// QR code login approver
|
||||||
|
///
|
||||||
|
/// This can be used to approve a login request from another device that is displaying a QR code.
|
||||||
|
pub struct QrApprover<'a, T>
|
||||||
|
where
|
||||||
|
T: Transport,
|
||||||
|
{
|
||||||
|
tokens: &'a Tokens,
|
||||||
|
client: AuthenticationClient<T>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, T> QrApprover<'a, T>
|
||||||
|
where
|
||||||
|
T: Transport,
|
||||||
|
{
|
||||||
|
pub fn new(transport: T, tokens: &'a Tokens) -> Self {
|
||||||
|
let client = AuthenticationClient::new(transport);
|
||||||
|
Self { tokens, client }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Approve a login request from a challenge URL
|
||||||
|
pub fn approve(
|
||||||
|
&mut self,
|
||||||
|
account: &SteamGuardAccount,
|
||||||
|
challenge_url: impl IntoUrl,
|
||||||
|
) -> Result<(), QrApproverError> {
|
||||||
|
debug!("building signature");
|
||||||
|
let challenge = parse_challenge_url(challenge_url)?;
|
||||||
|
let signature = build_signature(&account.shared_secret, account.steam_id, &challenge);
|
||||||
|
|
||||||
|
debug!("approving login");
|
||||||
|
let mut req = CAuthentication_UpdateAuthSessionWithMobileConfirmation_Request::new();
|
||||||
|
req.set_steamid(account.steam_id);
|
||||||
|
req.set_version(challenge.version.into());
|
||||||
|
req.set_client_id(challenge.client_id);
|
||||||
|
req.set_signature(signature.to_vec());
|
||||||
|
req.set_confirm(true);
|
||||||
|
req.set_persistence(
|
||||||
|
crate::protobufs::enums::ESessionPersistence::k_ESessionPersistence_Persistent,
|
||||||
|
);
|
||||||
|
|
||||||
|
let resp = self
|
||||||
|
.client
|
||||||
|
.update_session_with_mobile_confirmation(req, self.tokens.access_token())?;
|
||||||
|
|
||||||
|
if resp.result != EResult::OK {
|
||||||
|
return Err(resp.result.into());
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn build_signature(
|
||||||
|
shared_secret: &TwoFactorSecret,
|
||||||
|
steam_id: u64,
|
||||||
|
challenge: &Challenge,
|
||||||
|
) -> [u8; 32] {
|
||||||
|
let mut mac = Hmac::<Sha256>::new_from_slice(shared_secret.expose_secret()).unwrap();
|
||||||
|
mac.update(&challenge.version.to_le_bytes());
|
||||||
|
mac.update(&challenge.client_id.to_le_bytes());
|
||||||
|
mac.update(&steam_id.to_le_bytes());
|
||||||
|
let result = mac.finalize();
|
||||||
|
result.into_bytes().into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_challenge_url(challenge_url: impl IntoUrl) -> Result<Challenge, QrApproverError> {
|
||||||
|
let url = challenge_url
|
||||||
|
.into_url()
|
||||||
|
.map_err(|_| QrApproverError::InvalidChallengeUrl)?;
|
||||||
|
|
||||||
|
let regex = regex::Regex::new(r"^https?://s.team/q/(\d+)/(\d+)(\?|$)").unwrap();
|
||||||
|
|
||||||
|
let captures = regex
|
||||||
|
.captures(url.as_str())
|
||||||
|
.ok_or(QrApproverError::InvalidChallengeUrl)?;
|
||||||
|
|
||||||
|
let version = captures[1].parse().expect("regex should only match digits");
|
||||||
|
let client_id = captures[2].parse().expect("regex should only match digits");
|
||||||
|
|
||||||
|
Ok(Challenge { version, client_id })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct Challenge {
|
||||||
|
version: u16,
|
||||||
|
client_id: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum QrApproverError {
|
||||||
|
#[error("Invalid challenge URL")]
|
||||||
|
InvalidChallengeUrl,
|
||||||
|
#[error("Steam says that this qr login challege has already been used. Try again with a new QR code.")]
|
||||||
|
DuplicateRequest,
|
||||||
|
#[error("Steam says that this qr login challege has expired. Try again with a new QR code.")]
|
||||||
|
Expired,
|
||||||
|
#[error("Unauthorized")]
|
||||||
|
Unauthorized,
|
||||||
|
#[error("Transport error: {0}")]
|
||||||
|
TransportError(crate::transport::TransportError),
|
||||||
|
#[error("Unknown EResult: {0:?}")]
|
||||||
|
UnknownEResult(EResult),
|
||||||
|
#[error("Unknown error: {0}")]
|
||||||
|
Unknown(anyhow::Error),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<EResult> for QrApproverError {
|
||||||
|
fn from(result: EResult) -> Self {
|
||||||
|
match result {
|
||||||
|
EResult::DuplicateRequest => Self::DuplicateRequest,
|
||||||
|
_ => Self::UnknownEResult(result),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<anyhow::Error> for QrApproverError {
|
||||||
|
fn from(err: anyhow::Error) -> Self {
|
||||||
|
Self::Unknown(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<crate::transport::TransportError> for QrApproverError {
|
||||||
|
fn from(err: crate::transport::TransportError) -> Self {
|
||||||
|
match err {
|
||||||
|
crate::transport::TransportError::Unauthorized => Self::Unauthorized,
|
||||||
|
_ => Self::TransportError(err),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_parse_challenge_url() {
|
||||||
|
let url = "https://s.team/q/1/2372462679780599330";
|
||||||
|
let challenge = parse_challenge_url(url).unwrap();
|
||||||
|
assert_eq!(challenge.version, 1);
|
||||||
|
assert_eq!(challenge.client_id, 2372462679780599330);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_parse_challenge_url_fail() {
|
||||||
|
let urls = [
|
||||||
|
"https://s.team/q/1/asdf",
|
||||||
|
"https://s.team/q/1/123asdf",
|
||||||
|
"https://s.team/q/a/123",
|
||||||
|
"https://s.team/q/123a/123",
|
||||||
|
];
|
||||||
|
for url in urls {
|
||||||
|
let challenge = parse_challenge_url(url);
|
||||||
|
assert!(challenge.is_err(), "url: {}", url);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_build_signature() {
|
||||||
|
let challenge = Challenge {
|
||||||
|
version: 1,
|
||||||
|
client_id: 2372462679780599330,
|
||||||
|
};
|
||||||
|
let secret =
|
||||||
|
TwoFactorSecret::parse_shared_secret("zvIayp3JPvtvX/QGHqsqKBk/44s=".to_owned())
|
||||||
|
.unwrap();
|
||||||
|
let steam_id = 76561197960265728;
|
||||||
|
let signature = build_signature(&secret, steam_id, &challenge);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
signature,
|
||||||
|
[
|
||||||
|
56, 233, 253, 249, 254, 89, 110, 161, 18, 35, 35, 144, 14, 217, 210, 150, 170, 110,
|
||||||
|
61, 166, 176, 161, 140, 211, 108, 78, 138, 202, 61, 52, 85, 46
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
43
steamguard/src/refresher.rs
Normal file
43
steamguard/src/refresher.rs
Normal file
|
@ -0,0 +1,43 @@
|
||||||
|
use crate::{
|
||||||
|
protobufs::steammessages_auth_steamclient::CAuthentication_AccessToken_GenerateForApp_Request,
|
||||||
|
steamapi::{AuthenticationClient, EResult},
|
||||||
|
token::{Jwt, Tokens},
|
||||||
|
transport::Transport,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub struct TokenRefresher<T>
|
||||||
|
where
|
||||||
|
T: Transport,
|
||||||
|
{
|
||||||
|
client: AuthenticationClient<T>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> TokenRefresher<T>
|
||||||
|
where
|
||||||
|
T: Transport,
|
||||||
|
{
|
||||||
|
pub fn new(client: AuthenticationClient<T>) -> Self {
|
||||||
|
Self { client }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn refresh(&mut self, steam_id: u64, tokens: &Tokens) -> Result<Jwt, anyhow::Error> {
|
||||||
|
let mut req = CAuthentication_AccessToken_GenerateForApp_Request::new();
|
||||||
|
req.set_steamid(steam_id);
|
||||||
|
req.set_refresh_token(tokens.refresh_token().expose_secret().to_owned());
|
||||||
|
|
||||||
|
let resp = self
|
||||||
|
.client
|
||||||
|
.generate_access_token(req, tokens.access_token())?;
|
||||||
|
|
||||||
|
if resp.result != EResult::OK {
|
||||||
|
return Err(anyhow::anyhow!(
|
||||||
|
"Failed to refresh access token: {:?}",
|
||||||
|
resp.result
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut resp = resp.into_response_data();
|
||||||
|
|
||||||
|
Ok(resp.take_access_token().into())
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,25 +1,24 @@
|
||||||
pub mod authentication;
|
pub mod authentication;
|
||||||
|
pub mod phone;
|
||||||
pub mod twofactor;
|
pub mod twofactor;
|
||||||
|
|
||||||
use crate::{
|
use crate::transport::Transport;
|
||||||
protobufs::service_twofactor::CTwoFactor_Time_Response, token::Jwt, transport::WebApiTransport,
|
use crate::{protobufs::service_twofactor::CTwoFactor_Time_Response, token::Jwt};
|
||||||
};
|
|
||||||
use reqwest::Url;
|
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
||||||
pub use self::authentication::AuthenticationClient;
|
pub use self::authentication::AuthenticationClient;
|
||||||
|
pub use self::phone::PhoneClient;
|
||||||
pub use self::twofactor::TwoFactorClient;
|
pub use self::twofactor::TwoFactorClient;
|
||||||
|
|
||||||
lazy_static! {
|
lazy_static! {
|
||||||
static ref STEAM_COOKIE_URL: Url = "https://steamcommunity.com".parse::<Url>().unwrap();
|
|
||||||
static ref STEAM_API_BASE: String = "https://api.steampowered.com".into();
|
static ref STEAM_API_BASE: String = "https://api.steampowered.com".into();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Queries Steam for the current time. A convenience function around TwoFactorClient.
|
/// Queries Steam for the current time. A convenience function around TwoFactorClient.
|
||||||
///
|
///
|
||||||
/// Endpoint: `/ITwoFactorService/QueryTime/v0001`
|
/// Endpoint: `/ITwoFactorService/QueryTime/v0001`
|
||||||
pub fn get_server_time() -> anyhow::Result<CTwoFactor_Time_Response> {
|
pub fn get_server_time<T: Transport>(client: T) -> anyhow::Result<CTwoFactor_Time_Response> {
|
||||||
let mut client = TwoFactorClient::new(WebApiTransport::new());
|
let client = TwoFactorClient::new(client);
|
||||||
let resp = client.query_time()?;
|
let resp = client.query_time()?;
|
||||||
if resp.result != EResult::OK {
|
if resp.result != EResult::OK {
|
||||||
return Err(anyhow::anyhow!("QueryTime failed: {:?}", resp));
|
return Err(anyhow::anyhow!("QueryTime failed: {:?}", resp));
|
||||||
|
|
|
@ -4,14 +4,14 @@ use crate::{
|
||||||
steammessages_auth_steamclient::*,
|
steammessages_auth_steamclient::*,
|
||||||
},
|
},
|
||||||
token::Jwt,
|
token::Jwt,
|
||||||
transport::Transport,
|
transport::{Transport, TransportError},
|
||||||
};
|
};
|
||||||
|
|
||||||
const SERVICE_NAME: &str = "IAuthenticationService";
|
const SERVICE_NAME: &str = "IAuthenticationService";
|
||||||
|
|
||||||
use super::{ApiRequest, ApiResponse, BuildableRequest};
|
use super::{ApiRequest, ApiResponse, BuildableRequest};
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct AuthenticationClient<T>
|
pub struct AuthenticationClient<T>
|
||||||
where
|
where
|
||||||
T: Transport,
|
T: Transport,
|
||||||
|
@ -138,14 +138,18 @@ where
|
||||||
pub fn update_session_with_mobile_confirmation(
|
pub fn update_session_with_mobile_confirmation(
|
||||||
&mut self,
|
&mut self,
|
||||||
req: CAuthentication_UpdateAuthSessionWithMobileConfirmation_Request,
|
req: CAuthentication_UpdateAuthSessionWithMobileConfirmation_Request,
|
||||||
) -> anyhow::Result<ApiResponse<CAuthentication_UpdateAuthSessionWithMobileConfirmation_Response>>
|
access_token: &Jwt,
|
||||||
{
|
) -> Result<
|
||||||
|
ApiResponse<CAuthentication_UpdateAuthSessionWithMobileConfirmation_Response>,
|
||||||
|
TransportError,
|
||||||
|
> {
|
||||||
let req = ApiRequest::new(
|
let req = ApiRequest::new(
|
||||||
SERVICE_NAME,
|
SERVICE_NAME,
|
||||||
"UpdateAuthSessionWithMobileConfirmation",
|
"UpdateAuthSessionWithMobileConfirmation",
|
||||||
1u32,
|
1u32,
|
||||||
req,
|
req,
|
||||||
);
|
)
|
||||||
|
.with_access_token(access_token);
|
||||||
let resp = self
|
let resp = self
|
||||||
.transport
|
.transport
|
||||||
.send_request::<CAuthentication_UpdateAuthSessionWithMobileConfirmation_Request, CAuthentication_UpdateAuthSessionWithMobileConfirmation_Response>(
|
.send_request::<CAuthentication_UpdateAuthSessionWithMobileConfirmation_Request, CAuthentication_UpdateAuthSessionWithMobileConfirmation_Response>(
|
||||||
|
|
128
steamguard/src/steamapi/phone.rs
Normal file
128
steamguard/src/steamapi/phone.rs
Normal file
|
@ -0,0 +1,128 @@
|
||||||
|
use crate::{
|
||||||
|
protobufs::service_phone::*,
|
||||||
|
token::Jwt,
|
||||||
|
transport::{Transport, TransportError},
|
||||||
|
};
|
||||||
|
|
||||||
|
const SERVICE_NAME: &str = "IPhoneService";
|
||||||
|
|
||||||
|
use super::{ApiRequest, ApiResponse, BuildableRequest};
|
||||||
|
|
||||||
|
/// A client for the IPhoneService API.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct PhoneClient<T>
|
||||||
|
where
|
||||||
|
T: Transport,
|
||||||
|
{
|
||||||
|
transport: T,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> PhoneClient<T>
|
||||||
|
where
|
||||||
|
T: Transport,
|
||||||
|
{
|
||||||
|
#[must_use]
|
||||||
|
pub fn new(transport: T) -> Self {
|
||||||
|
Self { transport }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_account_phone_number(
|
||||||
|
&self,
|
||||||
|
req: CPhone_SetAccountPhoneNumber_Request,
|
||||||
|
access_token: &Jwt,
|
||||||
|
) -> Result<ApiResponse<CPhone_SetAccountPhoneNumber_Response>, TransportError> {
|
||||||
|
let req = ApiRequest::new(SERVICE_NAME, "SetAccountPhoneNumber", 1u32, req)
|
||||||
|
.with_access_token(access_token);
|
||||||
|
let resp = self
|
||||||
|
.transport
|
||||||
|
.send_request::<CPhone_SetAccountPhoneNumber_Request, CPhone_SetAccountPhoneNumber_Response>(
|
||||||
|
req,
|
||||||
|
)?;
|
||||||
|
Ok(resp)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn send_phone_verification_code(
|
||||||
|
&self,
|
||||||
|
req: CPhone_SendPhoneVerificationCode_Request,
|
||||||
|
access_token: &Jwt,
|
||||||
|
) -> Result<ApiResponse<CPhone_SendPhoneVerificationCode_Response>, TransportError> {
|
||||||
|
let req = ApiRequest::new(SERVICE_NAME, "SendPhoneVerificationCode", 1u32, req)
|
||||||
|
.with_access_token(access_token);
|
||||||
|
let resp = self
|
||||||
|
.transport
|
||||||
|
.send_request::<CPhone_SendPhoneVerificationCode_Request, CPhone_SendPhoneVerificationCode_Response>(
|
||||||
|
req,
|
||||||
|
)?;
|
||||||
|
Ok(resp)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_account_waiting_for_email_confirmation(
|
||||||
|
&self,
|
||||||
|
req: CPhone_IsAccountWaitingForEmailConfirmation_Request,
|
||||||
|
access_token: &Jwt,
|
||||||
|
) -> Result<ApiResponse<CPhone_IsAccountWaitingForEmailConfirmation_Response>, TransportError> {
|
||||||
|
let req = ApiRequest::new(
|
||||||
|
SERVICE_NAME,
|
||||||
|
"IsAccountWaitingForEmailConfirmation",
|
||||||
|
1u32,
|
||||||
|
req,
|
||||||
|
)
|
||||||
|
.with_access_token(access_token);
|
||||||
|
let resp = self
|
||||||
|
.transport
|
||||||
|
.send_request::<CPhone_IsAccountWaitingForEmailConfirmation_Request, CPhone_IsAccountWaitingForEmailConfirmation_Response>(
|
||||||
|
req,
|
||||||
|
)?;
|
||||||
|
Ok(resp)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn confirm_add_phone_to_account(
|
||||||
|
&self,
|
||||||
|
req: CPhone_ConfirmAddPhoneToAccount_Request,
|
||||||
|
access_token: &Jwt,
|
||||||
|
) -> Result<ApiResponse<CPhone_AddPhoneToAccount_Response>, TransportError> {
|
||||||
|
let req = ApiRequest::new(SERVICE_NAME, "ConfirmAddPhoneToAccount", 1u32, req)
|
||||||
|
.with_access_token(access_token);
|
||||||
|
let resp = self
|
||||||
|
.transport
|
||||||
|
.send_request::<CPhone_ConfirmAddPhoneToAccount_Request, CPhone_AddPhoneToAccount_Response>(
|
||||||
|
req,
|
||||||
|
)?;
|
||||||
|
Ok(resp)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn verify_account_phone_with_code(
|
||||||
|
&self,
|
||||||
|
req: CPhone_VerifyAccountPhoneWithCode_Request,
|
||||||
|
access_token: &Jwt,
|
||||||
|
) -> Result<ApiResponse<CPhone_VerifyAccountPhoneWithCode_Response>, TransportError> {
|
||||||
|
let req = ApiRequest::new(SERVICE_NAME, "VerifyAccountPhoneWithCode", 1u32, req)
|
||||||
|
.with_access_token(access_token);
|
||||||
|
let resp = self
|
||||||
|
.transport
|
||||||
|
.send_request::<CPhone_VerifyAccountPhoneWithCode_Request, CPhone_VerifyAccountPhoneWithCode_Response>(
|
||||||
|
req,
|
||||||
|
)?;
|
||||||
|
Ok(resp)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! impl_buildable_req {
|
||||||
|
($type:ty, $needs_auth:literal) => {
|
||||||
|
impl BuildableRequest for $type {
|
||||||
|
fn method() -> reqwest::Method {
|
||||||
|
reqwest::Method::POST
|
||||||
|
}
|
||||||
|
|
||||||
|
fn requires_access_token() -> bool {
|
||||||
|
$needs_auth
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
impl_buildable_req!(CPhone_SetAccountPhoneNumber_Request, true);
|
||||||
|
impl_buildable_req!(CPhone_SendPhoneVerificationCode_Request, true);
|
||||||
|
impl_buildable_req!(CPhone_IsAccountWaitingForEmailConfirmation_Request, true);
|
||||||
|
impl_buildable_req!(CPhone_ConfirmAddPhoneToAccount_Request, true);
|
||||||
|
impl_buildable_req!(CPhone_VerifyAccountPhoneWithCode_Request, true);
|
|
@ -1,9 +1,8 @@
|
||||||
use crate::token::Jwt;
|
use crate::token::Jwt;
|
||||||
use crate::transport::Transport;
|
use crate::transport::{Transport, TransportError};
|
||||||
|
|
||||||
use super::{ApiRequest, ApiResponse, BuildableRequest};
|
use super::{ApiRequest, ApiResponse, BuildableRequest};
|
||||||
|
|
||||||
use crate::protobufs::custom::CTwoFactor_Time_Request;
|
|
||||||
use crate::protobufs::service_twofactor::*;
|
use crate::protobufs::service_twofactor::*;
|
||||||
|
|
||||||
const SERVICE_NAME: &str = "ITwoFactorService";
|
const SERVICE_NAME: &str = "ITwoFactorService";
|
||||||
|
@ -26,7 +25,7 @@ where
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn add_authenticator(
|
pub fn add_authenticator(
|
||||||
&mut self,
|
&self,
|
||||||
req: CTwoFactor_AddAuthenticator_Request,
|
req: CTwoFactor_AddAuthenticator_Request,
|
||||||
access_token: &Jwt,
|
access_token: &Jwt,
|
||||||
) -> anyhow::Result<ApiResponse<CTwoFactor_AddAuthenticator_Response>> {
|
) -> anyhow::Result<ApiResponse<CTwoFactor_AddAuthenticator_Response>> {
|
||||||
|
@ -41,7 +40,7 @@ where
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn finalize_authenticator(
|
pub fn finalize_authenticator(
|
||||||
&mut self,
|
&self,
|
||||||
req: CTwoFactor_FinalizeAddAuthenticator_Request,
|
req: CTwoFactor_FinalizeAddAuthenticator_Request,
|
||||||
access_token: &Jwt,
|
access_token: &Jwt,
|
||||||
) -> anyhow::Result<ApiResponse<CTwoFactor_FinalizeAddAuthenticator_Response>> {
|
) -> anyhow::Result<ApiResponse<CTwoFactor_FinalizeAddAuthenticator_Response>> {
|
||||||
|
@ -56,10 +55,10 @@ where
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn remove_authenticator(
|
pub fn remove_authenticator(
|
||||||
&mut self,
|
&self,
|
||||||
req: CTwoFactor_RemoveAuthenticator_Request,
|
req: CTwoFactor_RemoveAuthenticator_Request,
|
||||||
access_token: &Jwt,
|
access_token: &Jwt,
|
||||||
) -> anyhow::Result<ApiResponse<CTwoFactor_RemoveAuthenticator_Response>> {
|
) -> Result<ApiResponse<CTwoFactor_RemoveAuthenticator_Response>, TransportError> {
|
||||||
let req = ApiRequest::new(SERVICE_NAME, "RemoveAuthenticator", 1, req)
|
let req = ApiRequest::new(SERVICE_NAME, "RemoveAuthenticator", 1, req)
|
||||||
.with_access_token(access_token);
|
.with_access_token(access_token);
|
||||||
let resp = self
|
let resp = self
|
||||||
|
@ -70,8 +69,47 @@ where
|
||||||
Ok(resp)
|
Ok(resp)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn remove_authenticator_via_challenge_start(
|
||||||
|
&self,
|
||||||
|
req: CTwoFactor_RemoveAuthenticatorViaChallengeStart_Request,
|
||||||
|
access_token: &Jwt,
|
||||||
|
) -> Result<ApiResponse<CTwoFactor_RemoveAuthenticatorViaChallengeStart_Response>, TransportError>
|
||||||
|
{
|
||||||
|
let req = ApiRequest::new(SERVICE_NAME, "RemoveAuthenticatorViaChallengeStart", 1, req)
|
||||||
|
.with_access_token(access_token);
|
||||||
|
let resp = self
|
||||||
|
.transport
|
||||||
|
.send_request::<CTwoFactor_RemoveAuthenticatorViaChallengeStart_Request, CTwoFactor_RemoveAuthenticatorViaChallengeStart_Response>(
|
||||||
|
req,
|
||||||
|
)?;
|
||||||
|
Ok(resp)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn remove_authenticator_via_challenge_continue(
|
||||||
|
&self,
|
||||||
|
req: CTwoFactor_RemoveAuthenticatorViaChallengeContinue_Request,
|
||||||
|
access_token: &Jwt,
|
||||||
|
) -> Result<
|
||||||
|
ApiResponse<CTwoFactor_RemoveAuthenticatorViaChallengeContinue_Response>,
|
||||||
|
TransportError,
|
||||||
|
> {
|
||||||
|
let req = ApiRequest::new(
|
||||||
|
SERVICE_NAME,
|
||||||
|
"RemoveAuthenticatorViaChallengeContinue",
|
||||||
|
1,
|
||||||
|
req,
|
||||||
|
)
|
||||||
|
.with_access_token(access_token);
|
||||||
|
let resp = self
|
||||||
|
.transport
|
||||||
|
.send_request::<CTwoFactor_RemoveAuthenticatorViaChallengeContinue_Request, CTwoFactor_RemoveAuthenticatorViaChallengeContinue_Response>(
|
||||||
|
req,
|
||||||
|
)?;
|
||||||
|
Ok(resp)
|
||||||
|
}
|
||||||
|
|
||||||
pub fn query_status(
|
pub fn query_status(
|
||||||
&mut self,
|
&self,
|
||||||
req: CTwoFactor_Status_Request,
|
req: CTwoFactor_Status_Request,
|
||||||
access_token: &Jwt,
|
access_token: &Jwt,
|
||||||
) -> anyhow::Result<ApiResponse<CTwoFactor_Status_Response>> {
|
) -> anyhow::Result<ApiResponse<CTwoFactor_Status_Response>> {
|
||||||
|
@ -83,7 +121,7 @@ where
|
||||||
Ok(resp)
|
Ok(resp)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn query_time(&mut self) -> anyhow::Result<ApiResponse<CTwoFactor_Time_Response>> {
|
pub fn query_time(&self) -> anyhow::Result<ApiResponse<CTwoFactor_Time_Response>> {
|
||||||
let req = ApiRequest::new(SERVICE_NAME, "QueryTime", 1, CTwoFactor_Time_Request::new());
|
let req = ApiRequest::new(SERVICE_NAME, "QueryTime", 1, CTwoFactor_Time_Request::new());
|
||||||
let resp = self
|
let resp = self
|
||||||
.transport
|
.transport
|
||||||
|
@ -109,5 +147,13 @@ macro_rules! impl_buildable_req {
|
||||||
impl_buildable_req!(CTwoFactor_AddAuthenticator_Request, true);
|
impl_buildable_req!(CTwoFactor_AddAuthenticator_Request, true);
|
||||||
impl_buildable_req!(CTwoFactor_FinalizeAddAuthenticator_Request, true);
|
impl_buildable_req!(CTwoFactor_FinalizeAddAuthenticator_Request, true);
|
||||||
impl_buildable_req!(CTwoFactor_RemoveAuthenticator_Request, true);
|
impl_buildable_req!(CTwoFactor_RemoveAuthenticator_Request, true);
|
||||||
|
impl_buildable_req!(
|
||||||
|
CTwoFactor_RemoveAuthenticatorViaChallengeStart_Request,
|
||||||
|
true
|
||||||
|
);
|
||||||
|
impl_buildable_req!(
|
||||||
|
CTwoFactor_RemoveAuthenticatorViaChallengeContinue_Request,
|
||||||
|
true
|
||||||
|
);
|
||||||
impl_buildable_req!(CTwoFactor_Status_Request, true);
|
impl_buildable_req!(CTwoFactor_Status_Request, true);
|
||||||
impl_buildable_req!(CTwoFactor_Time_Request, false);
|
impl_buildable_req!(CTwoFactor_Time_Request, false);
|
||||||
|
|
|
@ -1,5 +1,8 @@
|
||||||
|
use base64::Engine;
|
||||||
|
use hmac::{Hmac, Mac};
|
||||||
use secrecy::{ExposeSecret, Secret, SecretString};
|
use secrecy::{ExposeSecret, Secret, SecretString};
|
||||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||||
|
use sha1::Sha1;
|
||||||
use std::convert::TryInto;
|
use std::convert::TryInto;
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
|
@ -23,7 +26,10 @@ impl TwoFactorSecret {
|
||||||
|
|
||||||
pub fn parse_shared_secret(secret: String) -> anyhow::Result<Self> {
|
pub fn parse_shared_secret(secret: String) -> anyhow::Result<Self> {
|
||||||
ensure!(!secret.is_empty(), "unable to parse empty shared secret");
|
ensure!(!secret.is_empty(), "unable to parse empty shared secret");
|
||||||
let result: [u8; 20] = base64::decode(secret)?.try_into().unwrap();
|
let result: [u8; 20] = base64::engine::general_purpose::STANDARD
|
||||||
|
.decode(secret)?
|
||||||
|
.try_into()
|
||||||
|
.unwrap();
|
||||||
Ok(Self(result.into()))
|
Ok(Self(result.into()))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -34,9 +40,11 @@ impl TwoFactorSecret {
|
||||||
86, 87, 88, 89,
|
86, 87, 88, 89,
|
||||||
];
|
];
|
||||||
|
|
||||||
|
let mut mac = Hmac::<Sha1>::new_from_slice(self.0.expose_secret()).unwrap();
|
||||||
// this effectively makes it so that it creates a new code every 30 seconds.
|
// this effectively makes it so that it creates a new code every 30 seconds.
|
||||||
let time_bytes: [u8; 8] = build_time_bytes(time / 30u64);
|
mac.update(&build_time_bytes(time / 30u64));
|
||||||
let hashed_data = hmacsha1::hmac_sha1(self.0.expose_secret(), &time_bytes);
|
let result = mac.finalize();
|
||||||
|
let hashed_data = result.into_bytes();
|
||||||
let mut code_array: [u8; 5] = [0; 5];
|
let mut code_array: [u8; 5] = [0; 5];
|
||||||
let b = (hashed_data[19] & 0xF) as usize;
|
let b = (hashed_data[19] & 0xF) as usize;
|
||||||
let mut code_point: i32 = ((hashed_data[b] & 0x7F) as i32) << 24
|
let mut code_point: i32 = ((hashed_data[b] & 0x7F) as i32) << 24
|
||||||
|
@ -52,6 +60,10 @@ impl TwoFactorSecret {
|
||||||
|
|
||||||
String::from_utf8(code_array.to_vec()).unwrap()
|
String::from_utf8(code_array.to_vec()).unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn expose_secret(&self) -> &[u8; 20] {
|
||||||
|
self.0.expose_secret()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Serialize for TwoFactorSecret {
|
impl Serialize for TwoFactorSecret {
|
||||||
|
@ -59,7 +71,11 @@ impl Serialize for TwoFactorSecret {
|
||||||
where
|
where
|
||||||
S: Serializer,
|
S: Serializer,
|
||||||
{
|
{
|
||||||
serializer.serialize_str(base64::encode(self.0.expose_secret()).as_str())
|
serializer.serialize_str(
|
||||||
|
base64::engine::general_purpose::STANDARD
|
||||||
|
.encode(self.0.expose_secret())
|
||||||
|
.as_str(),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -102,6 +118,10 @@ impl Tokens {
|
||||||
&self.access_token
|
&self.access_token
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn set_access_token(&mut self, token: Jwt) {
|
||||||
|
self.access_token = token;
|
||||||
|
}
|
||||||
|
|
||||||
pub fn refresh_token(&self) -> &Jwt {
|
pub fn refresh_token(&self) -> &Jwt {
|
||||||
&self.refresh_token
|
&self.refresh_token
|
||||||
}
|
}
|
||||||
|
@ -140,7 +160,7 @@ fn decode_jwt(jwt: impl AsRef<str>) -> anyhow::Result<SteamJwtData> {
|
||||||
ensure!(parts.len() == 3, "Invalid JWT");
|
ensure!(parts.len() == 3, "Invalid JWT");
|
||||||
|
|
||||||
let data = parts[1];
|
let data = parts[1];
|
||||||
let bytes = base64::decode_config(data, base64::URL_SAFE)?;
|
let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(data)?;
|
||||||
let json = String::from_utf8(bytes)?;
|
let json = String::from_utf8(bytes)?;
|
||||||
let jwt_data: SteamJwtData = serde_json::from_str(&json)?;
|
let jwt_data: SteamJwtData = serde_json::from_str(&json)?;
|
||||||
Ok(jwt_data)
|
Ok(jwt_data)
|
||||||
|
@ -239,4 +259,13 @@ mod tests {
|
||||||
assert_eq!(data.sub, "76561199155706892");
|
assert_eq!(data.sub, "76561199155706892");
|
||||||
assert_eq!(data.jti, "18C5_22B3F431_CDF6A");
|
assert_eq!(data.jti, "18C5_22B3F431_CDF6A");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_decode_jwt_2() {
|
||||||
|
let sample: Jwt = "eyAidHlwIjogIkpXVCIsICJhbGciOiAiRWREU0EiIH0.eyAiaXNzIjogInI6MTRCM18yMkZEQjg0RF9BMjJDRCIsICJzdWIiOiAiNzY1NjExOTk0NDE5OTI5NzAiLCAiYXVkIjogWyAid2ViIiwgIm1vYmlsZSIgXSwgImV4cCI6IDE2OTE3NTc5MzUsICJuYmYiOiAxNjgzMDMxMDUxLCAiaWF0IjogMTY5MTY3MTA1MSwgImp0aSI6ICIxNTI1XzIyRkRCOUJBXzZBRDkwIiwgIm9hdCI6IDE2OTE2NzEwNTEsICJydF9leHAiOiAxNzEwMDExNjg5LCAicGVyIjogMCwgImlwX3N1YmplY3QiOiAiMTA0LjI0Ni4xMjUuMTQxIiwgImlwX2NvbmZpcm1lciI6ICIxMDQuMjQ2LjEyNS4xNDEiIH0.ncqc5TpVlD05lnZvy8c3Bkx70gXDvQQXN0iG5Z4mOLgY_rwasXIJXnR-X4JczT8PmZ2v5cisW5VRHAdfsz_8CA".to_owned().into();
|
||||||
|
let data = sample.decode().expect("Failed to decode JWT");
|
||||||
|
|
||||||
|
assert_eq!(data.aud, vec!["web", "mobile"]);
|
||||||
|
assert_eq!(data.sub, "76561199441992970");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -7,9 +7,31 @@ use crate::steamapi::{ApiRequest, ApiResponse, BuildableRequest};
|
||||||
|
|
||||||
pub trait Transport {
|
pub trait Transport {
|
||||||
fn send_request<Req: BuildableRequest + MessageFull, Res: MessageFull>(
|
fn send_request<Req: BuildableRequest + MessageFull, Res: MessageFull>(
|
||||||
&mut self,
|
&self,
|
||||||
req: ApiRequest<Req>,
|
req: ApiRequest<Req>,
|
||||||
) -> anyhow::Result<ApiResponse<Res>>;
|
) -> Result<ApiResponse<Res>, TransportError>;
|
||||||
|
|
||||||
fn close(&mut self);
|
fn close(&mut self);
|
||||||
|
|
||||||
|
fn innner_http_client(&self) -> anyhow::Result<reqwest::blocking::Client> {
|
||||||
|
bail!("Transport does not support extracting HTTP client")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum TransportError {
|
||||||
|
#[error("Transport failed to parse response headers")]
|
||||||
|
HeaderParseFailure {
|
||||||
|
header: String,
|
||||||
|
#[source]
|
||||||
|
source: anyhow::Error,
|
||||||
|
},
|
||||||
|
#[error("Transport failed to parse response body")]
|
||||||
|
ProtobufError(#[from] protobuf::Error),
|
||||||
|
#[error("Unauthorized: Access token is missing or invalid")]
|
||||||
|
Unauthorized,
|
||||||
|
#[error("NetworkFailure: Transport failed to make request: {0}")]
|
||||||
|
NetworkFailure(#[from] reqwest::Error),
|
||||||
|
#[error("Unexpected error when transport was making request: {0}")]
|
||||||
|
Unknown(#[from] anyhow::Error),
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,44 +1,26 @@
|
||||||
use log::{debug, trace};
|
use log::{debug, trace};
|
||||||
use protobuf::MessageFull;
|
use protobuf::MessageFull;
|
||||||
use reqwest::{blocking::multipart::Form, Url};
|
use reqwest::blocking::multipart::Form;
|
||||||
|
|
||||||
use super::Transport;
|
use super::{Transport, TransportError};
|
||||||
use crate::steamapi::{ApiRequest, ApiResponse, BuildableRequest, EResult};
|
use crate::steamapi::{ApiRequest, ApiResponse, BuildableRequest, EResult};
|
||||||
|
|
||||||
lazy_static! {
|
#[derive(Debug, Clone)]
|
||||||
static ref STEAM_COOKIE_URL: Url = "https://steamcommunity.com".parse::<Url>().unwrap();
|
|
||||||
static ref STEAM_API_BASE: String = "https://api.steampowered.com".into();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct WebApiTransport {
|
pub struct WebApiTransport {
|
||||||
client: reqwest::blocking::Client,
|
client: reqwest::blocking::Client,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for WebApiTransport {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self::new()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl WebApiTransport {
|
impl WebApiTransport {
|
||||||
pub fn new() -> WebApiTransport {
|
pub fn new(client: reqwest::blocking::Client) -> Self {
|
||||||
Self {
|
Self { client }
|
||||||
client: reqwest::blocking::Client::new(),
|
|
||||||
// client: reqwest::blocking::Client::builder()
|
|
||||||
// .danger_accept_invalid_certs(true)
|
|
||||||
// .proxy(reqwest::Proxy::all("http://localhost:8080").unwrap())
|
|
||||||
// .build()
|
|
||||||
// .unwrap(),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Transport for WebApiTransport {
|
impl Transport for WebApiTransport {
|
||||||
fn send_request<Req: BuildableRequest + MessageFull, Res: MessageFull>(
|
fn send_request<Req: BuildableRequest + MessageFull, Res: MessageFull>(
|
||||||
&mut self,
|
&self,
|
||||||
apireq: ApiRequest<Req>,
|
apireq: ApiRequest<Req>,
|
||||||
) -> anyhow::Result<ApiResponse<Res>> {
|
) -> anyhow::Result<ApiResponse<Res>, TransportError> {
|
||||||
// All the API endpoints accept 2 data formats: json and protobuf.
|
// All the API endpoints accept 2 data formats: json and protobuf.
|
||||||
// Depending on the http method for the request, the data can go in 2 places:
|
// Depending on the http method for the request, the data can go in 2 places:
|
||||||
// - GET: query string, with the key `input_protobuf_encoded` or `input_json`
|
// - GET: query string, with the key `input_protobuf_encoded` or `input_json`
|
||||||
|
@ -47,7 +29,7 @@ impl Transport for WebApiTransport {
|
||||||
// input protobuf data is always encoded in base64
|
// input protobuf data is always encoded in base64
|
||||||
|
|
||||||
if Req::requires_access_token() && apireq.access_token().is_none() {
|
if Req::requires_access_token() && apireq.access_token().is_none() {
|
||||||
return Err(anyhow::anyhow!("Access token required for this request"));
|
return Err(TransportError::Unauthorized);
|
||||||
}
|
}
|
||||||
|
|
||||||
let url = apireq.build_url();
|
let url = apireq.build_url();
|
||||||
|
@ -56,7 +38,10 @@ impl Transport for WebApiTransport {
|
||||||
let mut req = self.client.request(Req::method(), &url);
|
let mut req = self.client.request(Req::method(), &url);
|
||||||
|
|
||||||
req = if Req::method() == reqwest::Method::GET {
|
req = if Req::method() == reqwest::Method::GET {
|
||||||
let encoded = encode_msg(apireq.request_data(), base64::URL_SAFE)?;
|
let encoded = encode_msg(
|
||||||
|
apireq.request_data(),
|
||||||
|
base64::engine::general_purpose::URL_SAFE,
|
||||||
|
)?;
|
||||||
let mut params = vec![("input_protobuf_encoded", encoded.as_str())];
|
let mut params = vec![("input_protobuf_encoded", encoded.as_str())];
|
||||||
if let Some(access_token) = apireq.access_token() {
|
if let Some(access_token) = apireq.access_token() {
|
||||||
params.push(("access_token", access_token.expose_secret()));
|
params.push(("access_token", access_token.expose_secret()));
|
||||||
|
@ -66,7 +51,10 @@ impl Transport for WebApiTransport {
|
||||||
if let Some(access_token) = apireq.access_token() {
|
if let Some(access_token) = apireq.access_token() {
|
||||||
req = req.query(&[("access_token", access_token)]);
|
req = req.query(&[("access_token", access_token)]);
|
||||||
}
|
}
|
||||||
let encoded = encode_msg(apireq.request_data(), base64::STANDARD)?;
|
let encoded = encode_msg(
|
||||||
|
apireq.request_data(),
|
||||||
|
base64::engine::general_purpose::STANDARD,
|
||||||
|
)?;
|
||||||
let form = Form::new().text("input_protobuf_encoded", encoded);
|
let form = Form::new().text("input_protobuf_encoded", encoded);
|
||||||
req.multipart(form)
|
req.multipart(form)
|
||||||
};
|
};
|
||||||
|
@ -76,14 +64,31 @@ impl Transport for WebApiTransport {
|
||||||
debug!("Response HTTP status: {}", status);
|
debug!("Response HTTP status: {}", status);
|
||||||
|
|
||||||
let eresult = if let Some(eresult) = resp.headers().get("x-eresult") {
|
let eresult = if let Some(eresult) = resp.headers().get("x-eresult") {
|
||||||
debug!("HTTP Header x-eresult: {}", eresult.to_str()?);
|
let s = eresult
|
||||||
eresult.to_str()?.parse::<i32>()?.into()
|
.to_str()
|
||||||
|
.map_err(|err| TransportError::HeaderParseFailure {
|
||||||
|
header: "x-eresult".to_owned(),
|
||||||
|
source: err.into(),
|
||||||
|
})?;
|
||||||
|
debug!("HTTP Header x-eresult: {}", s);
|
||||||
|
s.parse::<i32>()
|
||||||
|
.map_err(|err| TransportError::HeaderParseFailure {
|
||||||
|
header: "x-eresult".to_owned(),
|
||||||
|
source: err.into(),
|
||||||
|
})?
|
||||||
|
.into()
|
||||||
} else {
|
} else {
|
||||||
EResult::Invalid
|
EResult::Invalid
|
||||||
};
|
};
|
||||||
let error_msg = if let Some(error_message) = resp.headers().get("x-error_message") {
|
let error_msg = if let Some(error_message) = resp.headers().get("x-error_message") {
|
||||||
debug!("HTTP Header x-error_message: {}", error_message.to_str()?);
|
let s = error_message
|
||||||
Some(error_message.to_str()?.to_owned())
|
.to_str()
|
||||||
|
.map_err(|err| TransportError::HeaderParseFailure {
|
||||||
|
header: "x-error_message".to_owned(),
|
||||||
|
source: err.into(),
|
||||||
|
})?;
|
||||||
|
debug!("HTTP Header x-error_message: {}", s);
|
||||||
|
Some(s.to_owned())
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
};
|
};
|
||||||
|
@ -91,6 +96,10 @@ impl Transport for WebApiTransport {
|
||||||
let bytes = resp.bytes()?;
|
let bytes = resp.bytes()?;
|
||||||
if !status.is_success() {
|
if !status.is_success() {
|
||||||
trace!("Response body (raw): {:?}", bytes);
|
trace!("Response body (raw): {:?}", bytes);
|
||||||
|
|
||||||
|
if status == reqwest::StatusCode::UNAUTHORIZED {
|
||||||
|
return Err(TransportError::Unauthorized);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let res = decode_msg::<Res>(bytes.as_ref())?;
|
let res = decode_msg::<Res>(bytes.as_ref())?;
|
||||||
|
@ -105,17 +114,20 @@ impl Transport for WebApiTransport {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn close(&mut self) {}
|
fn close(&mut self) {}
|
||||||
|
|
||||||
|
fn innner_http_client(&self) -> anyhow::Result<reqwest::blocking::Client> {
|
||||||
|
Ok(self.client.clone())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn encode_msg<T: MessageFull>(msg: &T, config: base64::Config) -> anyhow::Result<String> {
|
fn encode_msg<T: MessageFull>(msg: &T, engine: impl base64::Engine) -> anyhow::Result<String> {
|
||||||
let bytes = msg.write_to_bytes()?;
|
let bytes = msg.write_to_bytes()?;
|
||||||
let b64 = base64::encode_config(bytes, config);
|
let b64 = engine.encode(bytes);
|
||||||
Ok(b64)
|
Ok(b64)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn decode_msg<T: MessageFull>(bytes: &[u8]) -> anyhow::Result<T> {
|
fn decode_msg<T: MessageFull>(bytes: &[u8]) -> Result<T, protobuf::Error> {
|
||||||
let msg = T::parse_from_bytes(bytes)?;
|
T::parse_from_bytes(bytes)
|
||||||
Ok(msg)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
@ -127,12 +139,13 @@ mod tests {
|
||||||
};
|
};
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use base64::{engine::general_purpose::STANDARD, Engine};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_parse_poll_response() {
|
fn test_parse_poll_response() {
|
||||||
let sample = b"GuUDZXlBaWRIbHdJam9nSWtwWFZDSXNJQ0poYkdjaU9pQWlSV1JFVTBFaUlIMC5leUFpYVhOeklqb2dJbk4wWldGdElpd2dJbk4xWWlJNklDSTNOalUyTVRFNU9URTFOVGN3TmpnNU1pSXNJQ0poZFdRaU9pQmJJQ0ozWldJaUxDQWljbVZ1WlhjaUxDQWlaR1Z5YVhabElpQmRMQ0FpWlhod0lqb2dNVGN3TlRBeE1UazFOU3dnSW01aVppSTZJREUyTnpnME5qUTRNemNzSUNKcFlYUWlPaUF4TmpnM01UQTBPRE0zTENBaWFuUnBJam9nSWpFNFF6VmZNakpDTTBZME16RmZRMFJHTmtFaUxDQWliMkYwSWpvZ01UWTROekV3TkRnek55d2dJbkJsY2lJNklERXNJQ0pwY0Y5emRXSnFaV04wSWpvZ0lqWTVMakV5TUM0eE16WXVNVEkwSWl3Z0ltbHdYMk52Ym1acGNtMWxjaUk2SUNJMk9TNHhNakF1TVRNMkxqRXlOQ0lnZlEuR3A1VFBqOXBHUWJ4SXpXREROQ1NQOU9rS1lTZXduV0JFOEUtY1ZxalFxcVQ1M0FzRTRya213OER5TThoVXJ4T0VQQ1dDWHdyYkRVcmgxOTlSempQRHci/gNleUFpZEhsd0lqb2dJa3BYVkNJc0lDSmhiR2NpT2lBaVJXUkVVMEVpSUgwLmV5QWlhWE56SWpvZ0luSTZNVGhETlY4eU1rSXpSalF6TVY5RFJFWTJRU0lzSUNKemRXSWlPaUFpTnpZMU5qRXhPVGt4TlRVM01EWTRPVElpTENBaVlYVmtJam9nV3lBaWQyVmlJaUJkTENBaVpYaHdJam9nTVRZNE56RTVNamM0T0N3Z0ltNWlaaUk2SURFMk56ZzBOalE0TXpjc0lDSnBZWFFpT2lBeE5qZzNNVEEwT0RNM0xDQWlhblJwSWpvZ0lqRXlSREZmTWpKQ00wVTROekZmT1RaRk5EQWlMQ0FpYjJGMElqb2dNVFk0TnpFd05EZ3pOeXdnSW5KMFgyVjRjQ0k2SURFM01EVXdNVEU1TlRVc0lDSndaWElpT2lBd0xDQWlhWEJmYzNWaWFtVmpkQ0k2SUNJMk9TNHhNakF1TVRNMkxqRXlOQ0lzSUNKcGNGOWpiMjVtYVhKdFpYSWlPaUFpTmprdU1USXdMakV6Tmk0eE1qUWlJSDAuMVNnUEotSVZuWEp6Nk9nSW1udUdOQ0hMbEJTcGdvc0Z0UkxoOV9iVVBHQ1RaMmFtRWY2ZTZVYkJzVWZ3bnlYbEdFdG5LSHhPemhibTdLNzBwVFhEQ0EoADIKaHlkcmFzdGFyMg==";
|
let sample = b"GuUDZXlBaWRIbHdJam9nSWtwWFZDSXNJQ0poYkdjaU9pQWlSV1JFVTBFaUlIMC5leUFpYVhOeklqb2dJbk4wWldGdElpd2dJbk4xWWlJNklDSTNOalUyTVRFNU9URTFOVGN3TmpnNU1pSXNJQ0poZFdRaU9pQmJJQ0ozWldJaUxDQWljbVZ1WlhjaUxDQWlaR1Z5YVhabElpQmRMQ0FpWlhod0lqb2dNVGN3TlRBeE1UazFOU3dnSW01aVppSTZJREUyTnpnME5qUTRNemNzSUNKcFlYUWlPaUF4TmpnM01UQTBPRE0zTENBaWFuUnBJam9nSWpFNFF6VmZNakpDTTBZME16RmZRMFJHTmtFaUxDQWliMkYwSWpvZ01UWTROekV3TkRnek55d2dJbkJsY2lJNklERXNJQ0pwY0Y5emRXSnFaV04wSWpvZ0lqWTVMakV5TUM0eE16WXVNVEkwSWl3Z0ltbHdYMk52Ym1acGNtMWxjaUk2SUNJMk9TNHhNakF1TVRNMkxqRXlOQ0lnZlEuR3A1VFBqOXBHUWJ4SXpXREROQ1NQOU9rS1lTZXduV0JFOEUtY1ZxalFxcVQ1M0FzRTRya213OER5TThoVXJ4T0VQQ1dDWHdyYkRVcmgxOTlSempQRHci/gNleUFpZEhsd0lqb2dJa3BYVkNJc0lDSmhiR2NpT2lBaVJXUkVVMEVpSUgwLmV5QWlhWE56SWpvZ0luSTZNVGhETlY4eU1rSXpSalF6TVY5RFJFWTJRU0lzSUNKemRXSWlPaUFpTnpZMU5qRXhPVGt4TlRVM01EWTRPVElpTENBaVlYVmtJam9nV3lBaWQyVmlJaUJkTENBaVpYaHdJam9nTVRZNE56RTVNamM0T0N3Z0ltNWlaaUk2SURFMk56ZzBOalE0TXpjc0lDSnBZWFFpT2lBeE5qZzNNVEEwT0RNM0xDQWlhblJwSWpvZ0lqRXlSREZmTWpKQ00wVTROekZmT1RaRk5EQWlMQ0FpYjJGMElqb2dNVFk0TnpFd05EZ3pOeXdnSW5KMFgyVjRjQ0k2SURFM01EVXdNVEU1TlRVc0lDSndaWElpT2lBd0xDQWlhWEJmYzNWaWFtVmpkQ0k2SUNJMk9TNHhNakF1TVRNMkxqRXlOQ0lzSUNKcGNGOWpiMjVtYVhKdFpYSWlPaUFpTmprdU1USXdMakV6Tmk0eE1qUWlJSDAuMVNnUEotSVZuWEp6Nk9nSW1udUdOQ0hMbEJTcGdvc0Z0UkxoOV9iVVBHQ1RaMmFtRWY2ZTZVYkJzVWZ3bnlYbEdFdG5LSHhPemhibTdLNzBwVFhEQ0EoADIKaHlkcmFzdGFyMg==";
|
||||||
|
|
||||||
let bytes = base64::decode_config(sample, base64::STANDARD).unwrap();
|
let bytes = STANDARD.decode(sample).unwrap();
|
||||||
|
|
||||||
let resp: CAuthentication_PollAuthSessionStatus_Response = decode_msg(&bytes).unwrap();
|
let resp: CAuthentication_PollAuthSessionStatus_Response = decode_msg(&bytes).unwrap();
|
||||||
|
|
||||||
|
@ -143,7 +156,7 @@ mod tests {
|
||||||
fn parse_get_public_rsa_response() {
|
fn parse_get_public_rsa_response() {
|
||||||
let sample = b"CoAEYjYyMGI1ZWNhMWIxMjgyYjkxYzZkZmZkYWFhOWI0ODI0YjlhNmRiYmEyZDVmYjc0ODcxNDczZDc1MDYxNGEzNWM4ODQ3NDYzZTEyNjAwNTJmNzZlNTYxMDM5ODdlN2U3NGJkMWZjZGRjYWJhMDVmZGM5OTBjMWIyNmQ2ZDg5MGM2MTEzZmRkNTZmMmQ1YmZjNzU4ODhlMzZhNTM2NjM3N2IzZTE3ZTJiZWM5MjhlNGY4MmE1YzY0NGYxZTZlMTk3NzZkNjIzMDIxYjhmYTA0MGRjNWE5YjY0M2I0N2I5YmVhMjM2YmEyZjM4ODVjM2ZlNWVhNjMzZThlNjJjNGE1YTY4NjNmMzNiMzdlMTQ4M2MwZTUzZTg4ODIzMGFkNTVjNzg5ZmU4Y2NkMjVjNzdiMTkxOTg0ZThjN2JmNWYzNzY2MjI0OGI1NWVmOWM1OGY3NDM5YjA4ZjNhNWJiNzljNTc5ZDE5M2I3NzhmMzFiY2IwYTA3MmVhZWYxOGEyYjljZDY2M2VmYmY2YmRiZDU3MGEyMTNiOTIxNTc4ODk0MjJkMDY3ODFiNTVkY2VjYjQ4NjA4MjUyMmUzZWQyOWM4MjExYzQ5N2Q1YjNhYTk2OGM2MDY1YWFhZTNhNGVmYzZiMGJjNDYyMzMxNmVmYTUxN2JjNzRiZDYzODcxMWU4ZWYSBjAxMDAwMRiQn6Ly3wk=";
|
let sample = b"CoAEYjYyMGI1ZWNhMWIxMjgyYjkxYzZkZmZkYWFhOWI0ODI0YjlhNmRiYmEyZDVmYjc0ODcxNDczZDc1MDYxNGEzNWM4ODQ3NDYzZTEyNjAwNTJmNzZlNTYxMDM5ODdlN2U3NGJkMWZjZGRjYWJhMDVmZGM5OTBjMWIyNmQ2ZDg5MGM2MTEzZmRkNTZmMmQ1YmZjNzU4ODhlMzZhNTM2NjM3N2IzZTE3ZTJiZWM5MjhlNGY4MmE1YzY0NGYxZTZlMTk3NzZkNjIzMDIxYjhmYTA0MGRjNWE5YjY0M2I0N2I5YmVhMjM2YmEyZjM4ODVjM2ZlNWVhNjMzZThlNjJjNGE1YTY4NjNmMzNiMzdlMTQ4M2MwZTUzZTg4ODIzMGFkNTVjNzg5ZmU4Y2NkMjVjNzdiMTkxOTg0ZThjN2JmNWYzNzY2MjI0OGI1NWVmOWM1OGY3NDM5YjA4ZjNhNWJiNzljNTc5ZDE5M2I3NzhmMzFiY2IwYTA3MmVhZWYxOGEyYjljZDY2M2VmYmY2YmRiZDU3MGEyMTNiOTIxNTc4ODk0MjJkMDY3ODFiNTVkY2VjYjQ4NjA4MjUyMmUzZWQyOWM4MjExYzQ5N2Q1YjNhYTk2OGM2MDY1YWFhZTNhNGVmYzZiMGJjNDYyMzMxNmVmYTUxN2JjNzRiZDYzODcxMWU4ZWYSBjAxMDAwMRiQn6Ly3wk=";
|
||||||
|
|
||||||
let bytes = base64::decode_config(sample, base64::STANDARD).unwrap();
|
let bytes = STANDARD.decode(sample).unwrap();
|
||||||
|
|
||||||
let resp: CAuthentication_GetPasswordRSAPublicKey_Response = decode_msg(&bytes).unwrap();
|
let resp: CAuthentication_GetPasswordRSAPublicKey_Response = decode_msg(&bytes).unwrap();
|
||||||
|
|
||||||
|
@ -154,11 +167,11 @@ mod tests {
|
||||||
fn test_decode_encode_roundtrip() {
|
fn test_decode_encode_roundtrip() {
|
||||||
let sample = b"EgpoeWRyYXN0YXIyGtgCRUxaNTBXdHM2Z0kxWlZaVjl6bzRJNFBEcEhTMGRZR3RSNzJPbytqZkR5QmRBUitrbnBUcUVGcGF4NDd1UVdqdUQ1R2hpRC9JanA2cEtGQzlrdUZDdzBFT0RMSFpINERZUG5hci9IMktOZGoxSFNjWEhyemZjNmk1OWpsRE5OTTI0RVllNUEyUjVSdzBoa2lodU14Z1A4NDJESFUxMkgwNWFyYmdRUWp3NFJmVHh6cDBQQlRjdTk4VUViUjJnak1RajlVK3RsYStPdTN6WTQ5K1BKc0szTkpMTVdxWm4vaFZ1dTR3NFprZGhXNVBqNWphb2Flb3J6MG8zbWIvUXo2M0NlNFdwWmUra1lFYUlSa29oUXBaZkliaW4rTWdQcVpNelg4cW4vNDcyNFp5N05mblpETlVBV3RoTkowTkUxSDVESXZ4N0IwRFJHZVBwdk5FbVdqWEJ3PT0g4MCW2tYBOAFCBk1vYmlsZUocCgpHYWxheHkgUzIyEAMYjPz/////////ASCQBA==";
|
let sample = b"EgpoeWRyYXN0YXIyGtgCRUxaNTBXdHM2Z0kxWlZaVjl6bzRJNFBEcEhTMGRZR3RSNzJPbytqZkR5QmRBUitrbnBUcUVGcGF4NDd1UVdqdUQ1R2hpRC9JanA2cEtGQzlrdUZDdzBFT0RMSFpINERZUG5hci9IMktOZGoxSFNjWEhyemZjNmk1OWpsRE5OTTI0RVllNUEyUjVSdzBoa2lodU14Z1A4NDJESFUxMkgwNWFyYmdRUWp3NFJmVHh6cDBQQlRjdTk4VUViUjJnak1RajlVK3RsYStPdTN6WTQ5K1BKc0szTkpMTVdxWm4vaFZ1dTR3NFprZGhXNVBqNWphb2Flb3J6MG8zbWIvUXo2M0NlNFdwWmUra1lFYUlSa29oUXBaZkliaW4rTWdQcVpNelg4cW4vNDcyNFp5N05mblpETlVBV3RoTkowTkUxSDVESXZ4N0IwRFJHZVBwdk5FbVdqWEJ3PT0g4MCW2tYBOAFCBk1vYmlsZUocCgpHYWxheHkgUzIyEAMYjPz/////////ASCQBA==";
|
||||||
|
|
||||||
let bytes = base64::decode_config(sample, base64::STANDARD).unwrap();
|
let bytes = STANDARD.decode(sample).unwrap();
|
||||||
let decoded: CAuthentication_BeginAuthSessionViaCredentials_Request =
|
let decoded: CAuthentication_BeginAuthSessionViaCredentials_Request =
|
||||||
decode_msg(&bytes).expect("Failed to decode");
|
decode_msg(&bytes).expect("Failed to decode");
|
||||||
|
|
||||||
let encoded = encode_msg(&decoded, base64::STANDARD).expect("Failed to encode");
|
let encoded = encode_msg(&decoded, STANDARD).expect("Failed to encode");
|
||||||
|
|
||||||
assert_eq!(encoded, String::from_utf8(sample.to_vec()).unwrap());
|
assert_eq!(encoded, String::from_utf8(sample.to_vec()).unwrap());
|
||||||
}
|
}
|
||||||
|
|
|
@ -6,22 +6,22 @@ use crate::protobufs::steammessages_auth_steamclient::{
|
||||||
CAuthentication_PollAuthSessionStatus_Request, CAuthentication_PollAuthSessionStatus_Response,
|
CAuthentication_PollAuthSessionStatus_Request, CAuthentication_PollAuthSessionStatus_Response,
|
||||||
EAuthSessionGuardType,
|
EAuthSessionGuardType,
|
||||||
};
|
};
|
||||||
|
use crate::protobufs::steammessages_auth_steamclient::{
|
||||||
|
CAuthentication_BeginAuthSessionViaCredentials_Response,
|
||||||
|
CAuthentication_BeginAuthSessionViaQR_Request, CAuthentication_BeginAuthSessionViaQR_Response,
|
||||||
|
CAuthentication_GetPasswordRSAPublicKey_Response,
|
||||||
|
CAuthentication_UpdateAuthSessionWithSteamGuardCode_Request,
|
||||||
|
CAuthentication_UpdateAuthSessionWithSteamGuardCode_Response, EAuthTokenPlatformType,
|
||||||
|
};
|
||||||
|
use crate::refresher::TokenRefresher;
|
||||||
use crate::steamapi::authentication::AuthenticationClient;
|
use crate::steamapi::authentication::AuthenticationClient;
|
||||||
use crate::steamapi::EResult;
|
use crate::steamapi::EResult;
|
||||||
use crate::token::Tokens;
|
use crate::token::Tokens;
|
||||||
use crate::{
|
use crate::transport::Transport;
|
||||||
protobufs::steammessages_auth_steamclient::{
|
use anyhow::Context;
|
||||||
CAuthentication_BeginAuthSessionViaCredentials_Response,
|
use base64::Engine;
|
||||||
CAuthentication_BeginAuthSessionViaQR_Request,
|
|
||||||
CAuthentication_BeginAuthSessionViaQR_Response,
|
|
||||||
CAuthentication_GetPasswordRSAPublicKey_Response,
|
|
||||||
CAuthentication_UpdateAuthSessionWithSteamGuardCode_Request,
|
|
||||||
CAuthentication_UpdateAuthSessionWithSteamGuardCode_Response, EAuthTokenPlatformType,
|
|
||||||
},
|
|
||||||
transport::WebApiTransport,
|
|
||||||
};
|
|
||||||
use log::*;
|
use log::*;
|
||||||
use rsa::{PublicKey, RsaPublicKey};
|
use rsa::{Pkcs1v15Encrypt, RsaPublicKey};
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
|
@ -82,17 +82,23 @@ impl BeginQrLoginResponse {
|
||||||
|
|
||||||
/// Handles the user login flow.
|
/// Handles the user login flow.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct UserLogin {
|
pub struct UserLogin<T>
|
||||||
client: AuthenticationClient<WebApiTransport>,
|
where
|
||||||
|
T: Transport + Clone,
|
||||||
|
{
|
||||||
|
client: AuthenticationClient<T>,
|
||||||
device_details: DeviceDetails,
|
device_details: DeviceDetails,
|
||||||
|
|
||||||
started_auth: Option<StartAuth>,
|
started_auth: Option<StartAuth>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl UserLogin {
|
impl<T> UserLogin<T>
|
||||||
pub fn new(device_details: DeviceDetails) -> Self {
|
where
|
||||||
|
T: Transport + Clone,
|
||||||
|
{
|
||||||
|
pub fn new(transport: T, device_details: DeviceDetails) -> Self {
|
||||||
Self {
|
Self {
|
||||||
client: AuthenticationClient::new(WebApiTransport::new()),
|
client: AuthenticationClient::new(transport),
|
||||||
device_details,
|
device_details,
|
||||||
started_auth: None,
|
started_auth: None,
|
||||||
}
|
}
|
||||||
|
@ -210,11 +216,29 @@ impl UserLogin {
|
||||||
loop {
|
loop {
|
||||||
let mut next_poll = self.poll_until_info()?;
|
let mut next_poll = self.poll_until_info()?;
|
||||||
|
|
||||||
if next_poll.has_access_token() {
|
if next_poll.has_access_token() || next_poll.has_refresh_token() {
|
||||||
return Ok(Tokens::new(
|
// On 2023-09-12, Steam stopped issuing access tokens alongside refresh tokens for newly authenticated sessions.
|
||||||
next_poll.take_access_token(),
|
// If they decide to revert this change, we'll accept the access token if it's present.
|
||||||
next_poll.take_refresh_token(),
|
|
||||||
));
|
let access_token = next_poll.take_access_token();
|
||||||
|
if access_token.is_empty() {
|
||||||
|
// Let's go ahead an fetch the access token, because we are going to need it anyway.
|
||||||
|
let mut refresher = TokenRefresher::new(self.client.clone());
|
||||||
|
let mut tokens = Tokens::new(
|
||||||
|
next_poll.take_access_token(),
|
||||||
|
next_poll.take_refresh_token(),
|
||||||
|
);
|
||||||
|
let steamid = tokens
|
||||||
|
.refresh_token()
|
||||||
|
.decode()
|
||||||
|
.context("decoding refresh token for steam id")?
|
||||||
|
.steam_id();
|
||||||
|
let access_token = refresher.refresh(steamid, &tokens)?;
|
||||||
|
tokens.set_access_token(access_token);
|
||||||
|
return Ok(tokens);
|
||||||
|
} else {
|
||||||
|
return Ok(Tokens::new(access_token, next_poll.take_refresh_token()));
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -269,13 +293,12 @@ fn encrypt_password(
|
||||||
let rsa_modulus = rsa::BigUint::parse_bytes(rsa_resp.publickey_mod().as_bytes(), 16).unwrap();
|
let rsa_modulus = rsa::BigUint::parse_bytes(rsa_resp.publickey_mod().as_bytes(), 16).unwrap();
|
||||||
let public_key = RsaPublicKey::new(rsa_modulus, rsa_exponent).unwrap();
|
let public_key = RsaPublicKey::new(rsa_modulus, rsa_exponent).unwrap();
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
let mut rng = rand::rngs::mock::StepRng::new(2, 1);
|
let mut rng = tests::MockStepRng(rand::rngs::mock::StepRng::new(2, 1));
|
||||||
#[cfg(not(test))]
|
#[cfg(not(test))]
|
||||||
let mut rng = rand::rngs::OsRng;
|
let mut rng = rand::rngs::OsRng;
|
||||||
let padding = rsa::PaddingScheme::new_pkcs1v15_encrypt();
|
base64::engine::general_purpose::STANDARD.encode(
|
||||||
base64::encode(
|
|
||||||
public_key
|
public_key
|
||||||
.encrypt(&mut rng, padding, password.as_ref())
|
.encrypt(&mut rng, Pkcs1v15Encrypt, password.as_ref())
|
||||||
.unwrap(),
|
.unwrap(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
@ -403,6 +426,26 @@ impl From<anyhow::Error> for UpdateAuthSessionError {
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
pub(crate) struct MockStepRng(pub rand::rngs::mock::StepRng);
|
||||||
|
impl rand::RngCore for MockStepRng {
|
||||||
|
fn next_u32(&mut self) -> u32 {
|
||||||
|
self.0.next_u32()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn next_u64(&mut self) -> u64 {
|
||||||
|
self.0.next_u64()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fill_bytes(&mut self, dest: &mut [u8]) {
|
||||||
|
self.0.fill_bytes(dest)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand::Error> {
|
||||||
|
self.0.try_fill_bytes(dest)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl rand::CryptoRng for MockStepRng {}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_encrypt_password() {
|
fn test_encrypt_password() {
|
||||||
let mut rsa_resp = CAuthentication_GetPasswordRSAPublicKey_Response::new();
|
let mut rsa_resp = CAuthentication_GetPasswordRSAPublicKey_Response::new();
|
||||||
|
|
Loading…
Add table
Reference in a new issue