Compare commits

...

352 commits

Author SHA1 Message Date
Carson McManus
96a30c6150
setup: debug print full authenticator status when verification fails (#396) 2024-07-16 20:32:18 -04:00
Carson McManus
dd153a617c
fix a potential panic when querying authenticator status (#395) 2024-07-16 20:13:39 -04:00
Carson McManus
28c7a797cf
fix new lints (#397) 2024-07-16 20:07:33 -04:00
Carson McManus
c2a72fee6c update PKGBUILD 2024-06-02 18:21:36 -04:00
mp
602acc6641
PKGBUILD: disabled link time optimization to avoid build errors (#385)
This solves build errors for me described in
https://aur.archlinux.org/packages/steamguard-cli-git#comment-884235 and
also reproduced in
https://github.com/dyc3/steamguard-cli/actions/runs/9340294638/job/25705683797

```
error: linking with `cc` failed: exit status: 1
  |
  = note: LC_ALL="C" PATH="/usr/lib64/rustlib/x86_64-unknown-linux-gnu/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" VSLANG="1033" "cc" "-m64" "/tmp/rustcWfC4he/symbols.o" "/var/ab/.cache/yay/steamguard-cli-git/src/steamguard-cli/target/release/deps/steamguard-22c99af53504a9e5.steamguard.7abfd362c63e99bf-cgu.13.rcgu.o" "-Wl,--as-needed" "-L" "/var/ab/.cache/yay/steamguard-cli-git/src/steamguard-cli/target/release/deps" "-L" "/var/ab/.cache/yay/steamguard-cli-git/src/steamguard-cli/target/release/build/ring-0dc12641040c6e8f/out" "-L" "/usr/lib64/rustlib/x86_64-unknown-linux-gnu/lib" "-Wl,-Bstatic" "/tmp/rustcWfC4he/libring-949bba2bc6e40fcb.rlib" "/usr/lib64/rustlib/x86_64-unknown-linux-gnu/lib/libcompiler_builtins-3ce9c50abe6de474.rlib" "-Wl,-Bdynamic" "-lgcc_s" "-lutil" "-lrt" "-lpthread" "-lm" "-ldl" "-lc" "-Wl,--eh-frame-hdr" "-Wl,-z,noexecstack" "-L" "/usr/lib64/rustlib/x86_64-unknown-linux-gnu/lib" "-o" "/var/ab/.cache/yay/steamguard-cli-git/src/steamguard-cli/target/release/deps/steamguard-22c99af53504a9e5" "-Wl,--gc-sections" "-pie" "-Wl,-z,relro,-z,now" "-Wl,-O1" "-Wl,--strip-debug" "-nodefaultlibs"
  = note: /usr/sbin/ld: /var/ab/.cache/yay/steamguard-cli-git/src/steamguard-cli/target/release/deps/steamguard-22c99af53504a9e5.steamguard.7abfd362c63e99bf-cgu.13.rcgu.o: in function `ring::aead::aes_gcm::aes_gcm_seal':
          steamguard.7abfd362c63e99bf-cgu.13:(.text._ZN4ring4aead7aes_gcm12aes_gcm_seal17hdce0b4a4f2d32350E+0xa9): undefined reference to `ring_core_0_17_8_OPENSSL_ia32cap_P'
```
2024-06-02 21:59:36 +00:00
Carson McManus
b4564b7d5e Release steamguard v0.14.0, steamguard-cli v0.14.0 2024-06-02 14:12:44 -04:00
Carson McManus
d30ba017c9 Bump steamguard v0.14.0, steamguard-cli v0.14.0 2024-06-02 14:12:19 -04:00
Carson McManus
37ae7c76a6 Release steamguard v0.14.0, steamguard-cli v0.14.0 2024-06-02 14:10:37 -04:00
Carson McManus
ef72bd898c Bump steamguard v0.14.0, steamguard-cli v0.14.0, safety bump steamguard-cli v0.14.0 2024-06-02 14:02:38 -04:00
Carson McManus
52044c95bb
upgrade more misc dependencies (#384)
- upgrade uuid to 1.8
- remove scraper from deps
- upgrade cookie to 0.18
- upgrade reqwest to 0.12
- upgrade qrcode to 0.14
- upgrade dirs to 5.0.1
2024-06-02 17:56:05 +00:00
Carson McManus
b24a7415f6
upgrade misc deps, set rust edition to 2021 (#383) 2024-06-02 16:26:00 +00:00
Carson McManus
8d54a1254a
upgrade to clap v4 (#382) 2024-06-02 14:59:25 +00:00
Carson McManus
ab5cb00ee3
qr-login: add a --image argument for providing an image to scan for the QR code (#381)
closes #380
2024-06-01 18:47:24 -04:00
dependabot[bot]
c7fefc1452
Bump rustls from 0.21.2 to 0.21.11 (#379)
Bumps [rustls](https://github.com/rustls/rustls) from 0.21.2 to 0.21.11.
<details>
<summary>Commits</summary>
<ul>
<li><a
href="7b8d1dbc1e"><code>7b8d1db</code></a>
Prepare 0.21.11</li>
<li><a
href="ebcb4782f2"><code>ebcb478</code></a>
complete_io: bail out if progress is impossible</li>
<li><a
href="20f35dfb6d"><code>20f35df</code></a>
Regression test for <code>complete_io</code> infinite loop bug</li>
<li><a
href="2f2aae15a4"><code>2f2aae1</code></a>
Don't specially handle unauthenticated close_notify alerts</li>
<li><a
href="e163587b98"><code>e163587</code></a>
Don't deny warnings from nightly clippy</li>
<li><a
href="9f864874cf"><code>9f86487</code></a>
server::handy: fix new nightly clippy lint</li>
<li><a
href="7e0e8ab599"><code>7e0e8ab</code></a>
Correct assorted clippy warnings in test code</li>
<li><a
href="3587d98f4e"><code>3587d98</code></a>
Apply clippy suggestions from Rust 1.72</li>
<li><a
href="d082e837b3"><code>d082e83</code></a>
Address <code>clippy::redundant_static_lifetimes</code></li>
<li><a
href="5e7a06ca45"><code>5e7a06c</code></a>
Address <code>clippy::slow_vector_initialization</code></li>
<li>Additional commits viewable in <a
href="https://github.com/rustls/rustls/compare/v/0.21.2...v/0.21.11">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=rustls&package-manager=cargo&previous-version=0.21.2&new-version=0.21.11)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/dyc3/steamguard-cli/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-04-20 10:22:37 -04:00
dependabot[bot]
a64f7d4134
Bump h2 from 0.3.24 to 0.3.26 (#377)
Bumps [h2](https://github.com/hyperium/h2) from 0.3.24 to 0.3.26.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/hyperium/h2/releases">h2's
releases</a>.</em></p>
<blockquote>
<h2>v0.3.26</h2>
<h2>What's Changed</h2>
<ul>
<li>Limit number of CONTINUATION frames for misbehaving
connections.</li>
</ul>
<p>See <a
href="https://seanmonstar.com/blog/hyper-http2-continuation-flood/">https://seanmonstar.com/blog/hyper-http2-continuation-flood/</a>
for more info.</p>
<h2>v0.3.25</h2>
<h2>What's Changed</h2>
<ul>
<li>perf: optimize header list size calculations by <a
href="https://github.com/Noah-Kennedy"><code>@​Noah-Kennedy</code></a>
in <a
href="https://redirect.github.com/hyperium/h2/pull/750">hyperium/h2#750</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/hyperium/h2/compare/v0.3.24...v0.3.25">https://github.com/hyperium/h2/compare/v0.3.24...v0.3.25</a></p>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/hyperium/h2/blob/v0.3.26/CHANGELOG.md">h2's
changelog</a>.</em></p>
<blockquote>
<h1>0.3.26 (April 3, 2024)</h1>
<ul>
<li>Limit number of CONTINUATION frames for misbehaving
connections.</li>
</ul>
<h1>0.3.25 (March 15, 2024)</h1>
<ul>
<li>Improve performance decoding many headers.</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="357127e279"><code>357127e</code></a>
v0.3.26</li>
<li><a
href="1a357aaefc"><code>1a357aa</code></a>
fix: limit number of CONTINUATION frames allowed</li>
<li><a
href="5b6c9e0da0"><code>5b6c9e0</code></a>
refactor: cleanup new unused warnings (<a
href="https://redirect.github.com/hyperium/h2/issues/757">#757</a>)</li>
<li><a
href="3a79832721"><code>3a79832</code></a>
v0.3.25</li>
<li><a
href="94e80b1c72"><code>94e80b1</code></a>
perf: optimize header list size calculations (<a
href="https://redirect.github.com/hyperium/h2/issues/750">#750</a>)</li>
<li>See full diff in <a
href="https://github.com/hyperium/h2/compare/v0.3.24...v0.3.26">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=h2&package-manager=cargo&previous-version=0.3.24&new-version=0.3.26)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/dyc3/steamguard-cli/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-04-05 13:07:58 -04:00
Carson McManus
0a41e8b042 Release steamguard v0.13.0, steamguard-cli v0.13.0 2024-03-04 17:23:00 -05:00
Carson McManus
d3c1dfb3d5 Bump steamguard v0.13.0, steamguard-cli v0.13.0, safety bump steamguard-cli v0.13.0 2024-03-04 17:18:59 -05:00
Carson McManus
a8d3f3fc99 update release script 2024-03-04 17:17:38 -05:00
dependabot[bot]
5e24031719
Bump mio from 0.8.8 to 0.8.11 (#372)
Bumps [mio](https://github.com/tokio-rs/mio) from 0.8.8 to 0.8.11.
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/tokio-rs/mio/blob/master/CHANGELOG.md">mio's
changelog</a>.</em></p>
<blockquote>
<h1>0.8.11</h1>
<ul>
<li>Fix receiving IOCP events after deregistering a Windows named pipe
(<a
href="https://redirect.github.com/tokio-rs/mio/pull/1760">tokio-rs/mio#1760</a>,
backport pr:
<a
href="https://redirect.github.com/tokio-rs/mio/pull/1761">tokio-rs/mio#1761</a>).</li>
</ul>
<h1>0.8.10</h1>
<h2>Added</h2>
<ul>
<li>Solaris support
(<a
href="https://redirect.github.com/tokio-rs/mio/pull/1724">tokio-rs/mio#1724</a>).</li>
</ul>
<h1>0.8.9</h1>
<h2>Added</h2>
<ul>
<li>ESP-IDF framework support
(<a
href="https://redirect.github.com/tokio-rs/mio/pull/1692">tokio-rs/mio#1692</a>).</li>
<li>AIX operating system support
(<a
href="https://redirect.github.com/tokio-rs/mio/pull/1704">tokio-rs/mio#1704</a>).</li>
<li>Vita support
(<a
href="https://redirect.github.com/tokio-rs/mio/pull/1721">tokio-rs/mio#1721</a>).</li>
<li><code>{UnixListener,UnixStream}:bind_addr</code>
(<a
href="https://redirect.github.com/tokio-rs/mio/pull/1630">tokio-rs/mio#1630</a>).</li>
<li><code>mio_unsupported_force_poll_poll</code> and
<code>mio_unsupported_force_waker_pipe</code>
<strong>unsupported</strong> configuration flags to force a specific
poll or waker
implementation
(<a
href="https://redirect.github.com/tokio-rs/mio/pull/1684">tokio-rs/mio#1684</a>,
<a
href="https://redirect.github.com/tokio-rs/mio/pull/1685">tokio-rs/mio#1685</a>,
<a
href="https://redirect.github.com/tokio-rs/mio/pull/1692">tokio-rs/mio#1692</a>).</li>
</ul>
<h2>Fixed</h2>
<ul>
<li>The <code>pipe(2)</code> based waker (swapped file descriptors)
(<a
href="https://redirect.github.com/tokio-rs/mio/pull/1722">tokio-rs/mio#1722</a>).</li>
<li>The duplicate waker check to work correctly with cloned
<code>Registry</code>s.
(<a
href="https://redirect.github.com/tokio-rs/mio/pull/1706">tokio-rs/mio#1706</a>).</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="0328bdef90"><code>0328bde</code></a>
Release v0.8.11</li>
<li><a
href="7084498512"><code>7084498</code></a>
Fix warnings</li>
<li><a
href="90d4fe00df"><code>90d4fe0</code></a>
named-pipes: fix receiving IOCP events after deregister</li>
<li><a
href="c710a307f8"><code>c710a30</code></a>
Add v0.8.x to the CI</li>
<li><a
href="c29e21c244"><code>c29e21c</code></a>
Release v0.8.10</li>
<li><a
href="f6a20da1c8"><code>f6a20da</code></a>
Add Solaris operating system support (<a
href="https://redirect.github.com/tokio-rs/mio/issues/1724">#1724</a>)</li>
<li><a
href="e80c3b21b5"><code>e80c3b2</code></a>
Release v0.8.9</li>
<li><a
href="862786bbbf"><code>862786b</code></a>
Fix importing of IoSourceState</li>
<li><a
href="40348728e4"><code>4034872</code></a>
Add support for vita target</li>
<li><a
href="8eb4010a92"><code>8eb4010</code></a>
Fix receiver and sender fd in pipe based waker</li>
<li>Additional commits viewable in <a
href="https://github.com/tokio-rs/mio/compare/v0.8.8...v0.8.11">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=mio&package-manager=cargo&previous-version=0.8.8&new-version=0.8.11)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/dyc3/steamguard-cli/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-03-04 21:55:03 +00:00
Carson McManus
d67e925a47
ci: add workflow_dispatch trigger to aur-checker (#371) 2024-03-04 07:20:18 -05:00
Carson McManus
4c9f494ed3
chore: update CI to use node 20 actions (#369) 2024-03-04 07:05:23 -05:00
Carson McManus
46a1c2ed04
rename trade subcommand to confirm and deprecate trade subcommand (#368) 2024-03-04 06:56:48 -05:00
Carson McManus
ad146c97c9 Release steamguard v0.12.6, steamguard-cli v0.12.6 2024-02-19 09:33:29 -05:00
Carson McManus
d96b6e65a6 Bump steamguard v0.12.6, steamguard-cli v0.12.6 2024-02-19 09:29:22 -05:00
Carson McManus
84da432b2d
tests: Replace tempdir crate with tempfile (#366) 2024-02-19 13:43:52 +00:00
dependabot[bot]
2629b0b715
Bump h2 from 0.3.20 to 0.3.24 (#359)
Bumps [h2](https://github.com/hyperium/h2) from 0.3.20 to 0.3.24.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/hyperium/h2/releases">h2's
releases</a>.</em></p>
<blockquote>
<h2>v0.3.24</h2>
<h2>Fixed</h2>
<ul>
<li>Limit error resets for misbehaving connections.</li>
</ul>
<h2>v0.3.23</h2>
<h2>What's Changed</h2>
<ul>
<li>cherry-pick fix: streams awaiting capacity lockout in <a
href="https://redirect.github.com/hyperium/h2/pull/734">hyperium/h2#734</a></li>
</ul>
<h2>v0.3.22</h2>
<h2>What's Changed</h2>
<ul>
<li>Add <code>header_table_size(usize)</code> option to client and
server builders.</li>
<li>Improve throughput when vectored IO is not available.</li>
<li>Update indexmap to 2.</li>
</ul>
<h2>New Contributors</h2>
<ul>
<li><a href="https://github.com/tottoto"><code>@​tottoto</code></a> made
their first contribution in <a
href="https://redirect.github.com/hyperium/h2/pull/714">hyperium/h2#714</a></li>
<li><a href="https://github.com/xiaoyawei"><code>@​xiaoyawei</code></a>
made their first contribution in <a
href="https://redirect.github.com/hyperium/h2/pull/712">hyperium/h2#712</a></li>
<li><a href="https://github.com/Protryon"><code>@​Protryon</code></a>
made their first contribution in <a
href="https://redirect.github.com/hyperium/h2/pull/719">hyperium/h2#719</a></li>
<li><a href="https://github.com/4JX"><code>@​4JX</code></a> made their
first contribution in <a
href="https://redirect.github.com/hyperium/h2/pull/638">hyperium/h2#638</a></li>
<li><a
href="https://github.com/vuittont60"><code>@​vuittont60</code></a> made
their first contribution in <a
href="https://redirect.github.com/hyperium/h2/pull/724">hyperium/h2#724</a></li>
</ul>
<h2>v0.3.21</h2>
<h2>What's Changed</h2>
<ul>
<li>Fix opening of new streams over peer's max concurrent limit.</li>
<li>Fix <code>RecvStream</code> to return data even if it has received a
<code>CANCEL</code> stream error.</li>
<li>Update MSRV to 1.63.</li>
</ul>
<h2>New Contributors</h2>
<ul>
<li><a href="https://github.com/DDtKey"><code>@​DDtKey</code></a> made
their first contribution in <a
href="https://redirect.github.com/hyperium/h2/pull/703">hyperium/h2#703</a></li>
<li><a href="https://github.com/jwilm"><code>@​jwilm</code></a> made
their first contribution in <a
href="https://redirect.github.com/hyperium/h2/pull/707">hyperium/h2#707</a></li>
</ul>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/hyperium/h2/blob/v0.3.24/CHANGELOG.md">h2's
changelog</a>.</em></p>
<blockquote>
<h1>0.3.24 (January 17, 2024)</h1>
<ul>
<li>Limit error resets for misbehaving connections.</li>
</ul>
<h1>0.3.23 (January 10, 2024)</h1>
<ul>
<li>Backport fix from 0.4.1 for stream capacity assignment.</li>
</ul>
<h1>0.3.22 (November 15, 2023)</h1>
<ul>
<li>Add <code>header_table_size(usize)</code> option to client and
server builders.</li>
<li>Improve throughput when vectored IO is not available.</li>
<li>Update indexmap to 2.</li>
</ul>
<h1>0.3.21 (August 21, 2023)</h1>
<ul>
<li>Fix opening of new streams over peer's max concurrent limit.</li>
<li>Fix <code>RecvStream</code> to return data even if it has received a
<code>CANCEL</code> stream error.</li>
<li>Update MSRV to 1.63.</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="7243ab5854"><code>7243ab5</code></a>
Prepare v0.3.24</li>
<li><a
href="d919cd6fd8"><code>d919cd6</code></a>
streams: limit error resets for misbehaving connections</li>
<li><a
href="a7eb14a487"><code>a7eb14a</code></a>
v0.3.23</li>
<li><a
href="b668c7fbe2"><code>b668c7f</code></a>
fix: streams awaiting capacity lockout (<a
href="https://redirect.github.com/hyperium/h2/issues/730">#730</a>) (<a
href="https://redirect.github.com/hyperium/h2/issues/734">#734</a>)</li>
<li><a
href="0f412d8b9c"><code>0f412d8</code></a>
v0.3.22</li>
<li><a
href="c7ca62f69b"><code>c7ca62f</code></a>
docs: fix typos (<a
href="https://redirect.github.com/hyperium/h2/issues/724">#724</a>)</li>
<li><a
href="ef743ecb22"><code>ef743ec</code></a>
Add a setter for header_table_size (<a
href="https://redirect.github.com/hyperium/h2/issues/638">#638</a>)</li>
<li><a
href="56651e6e51"><code>56651e6</code></a>
fix lint about unused import</li>
<li><a
href="4aa7b16342"><code>4aa7b16</code></a>
Fix documentation for max_send_buffer_size (<a
href="https://redirect.github.com/hyperium/h2/issues/718">#718</a>)</li>
<li><a
href="d03c54a80d"><code>d03c54a</code></a>
chore(dependencies): update tracing minimal version to 0.1.35</li>
<li>Additional commits viewable in <a
href="https://github.com/hyperium/h2/compare/v0.3.20...v0.3.24">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=h2&package-manager=cargo&previous-version=0.3.20&new-version=0.3.24)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

You can trigger a rebase of this PR by commenting `@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/dyc3/steamguard-cli/network/alerts).

</details>

> **Note**
> Automatic rebases have been disabled on this pull request as it has
been open for over 30 days.

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-02-19 08:30:56 -05:00
Carson McManus
f7a4ce6133
Bump stderrlog to 0.6 (#365) 2024-02-19 08:26:03 -05:00
Carson McManus
c5d51b5174
trade: fix ApiKeyCreation confirmation getting iterpreted as Unknown (#363) 2024-02-19 08:20:43 -05:00
Carson McManus
8394baa157
remove dead code to fix lints (#364) 2024-02-19 13:12:44 +00:00
Carson McManus
25280abc62
add new confirmation type: api key creation (#357) 2024-01-04 21:59:18 -05:00
Carson McManus
bdc8d3c526 Release steamguard v0.12.5, steamguard-cli v0.12.5 2023-12-08 16:47:29 -05:00
Carson McManus
bcac6fa7a3 Bump steamguard v0.12.5, steamguard-cli v0.12.5 2023-12-08 16:43:47 -05:00
Carson McManus
225b53d719
setup: add support for transfering or removing authenticators (#354)
- add methods for remove auth via challenge
- add `transfer_start` and `transfer_finish` to account linker
2023-12-08 17:38:36 +00:00
Carson McManus
4ea44151b9
login: make the 2fa and email code prompts less easy to mess up (#352) 2023-12-08 11:48:14 -05:00
Carson McManus
68dcedaeb7
remove: move main remove_authenticator request logic into AccountLinker (#353) 2023-12-08 16:39:41 +00:00
Carson McManus
9358fb60c9 Release steamguard v0.12.4, steamguard-cli v0.12.4 2023-12-03 11:53:57 -05:00
Carson McManus
9795453a04 Bump steamguard v0.12.4, steamguard-cli v0.12.4 2023-12-03 11:45:35 -05:00
Carson McManus
8f7ca33e8a tweak the release script a little 2023-12-03 11:43:31 -05:00
Carson McManus
fca7e53a0d
fix a missing step (#349) 2023-12-03 16:39:45 +00:00
Carson McManus
166b7a908c
setup: add support for different link confirmation types, and verify that the authenticator was actually set up (#348)
fixes #345
2023-12-03 16:36:35 +00:00
Carson McManus
63805293ff
update steam protobufs (#347) 2023-12-03 15:14:59 +00:00
Carson McManus
d18dd378c3
login: don't print a warning for EAuthSessionGuardType::None (#346) 2023-12-03 10:12:03 -05:00
Carson McManus
41bf8a45ec Release steamguard v0.12.3, steamguard-cli v0.12.3 2023-10-25 10:23:51 -04:00
Carson McManus
37b7b75077 Bump steamguard v0.12.3, steamguard-cli v0.12.3 2023-10-25 10:20:26 -04:00
Carson McManus
8bfab8d2a2
adjust the types used for migrating from SDA to be a little more lenient (#338)
fixes #337
2023-10-25 10:17:21 -04:00
dependabot[bot]
a9e39b4215
Bump rustix from 0.37.22 to 0.37.25 (#336)
Bumps [rustix](https://github.com/bytecodealliance/rustix) from 0.37.22
to 0.37.25.
<details>
<summary>Commits</summary>
<ul>
<li><a
href="00b84d6aac"><code>00b84d6</code></a>
chore: Release rustix version 0.37.25</li>
<li><a
href="cad15a7076"><code>cad15a7</code></a>
Fixes for <code>Dir</code> on macOS, FreeBSD, and WASI.</li>
<li><a
href="df3c3a192c"><code>df3c3a1</code></a>
Merge pull request from GHSA-c827-hfw6-qwvm</li>
<li><a
href="b78aeff1a2"><code>b78aeff</code></a>
chore: Release rustix version 0.37.24</li>
<li><a
href="c0c3f01d7c"><code>c0c3f01</code></a>
Add GNU/Hurd support (<a
href="https://redirect.github.com/bytecodealliance/rustix/issues/852">#852</a>)</li>
<li><a
href="f416b6b27b"><code>f416b6b</code></a>
Fix the <code>test_ttyname_ok</code> test when /dev/stdin is
inaccessable. (<a
href="https://redirect.github.com/bytecodealliance/rustix/issues/821">#821</a>)</li>
<li><a
href="aee5b0954e"><code>aee5b09</code></a>
Downgrade dependencies and disable tests to compile under Rust
1.48.</li>
<li><a
href="6d42c38311"><code>6d42c38</code></a>
Disable MIPS in CI. (<a
href="https://redirect.github.com/bytecodealliance/rustix/issues/793">#793</a>)</li>
<li><a
href="7cdacb1145"><code>7cdacb1</code></a>
chore: Release rustix version 0.37.23</li>
<li><a
href="c6b1d4e690"><code>c6b1d4e</code></a>
Pin Rust nightly to 2023-07-03.</li>
<li>Additional commits viewable in <a
href="https://github.com/bytecodealliance/rustix/compare/v0.37.22...v0.37.25">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=rustix&package-manager=cargo&previous-version=0.37.22&new-version=0.37.25)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/dyc3/steamguard-cli/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-10-18 16:19:03 -04:00
Carson McManus
a50109ad63
login: add a debug log for available confirmation methods (#335) 2023-10-17 18:01:05 +00:00
Carson McManus
7eb62cfa7b
trade: if confirmation failure response contains a message, keep it so the user can see it (#329) 2023-10-08 15:12:34 +00:00
Carson McManus
94a3210f09
import: add support for importing winauth exports (#331)
closes #295
2023-10-08 11:10:46 -04:00
dependabot[bot]
6d4915a39c
Bump webpki from 0.22.1 to 0.22.2 (#330)
Bumps [webpki](https://github.com/briansmith/webpki) from 0.22.1 to
0.22.2.
<details>
<summary>Commits</summary>
<ul>
<li>See full diff in <a
href="https://github.com/briansmith/webpki/commits">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=webpki&package-manager=cargo&previous-version=0.22.1&new-version=0.22.2)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/dyc3/steamguard-cli/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-10-02 18:51:05 -04:00
Carson McManus
e529b76c97 Release steamguard v0.12.2, steamguard-cli v0.12.2 2023-09-28 18:11:40 -04:00
Carson McManus
47894cc217 Bump steamguard v0.12.2, steamguard-cli v0.12.2 2023-09-28 18:08:33 -04:00
Carson McManus
c809d1e725
clean up some unused code (#327) 2023-09-28 22:06:51 +00:00
Carson McManus
0c256a0e05
add --password argument and STEAMGUARD_CLI_STEAM_PASSWORD environment variable (#326)
closes #324
2023-09-28 21:52:42 +00:00
Carson McManus
04295dc742
update rpassword to 7.2.0 and add some debug logs (#325)
related: #324
2023-09-28 21:12:50 +00:00
dependabot[bot]
4fb0e4cfcd
Bump phonenumber from 0.3.2+8.13.9 to 0.3.3+8.13.9 (#323)
Bumps [phonenumber](https://github.com/whisperfish/rust-phonenumber)
from 0.3.2+8.13.9 to 0.3.3+8.13.9.
<details>
<summary>Commits</summary>
<ul>
<li>See full diff in <a
href="https://github.com/whisperfish/rust-phonenumber/commits">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=phonenumber&package-manager=cargo&previous-version=0.3.2+8.13.9&new-version=0.3.3+8.13.9)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/dyc3/steamguard-cli/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-09-22 10:04:11 -04:00
dependabot[bot]
e032008fdb
Bump webpki from 0.22.0 to 0.22.1 (#321)
Bumps [webpki](https://github.com/briansmith/webpki) from 0.22.0 to
0.22.1.
<details>
<summary>Commits</summary>
<ul>
<li>See full diff in <a
href="https://github.com/briansmith/webpki/commits">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=webpki&package-manager=cargo&previous-version=0.22.0&new-version=0.22.1)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/dyc3/steamguard-cli/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-09-13 10:29:08 -04:00
Carson McManus
5178238f8d Release steamguard v0.12.1, steamguard-cli v0.12.1 2023-09-13 10:20:59 -04:00
Carson McManus
90ba3b64b5 Bump steamguard v0.12.1, steamguard-cli v0.12.1 2023-09-13 10:17:20 -04:00
Carson McManus
14589e70d5
misc fixes for deb packaging (#315)
- change debian package arch to `amd64`
- change compression type for debian package to `xz`

fixes #314
2023-09-13 14:15:58 +00:00
Carson McManus
a9af82da13
fix how UserLogin handles access tokens for new api behavior, fixes #319 (#320)
fixes #319
2023-09-13 14:15:09 +00:00
Carson McManus
f952ed5b1b
remove normalize_comments rustfmt rule (#316) 2023-09-10 21:22:23 +00:00
Carson McManus
97a9040eb8 Release steamguard v0.12.0, steamguard-cli v0.12.0 2023-09-04 13:47:12 -04:00
Carson McManus
544608a330 Bump steamguard v0.12.0, steamguard-cli v0.12.0 2023-09-04 13:43:38 -04:00
Carson McManus
9f26e6b241 update version numbers 2023-09-04 13:43:05 -04:00
Carson McManus
2c63350bcf update release script 2023-09-04 13:39:27 -04:00
Carson McManus
29aca56067
adjust error message for when mobile confirmation fails (#311)
- adjust error message for when mobile confirmation fails
- update issue template
2023-09-04 17:10:30 +00:00
Carson McManus
f2821d2837 Release steamguard-cli v0.11.0 2023-08-23 17:41:18 -04:00
Carson McManus
84993dedae Bump steamguard-cli v0.11.0 2023-08-23 17:37:26 -04:00
Carson McManus
4348529ffd
import: add support for importing steam mobile app v2 format, remove --sda argument (#307)
- add account schema for steam app v2
- make it possible to import steam v2 accounts
- import: remove the `--sda` flag, the format should be detected
automatically
- add unit tests
- make it actually work

closes #305
2023-08-23 17:59:14 +00:00
dependabot[bot]
40d81f360b
Bump rustls-webpki from 0.100.1 to 0.100.2 (#306)
Bumps [rustls-webpki](https://github.com/rustls/webpki) from 0.100.1 to
0.100.2.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/rustls/webpki/releases">rustls-webpki's
releases</a>.</em></p>
<blockquote>
<h2>v/0.100.2</h2>
<h2>Release notes</h2>
<ul>
<li>certificate path building and verification is now capped at 100
signature validation operations to avoid the risk of CPU usage
denial-of-service attack when validating crafted certificate chains
producing quadratic runtime. This risk affected both clients, as well as
servers that verified client certificates.</li>
</ul>
<h2>What's Changed</h2>
<ul>
<li>v0.100.2 prep by <a
href="https://github.com/cpu"><code>@​cpu</code></a> in <a
href="https://redirect.github.com/rustls/webpki/pull/154">rustls/webpki#154</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/rustls/webpki/compare/v/0.100.1...v/0.100.2">https://github.com/rustls/webpki/compare/v/0.100.1...v/0.100.2</a></p>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="c8b821450b"><code>c8b8214</code></a>
Bump MSRV to 1.60</li>
<li><a
href="855752292e"><code>8557522</code></a>
Avoid testing MSRV of dev-dependencies</li>
<li><a
href="73a7f0c7d7"><code>73a7f0c</code></a>
Cargo: version 0.100.1 -&gt; 0.100.2</li>
<li><a
href="4ea052366f"><code>4ea0523</code></a>
verify_cert: enforce maximum number of signatures.</li>
<li>See full diff in <a
href="https://github.com/rustls/webpki/compare/v/0.100.1...v/0.100.2">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=rustls-webpki&package-manager=cargo&previous-version=0.100.1&new-version=0.100.2)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/dyc3/steamguard-cli/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-08-22 14:29:36 -04:00
Carson McManus
84f488a7bd Release steamguard v0.10.3, steamguard-cli v0.10.5 2023-08-10 09:20:29 -04:00
Carson McManus
34d17a2462 Bump steamguard v0.10.3, steamguard-cli v0.10.5 2023-08-10 09:15:11 -04:00
Carson McManus
e960b7cedc add a comment 2023-08-10 09:14:59 -04:00
Carson McManus
3957177709
ci: fix tests from steamguard crate not running in CI (#301) 2023-08-10 12:55:06 +00:00
Carson McManus
f0e66a4651
fix jwt decoding, fixes #299 (#300) 2023-08-10 12:49:37 +00:00
Carson McManus
94a7ca8bc8 Release steamguard-cli v0.10.4 2023-08-09 13:59:45 -04:00
Carson McManus
8bd0079ffc Bump steamguard-cli v0.10.4 2023-08-09 13:56:09 -04:00
Carson McManus
aa5168e663
fix manifest failing to save after migration on encrypted maFiles when providing passkey via the prompts on stdin (#297) 2023-08-09 17:40:58 +00:00
Carson McManus
28733e029d Release steamguard v0.10.2, steamguard-cli v0.10.3 2023-08-09 10:04:11 -04:00
Carson McManus
2114d0a98d Bump steamguard v0.10.2, steamguard-cli v0.10.3 2023-08-09 09:59:57 -04:00
Carson McManus
fff3427d8d fix a lint 2023-07-24 10:44:39 -04:00
Carson McManus
d7173b4efb
trade: automatically retry submitting confirmations (#294)
closes #293
2023-07-24 10:29:49 -04:00
Carson McManus
96f342137a
upgrade base64 crate to 0.21 (#289) 2023-07-10 15:41:36 +00:00
Carson McManus
d1ff150cbf
replace crates hmac-sha1 and hmac-sha256 with equivalent crates from RustCrypto (#288) 2023-07-10 14:53:31 +00:00
Carson McManus
9c6d10dc1f
import: improve error messages (#287) 2023-07-10 13:43:02 +00:00
Carson McManus
d31a1435c2 update release script 2023-07-09 11:09:08 -04:00
Carson McManus
e5b76fe4a4 Release steamguard v0.10.1, steamguard-cli v0.10.2 2023-07-09 11:07:38 -04:00
Carson McManus
942ac6f35f Bump steamguard v0.10.1, steamguard-cli v0.10.2 2023-07-09 11:07:25 -04:00
Carson McManus
e1a27e8b23 fix dependency thing 2023-07-09 11:07:02 -04:00
Carson McManus
eb51a7a2a7
improve robustness of account migrations (#284)
- add an extreme test case for migrations
- improve robustness of manifest migrations

fixes #283
2023-07-09 10:16:02 -04:00
Carson McManus
17d19c53c0 update readme 2023-07-07 07:25:00 -04:00
Carson McManus
7c985f62ff
zeroize more stuff during runtime (#282)
- add zeroize features to some dependencies
- zeroize protobuf messages when they are dropped
2023-07-05 14:25:03 +00:00
Carson McManus
df47ff1823
refactor passkey/password prompts so they are always SecretString (#281) 2023-07-05 12:35:32 +00:00
Carson McManus
d9261d0ac8 Release steamguard-cli v0.10.1 2023-07-05 07:03:54 -04:00
Carson McManus
b98cd2d4c7 Bump steamguard-cli v0.10.1 2023-07-05 06:59:44 -04:00
Carson McManus
3fdf2fdbc9
add an argument to accept invalid TLS certs (#279) 2023-07-05 10:58:08 +00:00
Carson McManus
7635e5ca10
add argument to specify proxy credentials (#278) 2023-07-05 10:49:17 +00:00
Carson McManus
a2b3f18d76
search directory that the executable is in for maFiles (#277)
closes #275
2023-07-05 10:28:13 +00:00
Carson McManus
d3b9471e95 update release script 2023-07-03 12:37:00 -04:00
Carson McManus
391371002b Release steamguard v0.10.0, steamguard-cli v0.10.0 2023-07-03 12:30:14 -04:00
Carson McManus
06af8c2219 Bump steamguard v0.10.0, steamguard-cli v0.10.0, safety bump steamguard-cli v0.10.0 2023-07-03 12:26:35 -04:00
Carson McManus
8f4ec79144
parallelize account loading and saving (#273)
- parallelize account loading
- parallelize account saving
2023-07-03 16:25:43 +00:00
Carson McManus
969baeed4c
upgrade some dependencies (#272)
- upgrade `rsa`, `zeroize` crates, closes #268
- switch to parrallelized pbkdf2, closes #271
- cargo update
2023-07-03 15:42:10 +00:00
Carson McManus
d5218d770e
add a new, faster encryption scheme (Argon2idAes256) and make it the default (#270)
- move legacy scheme to new module
- add argon2 crate
- mvoe test
- add argon2id aes encryption scheme
- refactor encryption to be less shit
- fix all the errors
- fix lints
2023-07-03 10:23:56 -04:00
Carson McManus
26c6916e79 update readme 2023-07-02 11:09:49 -04:00
Carson McManus
11b36c566e
Minor code refactors (#266) 2023-07-02 14:54:01 +00:00
Carson McManus
7e94f76653
Add support for storing encryption passkey in system keyring (#265)
- add keyring package
- add keyring id field to manifest
- automatically attempt to load encryption passkey from keyring
- have decrypt delete the passkey on decrypt
- have encrypt command ask if it should store the passkey in the keyring
- fix lints

closes #117
2023-07-02 14:44:18 +00:00
Carson McManus
fe663cf43f
add HTTP proxy support (#264)
- allow extracting the http client from web api transport
- refactor most commands so that they can accept an external transport
- update confirmer to use transport's http client
- update remove command
- update TwoFactorClient so it doesn't need to be mutable
- update get_server_time so it requires a transport
- update remove_authenticator
- update login proceedure to use given transport
- update usages of do_login
- update setup
- update trade
- update code command
- update qr-login command
- make borrowcheck happy
- make WebApiTransport Clone and remove Default impl
- remove dead code
- fix lints

closes #177
2023-07-02 12:57:13 +00:00
Carson McManus
1d99bae469 Release steamguard v0.9.5, steamguard-cli v0.9.7 2023-07-02 07:40:10 -04:00
Carson McManus
e25ab17fd6 Bump steamguard v0.9.5, steamguard-cli v0.9.7 2023-07-02 07:39:57 -04:00
Carson McManus
6f4064ff58 update release script 2023-07-02 07:39:46 -04:00
Carson McManus
3146d4824c
refactor to make adding proxy support easier later (#263) 2023-07-02 11:17:09 +00:00
Carson McManus
55a8bee695 update release script 2023-07-01 07:15:20 -04:00
Marvin Lehmann
b9d9179537
Add env option to configure maFiles path (#258)
I'd like to add this awesome tool to Scoop
(https://github.com/ScoopInstaller/Scoop) which works best with portable
programs.
Currently the problem is that steamguard-cli doesn't look for a
local/relative maFiles folder.
The alternative I opted for would be to use an env var which Scoop can
also set to its persist dir.
2023-06-30 23:44:57 +00:00
Carson McManus
f05f423d23 Bump steamguard v0.9.4, steamguard-cli v0.9.6 2023-06-30 11:11:09 -04:00
Carson McManus
4cc4d2370c update release script 2023-06-30 10:58:30 -04:00
Carson McManus
b3c6639146
remove: refactor to make it more reliable (#257)
fixes #256
2023-06-30 14:53:05 +00:00
Carson McManus
71d399f645 Bump steamguard v0.9.3, steamguard-cli v0.9.5 2023-06-29 19:04:11 -04:00
Carson McManus
4990d23c32
update release script (#255) 2023-06-29 18:49:03 -04:00
Carson McManus
6c4af1c9de
don't unwrap for path.extension() in manifest migration (#254)
should fix #253
2023-06-29 22:16:52 +00:00
Carson McManus
f7f9c916ba revert changes to release script 2023-06-29 17:59:16 -04:00
Carson McManus
b30eb050de update log crate 2023-06-29 17:58:48 -04:00
Carson McManus
3cb0869597 adjust release script 2023-06-29 17:51:10 -04:00
Carson McManus
06ea485e55 adjust release script 2023-06-29 17:50:14 -04:00
Carson McManus
dc591212bb
fix typo in update available text (#252) 2023-06-29 21:16:02 +00:00
Carson McManus
9bfd07c6b4
update ConfirmationType enum (#250) 2023-06-29 19:35:14 +00:00
Carson McManus
39fa6bb4a1
CI: fix rust cache collisions messing up the windows build (#249) 2023-06-29 14:51:41 +00:00
Carson McManus
0341db0046 CI: update rust cache steps 2023-06-29 10:38:37 -04:00
Carson McManus
201288952a CI: update rust cache steps 2023-06-29 10:35:50 -04:00
Carson McManus
4b92d46049
trade: use bulk confirmation operations (#248)
- Confirmer: add bulk confirmation operations
- trade: use bulk confirmation operations

closes #241
2023-06-29 14:33:56 +00:00
Carson McManus
0b8de57e3a
misc workflow improvements (#247)
- CI: add checks for build targets
- adjust release script
2023-06-29 08:33:34 -04:00
Carson McManus
6af4374da3
trade: misc confirmation fixes and tests (#246) 2023-06-27 19:13:26 +00:00
Carson McManus
0d24d12c55
trade: refactor how confirmations work so it's more reliable (#245) 2023-06-27 10:20:27 -04:00
Carson McManus
09fd78a5a5 Bump steamguard v0.9.2, steamguard-cli v0.9.4 2023-06-26 20:22:31 -04:00
Carson McManus
79c01833e8
fix manifest migration flow not prompting for passkey if not provided in args (#240) 2023-06-26 20:15:22 -04:00
Carson McManus
ad5a9b3131
trade: fix Account Details confirmation not parsing (#239)
fixes #238
2023-06-26 23:57:17 +00:00
Carson McManus
7d39da8213 Bump steamguard v0.9.1, steamguard-cli v0.9.3 2023-06-26 19:12:07 -04:00
Carson McManus
4fed9486de
trade: adjust logging for deserializing confirmations (#237) 2023-06-26 23:11:15 +00:00
Carson McManus
f8ae7d4e0e
fix SDA encryption compatibility (#236)
fixes #233
2023-06-26 23:02:48 +00:00
Carson McManus
da44f49c56
add some unit tests (#234)
- add unit test for migrating single accounts
- add manifest v1 loading tests
- disable a test
- update comment
- update vscode runners
- add a unit test to make sure migrated maFiles can still be read
2023-06-26 16:44:14 +00:00
Carson McManus
46ddaad281
import: tweak the helptext a little bit (#232) 2023-06-26 12:36:37 -04:00
Carson McManus
fdf54e6498 Bump steamguard-cli v0.9.2 2023-06-25 20:27:47 -04:00
Carson McManus
a062e718d7
fix passkey cli argument being printed in plaintext with debug logging (#229)
fixes #228
2023-06-26 00:23:26 +00:00
Carson McManus
ac7717bde8 Bump steamguard-cli v0.9.1 2023-06-25 19:53:12 -04:00
Carson McManus
d2ba7d8f1d
fix null OAuthToken field in SDA accounts causing migrations to crash and burn (#227) 2023-06-25 23:52:48 +00:00
Carson McManus
93a5fe643c Bump steamguard v0.9.0, steamguard-cli v0.9.0, safety bump steamguard-cli v0.9.0 2023-06-25 13:15:00 -04:00
Carson McManus
1632e2f10e
add PhoneLinker, and the ability to add a phone number to the account during setup (#223)
- add proto for IPhoneService
- add PhoneClient
- add PhoneLinker
- fix lints and such
- add comments
- update phone linker
- use phonenumber crate for phone linker
- adjust errors for account linker
- update setup command to be able to add phone numbers
- adjust logging in the setup command
- update account linker
2023-06-25 17:11:24 +00:00
Carson McManus
d87caa06f6
add an update checker (#222) 2023-06-25 09:24:53 -04:00
Carson McManus
f1855ba7c0 fix typo in quickstart 2023-06-24 15:52:36 -04:00
Carson McManus
a5be7b26bb
Add qr-login command to be able to approve qr code logins on other devices (#214)
- add QrApprover
- implement qr-login subcommand

closes #197
2023-06-24 13:45:03 -04:00
Carson McManus
bff16bd341
automatically refresh access token to avoid prompting to log in (#221) 2023-06-24 17:18:22 +00:00
Carson McManus
64697b6808
trade: fix not saving new tokens if there are no available confirmations (#220) 2023-06-24 13:02:54 -04:00
Carson McManus
7e04a4240a
Add TransportError type (#219)
- add TransportError type
- adjust Transport trait
2023-06-24 16:41:03 +00:00
Carson McManus
2dc6376533
print better errors when deserializing json (#218)
- print stripped json whenever there is a type mismatch when
deserializing
- Revert "print stripped json whenever there is a type mismatch when
deserializing"
- print better errors when deserializing json
2023-06-24 16:06:12 +00:00
Carson McManus
f080e35971
add quickstart document (#216) 2023-06-24 09:47:25 -04:00
Carson McManus
2d180f0209 Bump steamguard-cli v0.8.2 2023-06-24 08:25:56 -04:00
Carson McManus
2934dd3927
add a debug command to help triage deserialization issues (#213)
- add a debug command to help triage deserialization issues
- adjust the parsing for legacy accounts
2023-06-24 08:17:56 -04:00
Carson McManus
6a5b8d5573 fix exec permission on aur publish script 2023-06-23 15:42:35 -04:00
Carson McManus
a72126ffcd update pkgbuild 2023-06-23 15:41:04 -04:00
Carson McManus
fe0d6e9aca Bump steamguard v0.8.1, steamguard-cli v0.8.1 2023-06-23 15:22:51 -04:00
Carson McManus
9835b8a52f
change built artifact name from steamguard-cli to steamguard (#208) 2023-06-23 15:21:46 -04:00
Carson McManus
3eb17d78d2 add issue templates 2023-06-23 14:07:27 -04:00
Carson McManus
4deff5f633
make CI faster and more comprehensive (#207) 2023-06-23 13:46:55 -04:00
Carson McManus
cbc46ad8eb
Dead code cleanup, subcommand refactor (#206)
- clean up dead code
- fix lints
- move Session type to legacy module
- refactor service names into constants
- refactor build_url to be less restrictive for service names
- refactor most commands into their own modules
2023-06-23 17:36:23 +00:00
Carson McManus
8defefb11e
fix manifest migrations not working for encrypted maFiles (#201)
fixes #200
2023-06-23 12:40:23 +00:00
Carson McManus
7950e43f70 fix formatting in readme 2023-06-23 06:52:13 -04:00
Carson McManus
bd0d1f1fba add funding.yml 2023-06-22 17:27:22 -04:00
Carson McManus
e4eabdcdd3 Bump steamguard v0.8.0, steamguard-cli v0.8.0, safety bump steamguard-cli v0.8.0 2023-06-22 17:01:58 -04:00
Carson McManus
ac3120b016 update release script 2023-06-22 16:51:27 -04:00
Carson McManus
ee670c41c0 update release script 2023-06-22 16:46:38 -04:00
Carson McManus
ef382c1dce
add windows builds to release script, update readme (#195) 2023-06-22 16:42:44 -04:00
Carson McManus
bfd0667f3a
Use IAuthenticationService for login, account migrations, other major refactors (#194)
fixes #193
fixes #192  
fixes #107

- [x] Implement the new login process
    - [x] Tested
- [x] Update the authenticator setup process
    - [x] Tested
- [x] Update the authenticator remove process
    - [x] Tested
- [x] Manifest format migrator
    - [x] Tested
- [x] Make it possible to import SDA accounts
- [x] Make sure confirmations still work
    - [x] Fetching
    - [x] Responding
- [x] Make it so that the login process doesn't prompt for which method
to use
- [x] Make it so that device confirmation and email confirmation auth
session guards work
2023-06-22 20:20:15 +00:00
Jonas Süskind
75fcf3c456
Remove debug print to stdout in trade sub command (#191)
Every time when the `trade` sub command is executed, the webpage gets
printed to stdout which is a bit irritating and unnecessary.

This PR fixes this, in that it changes the `println!` macro to a
`trace!` macro.
2023-04-19 18:07:10 -04:00
Jonas Süskind
bf553ba251
Change steamguard-cli command to steamguard in example (#189)
A very minor pull request for a small (I believe) mistake in the
`README.md`. The command for generating and copying a new code to the
clipboard used `steamguard-cli` as command which took me a bit off guard
and made me question if I installed steamguard-cli correctly.

This PR changes it to `steamguard`.
2023-03-22 19:10:46 +00:00
Carson McManus
b277e53099 Bump steamguard v0.7.1, steamguard-cli v0.7.1 2023-03-18 10:52:41 -04:00
Carson McManus
4ba0459bb6
fix prompts sometimes not showing up (again) (#187)
- fix tui::pause only accept enter  to continue so it's less confusing
- replace unwrap with flush
- replace some prints with eprints
- make tui::prompt flush stdout and stderr

fixes #178
2023-03-18 14:20:37 +00:00
Carson McManus
3457f9cb43
disallow blank encryption passkeys (#186)
fixes #185
2023-03-18 10:08:57 -04:00
Carson McManus
2d4f9bb25c
Merge pull request #180 from dyc3/dependabot/cargo/tokio-1.20.3
Bump tokio from 1.19.2 to 1.20.3
2023-01-07 12:10:13 -05:00
dependabot[bot]
b4e5574815
Bump tokio from 1.19.2 to 1.20.3
Bumps [tokio](https://github.com/tokio-rs/tokio) from 1.19.2 to 1.20.3.
- [Release notes](https://github.com/tokio-rs/tokio/releases)
- [Commits](https://github.com/tokio-rs/tokio/compare/tokio-1.19.2...tokio-1.20.3)

---
updated-dependencies:
- dependency-name: tokio
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-01-06 21:46:32 +00:00
Carson McManus
15bb6230f0
Merge pull request #176 from dyc3/api-response-refactor
api response refactor
2022-12-06 10:12:25 -05:00
Carson McManus
8366173eb1 fix a couple of lints 2022-12-06 10:07:25 -05:00
Carson McManus
99f977d7df reorganize steam api responses 2022-12-06 10:02:07 -05:00
Carson McManus
911ead0242 actually fix architecture field on deb package 2022-12-05 12:07:39 -05:00
Carson McManus
9def58a39c Release steamguard v0.7.0, steamguard-cli v0.7.0, safety bump steamguard-cli v0.7.0 2022-12-05 11:58:57 -05:00
Carson McManus
c86eedd63c increment to v0.6.0 so smart-release increments it again 2022-12-05 11:58:27 -05:00
Carson McManus
932c98def5 update full release script to check for master branch 2022-12-05 11:50:37 -05:00
Carson McManus
daa930fbee
Merge pull request #174 from dyc3/qr
add the ability to generate a QR code for 2fa secrets
2022-12-05 11:24:17 -05:00
Carson McManus
27adb3d019
Merge pull request #175 from dyc3/setup-update
fix using uppercase letters in username during setup causing panic
2022-12-05 11:24:08 -05:00
Carson McManus
5634cf82ee fix doc comment 2022-12-05 11:18:59 -05:00
Carson McManus
cae60f6ed6 fix using uppercase letters in username during setup causing panic
fixes #171
2022-12-05 10:55:45 -05:00
Carson McManus
738e8f1664 update comment 2022-12-05 10:41:15 -05:00
Carson McManus
b5f4364733 update some comments and some printed messages 2022-12-05 10:36:38 -05:00
Carson McManus
2a5284f678 update some docs 2022-12-05 10:32:58 -05:00
Carson McManus
dcf1779f39 update AddAuthenticatorResponse 2022-12-05 10:29:54 -05:00
Carson McManus
d3099d7686 implement phone_validate 2022-12-05 10:29:28 -05:00
Carson McManus
85c4662a61 remove username argument from ArgsSetup because it was causing problems 2022-12-05 09:18:38 -05:00
Carson McManus
5599e28c9f add the ability to generate a QR code for 2fa secrets 2022-12-05 08:47:33 -05:00
Carson McManus
ea7bd32ec7
Merge pull request #168 from dyc3/fix-deb
fix Architecture field for debian package
2022-10-11 17:44:26 -04:00
Carson McManus
409518f455 fix Architecture field for debian package 2022-09-08 16:31:39 -04:00
Carson McManus
8c453585d5
Merge pull request #167 from dyc3/stderr-for-prompts
write input prompts to stderr instead of stdout
2022-09-08 16:29:10 -04:00
Carson McManus
7f0d5ca8ab write input prompts to stderr instead of stdout
closes #166
2022-09-08 16:24:23 -04:00
Carson McManus
db6557ca0d
Merge pull request #162 from dyc3/from-reader
add SteamGuardAccount::from_reader
2022-08-13 09:33:47 -04:00
Carson McManus
9f1d692d6d steamguard: add SteamGuardAccount::from_reader 2022-08-13 09:29:40 -04:00
Carson McManus
0d90792c47 add check in prompt_confirmation_menu to make sure confirmations is not empty 2022-08-04 23:07:43 -04:00
Carson McManus
980a14deb1
Merge pull request #161 from dyc3/confirmation-debug-logging
add some more debug logging around sending confirmations
2022-07-23 07:51:14 -04:00
Carson McManus
2409fac47e add some more debug logging around sending confirmations 2022-07-23 07:48:08 -04:00
Carson McManus
352a892075 specify version for steamguard in steamguard-cli 2022-06-25 11:26:43 -04:00
Carson McManus
9657ea6822 Release steamguard v0.5.0, steamguard-cli v0.5.0, safety bump steamguard-cli v0.5.0 2022-06-25 11:24:43 -04:00
Carson McManus
f9385ac78e update full release script 2022-06-25 11:24:26 -04:00
Carson McManus
9d1f2a7ee7 remove version specification for steamguard in steamguard-cli 2022-06-25 11:22:43 -04:00
Carson McManus
c78dd00731
Merge pull request #159 from dyc3/crossterm
Switch to crossterm library for terminal ui stuff
2022-06-25 11:13:19 -04:00
Carson McManus
6e31f66dde cargo fmt 2022-06-25 11:08:03 -04:00
Carson McManus
a9e5d4b1c5 fix up unit tests 2022-06-25 11:07:57 -04:00
Carson McManus
15349156db remove termion 2022-06-25 11:04:12 -04:00
Carson McManus
0b340a3cf1 replace tty check with crossterm 2022-06-25 11:01:40 -04:00
Carson McManus
5a262650a0 converted remaining tui module to crossterm 2022-06-25 10:57:37 -04:00
Carson McManus
ebe31b6df7 convert prompt_confirmation_menu to crossterm 2022-06-25 10:14:34 -04:00
Carson McManus
230f85b6ac add crossterm to cargo.toml 2022-06-25 09:09:23 -04:00
Carson McManus
afb1d79aea adjust visibility of some functions/modules 2022-06-25 09:06:29 -04:00
Carson McManus
ad8344460d Merge branch 'master' of github.com:dyc3/steamguard-cli 2022-06-25 09:02:14 -04:00
Carson McManus
5303bd69d0 small improvements to full release script 2022-06-25 09:01:00 -04:00
Carson McManus
9f338a7af3
Merge pull request #158 from dyc3/passkey-env-var
add STEAMGUARD_CLI_PASSKEY environment variable
2022-06-23 23:58:18 -04:00
Carson McManus
cac5f57cc7 add STEAMGUARD_CLI_PASSKEY environment variable 2022-06-23 23:39:41 -04:00
Carson McManus
3f5fa9a033
Merge pull request #156 from dyc3/offline-code-gen
Make it possible to generate codes offline
2022-06-21 20:38:02 -04:00
Carson McManus
a52af3675b add code subcommand back in, because it makes the arg parsing better 2022-06-21 19:31:39 -04:00
Carson McManus
fdc61e63d1 add --offline flag for generating codes, closes #155 2022-06-20 20:57:04 -04:00
Carson McManus
610cda120e get_server_time now returns Result, fixes #152 2022-06-20 20:56:36 -04:00
Carson McManus
2678961a4c fix not prompting for password for decrypt 2022-06-19 15:23:55 -04:00
Carson McManus
1ee063f58e
Merge pull request #154 from dyc3/more-memory-protection
Mark all sensitive fields in SteamGuardAccount as secret
2022-06-19 14:59:39 -04:00
Carson McManus
1a6ad62a2e cargo fmt 2022-06-19 14:52:17 -04:00
Carson McManus
eeded86641 protect Session memory, values are zeroized when dropped 2022-06-19 14:52:17 -04:00
Carson McManus
deabfc299d protect top level secrets in SteamGuardAccount
except for session
2022-06-19 14:52:17 -04:00
Carson McManus
d8db1ae9b3
Merge pull request #151 from dyc3/refactor-clap-derive
Upgrade to clap v3, switch argument parsing to derive api
2022-06-19 14:48:53 -04:00
Carson McManus
8839a18543 cargo fmt 2022-06-19 14:44:47 -04:00
Carson McManus
c86e31648a fix some warnings 2022-06-19 13:01:25 -04:00
Carson McManus
0b84a103e5 remove old arg parsing completely 2022-06-19 13:00:36 -04:00
Carson McManus
d13ca2079e add conflicts_with arg metadata 2022-06-19 12:59:20 -04:00
Carson McManus
2fc13d40e2 switch get_selected_accounts to new args 2022-06-19 12:57:54 -04:00
Carson McManus
174456226b improve help test for verbosity 2022-06-19 12:48:07 -04:00
Carson McManus
5e3b2507ab add arg_enum marker for verbosity arg 2022-06-19 12:47:07 -04:00
Carson McManus
ed9cf91cfb return better error for unimplemented subcommand 2022-06-19 12:45:33 -04:00
Carson McManus
e653ac684f set name and bin_name metadata 2022-06-19 12:42:36 -04:00
Carson McManus
1b7c089fa1 fix arg parsing for shell arg 2022-06-19 12:39:33 -04:00
Carson McManus
221e64ab8c change debug line 2022-06-19 12:38:47 -04:00
Carson McManus
4a8f7a74d2 reimplement completion subcommand 2022-06-19 12:37:40 -04:00
Carson McManus
8dd10c9b29 move debug subcommand impl 2022-06-19 12:16:20 -04:00
Carson McManus
aaded51d38 move generate code subcommand impl 2022-06-19 11:54:42 -04:00
Carson McManus
31c08ac206 move trade and remove subcommand impls 2022-06-19 11:54:16 -04:00
Carson McManus
73281ef069 move import subcommand impl 2022-06-19 11:52:26 -04:00
Carson McManus
37539f7679 move encrypt and decrypt subcommand impls to functions 2022-06-19 11:40:20 -04:00
Carson McManus
138f36f562 move help text 2022-06-19 11:32:04 -04:00
Carson McManus
9f7c8fef68 remove old verbosity arg 2022-06-19 11:31:56 -04:00
Carson McManus
b040088038 swtich mafiles path to new args 2022-06-19 11:26:18 -04:00
Carson McManus
07b9439c27 switch to a better setup for subcommands 2022-06-19 11:14:35 -04:00
Carson McManus
2f4d1e3cfa make it compile again 2022-06-19 10:56:52 -04:00
Carson McManus
14d49d33b1 move args definitions to new file 2022-06-19 10:48:18 -04:00
Carson McManus
b55df7ea26 add subcommand arg types 2022-06-19 10:38:59 -04:00
Carson McManus
e6847975ff converted some subcommands 2022-06-14 06:37:30 -04:00
Carson McManus
6ef038efc9 convert most of the remaining arg definitions 2022-06-14 06:37:30 -04:00
Carson McManus
abe808b7bf upgrade to clap v3, convert global level arguments 2022-06-14 06:37:30 -04:00
Carson McManus
a19f379314 Release steamguard-cli v0.4.5 2022-06-14 06:17:40 -04:00
Carson McManus
eb08e751b4 fix architecture string for deb packages, again 2022-06-14 06:16:59 -04:00
Carson McManus
57c64b346d
Merge pull request #150 from dyc3/fix-149
fix not getting prompted interactively for encryption passkey
2022-06-13 22:22:01 -04:00
Carson McManus
2c68f3389d fix not getting prompted interactively for encryption passkey 2022-06-12 22:01:35 -04:00
Carson McManus
84e2712403 fix aur tester job 2022-06-12 11:36:43 -04:00
Carson McManus
43f73e91bd Release steamguard v0.4.2, steamguard-cli v0.4.4 2022-06-12 11:05:19 -04:00
Carson McManus
01498ff069 fix typo 2022-06-12 11:04:17 -04:00
Carson McManus
af0379ac3d
Merge pull request #148 from dyc3/bin-portability
Better binary portability
2022-06-12 10:31:30 -04:00
Carson McManus
944bd2abcd remove aur updater from full release script 2022-06-12 10:24:55 -04:00
Carson McManus
bc0ec74596 fix deb package architecture metadata 2022-06-12 10:20:46 -04:00
Carson McManus
6a82b236aa add symlink for "steamguard-cli" in deb packages 2022-06-12 10:19:54 -04:00
Carson McManus
28b4f8ea39 build releases using cross for more portable builds 2022-06-12 09:46:44 -04:00
Carson McManus
0374525697 switch to using rustls-tls to make binaries more portable 2022-06-12 09:41:47 -04:00
Carson McManus
fc8653fab7 log distro info when building deb 2022-06-12 09:24:04 -04:00
Carson McManus
603d8555ab
Merge pull request #146 from dyc3/update-deps
update dependencies
2022-06-08 20:53:49 -04:00
Carson McManus
39707e808a update dependencies 2022-06-08 20:49:29 -04:00
Carson McManus
2da17c9a0a
Merge pull request #138 from dyc3/manifest-upgrades
Manifest auto-upgrades and Lazy account loading
2022-02-22 09:46:26 -05:00
Carson McManus
be80904f96 cargo fmt 2022-02-22 09:38:41 -05:00
Carson McManus
a56659e44f force load all accounts when encrypting and decrypting 2022-02-22 09:29:34 -05:00
Carson McManus
ae2049abe8 make auto-upgrades more explicit 2022-02-22 09:19:56 -05:00
Carson McManus
7dcfbc112f refactor: move selected account logic into function 2022-02-22 09:17:04 -05:00
Carson McManus
10d97efe16 refactor: make loading single account not borrow manifest mutably 2022-02-22 09:08:39 -05:00
Carson McManus
02014972b4
Merge pull request #136 from dyc3/refactor-dont-require-all-accounts
refactor: account manager no longer needs to have all accounts loaded in order to function
2022-02-21 14:03:20 -05:00
Carson McManus
0bdaa60bbf add test for manifest with 2 accounts 2022-02-21 13:23:59 -05:00
Carson McManus
00ea8dca71 refactor: account manager no longer needs to have all accounts loaded in order to function 2022-02-21 12:50:50 -05:00
Carson McManus
eb3c417ff2
Merge pull request #134 from dyc3/non-zero-exit-codes
non zero exit codes
2022-02-21 12:26:32 -05:00
Carson McManus
69159b9360 cargo fmt 2022-02-21 12:22:03 -05:00
Carson McManus
c11593e7e4 add --fail-fast argument for responding to confirmations 2022-02-21 12:14:15 -05:00
Carson McManus
b1d559ea00 add non-zero exit codes when unrecoverable errors occur. 2022-02-21 11:59:14 -05:00
Carson McManus
c6bd5b5dc4 update badges 2022-02-04 12:29:55 -05:00
Carson McManus
0c797f41f6
Merge pull request #125 from kasp1/patch-1
Update README.md
2022-02-04 12:19:14 -05:00
Mirek Kaspar
d8dec8a29f
Update README.md 2022-02-04 13:28:06 +00:00
Carson McManus
55ca4dc049
Merge pull request #124 from h44z/fix-pkgbuild
Fix pkgver, always use version for steamguard-cli
2022-02-02 11:29:48 -05:00
h44z
537060fc1f
Fix pkgver, always use version for steamguard-cli
Instead of using the tag name of steamguard (steamguard-vX.X.X), use the tag for steamguard-cli (vX.X.X).
2022-02-02 16:34:01 +01:00
Carson McManus
1901994d0e Release steamguard v0.4.1, steamguard-cli v0.4.3 2022-01-15 12:32:25 -05:00
Carson McManus
14cd422207 disable changelog generation for releases 2022-01-15 12:32:18 -05:00
Carson McManus
eb199178b1 Adjusting changelogs prior to release of steamguard v0.4.1, steamguard-cli v0.4.3 2022-01-15 12:26:40 -05:00
Carson McManus
b4fc32f6f9 update pkgbuild for new release 2022-01-15 12:23:48 -05:00
Carson McManus
145c03e926
Merge pull request #122 from dyc3/CI-AUR-install
Fix for aur install script running in CI
2022-01-15 12:09:52 -05:00
Carson McManus
c75db0f6e3 fix check aur CI job 2022-01-15 12:06:23 -05:00
Carson McManus
86d5f40989
Merge pull request #121 from dyc3/CI-AUR-install
CI AUR install
2022-01-15 12:03:16 -05:00
Carson McManus
dfdd9563c4 add aur install checker to CI, closes #102 2022-01-15 11:56:31 -05:00
Carson McManus
8b1f3a145d add check-aur.sh to check if the aur package works
intended to be used in CI
2022-01-15 11:40:25 -05:00
Carson McManus
743abea8bf
Merge pull request #120 from gergesh/make-webcookie-optional
Make WebCookie optional in Session
2022-01-15 09:40:38 -05:00
Carson McManus
d21ceef797 add sda compat unit test for no web cookie 2022-01-15 09:36:10 -05:00
Carson McManus
070be5b629 re-add no webcookie test fixture as a seperate fixture 2022-01-15 09:24:12 -05:00
Carson McManus
669d8e4dad Revert "Add test case for maFile with null WebCookie"
This reverts commit a48ada2252.
2022-01-15 09:23:21 -05:00
Yoav Shai
a48ada2252 Add test case for maFile with null WebCookie 2022-01-15 14:22:50 +02:00
Yoav Shai
4900a2ede7 Make WebCookie optional in Session
The maFile from Steam Desktop Authenticator may set this field to null
2022-01-15 02:21:36 +02:00
Carson McManus
ccc087b797
Merge pull request #119 from dyc3/better-failure-message
add a better failure message for account link status 2
2022-01-02 09:51:16 -05:00
Carson McManus
c27b01318b add a better failure message for account link status 2 2022-01-02 09:46:01 -05:00
Carson McManus
6ee4b4eab8 Revert broken AUR automation 2021-11-14 15:23:51 -05:00
Carson McManus
9a5b0fbf6a
Merge pull request #115 from dyc3/aur-automation
AUR automation
2021-11-14 14:47:07 -05:00
Carson McManus
033ef7a4a1 add publish to AUR workflow 2021-11-14 14:42:57 -05:00
Carson McManus
672e4bbce8 generate .SRCINFO 2021-11-14 14:42:30 -05:00
Carson McManus
2e96ca8f6e move aur publish to separate script 2021-11-14 12:30:30 -05:00
Carson McManus
5d38ad84c7 remove gitmodules 2021-11-14 12:21:09 -05:00
Carson McManus
00b6bcb7c7 remove old release workflows 2021-11-14 12:15:40 -05:00
Carson McManus
3bcfaff786 link to the AUR in the readme 2021-11-14 12:05:58 -05:00
Carson McManus
4b9745237d update PKGBUILD 2021-11-14 11:58:59 -05:00
Carson McManus
df699f0785 Release steamguard-cli v0.4.2 2021-11-14 11:46:08 -05:00
Carson McManus
37e818e9ca Merge branch 'master' of github.com:dyc3/steamguard-cli 2021-11-14 11:44:36 -05:00
Carson McManus
e6f75fa5aa fix full release script so that version bumps are actually respected 2021-11-14 11:44:29 -05:00
Carson McManus
873e564104
Update README.md 2021-10-26 13:36:16 -04:00
Carson McManus
17a4ebe813
Merge pull request #110 from dyc3/forbid-duplicates
forbid duplicates
2021-09-06 17:01:28 -04:00
Carson McManus
1ffe464ed8 cargo fmt 2021-09-06 16:57:36 -04:00
Carson McManus
4ac3c09338 fix small logic bug in prompt_char 2021-09-06 16:56:22 -04:00
Carson McManus
e4cf29e852 don't allow setup or import for account_names already in the manifest, fixes #109 2021-09-06 16:51:44 -04:00
Carson McManus
a92cd5b1aa allow accounts to be removed from manifest without successfully removing authenticator from account 2021-09-06 16:14:57 -04:00
Carson McManus
274dd373c2 cargo fmt 2021-09-06 16:05:26 -04:00
Carson McManus
e6d8de4dc2 add some logging for generating codes 2021-09-06 15:49:23 -04:00
Carson McManus
a311df931b indicate that the username arg is case sensitive 2021-09-01 08:56:24 -04:00
Carson McManus
376b7b8870 add a little bit of logging 2021-09-01 08:52:23 -04:00
Carson McManus
3e0397ace7 add version match check 2021-09-01 08:44:23 -04:00
Carson McManus
d285a4ba3b explicitly cargo build 2021-08-29 21:04:06 -04:00
Carson McManus
7c949a75c8 Release steamguard-cli v0.4.1 2021-08-29 21:01:17 -04:00
Carson McManus
a36544e1ff add --update-crates-index arg 2021-08-29 21:01:02 -04:00
Carson McManus
6fa5e6d78a add git to makedepends in PKGBUILD 2021-08-29 20:38:39 -04:00
Carson McManus
6d2b10022e flush output before waiting for input in prompt_char_impl, fixes #103 2021-08-29 20:36:51 -04:00
Carson McManus
bb6c733999 save empty manifest directly after prompting to create one 2021-08-29 20:17:17 -04:00
Carson McManus
b941415715 update release script 2021-08-27 11:39:57 -04:00
Carson McManus
add51351c1
Merge pull request #100 from mads256h/add-pkgbuild
Add PKGBUILD
2021-08-26 15:15:23 -04:00
Mads Mogensen
86733d50a8
Add PKGBUILD
The one generated with cargo-pkgbuild is really broken
2021-08-26 19:32:52 +02:00
Carson McManus
6d546e6298
Merge pull request #99 from dyc3/remove-old-stuff
remove all the old C# stuff
2021-08-25 19:40:58 -04:00
Carson McManus
3c05e95fda remove all the old C# stuff 2021-08-25 19:37:14 -04:00
Carson McManus
5153bcd1dc update readme and release script 2021-08-25 13:04:06 -04:00
Carson McManus
692d431fab Release steamguard-cli v0.4.0 2021-08-25 12:18:32 -04:00
Carson McManus
26184d5544 replace old release if it is still a draft 2021-08-25 12:18:27 -04:00
Carson McManus
e9ca3f6a42 Release steamguard-cli v0.4.0 2021-08-25 12:06:54 -04:00
Carson McManus
a2ab02c3a2 supply version in cargo toml 2021-08-25 12:06:49 -04:00
Carson McManus
6aab910403 Release steamguard-cli v0.4.0 2021-08-25 12:04:41 -04:00
140 changed files with 13743 additions and 5426 deletions

3
.github/FUNDING.yml vendored Normal file
View file

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

42
.github/ISSUE_TEMPLATE/bug.yml vendored Normal file
View file

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

5
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View file

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

13
.github/ISSUE_TEMPLATE/feature.yml vendored Normal file
View file

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

17
.github/workflows/aur-checker.yml vendored Normal file
View file

@ -0,0 +1,17 @@
name: AUR Tester
on:
schedule:
- cron: "32 5 */3 * *"
push:
branches: [ master, main ]
workflow_dispatch:
jobs:
test-install:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install AUR package
run: ./scripts/check-aur.sh

View file

@ -1,88 +0,0 @@
name: Release new version
on:
workflow_dispatch:
inputs:
version:
description: 'The version number to use'
default: '0.0.0.0'
# Input has to be provided for the workflow to run
required: true
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Validate version number
run: |
# validate version structure
bash -c '[[ ${{ github.event.inputs.version }} =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]] || exit 1'
# ensure version doesn't already exist
bash -c 'git rev-parse "v${{ github.event.inputs.version }}" >/dev/null 2>&1 && exit 2 || exit 0'
- name: Checkout
uses: actions/checkout@v2.3.3
with:
submodules: true
- name: Install dependencies
run: sudo apt install nuget mono-complete make
- name: Update version number, and commit
run: |
git config --global user.name "Github Actions"
git config --global user.email "dyc3@users.noreply.github.com"
sed -ri "s/Version\(\"[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\"\)/Version\(\"${{ github.event.inputs.version }}\"\)/g" AssemblyInfo.cs
git commit -m "Update version" AssemblyInfo.cs
- name: Build
run: |
nuget restore SteamAuth/SteamAuth/SteamAuth.sln
make
mv build steamguard-cli-v${{ github.event.inputs.version }}
tar -cf steamguard-cli-v${{ github.event.inputs.version }}.tar.gz steamguard-cli-v${{ github.event.inputs.version }}
- name: Tag and push version commit
run: |
git push origin master
git tag -a "v${{ github.event.inputs.version }}" -m "Release v${{ github.event.inputs.version }}"
git push origin "v${{ github.event.inputs.version }}"
- name: Upload Build Artifact
uses: actions/upload-artifact@v2.2.0
with:
name: build
path: steamguard-cli-v${{ github.event.inputs.version }}.tar.gz
deb-package:
runs-on: ubuntu-latest
needs: [build]
steps:
- name: Checkout
uses: actions/checkout@v2.3.3
- name: Download Build Artifact (tar)
uses: actions/download-artifact@v2.0.5
with:
name: build
- run: |
tar -xf steamguard-cli-v${{ github.event.inputs.version }}.tar.gz
mv steamguard-cli-v${{ github.event.inputs.version }} build
bash package.sh
- name: Upload deb
uses: actions/upload-artifact@v2.2.0
with:
name: deb
path: steamguard-cli_${{ github.event.inputs.version }}-0.deb
# TODO: update AUR pkgbuild
draft:
needs: [build, deb-package]
runs-on: ubuntu-latest
steps:
- name: Download Build Artifact (tar)
uses: actions/download-artifact@v2.0.5
with:
name: build
- name: Download Build Artifact (deb)
uses: actions/download-artifact@v2.0.5
with:
name: deb
- name: Release Drafter
uses: release-drafter/release-drafter@v5.11.0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
name: v${{ github.event.inputs.version }}
tag: v${{ github.event.inputs.version }}
version: ${{ github.event.inputs.version }}
publish: false

View file

@ -1,88 +0,0 @@
name: Release new version
on:
workflow_dispatch:
inputs:
version:
description: 'The version number to use'
default: '0.0.0.0'
# Input has to be provided for the workflow to run
required: true
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Validate version number
run: |
# validate version structure
bash -c '[[ ${{ github.event.inputs.version }} =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]] || exit 1'
# ensure version doesn't already exist
bash -c 'git rev-parse "v${{ github.event.inputs.version }}" >/dev/null 2>&1 && exit 2 || exit 0'
- name: Checkout
uses: actions/checkout@v2.3.3
with:
submodules: true
- name: Install dependencies
run: sudo apt install nuget mono-complete make
- name: Update version number, and commit
run: |
git config --global user.name "Github Actions"
git config --global user.email "dyc3@users.noreply.github.com"
sed -ri "s/Version\(\"[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\"\)/Version\(\"${{ github.event.inputs.version }}\"\)/g" AssemblyInfo.cs
git commit -m "Update version" AssemblyInfo.cs
- name: Build
run: |
nuget restore SteamAuth/SteamAuth/SteamAuth.sln
make
mv build steamguard-cli-v${{ github.event.inputs.version }}
tar -cf steamguard-cli-v${{ github.event.inputs.version }}.tar.gz steamguard-cli-v${{ github.event.inputs.version }}
- name: Tag and push version commit
run: |
git push origin master
git tag -a "v${{ github.event.inputs.version }}" -m "Release v${{ github.event.inputs.version }}"
git push origin "v${{ github.event.inputs.version }}"
- name: Upload Build Artifact
uses: actions/upload-artifact@v2.2.0
with:
name: build
path: steamguard-cli-v${{ github.event.inputs.version }}.tar.gz
deb-package:
runs-on: ubuntu-latest
needs: [build]
steps:
- name: Checkout
uses: actions/checkout@v2.3.3
- name: Download Build Artifact (tar)
uses: actions/download-artifact@v2.0.5
with:
name: build
- run: |
tar -xf steamguard-cli-v${{ github.event.inputs.version }}.tar.gz
mv steamguard-cli-v${{ github.event.inputs.version }} build
bash package.sh
- name: Upload deb
uses: actions/upload-artifact@v2.2.0
with:
name: deb
path: steamguard-cli_${{ github.event.inputs.version }}-0.deb
# TODO: update AUR pkgbuild
draft:
needs: [build, deb-package]
runs-on: ubuntu-latest
steps:
- name: Download Build Artifact (tar)
uses: actions/download-artifact@v2.0.5
with:
name: build
- name: Download Build Artifact (deb)
uses: actions/download-artifact@v2.0.5
with:
name: deb
- name: Release Drafter
uses: release-drafter/release-drafter@v5.11.0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
name: v${{ github.event.inputs.version }}
tag: v${{ github.event.inputs.version }}
version: ${{ github.event.inputs.version }}
publish: false

View file

@ -1,42 +1,47 @@
name: Rust
name: Lint, Build, Test
on:
push:
branches: [ master, main ]
branches: [master, main]
pull_request:
branches: [ master, main ]
branches: [master, main]
env:
CARGO_TERM_COLOR: always
jobs:
build:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Build
run: cargo build --workspace --verbose
- run: rustup component add clippy rustfmt
- uses: actions/checkout@v4
- name: Rust Cache
uses: Swatinem/rust-cache@v2
- name: Check format
run: cargo fmt --all -- --check
- name: Check
run: cargo check --verbose --all-targets --all-features
- name: Clippy
run: cargo clippy --workspace --no-deps --all-features --all-targets -- -D warnings
- name: Validate documentation
run: cargo doc --workspace --no-deps --all-features
- name: Run tests
run: cargo test --workspace --verbose
lint:
name: rustfmt
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:
- name: Checkout sources
uses: actions/checkout@v2
- name: Install stable toolchain
uses: actions-rs/toolchain@v1
- uses: actions/checkout@v4
- name: Rust Cache
uses: Swatinem/rust-cache@v2
with:
profile: minimal
toolchain: stable
override: true
components: rustfmt
- name: Run cargo fmt
uses: actions-rs/cargo@v1
prefix-key: v0-rust-${{ matrix.target }}
- name: Install Cross
uses: baptiste0928/cargo-install@v2
with:
command: fmt
args: --all -- --check
crate: cross
- name: Check
run: cross check --verbose --all-targets --all-features --target ${{ matrix.target }}

1
.gitignore vendored
View file

@ -6,6 +6,7 @@ SteamAuth/SteamAuth/packages/
test_maFiles/
*.deb
*.tar.gz
target/
aur/

3
.gitmodules vendored
View file

@ -1,3 +0,0 @@
[submodule "SteamAuth"]
path = SteamAuth
url = https://github.com/dyc3/SteamAuth.git

8
.vscode/launch.json vendored
View file

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

View file

@ -1,36 +0,0 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("steamguard-cli")]
[assembly: AssemblyDescription("https://github.com/dyc3/steamguard-cli")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("steamguard-cli")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.3.5.1")]
[assembly: AssemblyFileVersion("0.3.5.1")]

3892
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -1,55 +1,82 @@
[workspace]
members = [
"steamguard"
]
members = ["steamguard"]
[package]
name = "steamguard-cli"
version = "0.4.0"
authors = ["Carson McManus <carson.mcmanus1@gmail.com>"]
edition = "2018"
version = "0.14.0"
authors = ["dyc3 (Carson McManus) <carson.mcmanus1@gmail.com>"]
edition = "2021"
description = "A command line utility to generate Steam 2FA codes and respond to confirmations."
keywords = ["steam", "2fa", "steamguard", "authentication", "cli"]
categories = ["command-line-utilities"]
repository = "https://github.com/dyc3/steamguard-cli"
license = "GPL-3.0-or-later"
[[bin]]
name = "steamguard-cli"
[features]
default = ["qr", "updater", "keyring"]
qr = ["dep:qrcode"]
updater = ["dep:update-informer"]
keyring = ["dep:keyring"]
# [[bin]]
# name = "steamguard-cli"
# filename = "steamguard" # TODO: uncomment when https://github.com/rust-lang/cargo/issues/9778 is stablized.
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[[bin]]
name = "steamguard"
path = "src/main.rs"
[dependencies]
anyhow = "^1.0"
hmac-sha1 = "^0.1"
base64 = "0.13.0"
base64 = "0.22.1"
text_io = "0.1.8"
rpassword = "5.0"
reqwest = { version = "0.11", features = ["blocking", "json", "cookies", "gzip"] }
rpassword = "7.2.0"
reqwest = { version = "0.12", default-features = false, features = [
"blocking",
"json",
"cookies",
"gzip",
"rustls-tls",
] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
rsa = "0.5.0"
rand = "0.8.4"
standback = "0.2.17" # required to fix a compilation error on a transient dependency
clap = "2.33.3"
log = "0.4.14"
stderrlog = "0.4"
cookie = "0.14"
rsa = "0.9.2"
rand = "0.8.5"
clap = { version = "4.5.4", features = ["derive", "cargo", "env"] }
clap_complete = "4.5.2"
log = "0.4.19"
stderrlog = "0.6"
cookie = "0.18"
regex = "1"
lazy_static = "1.4.0"
uuid = { version = "0.8", features = ["v4"] }
termion = "1.5.6"
steamguard = { path = "./steamguard" }
dirs = "3.0.2"
ring = "0.16.20"
aes = "0.7.4"
block-modes = "0.8.1"
thiserror = "1.0.26"
uuid = { version = "1.8", features = ["v4"] }
steamguard = { version = "^0.14.0", path = "./steamguard" }
dirs = "5.0.1"
aes = { version = "0.8.3", features = ["zeroize"] }
thiserror = "1.0.61"
crossterm = { version = "0.23.2", features = ["event-stream"] }
qrcode = { version = "0.14.0", optional = true }
gethostname = "0.4.3"
secrecy = { version = "0.8", features = ["serde"] }
zeroize = { version = "^1.6.0", features = ["std", "zeroize_derive"] }
serde_path_to_error = "0.1.11"
update-informer = { version = "1.0.0", optional = true, default-features = false, features = [
"github",
] }
phonenumber = "0.3"
cbc = { version = "0.1.2", features = ["std", "zeroize"] }
inout = { version = "0.1.3", features = ["std"] }
keyring = { version = "2.0.4", optional = true }
argon2 = { version = "0.5.0", features = ["std", "zeroize"] }
pbkdf2 = { version = "0.12.1", features = ["parallel"] }
sha1 = "0.10.5"
rayon = "1.7.0"
rqrr = "0.7.1"
image = "0.25"
[dev-dependencies]
tempdir = "0.3"
tempfile = "3"
proptest = "1"
[profile.release]

View file

@ -1,546 +0,0 @@
using Newtonsoft.Json;
using SteamAuth;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
namespace SteamGuard
{
public class Manifest
{
private const int PBKDF2_ITERATIONS = 50000; //Set to 50k to make program not unbearably slow. May increase in future.
private const int SALT_LENGTH = 8;
private const int KEY_SIZE_BYTES = 32;
private const int IV_LENGTH = 16;
[JsonProperty("encrypted")]
public bool Encrypted { get; set; }
[JsonProperty("first_run")]
public bool FirstRun { get; set; } = true;
[JsonProperty("entries")]
public List<ManifestEntry> Entries { get; set; }
[JsonProperty("periodic_checking")]
public bool PeriodicChecking { get; set; } = false;
[JsonProperty("periodic_checking_interval")]
public int PeriodicCheckingInterval { get; set; } = 5;
[JsonProperty("periodic_checking_checkall")]
public bool CheckAllAccounts { get; set; } = false;
[JsonProperty("auto_confirm_market_transactions")]
public bool AutoConfirmMarketTransactions { get; set; } = false;
[JsonProperty("auto_confirm_trades")]
public bool AutoConfirmTrades { get; set; } = false;
private static Manifest _manifest { get; set; }
public static Manifest GetManifest(bool forceLoad = false)
{
// Check if already staticly loaded
if (_manifest != null && !forceLoad)
{
return _manifest;
}
// Find config dir and manifest file
string maFile = Path.Combine(Program.SteamGuardPath, "manifest.json");
// If there's no config dir, create it
if (!Directory.Exists(Program.SteamGuardPath))
{
_manifest = _generateNewManifest();
return _manifest;
}
// If there's no manifest, create it
if (!File.Exists(maFile))
{
Utils.Verbose("warn: No manifest file found at {0}", maFile);
bool? createNewManifest = Program.SteamGuardPath ==
Program.defaultSteamGuardPath.Replace("~", Environment.GetEnvironmentVariable("HOME")) ? true : (bool?) null;
while (createNewManifest == null)
{
Console.Write($"Generate new manifest.json in {Program.SteamGuardPath}? [Y/n]");
var answer = Console.ReadLine();
if (answer != null)
createNewManifest = !answer.StartsWith("n") && !answer.StartsWith("N");
}
if ((bool) createNewManifest)
{
_manifest = _generateNewManifest(true);
return _manifest;
}
return null;
}
try
{
string manifestContents = File.ReadAllText(maFile);
_manifest = JsonConvert.DeserializeObject<Manifest>(manifestContents);
if (_manifest.Encrypted && _manifest.Entries.Count == 0)
{
_manifest.Encrypted = false;
_manifest.Save();
}
_manifest.RecomputeExistingEntries();
Utils.Verbose($"{_manifest.Entries.Count} accounts loaded");
return _manifest;
}
catch (Exception ex)
{
Console.WriteLine("error: Could not open manifest file: {0}", ex.ToString());
return null;
}
}
private static Manifest _generateNewManifest(bool scanDir = false)
{
Utils.Verbose("Generating new manifest...");
// No directory means no manifest file anyways.
Manifest newManifest = new Manifest();
newManifest.Encrypted = false;
newManifest.PeriodicCheckingInterval = 5;
newManifest.PeriodicChecking = false;
newManifest.AutoConfirmMarketTransactions = false;
newManifest.AutoConfirmTrades = false;
newManifest.Entries = new List<ManifestEntry>();
newManifest.FirstRun = true;
// Take a pre-manifest version and generate a manifest for it.
if (scanDir)
{
if (Directory.Exists(Program.SteamGuardPath))
{
DirectoryInfo dir = new DirectoryInfo(Program.SteamGuardPath);
var files = dir.GetFiles();
foreach (var file in files)
{
if (file.Extension != ".maFile") continue;
string contents = File.ReadAllText(file.FullName);
try
{
SteamGuardAccount account = JsonConvert.DeserializeObject<SteamGuardAccount>(contents);
ManifestEntry newEntry = new ManifestEntry()
{
Filename = file.Name,
SteamID = account.Session.SteamID
};
newManifest.Entries.Add(newEntry);
}
catch (Exception ex)
{
Utils.Verbose("warn: {0}", ex.Message);
}
}
if (newManifest.Entries.Count > 0)
{
newManifest.Save();
newManifest.PromptSetupPassKey(true);
}
}
}
if (newManifest.Save())
{
return newManifest;
}
return null;
}
public class IncorrectPassKeyException : Exception { }
public class ManifestNotEncryptedException : Exception { }
// TODO: move PromptForPassKey to Program.cs
// TODO: make PromptForPassKey more secure
public string PromptForPassKey()
{
if (!this.Encrypted)
{
throw new ManifestNotEncryptedException();
}
bool passKeyValid = false;
string passKey = "";
while (!passKeyValid)
{
Console.WriteLine("Please enter encryption password: ");
passKey = Utils.ReadLineSecure();
if (passKey == "")
continue;
passKeyValid = this.VerifyPasskey(passKey);
if (!passKeyValid)
{
Console.WriteLine("Incorrect.");
}
}
return passKey;
}
// TODO: move PromptSetupPassKey to Program.cs
public string PromptSetupPassKey(bool inAccountSetupProcess = false)
{
if (inAccountSetupProcess)
{
Console.Write("Would you like to use encryption? [Y/n] ");
string doEncryptAnswer = Console.ReadLine();
if (doEncryptAnswer == "n" || doEncryptAnswer == "N")
{
Console.WriteLine("WARNING: You chose to not encrypt your files. Doing so imposes a security risk for yourself. If an attacker were to gain access to your computer, they could completely lock you out of your account and steal all your items.");
Console.WriteLine("You may add encryption later using the --encrypt argument.");
return null;
}
}
string newPassKey = "";
string confirmPassKey = "";
do
{
Console.Write("Enter" + (inAccountSetupProcess ? " " : " new ") + "passkey: ");
newPassKey = Utils.ReadLineSecure();
Console.Write("Confirm" + (inAccountSetupProcess ? " " : " new ") + "passkey: ");
confirmPassKey = Utils.ReadLineSecure();
if (newPassKey != confirmPassKey)
{
Console.WriteLine("Passkeys do not match.");
}
} while (newPassKey != confirmPassKey || newPassKey == "");
return newPassKey;
}
public SteamAuth.SteamGuardAccount[] GetAllAccounts(string passKey = null, int limit = -1)
{
if (passKey == null && this.Encrypted) return new SteamGuardAccount[0];
List<SteamAuth.SteamGuardAccount> accounts = new List<SteamAuth.SteamGuardAccount>();
foreach (var entry in this.Entries)
{
var account = GetAccount(entry, passKey);
if (account == null) continue;
accounts.Add(account);
if (limit != -1 && limit >= accounts.Count)
break;
}
return accounts.ToArray();
}
public SteamGuardAccount GetAccount(ManifestEntry entry, string passKey = null)
{
string fileText = "";
Stream stream = null;
RijndaelManaged aes256;
string filename = Path.Combine(Program.SteamGuardPath, entry.Filename);
if (this.Encrypted)
{
MemoryStream ms = new MemoryStream(Convert.FromBase64String(File.ReadAllText(filename)));
byte[] key = GetEncryptionKey(passKey, entry.Salt);
aes256 = new RijndaelManaged
{
IV = Convert.FromBase64String(entry.IV),
Key = key,
Padding = PaddingMode.PKCS7,
Mode = CipherMode.CBC
};
ICryptoTransform decryptor = aes256.CreateDecryptor(aes256.Key, aes256.IV);
stream = new CryptoStream(ms, decryptor, CryptoStreamMode.Read);
Utils.Verbose($"Decrypting {filename}...");
}
else
{
FileStream fileStream = File.OpenRead(filename);
stream = fileStream;
}
using (StreamReader reader = new StreamReader(stream))
{
fileText = reader.ReadToEnd();
}
stream.Close();
return JsonConvert.DeserializeObject<SteamAuth.SteamGuardAccount>(fileText);
}
public bool VerifyPasskey(string passkey)
{
if (!this.Encrypted || this.Entries.Count == 0) return true;
var accounts = this.GetAllAccounts(passkey, 1);
return accounts != null && accounts.Length == 1;
}
public bool RemoveAccount(SteamGuardAccount account, bool deleteMaFile = true)
{
ManifestEntry entry = (from e in this.Entries where e.SteamID == account.Session.SteamID select e).FirstOrDefault();
if (entry == null) return true; // If something never existed, did you do what they asked?
string filename = Path.Combine(Program.SteamGuardPath, entry.Filename);
this.Entries.Remove(entry);
if (this.Entries.Count == 0)
{
this.Encrypted = false;
}
if (this.Save() && deleteMaFile)
{
try
{
File.Delete(filename);
return true;
}
catch (Exception)
{
return false;
}
}
return false;
}
public bool SaveAccount(SteamGuardAccount account, bool encrypt, string passKey = null, string salt = null, string iV = null)
{
if (encrypt && (String.IsNullOrEmpty(passKey) || String.IsNullOrEmpty(salt) || String.IsNullOrEmpty(iV))) return false;
string jsonAccount = JsonConvert.SerializeObject(account);
string filename = account.Session.SteamID.ToString() + ".maFile";
Utils.Verbose($"Saving account {account.AccountName} to {filename}...");
ManifestEntry newEntry = new ManifestEntry()
{
SteamID = account.Session.SteamID,
IV = iV,
Salt = salt,
Filename = filename
};
bool foundExistingEntry = false;
for (int i = 0; i < this.Entries.Count; i++)
{
if (this.Entries[i].SteamID == account.Session.SteamID)
{
this.Entries[i] = newEntry;
foundExistingEntry = true;
break;
}
}
if (!foundExistingEntry)
{
this.Entries.Add(newEntry);
}
bool wasEncrypted = this.Encrypted;
this.Encrypted = encrypt;
if (!this.Save())
{
this.Encrypted = wasEncrypted;
return false;
}
try
{
Stream stream = null;
MemoryStream ms = null;
RijndaelManaged aes256;
if (encrypt)
{
ms = new MemoryStream();
byte[] key = GetEncryptionKey(passKey, newEntry.Salt);
aes256 = new RijndaelManaged
{
IV = Convert.FromBase64String(newEntry.IV),
Key = key,
Padding = PaddingMode.PKCS7,
Mode = CipherMode.CBC
};
ICryptoTransform encryptor = aes256.CreateEncryptor(aes256.Key, aes256.IV);
stream = new CryptoStream(ms, encryptor, CryptoStreamMode.Write);
}
else
{
// An unencrypted maFile is shorter than the encrypted version,
// so when an unencrypted maFile gets written this way, the file does not get wiped
// leaving encrypted text after the final } bracket. Deleting and recreating the file fixes this.
File.Delete(Path.Combine(Program.SteamGuardPath, newEntry.Filename));
stream = File.OpenWrite(Path.Combine(Program.SteamGuardPath, newEntry.Filename)); // open or create
}
using (StreamWriter writer = new StreamWriter(stream))
{
writer.Write(jsonAccount);
}
if (encrypt)
{
File.WriteAllText(Path.Combine(Program.SteamGuardPath, newEntry.Filename), Convert.ToBase64String(ms.ToArray()));
}
stream.Close();
return true;
}
catch (Exception ex)
{
Utils.Verbose("error: {0}", ex.ToString());
return false;
}
}
public bool Save()
{
string filename = Path.Combine(Program.SteamGuardPath, "manifest.json");
if (!Directory.Exists(Program.SteamGuardPath))
{
try
{
Utils.Verbose("Creating {0}", Program.SteamGuardPath);
Directory.CreateDirectory(Program.SteamGuardPath);
}
catch (Exception ex)
{
Utils.Verbose($"error: {ex.Message}");
return false;
}
}
try
{
string contents = JsonConvert.SerializeObject(this);
File.WriteAllText(filename, contents);
return true;
}
catch (Exception ex)
{
Utils.Verbose($"error: {ex.Message}");
return false;
}
}
private void RecomputeExistingEntries()
{
List<ManifestEntry> newEntries = new List<ManifestEntry>();
foreach (var entry in this.Entries)
{
string filename = Path.Combine(Program.SteamGuardPath, entry.Filename);
if (File.Exists(filename))
{
newEntries.Add(entry);
}
}
this.Entries = newEntries;
if (this.Entries.Count == 0)
{
this.Encrypted = false;
}
}
public void MoveEntry(int from, int to)
{
if (from < 0 || to < 0 || from > Entries.Count || to > Entries.Count - 1) return;
ManifestEntry sel = Entries[from];
Entries.RemoveAt(from);
Entries.Insert(to, sel);
Save();
}
public class ManifestEntry
{
[JsonProperty("encryption_iv")]
public string IV { get; set; }
[JsonProperty("encryption_salt")]
public string Salt { get; set; }
[JsonProperty("filename")]
public string Filename { get; set; }
[JsonProperty("steamid")]
public ulong SteamID { get; set; }
}
/*
Crypto Functions
*/
/// <summary>
/// Returns an 8-byte cryptographically random salt in base64 encoding
/// </summary>
/// <returns></returns>
public static string GetRandomSalt()
{
byte[] salt = new byte[SALT_LENGTH];
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
rng.GetBytes(salt);
}
return Convert.ToBase64String(salt);
}
/// <summary>
/// Returns a 16-byte cryptographically random initialization vector (IV) in base64 encoding
/// </summary>
/// <returns></returns>
public static string GetInitializationVector()
{
byte[] IV = new byte[IV_LENGTH];
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
rng.GetBytes(IV);
}
return Convert.ToBase64String(IV);
}
/// <summary>
/// Generates an encryption key derived using a password, a random salt, and specified number of rounds of PBKDF2
/// </summary>
/// <param name="password"></param>
/// <param name="salt"></param>
/// <returns></returns>
private static byte[] GetEncryptionKey(string password, string salt)
{
if (string.IsNullOrEmpty(password))
{
throw new ArgumentException("Password is empty");
}
if (string.IsNullOrEmpty(salt))
{
throw new ArgumentException("Salt is empty");
}
using (Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(password, Convert.FromBase64String(salt), PBKDF2_ITERATIONS))
{
return pbkdf2.GetBytes(KEY_SIZE_BYTES);
}
}
}
}

30
PKGBUILD Normal file
View file

@ -0,0 +1,30 @@
# Maintainer: Carson McManus <carson.mcmanus1@gmail.com>
# Contributor: Mads Mogensen <mads256h at gmail dot com>
_pkgname=steamguard-cli
pkgname=${_pkgname}-git
pkgver=0.14.0.r1.602acc66
pkgrel=1
pkgdesc="A command line utility to generate Steam 2FA codes and respond to confirmations."
arch=('i686' 'x86_64' 'armv6h' 'armv7h')
url="https://github.com/dyc3/steamguard-cli"
license=('GPL3')
makedepends=('rust' 'cargo' 'git')
source=("git+https://github.com/dyc3/steamguard-cli.git")
sha256sums=('SKIP')
options=(!lto)
pkgver() {
cd "${srcdir}/${_pkgname}"
git describe --long --tags --match 'v*' | sed 's/\([^-]*-g\)/r\1/;s/-/./g;s/v//g'
}
build() {
cd "${srcdir}/${_pkgname}"
cargo build --release
}
package() {
install -Dm755 "${srcdir}/${_pkgname}/target/release/steamguard" "${pkgdir}/usr/bin/steamguard"
ln -s "${pkgdir}/usr/bin/steamguard" "${pkgdir}/usr/bin/${_pkgname}"
}

View file

@ -1,795 +0,0 @@
using Newtonsoft.Json;
using SteamAuth;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace SteamGuard
{
public static class Program
{
public const string defaultSteamGuardPath = "~/maFiles";
public static string SteamGuardPath { get; set; } = defaultSteamGuardPath;
public static Manifest Manifest { get; set; }
public static SteamGuardAccount[] SteamGuardAccounts { get; set; }
public static bool Verbose { get; set; } = false;
/// <summary>
/// The main entry point for the application
/// </summary>
[STAThread]
public static void Main(string[] args)
{
string action = "";
string user = "";
string passkey = "";
// Parse cli arguments
for (int i = 0; i < args.Length; i++)
{
if (args[i].StartsWith("-"))
{
// TODO: there's gotta be some framework or tool or something for this
if (args[i] == "-v" || args[i] == "--verbose")
{
Verbose = true;
}
else if (args[i] == "-m" || args[i] == "--mafiles-path")
{
i++;
if (i < args.Length)
{
SteamGuardPath = args[i];
}
else
{
Console.WriteLine($"Expected path after {args[i-1]}");
return;
}
}
else if (args[i] == "-p" || args[i] == "--passkey")
{
i++;
if (i < args.Length)
{
passkey = args[i];
}
else
{
Console.WriteLine($"Expected encryption passkey after {args[i-1]}");
return;
}
}
else if (args[i] == "--help" || args[i] == "-h")
{
ShowHelp();
return;
}
}
else // Parse as action or username
{
if (string.IsNullOrEmpty(action))
{
if (args[i] == "add" || args[i] == "setup")
{
action = "setup";
}
else if (args[i] == "trade")
{
action = "trade";
}
else if (args[i] == "encrypt")
{
action = "encrypt";
}
else if (args[i] == "decrypt")
{
action = "decrypt";
}
else if (args[i] == "remove")
{
action = "remove";
}
else if (args[i] == "2fa" || args[i] == "code" || args[i] == "generate-code")
{
action = "generate-code";
}
else if (args[i] == "accept-all")
{
action = "accept-all";
}
else if (string.IsNullOrEmpty(user))
{
user = args[i];
}
}
else if (string.IsNullOrEmpty(user))
{
user = args[i];
}
}
}
if (string.IsNullOrEmpty(action))
{
action = "generate-code";
}
// Do some configuring
SteamGuardPath = SteamGuardPath.Replace("~", Environment.GetEnvironmentVariable("HOME"));
if (!Directory.Exists(SteamGuardPath))
{
if (SteamGuardPath == defaultSteamGuardPath.Replace("~", Environment.GetEnvironmentVariable("HOME")))
{
Utils.Verbose("warn: {0} does not exist, creating...", SteamGuardPath);
Directory.CreateDirectory(SteamGuardPath);
}
else
{
Console.WriteLine("error: {0} does not exist.", SteamGuardPath);
return;
}
}
Utils.Verbose($"Action: {action}");
if (user.Length > 0)
{
Utils.Verbose($"User: {user}");
}
Utils.Verbose($"Passkey: {passkey.Length > 0 ? "[specified]" : "[not specified]" }");
Utils.Verbose($"maFiles path: {SteamGuardPath}");
// Perform desired action
switch (action)
{
case "generate-code":
GenerateCode(user, passkey);
break;
case "encrypt": // Can also be used to change passkey
Console.WriteLine(Encrypt(passkey));
break;
case "decrypt":
Console.WriteLine(Decrypt(passkey));
break;
case "setup":
Setup(user, passkey);
break;
case "trade":
Trade(user, passkey);
break;
case "accept-all":
AcceptAllTrades(user, passkey);
break;
default:
Console.WriteLine("error: Unknown action: {0}", action);
return;
}
}
static void ShowHelp()
{
var descPadding = 26;
var descWidth = Console.BufferWidth - descPadding;
if (descWidth < 20)
descWidth = 20;
var flags = new Dictionary<string, string>
{
{ "-h, --help", "Display this help message." },
{ "-v, --verbose", "Display some extra information when the program is running." },
{ "-m, --mafiles-path", "Specify which folder your maFiles are in. Ex: ~/maFiles" },
{ "-p, --passkey", "Specify your encryption passkey." },
};
var actions = new Dictionary<string, string>
{
{ "code", "Generate a Steam Guard code for the specified user (if any) and exit. (default)" },
{ "encrypt", "Encrypt your maFiles or change your encryption passkey." },
{ "decrypt", "Remove encryption from your maFiles." },
{ "add", "Set up Steam Guard for 2 factor authentication." },
{ "trade", "Opens an interactive prompt to handle trade confirmations." },
{ "accept-all", "Accepts all trade confirmations." }
};
Console.WriteLine($"steamguard-cli - v{Assembly.GetExecutingAssembly().GetName().Version}");
Console.WriteLine("usage: steamguard ACTION [STEAM USERNAME] [OPTIONS]...");
Console.WriteLine();
foreach (var flag in flags)
{
// word wrap the descriptions, if needed
var desc = flag.Value;
if (desc.Length > descWidth)
{
var sb = new StringBuilder();
for (int i = 0; i < desc.Length; i += descWidth)
{
if (i > 0)
sb.Append("".PadLeft((flag.Key.StartsWith("--") ? 5 : 2) + descPadding));
sb.AppendLine(desc.Substring(i, i + descWidth > desc.Length ? desc.Length - i : descWidth).Trim());
}
desc = sb.ToString().TrimEnd('\n');
}
Console.WriteLine($"{(flag.Key.StartsWith("--") ? " " : " " )}{flag.Key.PadRight(descPadding)}{desc}");
}
Console.WriteLine();
Console.WriteLine("Actions:");
foreach (var action in actions)
{
// word wrap the descriptions, if needed
var desc = action.Value;
if (desc.Length > descWidth)
{
var sb = new StringBuilder();
for (int i = 0; i < desc.Length; i += descWidth)
{
if (i > 0)
sb.Append("".PadLeft(descPadding + 2));
sb.AppendLine(desc.Substring(i, i + descWidth > desc.Length ? desc.Length - i : descWidth).Trim());
}
desc = sb.ToString().TrimEnd('\n');
}
Console.WriteLine($" {action.Key.PadRight(descPadding)}{desc}");
}
}
static void GenerateCode(string user = "", string passkey = "")
{
Utils.Verbose("Aligning time...");
TimeAligner.AlignTime();
Utils.Verbose("Opening manifest...");
Manifest = Manifest.GetManifest(true);
Utils.Verbose("Reading accounts from manifest...");
if (Manifest.Encrypted)
{
if (string.IsNullOrEmpty(passkey))
{
passkey = Manifest.PromptForPassKey();
}
SteamGuardAccounts = Manifest.GetAllAccounts(passkey);
}
else
{
SteamGuardAccounts = Manifest.GetAllAccounts();
}
if (SteamGuardAccounts.Length == 0)
{
Console.WriteLine("error: No accounts read.");
return;
}
Utils.Verbose("Selecting account...");
string code = "";
for (int i = 0; i < SteamGuardAccounts.Length; i++)
{
SteamGuardAccount account = SteamGuardAccounts[i];
if (user != "")
{
if (account.AccountName.ToLower() == user.ToLower())
{
Utils.Verbose("Generating code for {0}...", account.AccountName);
code = account.GenerateSteamGuardCode();
break;
}
}
else
{
Utils.Verbose("Generating code for {0}...", account.AccountName);
code = account.GenerateSteamGuardCode();
break;
}
}
if (code != "")
Console.WriteLine(code);
else
Console.WriteLine("error: No Steam accounts found in {0}", SteamGuardAccounts);
}
static bool Encrypt(string passkey = "")
{
// NOTE: in this context, `passkey` refers to the old passkey, if there was one
Utils.Verbose("Opening manifest...");
Manifest = Manifest.GetManifest(true);
Utils.Verbose("Reading accounts from manifest...");
if (Manifest.Encrypted)
{
if (string.IsNullOrEmpty(passkey))
{
passkey = Manifest.PromptForPassKey();
}
SteamGuardAccounts = Manifest.GetAllAccounts(passkey);
}
else
{
SteamGuardAccounts = Manifest.GetAllAccounts();
}
string newPassKey = Manifest.PromptSetupPassKey();
for (int i = 0; i < SteamGuardAccounts.Length; i++)
{
var account = SteamGuardAccounts[i];
var salt = Manifest.GetRandomSalt();
var iv = Manifest.GetInitializationVector();
bool success = Manifest.SaveAccount(account, true, newPassKey, salt, iv);
Utils.Verbose("Encrypted {0}: {1}", account.AccountName, success);
if (!success) return false;
}
return true;
}
static bool Decrypt(string passkey = "")
{
Utils.Verbose("Opening manifest...");
Manifest = Manifest.GetManifest(true);
Utils.Verbose("Reading accounts from manifest...");
if (Manifest.Encrypted)
{
if (string.IsNullOrEmpty(passkey))
{
passkey = Manifest.PromptForPassKey();
}
SteamGuardAccounts = Manifest.GetAllAccounts(passkey);
}
else
{
Utils.Verbose("Decryption not required.");
return true;
}
for (int i = 0; i < SteamGuardAccounts.Length; i++)
{
var account = SteamGuardAccounts[i];
bool success = Manifest.SaveAccount(account, false);
Utils.Verbose("Decrypted {0}: {1}", account.AccountName, success);
if (!success) return false;
}
return true;
}
static void Setup(string username = "", string passkey = "")
{
Utils.Verbose("Opening manifest...");
Manifest = Manifest.GetManifest(true);
if (string.IsNullOrWhiteSpace(username))
{
Console.Write("Username: ");
username = Console.ReadLine();
}
Console.Write("Password: ");
var password = Utils.ReadLineSecure();
UserLogin login = new UserLogin(username, password);
LoginResult loginResult;
do
{
Console.Write($"Logging in {username}... ");
loginResult = login.DoLogin();
Console.WriteLine(loginResult);
switch (loginResult)
{
case LoginResult.NeedEmail:
Console.Write("Email code: ");
login.EmailCode = Console.ReadLine();
break;
case LoginResult.Need2FA:
Console.Write("2FA code: ");
login.TwoFactorCode = Console.ReadLine();
break;
case LoginResult.NeedCaptcha:
Console.WriteLine($"Please open: https://steamcommunity.com/public/captcha.php?gid={login.CaptchaGID}");
Console.Write("Captcha text: ");
login.CaptchaText = Console.ReadLine();
break;
case LoginResult.BadCredentials:
Console.WriteLine("error: Bad Credentials");
return;
case LoginResult.TooManyFailedLogins:
Console.WriteLine("error: Too many failed logins. Wait a bit before trying again.");
return;
case LoginResult.LoginOkay:
break;
default:
Console.WriteLine($"Unknown login result: {loginResult}");
break;
}
} while (loginResult != LoginResult.LoginOkay);
AuthenticatorLinker linker = new AuthenticatorLinker(login.Session);
AuthenticatorLinker.LinkResult linkResult = AuthenticatorLinker.LinkResult.GeneralFailure;
do
{
linkResult = linker.AddAuthenticator();
Console.WriteLine($"Link result: {linkResult}");
switch (linkResult)
{
case AuthenticatorLinker.LinkResult.MustProvidePhoneNumber:
var phonenumber = "";
do
{
Console.WriteLine("Enter your mobile phone number in the following format: +{cC} phoneNumber. EG, +1 123-456-7890");
phonenumber = Console.ReadLine();
phonenumber = FilterPhoneNumber(phonenumber);
linker.PhoneNumber = phonenumber;
} while (!PhoneNumberOkay(phonenumber));
break;
case AuthenticatorLinker.LinkResult.MustConfirmEmail:
Console.WriteLine("Check your email. Before continuing, click the link in the email to confirm your phone number. Press enter to continue...");
Console.ReadLine();
break;
case AuthenticatorLinker.LinkResult.MustRemovePhoneNumber:
linker.PhoneNumber = null;
break;
case AuthenticatorLinker.LinkResult.AwaitingFinalization:
break;
case AuthenticatorLinker.LinkResult.GeneralFailure:
Console.WriteLine("error: Unable to add your phone number. Steam returned GeneralFailure");
return;
case AuthenticatorLinker.LinkResult.AuthenticatorPresent:
Console.WriteLine("An authenticator is already present.");
Console.WriteLine("If you have the revocation code (Rxxxxx), this program can remove it for you.");
Console.Write("Would you like to remove the current authenticator using your revocation code? (y/n) ");
var answer = Console.ReadLine();
if (answer != "y")
continue;
Console.Write("Revocation code (Rxxxxx): ");
var revocationCode = Console.ReadLine();
var account = new SteamGuardAccount();
account.Session = login.Session;
account.RevocationCode = revocationCode;
if (account.DeactivateAuthenticator())
Console.WriteLine("Successfully deactivated the current authenticator.");
else
Console.WriteLine("Deactivating the current authenticator was unsuccessful.");
continue;
default:
Console.WriteLine($"error: Unexpected linker result: {linkResult}");
return;
}
} while (linkResult != AuthenticatorLinker.LinkResult.AwaitingFinalization);
string passKey = null;
if (Manifest.Entries.Count == 0)
{
Console.WriteLine("Looks like we are setting up your first account.");
passKey = Manifest.PromptSetupPassKey(true);
}
else if (Manifest.Entries.Count > 0 && Manifest.Encrypted)
{
if (string.IsNullOrEmpty(passkey))
{
passkey = Manifest.PromptForPassKey();
}
}
//Save the file immediately; losing this would be bad.
if (!Manifest.SaveAccount(linker.LinkedAccount, passKey != null, passKey))
{
Manifest.RemoveAccount(linker.LinkedAccount);
Console.WriteLine("Unable to save mobile authenticator file. The mobile authenticator has not been linked.");
return;
}
Console.WriteLine(
$"The Mobile Authenticator has not yet been linked. Before finalizing the authenticator, please write down your revocation code: {linker.LinkedAccount.RevocationCode}");
AuthenticatorLinker.FinalizeResult finalizeResponse = AuthenticatorLinker.FinalizeResult.GeneralFailure;
do
{
Console.Write("Please input the SMS message sent to your phone number: ");
string smsCode = Console.ReadLine();
finalizeResponse = linker.FinalizeAddAuthenticator(smsCode);
Utils.Verbose(finalizeResponse);
switch (finalizeResponse)
{
case AuthenticatorLinker.FinalizeResult.BadSMSCode:
continue;
case AuthenticatorLinker.FinalizeResult.UnableToGenerateCorrectCodes:
Console.WriteLine(
"Unable to generate the proper codes to finalize this authenticator. The authenticator should not have been linked.");
Console.WriteLine(
$"In the off-chance it was, please write down your revocation code, as this is the last chance to see it: {linker.LinkedAccount.RevocationCode}");
Manifest.RemoveAccount(linker.LinkedAccount);
return;
case AuthenticatorLinker.FinalizeResult.GeneralFailure:
Console.WriteLine("Unable to finalize this authenticator. The authenticator should not have been linked.");
Console.WriteLine(
$"In the off-chance it was, please write down your revocation code, as this is the last chance to see it: {linker.LinkedAccount.RevocationCode}");
Manifest.RemoveAccount(linker.LinkedAccount);
return;
}
} while (finalizeResponse != AuthenticatorLinker.FinalizeResult.Success);
//Linked, finally. Re-save with FullyEnrolled property.
Manifest.SaveAccount(linker.LinkedAccount, passKey != null, passKey);
Console.WriteLine(
$"Mobile authenticator successfully linked. Please actually write down your revocation code: {linker.LinkedAccount.RevocationCode}");
}
public static string FilterPhoneNumber(string phoneNumber)
=> phoneNumber.Replace("-", "").Replace("(", "").Replace(")", "");
public static bool PhoneNumberOkay(string phoneNumber)
{
if (phoneNumber == null || phoneNumber.Length == 0) return false;
if (phoneNumber[0] != '+') return false;
return true;
}
static void Trade(string user = "", string passkey = "")
{
Utils.Verbose("Opening manifest...");
Manifest = Manifest.GetManifest(true);
Utils.Verbose("Reading accounts from manifest...");
if (Manifest.Encrypted)
{
if (string.IsNullOrEmpty(passkey))
{
passkey = Manifest.PromptForPassKey();
}
SteamGuardAccounts = Manifest.GetAllAccounts(passkey);
}
else
{
SteamGuardAccounts = Manifest.GetAllAccounts();
}
if (SteamGuardAccounts.Length == 0)
{
Console.WriteLine("error: No accounts read.");
return;
}
foreach (var account in SteamGuardAccounts)
{
if (user != "")
if (!string.Equals(account.AccountName, user, StringComparison.CurrentCultureIgnoreCase))
continue;
processConfirmations(account);
}
}
enum TradeAction
{
Accept = 1,
Deny = 0,
Ignore = -1
}
static bool promptRefreshSession(SteamGuardAccount account)
{
Console.WriteLine("Your Steam credentials have expired. For trade and market confirmations to work properly, please login again.");
string username = account.AccountName;
Console.WriteLine($"Username: {username}");
Console.Write("Password: ");
var password = Console.ReadLine();
UserLogin login = new UserLogin(username, password);
Console.Write($"Logging in {username}... ");
LoginResult loginResult = login.DoLogin();
if (loginResult == LoginResult.Need2FA && !string.IsNullOrEmpty(account.SharedSecret))
{
// if we need a 2fa code, and we can generate it, generate a 2fa code and log in.
Utils.Verbose(loginResult);
TimeAligner.AlignTime();
login.TwoFactorCode = account.GenerateSteamGuardCode();
Utils.Verbose($"Logging in {username}... ");
loginResult = login.DoLogin();
}
Console.WriteLine(loginResult);
if (loginResult == LoginResult.LoginOkay)
{
account.Session = login.Session;
}
if (account.RefreshSession())
{
Utils.Verbose("Session refreshed");
Manifest.SaveAccount(account, Manifest.Encrypted);
return true;
}
else
{
return false;
}
}
static void processConfirmations(SteamGuardAccount account)
{
Utils.Verbose("Refeshing Session...");
if (account.RefreshSession())
{
Utils.Verbose("Session refreshed");
Manifest.SaveAccount(account, Manifest.Encrypted);
}
else
{
Utils.Verbose("Failed to refresh session, prompting user...");
if (!promptRefreshSession(account))
{
Console.WriteLine("Failed to refresh session, aborting...");
}
}
Console.WriteLine("Retrieving trade confirmations...");
var tradesTask = account.FetchConfirmationsAsync();
tradesTask.Wait();
var trades = tradesTask.Result;
var tradeActions = new TradeAction[trades.Length];
for (var i = 0; i < tradeActions.Length; i++)
{
tradeActions[i] = TradeAction.Ignore;
}
if (trades.Length == 0)
{
Console.WriteLine($"No trade confirmations for {account.AccountName}.");
return;
}
var selected = 0;
var colorAccept = ConsoleColor.Green;
var colorDeny = ConsoleColor.Red;
var colorIgnore = ConsoleColor.Gray;
var colorSelected = ConsoleColor.Yellow;
var confirm = false;
do
{
Console.Clear();
if (selected >= trades.Length)
selected = trades.Length - 1;
else if (selected < 0)
selected = 0;
Console.ResetColor();
Console.WriteLine($"Trade confirmations for {account.AccountName}...");
Console.WriteLine("No action will be made without your confirmation.");
Console.WriteLine("[a]ccept [d]eny [i]gnore [enter] Confirm [q]uit"); // accept = 1, deny = 0, ignore = -1
Console.WriteLine();
for (var t = 0; t < trades.Length; t++)
{
ConsoleColor itemColor;
switch (tradeActions[t])
{
case TradeAction.Accept:
itemColor = colorAccept;
break;
case TradeAction.Deny:
itemColor = colorDeny;
break;
case TradeAction.Ignore:
itemColor = colorIgnore;
break;
default:
throw new ArgumentOutOfRangeException();
}
Console.ForegroundColor = t == selected ? colorSelected : itemColor;
Console.WriteLine($" [{t}] [{tradeActions[t]}] {trades[t].ConfType} {trades[t].Creator} {trades[t].Description}");
}
var key = Console.ReadKey();
switch (key.Key)
{
case ConsoleKey.UpArrow:
case ConsoleKey.W:
selected--;
break;
case ConsoleKey.DownArrow:
case ConsoleKey.S:
selected++;
break;
case ConsoleKey.A:
tradeActions[selected] = TradeAction.Accept;
break;
case ConsoleKey.D:
tradeActions[selected] = TradeAction.Deny;
break;
case ConsoleKey.I:
tradeActions[selected] = TradeAction.Ignore;
break;
case ConsoleKey.Enter:
confirm = true;
break;
case ConsoleKey.Escape:
case ConsoleKey.Q:
Console.ResetColor();
Console.WriteLine("Quitting...");
return;
default:
break;
}
} while (!confirm);
Console.ResetColor();
Console.WriteLine();
Console.WriteLine("Processing...");
for (var t = 0; t < trades.Length; t++)
{
bool success = false;
switch (tradeActions[t])
{
case TradeAction.Accept:
if (Verbose) Console.Write($"Accepting {trades[t].ConfType} {trades[t].Creator} {trades[t].Description}...");
success = account.AcceptConfirmation(trades[t]);
break;
case TradeAction.Deny:
if (Verbose) Console.Write($"Denying {trades[t].ConfType} {trades[t].Creator} {trades[t].Description}...");
success = account.DenyConfirmation(trades[t]);
break;
case TradeAction.Ignore:
if (Verbose) Console.Write($"Ignoring {trades[t].ConfType} {trades[t].Creator} {trades[t].Description}...");
success = true;
break;
default:
throw new ArgumentOutOfRangeException();
}
Utils.Verbose(success);
}
Console.WriteLine("Done.");
}
static void AcceptAllTrades(string user = "", string passkey = "")
{
Utils.Verbose("Opening manifest...");
Manifest = Manifest.GetManifest(true);
Utils.Verbose("Reading accounts from manifest...");
if (Manifest.Encrypted)
{
if (string.IsNullOrEmpty(passkey))
{
passkey = Manifest.PromptForPassKey();
}
SteamGuardAccounts = Manifest.GetAllAccounts(passkey);
}
else
{
SteamGuardAccounts = Manifest.GetAllAccounts();
}
if (SteamGuardAccounts.Length == 0)
{
Console.WriteLine("error: No accounts read.");
return;
}
for (int i = 0; i < SteamGuardAccounts.Length; i++)
{
SteamGuardAccount account = SteamGuardAccounts[i];
if ((user != "" && account.AccountName.ToLower() == user.ToLower()) || user == "")
{
Console.WriteLine($"Accepting Confirmations on {account.AccountName}");
Utils.Verbose("Refeshing Session...");
if (account.RefreshSession())
{
Utils.Verbose("Session refreshed");
Manifest.SaveAccount(account, Manifest.Encrypted);
}
else
{
Utils.Verbose("Failed to refresh session, prompting user...");
if (!promptRefreshSession(account))
{
Console.WriteLine("Failed to refresh session, aborting...");
}
}
Utils.Verbose("Fetching Confirmations...");
var tradesTask = account.FetchConfirmationsAsync();
tradesTask.Wait();
Confirmation[] confirmations = tradesTask.Result;
Utils.Verbose("Accepting Confirmations...");
account.AcceptMultipleConfirmations(confirmations);
if (user != "")
{
break;
}
}
}
}
}
}

View file

@ -1,14 +1,31 @@
# steamguard-cli
[![Rust](https://github.com/dyc3/steamguard-cli/actions/workflows/rust.yml/badge.svg)](https://github.com/dyc3/steamguard-cli/actions/workflows/rust.yml)
[![Lint, Build, Test](https://github.com/dyc3/steamguard-cli/actions/workflows/rust.yml/badge.svg)](https://github.com/dyc3/steamguard-cli/actions/workflows/rust.yml)
[![AUR Tester](https://github.com/dyc3/steamguard-cli/actions/workflows/aur-checker.yml/badge.svg)](https://github.com/dyc3/steamguard-cli/actions/workflows/aur-checker.yml)
A command line utility for setting up and using Steam Mobile Authenticator (AKA Steam 2FA). It can also be used to respond to trade 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 legitamate 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
**This utility is effectively in beta. Use this software at your own risk. Make sure to back up your maFiles regularly, and make sure to actually write down your revocation code. If you lose both of these, we can't help you, your only recourse is to beg Steam support.**
# Quickstart
If you have no idea what the rest of this document is talking about, go read the [quickstart](docs/quickstart.md).
# Features
- Generate 2FA codes
- Respond to trade, market or any other confirmations
- Encrypted storage of your 2FA secrets
- With the option to store your encryption passkey in the system keyring
- Special memory-clearing data structures to prevent leaking secrets
- QR code generation for importing 2FA secrets into other applications, like KeeWeb
- QR code logins for quickly logging into Steam on a new device, like the Steam Deck
- Able to read Steam Desktop Authenticator's `maFiles` format
- Uses as many official Steam APIs as possible, unlikely to break
# Install
If you have the Rust toolchain installed:
@ -16,6 +33,11 @@ If you have the Rust toolchain installed:
cargo install steamguard-cli
```
Arch-based systems can install from the AUR:
- [steamguard-cli](https://aur.archlinux.org/packages/steamguard-cli/) tracks the latest release
- [steamguard-cli-git](https://aur.archlinux.org/packages/steamguard-cli-git/) tracks the latest git commit
Otherwise, you can download binaries from the releases.
## Building From Source
@ -26,9 +48,15 @@ cargo build --release
# Usage
`steamguard-cli` looks for your `maFiles/manifest.json` in at these paths, in this order:
Linux:
- `~/.config/steamguard-cli/maFiles/`
- `~/maFiles/`
Windows:
- `%APPDATA%\Roaming\steamguard-cli\maFiles\`
- `%USERPROFILE%\maFiles\`
Your `maFiles` can be created with or imported from [Steam Desktop Authenticator][SDA]. You can create `maFiles` with steamguard-cli using the `setup` action (`steamguard setup`).
**REMEMBER TO MAKE BACKUPS OF YOUR `maFiles`, AND TO WRITE DOWN YOUR RECOVERY CODE!**
@ -40,9 +68,27 @@ Full helptext can be displayed with:
steamguard --help
```
## One Liners
Generate and copy a new code to clipboard:
```bash
steamguard | xclip -selection clipboard
```
## Importing 2FA Secret Into Other Applications
It's possible to import your 2FA secret into other applications, like Google Authenticator or KeeWeb. The `uri` field contains a URI in that starts with `otpauth://...`, which you can create a QR code for.
It's possible to import your 2FA secret into other applications. This is useful if you want to use a password manager to generate your 2FA codes, like KeeWeb.
To make this easy, steamguard-cli can generate a QR code for your 2FA secret. You can then scan this QR code with your password manager.
```bash
steamguard qr # print QR code for the first account in your maFiles
steamguard -u <account name> qr # print QR code for a specific account
```
There are some applications that do not generate correct 2fa codes from the secret, so **do not use them**:
- Google Authenticator
- Authy
# Contributing
@ -53,3 +99,7 @@ By contributing code to this project, you give me and any future maintainers a n
`steamguard-cli`, the command line program is licensed under GPLv3.
`steamguard`, the library that is used by `steamguard-cli` is dual licensed under MIT or Apache 2.0, at your option.
# Used By
* [Unreal Engine to Steam publishing CI/CD pipeline](https://github.com/kasp1/dozer-pipelines), a sample pipeline built for [Dozer](https://github.com/kasp1/Dozer), a simple CI/CD runner

@ -1 +0,0 @@
Subproject commit e0619528fbe8f4c6f74135283b3f991219e73cf4

View file

@ -1,38 +0,0 @@
using System;
using System.Diagnostics;
namespace SteamGuard
{
public static class Utils
{
public static string ReadLineSecure()
{
// Have bash handle the password input, because apparently it's impossible in C#,
// and we don't need to worry about windows compatibility.
string bash_cmd = @"read -s -p ""Password: "" password; echo $password";
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = "bash";
p.StartInfo.Arguments = string.Format("-c '{0}'", bash_cmd);
p.StartInfo.RedirectStandardOutput = true;
p.Start();
p.WaitForExit();
Console.WriteLine();
return p.StandardOutput.ReadToEnd().Trim();
}
public static void Verbose(object obj)
{
Verbose(obj.ToString(), null);
}
public static void Verbose(string format, params object[] arg)
{
if (Program.Verbose)
{
Console.WriteLine(format, arg);
}
}
}
}

View file

@ -1,13 +0,0 @@
_steamguard()
{
local cur prev opts
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
opts="--help --verbose --maFiles-path --passkey"
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
}
complete -F _steamguard steamguard

55
docs/quickstart.md Normal file
View 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

View file

@ -1,27 +0,0 @@
$(eval SHELL:=/bin/bash)
all: Program.cs
mkdir -p build/ ;\
nuget restore SteamAuth/SteamAuth/SteamAuth.sln ;\
NEWTONSOFT_JSON_PATH=$$(find -name Newtonsoft.Json.dll | grep \/net45\/ | sort -t. -k 1,1n -k 2,2n -k 3,3n -k 4,4n | tail -n 1) ;\
mcs -target:library -out:build/SteamAuth.dll -r:"$$NEWTONSOFT_JSON_PATH" SteamAuth/SteamAuth/APIEndpoints.cs SteamAuth/SteamAuth/AuthenticatorLinker.cs SteamAuth/SteamAuth/Confirmation.cs SteamAuth/SteamAuth/SessionData.cs SteamAuth/SteamAuth/SteamGuardAccount.cs SteamAuth/SteamAuth/SteamWeb.cs SteamAuth/SteamAuth/TimeAligner.cs SteamAuth/SteamAuth/UserLogin.cs SteamAuth/SteamAuth/Util.cs SteamAuth/SteamAuth/Properties/AssemblyInfo.cs ;\
cp "$$NEWTONSOFT_JSON_PATH" build/ ;\
mcs -out:build/steamguard -r:build/SteamAuth.dll -r:build/Newtonsoft.Json.dll -r:/usr/lib/mono/4.5/System.Security.dll Program.cs Manifest.cs AssemblyInfo.cs Utils.cs
run:
build/steamguard -v
clean:
rm -r build/
install:
cp build/steamguard /usr/local/bin/
cp build/Newtonsoft.Json.dll /usr/local/bin/
cp build/SteamAuth.dll /usr/local/bin/
cp bash-tab-completion /etc/bash_completion.d/steamguard
uninstall:
rm -f /usr/local/bin/steamguard
rm -f /usr/local/bin/Newtonsoft.Json.dll
rm -f /usr/local/bin/SteamAuth.dll
rm -f /etc/bash_completion.d/steamguard

View file

@ -1,24 +0,0 @@
all: Program.cs
mkdir -p build/
nuget restore SteamAuth/SteamAuth/SteamAuth.sln
mcs -target:library -out:build/SteamAuth.dll -r:SteamAuth/SteamAuth/packages/Newtonsoft.Json.11.0.1/lib/net45/Newtonsoft.Json.dll SteamAuth/SteamAuth/APIEndpoints.cs SteamAuth/SteamAuth/AuthenticatorLinker.cs SteamAuth/SteamAuth/Confirmation.cs SteamAuth/SteamAuth/SessionData.cs SteamAuth/SteamAuth/SteamGuardAccount.cs SteamAuth/SteamAuth/SteamWeb.cs SteamAuth/SteamAuth/TimeAligner.cs SteamAuth/SteamAuth/UserLogin.cs SteamAuth/SteamAuth/Util.cs SteamAuth/SteamAuth/Properties/AssemblyInfo.cs
cp SteamAuth/SteamAuth/packages/Newtonsoft.Json.11.0.1/lib/net45/Newtonsoft.Json.dll build/
mcs -out:build/steamguard -r:build/SteamAuth.dll -r:build/Newtonsoft.Json.dll -r:/usr/local/lib/mono/4.5/System.Security.dll Program.cs Manifest.cs AssemblyInfo.cs Utils.cs
run:
mono build/steamguard -v
clean:
rm -r build/
install:
cp build/steamguard /usr/local/bin/
cp build/Newtonsoft.Json.dll /usr/local/bin/
cp build/SteamAuth.dll /usr/local/bin/
cp bash-tab-completion /etc/bash_completion.d/steamguard
uninstall:
rm -f /usr/local/bin/steamguard
rm -f /usr/local/bin/Newtonsoft.Json.dll
rm -f /usr/local/bin/SteamAuth.dll
rm -f /etc/bash_completion.d/steamguard

View file

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

17
scripts/check-aur.sh Executable file
View file

@ -0,0 +1,17 @@
#!/bin/bash
# Performs a test install of the package from the AUR. If the package fails to install, there should be a non-zero exit code.
# Intended for use with CI.
set -e
cd scripts/docker/arch/
tar -cvf arch-docker.tar.gz .
docker image build -t steamguard-cli-archlinux-builder - < arch-docker.tar.gz
rm arch-docker.tar.gz
BIN_NAME="steamguard"
docker run --rm steamguard-cli-archlinux-builder /bin/bash -c "./install.sh steamguard-cli-git && $BIN_NAME --version"
docker image rm steamguard-cli-archlinux-builder:latest

View file

@ -0,0 +1,3 @@
FROM greyltc/archlinux-aur:yay
COPY install.sh /install.sh

5
scripts/docker/arch/install.sh Executable file
View file

@ -0,0 +1,5 @@
#!/bin/bash
PACKAGE="$1"
echo "Installing $PACKAGE"
sudo -u ab -D~ bash -c "yay -Syu --removemake --needed --noprogressbar --noconfirm $PACKAGE"

View file

@ -3,6 +3,8 @@
set -e
DRY_RUN=true
SKIP_CRATE_PUBLISH=false
ALLOW_DIRTY=false
POSITIONAL=()
while [[ $# -gt 0 ]]; do
@ -18,6 +20,14 @@ while [[ $# -gt 0 ]]; do
shift # past argument
shift # past value
;;
--skip-publish)
SKIP_CRATE_PUBLISH=true
shift # past argument
;;
--allow-dirty)
ALLOW_DIRTY=true
shift # past argument
;;
*) # unknown option
POSITIONAL+=("$1") # save it in an array for later
shift # past argument
@ -25,6 +35,15 @@ while [[ $# -gt 0 ]]; do
esac
done
current_branch=$(git rev-parse --abbrev-ref HEAD)
if [[ "$current_branch" != "master" ]]; then
echo "You must be on the master branch to run this script"
exit 1
fi
git pull
echo """
This will do everything needed to release a new version:
- bump the version number
@ -33,44 +52,75 @@ This will do everything needed to release a new version:
- publish crates on crates.io
- upload artifacts to a new release on github
"""
echo "Previewing changes..."
params=()
if [[ $BUMP != "" ]]; then
params+=(--bump "$BUMP")
params+=(--bump-dependencies "$BUMP")
fi
if [[ $SKIP_CRATE_PUBLISH == true ]]; then
params+=(--no-publish)
fi
if [[ $ALLOW_DIRTY == true ]]; then
params+=(--allow-dirty)
fi
cargo smart-release --update-crates-index --no-changelog --no-tag --no-push --no-publish "${params[@]}"
if [ "$DRY_RUN" = true ]; then
echo "This is a dry run, nothing will be done. Artifacts will be built, but not published."
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
echo "This is not a dry run. This is the real deal!"
fi
echo "Press any key to continue..."
read -n 1 -s -r
params=()
if [[ $DRY_RUN == false ]]; then
params+=(--execute)
fi
if [[ $BUMP != "" ]]; then
params+=(--bump "$BUMP")
cargo smart-release --update-crates-index --no-changelog --no-tag --no-push --no-publish "${params[@]}"
#echo "Verify that the publish succeeded, and Press any key to continue..."
# read -n 1 -s -r
if ! which cross; then
echo "cross not found, installing..."
cargo install cross
fi
cargo smart-release "${params[@]}"
BUILD_TARGET="x86_64-unknown-linux-musl"
BUILD_TARGET2="x86_64-pc-windows-gnu"
# HACK: build targets in this order to avoid a bug in cross
cross build --release "--target=$BUILD_TARGET2"
cross build --release "--target=$BUILD_TARGET"
./scripts/package-deb.sh
BIN_PATH="target/release/steamguard-cli"
BIN_PATH="target/$BUILD_TARGET/release/steamguard"
BIN_PATH2="target/$BUILD_TARGET2/release/steamguard.exe"
RAW_VERSION="$("$BIN_PATH" --version | cut -d " " -f 2)"
# TODO: can't compare with the tag anymore because it doesn't exist yet. maybe get a better condition?
# TAGGED_VERSION="$(git tag | grep "^v" | tail -n 1 | tr -d v)"
# if [[ "v$RAW_VERSION" != "v$TAGGED_VERSION" ]]; then
# echo "Version mismatch: $RAW_VERSION != $TAGGED_VERSION"
# if [[ $DRY_RUN == false ]]; then
# echo "Aborting."
# exit 2
# fi
# fi
VERSION="v$RAW_VERSION"
echo "It's now safe to push tags and publish for the affected crates."
if [[ $DRY_RUN == false ]]; then
gh release create "$VERSION" --title "$VERSION" --draft "$BIN_PATH" "./steamguard-cli_$RAW_VERSION-0.deb"
cargo smart-release --update-crates-index --no-changelog --execute
fi
# update PKGBUILD for AUR
if [[ -d "aur" ]]; then
rm -rf aur
fi
git clone ssh://aur@aur.archlinux.org/steamguard-cli-git.git aur
cargo pkgbuild
mv PKGBUILD aur/PKGBUILD
cd aur
git commit -m "release $VERSION" PKGBUILD
if [[ $DRY_RUN == false ]]; then
git push
rm -rf aur
if [[ $(gh release list | grep -i "Draft" | grep -i "$VERSION" && echo "true" || echo "false") == "true" ]]; then
gh release delete --yes "$VERSION"
fi
gh release create "$VERSION" --discussion-category "General" --title "$VERSION" "$BIN_PATH" "$BIN_PATH2" "./steamguard-cli_$RAW_VERSION-0.deb"
fi
cd ..

View file

@ -2,14 +2,22 @@
set -e
BIN_PATH="target/release/steamguard-cli"
DISTRO=$(lsb_release -i -s)
DISTRO_VERSION=$(lsb_release -r -s)
if ! which cross; then
echo "cross not found, installing..."
cargo install cross
fi
BIN_PATH="target/x86_64-unknown-linux-musl/release/steamguard"
if [[ ! -f "$BIN_PATH" ]]; then
echo "ERROR: Could not find release binaries, building them..."
cargo build --release
cross build --release --target=x86_64-unknown-linux-musl
fi
VERSION="$("$BIN_PATH" --version | cut -d " " -f 2)-0"
VERSION="$("$BIN_PATH" --version | cut -d " " -f 2)"
TEMP_PKG_PATH="/tmp/steamguard-cli_$VERSION"
echo "Building Debian package for v$VERSION..."
echo "Building package on $DISTRO $DISTRO_VERSION for v$VERSION..."
mkdir -p "$TEMP_PKG_PATH/usr/local/bin"
mkdir -p "$TEMP_PKG_PATH/etc/bash_completion.d"
@ -24,12 +32,12 @@ Depends:
Version: $VERSION
Section: base
Priority: optional
Architecture: all
Architecture: amd64
Maintainer: Carson McManus <carson.mcmanus1@gmail.com>
Description: steamguard-cli
A command line utility to generate Steam 2FA codes and respond to confirmations.
EOT
dpkg-deb --build "$TEMP_PKG_PATH" "steamguard-cli_$VERSION.deb"
dpkg-deb -Zxz --build "$TEMP_PKG_PATH" "steamguard-cli_$VERSION-0.deb"
rm -rf "$TEMP_PKG_PATH"

57
scripts/publish-aur.sh Executable file
View file

@ -0,0 +1,57 @@
#!/bin/bash
set -e
DRY_RUN=true
POSITIONAL=()
while [[ $# -gt 0 ]]; do
key="$1"
case $key in
--execute)
DRY_RUN=false
shift # past argument
;;
*) # unknown option
POSITIONAL+=("$1") # save it in an array for later
shift # past argument
;;
esac
done
# prerequisites
if ! command -v makepkg &> /dev/null; then
echo "Error: makepkg is not installed"
exit 1
fi
if ! command -v git &> /dev/null; then
echo "Error: git is not installed"
exit 2
fi
# get version info
BIN_PATH="target/release/steamguard"
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
echo "Version mismatch: $RAW_VERSION != $TAGGED_VERSION"
exit 10
fi
VERSION="v$RAW_VERSION"
# update PKGBUILD for AUR
if [[ -d "aur" ]]; then
rm -rf aur
fi
git clone ssh://aur@aur.archlinux.org/steamguard-cli-git.git aur
cp PKGBUILD aur/PKGBUILD
cd aur
makepkg -si --noconfirm
makepkg --printsrcinfo > .SRCINFO
git commit -m "release $VERSION" PKGBUILD
if [[ $DRY_RUN == false ]]; then
git push
rm -rf aur
fi
cd ..

View file

@ -1,7 +1,10 @@
pub use crate::encryption::EntryEncryptionParams;
use crate::accountmanager::legacy::SdaManifest;
pub use crate::encryption::EncryptionScheme;
use crate::encryption::EntryEncryptor;
use log::*;
use serde::{Deserialize, Serialize};
use rayon::prelude::*;
use secrecy::{ExposeSecret, SecretString};
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufReader, Read, Write};
use std::path::Path;
@ -9,463 +12,692 @@ use std::sync::{Arc, Mutex};
use steamguard::SteamGuardAccount;
use thiserror::Error;
#[derive(Debug, Serialize, Deserialize)]
pub struct Manifest {
pub entries: Vec<ManifestEntry>,
/// Not really used, kept mostly for compatibility with SDA.
pub encrypted: bool,
/// Not implemented, kept for compatibility with SDA.
pub first_run: bool,
/// Not implemented, kept for compatibility with SDA.
pub periodic_checking: bool,
/// Not implemented, kept for compatibility with SDA.
pub periodic_checking_interval: i32,
/// Not implemented, kept for compatibility with SDA.
pub periodic_checking_checkall: bool,
/// Not implemented, kept for compatibility with SDA.
pub auto_confirm_market_transactions: bool,
/// Not implemented, kept for compatibility with SDA.
pub auto_confirm_trades: bool,
mod legacy;
pub mod manifest;
pub mod migrate;
mod steamv2;
mod winauth;
#[serde(skip)]
pub accounts: Vec<Arc<Mutex<SteamGuardAccount>>>,
#[serde(skip)]
folder: String, // I wanted to use a Path here, but it was too hard to make it work...
pub use manifest::*;
#[derive(Debug, Default)]
pub struct AccountManager {
manifest: Manifest,
accounts: HashMap<String, Arc<Mutex<SteamGuardAccount>>>,
folder: String,
passkey: Option<SecretString>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ManifestEntry {
pub filename: String,
#[serde(default, rename = "steamid")]
pub steam_id: u64,
#[serde(default)]
pub account_name: String,
#[serde(default, flatten)]
pub encryption: Option<EntryEncryptionParams>,
}
impl Default for Manifest {
fn default() -> Self {
Manifest {
encrypted: false,
entries: vec![],
first_run: false,
periodic_checking: false,
periodic_checking_interval: 0,
periodic_checking_checkall: false,
auto_confirm_market_transactions: false,
auto_confirm_trades: false,
accounts: vec![],
folder: "".into(),
}
}
}
impl Manifest {
impl AccountManager {
/// `path` should be the path to manifest.json
pub fn new(path: &Path) -> Self {
Manifest {
Self {
folder: String::from(path.parent().unwrap().to_str().unwrap()),
..Default::default()
}
}
pub fn load(path: &Path) -> anyhow::Result<Self> {
debug!("loading manifest: {:?}", &path);
let file = File::open(path)?;
let reader = BufReader::new(file);
let mut manifest: Manifest = serde_json::from_reader(reader)?;
manifest.folder = String::from(path.parent().unwrap().to_str().unwrap());
return Ok(manifest);
pub fn from_manifest(manifest: Manifest, folder: String) -> Self {
Self {
manifest,
folder,
..Default::default()
}
}
pub fn load_accounts(
&mut self,
passkey: &Option<String>,
) -> anyhow::Result<(), ManifestAccountLoadError> {
for entry in &mut self.entries {
let path = Path::new(&self.folder).join(&entry.filename);
debug!("loading account: {:?}", path);
pub fn register_accounts(&mut self, accounts: Vec<SteamGuardAccount>) {
for account in accounts {
self.register_loaded_account(Arc::new(Mutex::new(account)));
}
}
pub fn load(path: &Path) -> anyhow::Result<Self, ManifestLoadError> {
debug!("loading manifest: {:?}", &path);
let file = File::open(path)?;
let mut reader = BufReader::new(file);
let account: SteamGuardAccount;
match (passkey, entry.encryption.as_ref()) {
(Some(passkey), Some(params)) => {
let mut ciphertext: Vec<u8> = vec![];
reader.read_to_end(&mut ciphertext)?;
let plaintext = crate::encryption::LegacySdaCompatible::decrypt(
passkey, params, ciphertext,
)?;
if plaintext[0] != '{' as u8 && plaintext[plaintext.len() - 1] != '}' as u8 {
return Err(ManifestAccountLoadError::IncorrectPasskey);
}
let s = std::str::from_utf8(&plaintext).unwrap();
account = serde_json::from_str(&s)?;
}
(None, Some(_)) => {
return Err(ManifestAccountLoadError::MissingPasskey);
}
(_, None) => {
account = serde_json::from_reader(reader)?;
}
let mut buffer = String::new();
reader.read_to_string(&mut buffer)?;
let mut deser = serde_json::Deserializer::from_str(&buffer);
let manifest: Manifest = match serde_path_to_error::deserialize(&mut deser) {
Ok(m) => m,
Err(orig_err) => match serde_json::from_str::<SdaManifest>(&buffer) {
Ok(_) => return Err(ManifestLoadError::MigrationNeeded)?,
Err(_) => return Err(orig_err)?,
},
};
entry.account_name = account.account_name.clone();
self.accounts.push(Arc::new(Mutex::new(account)));
if manifest.version != CURRENT_MANIFEST_VERSION {
return Err(ManifestLoadError::MigrationNeeded)?;
}
let accountmanager = Self {
manifest,
folder: String::from(path.parent().unwrap().to_str().unwrap()),
..Default::default()
};
Ok(accountmanager)
}
/// Tells the manager to keep track of the encryption passkey, and use it for encryption when loading or saving accounts.
pub fn submit_passkey(&mut self, passkey: Option<SecretString>) {
if let Some(p) = passkey.as_ref() {
if p.expose_secret().is_empty() {
panic!("Encryption passkey cannot be empty");
}
}
if passkey.is_some() {
debug!("passkey was submitted to manifest");
} else {
debug!("passkey was revoked from manifest");
}
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.
pub fn load_accounts(&mut self) -> anyhow::Result<(), ManifestAccountLoadError> {
let accounts = self
.manifest
.entries
.par_iter()
.map(|entry| self.load_account_by_entry(entry))
.collect::<Vec<_>>();
for account in accounts {
self.register_loaded_account(account?);
}
Ok(())
}
/// Loads an account by account name.
/// Must call `register_loaded_account` after loading the account.
fn load_account(
&self,
account_name: impl AsRef<str>,
) -> anyhow::Result<Arc<Mutex<SteamGuardAccount>>, ManifestAccountLoadError> {
let entry = self.get_entry(account_name)?;
self.load_account_by_entry(entry)
}
/// Loads an account from a manifest entry.
/// Must call `register_loaded_account` after loading the account.
fn load_account_by_entry(
&self,
entry: &ManifestEntry,
) -> anyhow::Result<Arc<Mutex<SteamGuardAccount>>, ManifestAccountLoadError> {
let path = Path::new(&self.folder).join(&entry.filename);
let account = entry.load(
path.as_path(),
self.passkey.as_ref(),
entry.encryption.as_ref(),
)?;
let account = Arc::new(Mutex::new(account));
Ok(account)
}
/// Register an account as loaded, so it can be operated on.
fn register_loaded_account(&mut self, account: Arc<Mutex<SteamGuardAccount>>) {
let account_name = account.lock().unwrap().account_name.clone();
self.accounts.insert(account_name, account);
}
pub fn account_exists(&self, account_name: &String) -> bool {
for entry in &self.manifest.entries {
if &entry.account_name == account_name {
return true;
}
}
false
}
pub fn add_account(&mut self, account: SteamGuardAccount) {
debug!("adding account to manifest: {}", account.account_name);
let steamid = account.session.as_ref().map_or(0, |s| s.steam_id);
self.entries.push(ManifestEntry {
self.manifest.entries.push(ManifestEntry {
filename: format!("{}.maFile", &account.account_name),
steam_id: steamid,
steam_id: account.steam_id,
account_name: account.account_name.clone(),
encryption: None,
});
self.accounts.push(Arc::new(Mutex::new(account)));
self.accounts
.insert(account.account_name.clone(), Arc::new(Mutex::new(account)));
}
pub fn import_account(&mut self, import_path: String) -> anyhow::Result<()> {
let path = Path::new(&import_path);
ensure!(path.exists(), "{} does not exist.", import_path);
ensure!(path.is_file(), "{} is not a file.", import_path);
pub fn import_account(
&mut self,
import_path: &String,
) -> anyhow::Result<(), ManifestAccountImportError> {
let path = Path::new(import_path);
if !path.exists() {
return Err(ManifestAccountImportError::FileNotFound);
}
if !path.is_file() {
return Err(ManifestAccountImportError::NotAFile);
}
let file = File::open(path)?;
let reader = BufReader::new(file);
let account: SteamGuardAccount = serde_json::from_reader(reader)?;
let mut deser = serde_json::Deserializer::from_reader(reader);
let account: SteamGuardAccount = serde_path_to_error::deserialize(&mut deser)?;
if self.account_exists(&account.account_name) {
return Err(ManifestAccountImportError::AlreadyExists {
account_name: account.account_name,
});
}
self.add_account(account);
return Ok(());
Ok(())
}
pub fn remove_account(&mut self, account_name: String) {
pub fn remove_account(&mut self, account_name: &String) {
let index = self
.accounts
.manifest
.entries
.iter()
.position(|a| a.lock().unwrap().account_name == account_name)
.position(|a| &a.account_name == account_name)
.unwrap();
self.accounts.remove(index);
self.entries.remove(index);
self.accounts.remove(account_name);
self.manifest.entries.remove(index);
}
pub fn save(&self, passkey: &Option<String>) -> anyhow::Result<()> {
ensure!(
self.entries.len() == self.accounts.len(),
"Manifest entries don't match accounts."
);
for (entry, account) in self.entries.iter().zip(&self.accounts) {
/// Saves the manifest and all loaded accounts.
pub fn save(&self) -> anyhow::Result<()> {
info!("Saving manifest and accounts...");
let save_results: Vec<_> = self
.accounts
.values()
.par_bridge()
.map(|account| -> anyhow::Result<()> {
let account = account.lock().unwrap();
let entry = self.get_entry(&account.account_name)?.clone();
debug!("saving {}", entry.filename);
let serialized = serde_json::to_vec(account.as_ref())?;
let serialized = serde_json::to_vec(&account.clone())?;
ensure!(
serialized.len() > 2,
"Something extra weird happened and the account was serialized into nothing."
);
let final_buffer: Vec<u8>;
match (passkey, entry.encryption.as_ref()) {
(Some(passkey), Some(params)) => {
final_buffer = crate::encryption::LegacySdaCompatible::encrypt(
passkey, params, serialized,
)?;
let final_buffer: Vec<u8> = match (&self.passkey, entry.encryption.as_ref()) {
(Some(passkey), Some(scheme)) => {
scheme.encrypt(passkey.expose_secret(), serialized)?
}
(None, Some(_)) => {
bail!("maFiles are encrypted, but no passkey was provided.");
}
(_, None) => {
final_buffer = serialized;
}
(_, None) => serialized,
};
let path = Path::new(&self.folder).join(&entry.filename);
let mut file = File::create(path)?;
file.write_all(final_buffer.as_slice())?;
file.sync_data()?;
Ok(())
})
.collect();
for result in save_results {
result?;
}
debug!("saving manifest");
let manifest_serialized = serde_json::to_string(&self)?;
let manifest_serialized = serde_json::to_string(&self.manifest)?;
let path = Path::new(&self.folder).join("manifest.json");
let mut file = File::create(path)?;
file.write_all(manifest_serialized.as_bytes())?;
file.sync_data()?;
Ok(())
}
/// Return all loaded accounts. Order is not guarenteed.
#[allow(dead_code)]
pub fn get_all_loaded(&self) -> Vec<Arc<Mutex<SteamGuardAccount>>> {
return self.accounts.values().cloned().collect();
}
#[allow(dead_code)]
pub fn get_entry(
&self,
account_name: impl AsRef<str>,
) -> anyhow::Result<&ManifestEntry, ManifestAccountLoadError> {
self.manifest
.entries
.iter()
.find(|e| e.account_name == account_name.as_ref())
.ok_or(ManifestAccountLoadError::MissingManifestEntry)
}
#[allow(dead_code)]
pub fn get_entry_mut(
&mut self,
account_name: impl AsRef<str>,
) -> anyhow::Result<&mut ManifestEntry, ManifestAccountLoadError> {
self.manifest
.entries
.iter_mut()
.find(|e| e.account_name == account_name.as_ref())
.ok_or(ManifestAccountLoadError::MissingManifestEntry)
}
pub fn has_passkey(&self) -> bool {
self.passkey.is_some()
}
/// Gets the specified account by name.
/// Fails if the account does not exist in the manifest entries.
pub fn get_account(
&self,
account_name: impl AsRef<str>,
) -> anyhow::Result<Arc<Mutex<SteamGuardAccount>>> {
let account = self
.accounts
.get(account_name.as_ref())
.cloned()
.ok_or(anyhow!("Account not loaded"));
account
}
/// Get or load the spcified account.
pub fn get_or_load_account(
&mut self,
account_name: impl AsRef<str>,
) -> anyhow::Result<Arc<Mutex<SteamGuardAccount>>, ManifestAccountLoadError> {
let account = self.get_account(account_name.as_ref());
if let Ok(account) = account {
return Ok(account);
}
let account = self.load_account(account_name.as_ref())?;
self.register_loaded_account(account.clone());
Ok(account)
}
/// Determine if any manifest entries are missing `account_name`.
fn is_missing_account_name(&self) -> bool {
self.manifest
.entries
.iter()
.any(|e| e.account_name.is_empty())
}
fn has_any_uppercase_in_account_names(&self) -> bool {
self.manifest
.entries
.iter()
.any(|e| e.account_name != e.account_name.to_lowercase())
}
/// Performs auto-upgrades on the manifest. Returns true if any upgrades were performed.
pub fn auto_upgrade(&mut self) -> anyhow::Result<bool, ManifestAccountLoadError> {
debug!("Performing auto-upgrade...");
let mut upgraded = false;
if self.is_missing_account_name() {
debug!("Adding missing account names");
for i in 0..self.manifest.entries.len() {
let account = self.load_account_by_entry(&self.manifest.entries[i].clone())?;
self.manifest.entries[i]
.account_name
.clone_from(&account.lock().unwrap().account_name);
}
upgraded = true;
}
if self.has_any_uppercase_in_account_names() {
debug!("Lowercasing account names");
for i in 0..self.manifest.entries.len() {
self.manifest.entries[i].account_name =
self.manifest.entries[i].account_name.to_lowercase();
}
upgraded = true;
}
Ok(upgraded)
}
pub fn iter(&self) -> impl Iterator<Item = &ManifestEntry> {
self.manifest.entries.iter()
}
pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut ManifestEntry> {
self.manifest.entries.iter_mut()
}
}
trait EntryLoader<T> {
fn load(
&self,
path: &Path,
passkey: Option<&SecretString>,
encryption_params: Option<&EncryptionScheme>,
) -> anyhow::Result<T, ManifestAccountLoadError>;
}
impl EntryLoader<SteamGuardAccount> for ManifestEntry {
fn load(
&self,
path: &Path,
passkey: Option<&SecretString>,
encryption_params: Option<&EncryptionScheme>,
) -> anyhow::Result<SteamGuardAccount, ManifestAccountLoadError> {
debug!("loading entry: {:?}", path);
let file = File::open(path)?;
let mut reader = BufReader::new(file);
let account: SteamGuardAccount = match (&passkey, encryption_params.as_ref()) {
(Some(passkey), Some(scheme)) => {
let mut ciphertext: Vec<u8> = vec![];
reader.read_to_end(&mut ciphertext)?;
let plaintext = scheme.decrypt(passkey.expose_secret(), ciphertext)?;
if plaintext[0] != b'{' && plaintext[plaintext.len() - 1] != b'}' {
return Err(ManifestAccountLoadError::IncorrectPasskey);
}
let s = std::str::from_utf8(&plaintext).unwrap();
let mut deser = serde_json::Deserializer::from_str(s);
serde_path_to_error::deserialize(&mut deser)?
}
(None, Some(_)) => {
return Err(ManifestAccountLoadError::MissingPasskey);
}
(_, None) => {
let mut deser = serde_json::Deserializer::from_reader(reader);
serde_path_to_error::deserialize(&mut deser)?
}
};
Ok(account)
}
}
#[derive(Debug, Error)]
pub enum ManifestLoadError {
#[error("Could not find manifest.json in the specified directory.")]
Missing(#[from] std::io::Error),
#[error("Manifest needs to be migrated to the latest format.")]
MigrationNeeded,
#[error("Failed to deserialize the manifest. {self:?}")]
DeserializationFailed(#[from] serde_path_to_error::Error<serde_json::Error>),
#[error(transparent)]
Unknown(#[from] anyhow::Error),
}
#[derive(Debug, Error)]
pub enum ManifestAccountLoadError {
#[error("Could not find an entry in the manifest for this account. Check your spelling.")]
MissingManifestEntry,
#[error("Manifest accounts are encrypted, but no passkey was provided.")]
MissingPasskey,
#[error("Incorrect passkey provided.")]
IncorrectPasskey,
#[error("Failed to decrypt account. {self:?}")]
DecryptionFailed(#[from] crate::encryption::EntryEncryptionError),
#[error("Failed to deserialize the account.")]
DeserializationFailed(#[from] serde_json::Error),
#[error("Failed to deserialize the account. {self:?}")]
DeserializationFailed(#[from] serde_path_to_error::Error<serde_json::Error>),
#[error(transparent)]
Unknown(#[from] anyhow::Error),
}
impl From<block_modes::BlockModeError> for ManifestAccountLoadError {
fn from(error: block_modes::BlockModeError) -> Self {
return Self::Unknown(anyhow::Error::from(error));
}
}
impl From<base64::DecodeError> for ManifestAccountLoadError {
fn from(error: base64::DecodeError) -> Self {
return Self::Unknown(anyhow::Error::from(error));
}
}
impl From<block_modes::InvalidKeyIvLength> for ManifestAccountLoadError {
fn from(error: block_modes::InvalidKeyIvLength) -> Self {
return Self::Unknown(anyhow::Error::from(error));
Self::Unknown(anyhow::Error::from(error))
}
}
impl From<std::io::Error> for ManifestAccountLoadError {
fn from(error: std::io::Error) -> Self {
return Self::Unknown(anyhow::Error::from(error));
Self::Unknown(anyhow::Error::from(error))
}
}
#[derive(Debug, Error)]
pub enum ManifestAccountImportError {
#[error("Could not find the specified file.")]
FileNotFound,
#[error("The specified path is not a file.")]
NotAFile,
#[error(
"The account you are trying to import, \"{account_name}\", already exists in the manifest."
)]
AlreadyExists { account_name: String },
#[error(transparent)]
IOError(#[from] std::io::Error),
#[error("Failed to deserialize the account. {self:?}")]
DeserializationFailed(#[from] serde_path_to_error::Error<serde_json::Error>),
#[error(transparent)]
Unknown(#[from] anyhow::Error),
}
#[cfg(test)]
mod tests {
use super::*;
use tempdir::TempDir;
use steamguard::ExposeSecret;
use tempfile::TempDir;
#[test]
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 = Manifest::new(manifest_path.as_path());
assert!(matches!(manifest.save(&None), Ok(_)));
let manager = AccountManager::new(manifest_path.as_path());
assert!(manager.save().is_ok());
}
#[test]
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");
println!("tempdir: {}", manifest_path.display());
let mut manifest = Manifest::new(manifest_path.as_path());
let mut manager = AccountManager::new(manifest_path.as_path());
let mut account = SteamGuardAccount::new();
account.account_name = "asdf1234".into();
account.revocation_code = "R12345".into();
account.revocation_code = String::from("R12345").into();
account.shared_secret = steamguard::token::TwoFactorSecret::parse_shared_secret(
"zvIayp3JPvtvX/QGHqsqKBk/44s=".into(),
)?;
manifest.add_account(account);
manifest.save(&None)?;
manager.add_account(account);
manager.save()?;
let mut loaded_manifest = Manifest::load(manifest_path.as_path())?;
assert_eq!(loaded_manifest.entries.len(), 1);
assert_eq!(loaded_manifest.entries[0].filename, "asdf1234.maFile");
loaded_manifest.load_accounts(&None)?;
let mut manager = AccountManager::load(manifest_path.as_path())?;
assert_eq!(manager.manifest.entries.len(), 1);
assert_eq!(manager.manifest.entries[0].filename, "asdf1234.maFile");
manager.load_accounts()?;
assert_eq!(manager.manifest.entries.len(), manager.accounts.len());
let account_name = "asdf1234";
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!(
loaded_manifest.entries.len(),
loaded_manifest.accounts.len()
);
assert_eq!(
loaded_manifest.accounts[0].lock().unwrap().account_name,
"asdf1234"
);
assert_eq!(
loaded_manifest.accounts[0].lock().unwrap().revocation_code,
"R12345"
);
assert_eq!(
loaded_manifest.accounts[0].lock().unwrap().shared_secret,
steamguard::token::TwoFactorSecret::parse_shared_secret(
"zvIayp3JPvtvX/QGHqsqKBk/44s=".into()
)?,
);
return Ok(());
}
#[test]
fn test_should_save_and_load_manifest_encrypted() {
let passkey: Option<String> = Some("password".into());
let tmp_dir = TempDir::new("steamguard-cli-test").unwrap();
let manifest_path = tmp_dir.path().join("manifest.json");
let mut manifest = Manifest::new(manifest_path.as_path());
let mut account = SteamGuardAccount::new();
account.account_name = "asdf1234".into();
account.revocation_code = "R12345".into();
account.shared_secret = steamguard::token::TwoFactorSecret::parse_shared_secret(
"zvIayp3JPvtvX/QGHqsqKBk/44s=".into(),
)
.unwrap();
manifest.add_account(account);
manifest.entries[0].encryption = Some(EntryEncryptionParams::generate());
assert!(matches!(manifest.save(&passkey), Ok(_)));
let mut loaded_manifest = Manifest::load(manifest_path.as_path()).unwrap();
assert_eq!(loaded_manifest.entries.len(), 1);
assert_eq!(loaded_manifest.entries[0].filename, "asdf1234.maFile");
assert!(matches!(loaded_manifest.load_accounts(&passkey), Ok(_)));
assert_eq!(
loaded_manifest.entries.len(),
loaded_manifest.accounts.len()
);
assert_eq!(
loaded_manifest.accounts[0].lock().unwrap().account_name,
"asdf1234"
);
assert_eq!(
loaded_manifest.accounts[0].lock().unwrap().revocation_code,
"R12345"
);
assert_eq!(
loaded_manifest.accounts[0].lock().unwrap().shared_secret,
account.shared_secret,
steamguard::token::TwoFactorSecret::parse_shared_secret(
"zvIayp3JPvtvX/QGHqsqKBk/44s=".into()
)
.unwrap(),
);
Ok(())
}
#[test]
fn test_should_save_and_load_manifest_encrypted() -> anyhow::Result<()> {
let passkey = Some(SecretString::new("password".into()));
let tmp_dir = TempDir::new()?;
let manifest_path = tmp_dir.path().join("manifest.json");
let mut manager = AccountManager::new(manifest_path.as_path());
let mut account = SteamGuardAccount::new();
account.account_name = "asdf1234".into();
account.revocation_code = String::from("R12345").into();
account.shared_secret = steamguard::token::TwoFactorSecret::parse_shared_secret(
"zvIayp3JPvtvX/QGHqsqKBk/44s=".into(),
)?;
manager.add_account(account);
manager.manifest.entries[0].encryption = Some(EncryptionScheme::generate());
manager.submit_passkey(passkey.clone());
assert!(manager.save().is_ok());
let mut loaded_manager = AccountManager::load(manifest_path.as_path()).unwrap();
loaded_manager.submit_passkey(passkey);
assert_eq!(loaded_manager.manifest.entries.len(), 1);
assert_eq!(
loaded_manager.manifest.entries[0].filename,
"asdf1234.maFile"
);
let _r = loaded_manager.load_accounts();
if _r.is_err() {
eprintln!("{:?}", _r);
}
assert!(_r.is_ok());
assert_eq!(
loaded_manager.manifest.entries.len(),
loaded_manager.accounts.len()
);
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!(
account.shared_secret,
steamguard::token::TwoFactorSecret::parse_shared_secret(
"zvIayp3JPvtvX/QGHqsqKBk/44s=".into()
)
.unwrap(),
);
Ok(())
}
#[test]
fn test_should_save_and_load_manifest_encrypted_longer() -> anyhow::Result<()> {
let passkey: Option<String> = Some("password".into());
let tmp_dir = TempDir::new("steamguard-cli-test").unwrap();
let passkey = Some(SecretString::new("password".into()));
let tmp_dir = TempDir::new()?;
let manifest_path = tmp_dir.path().join("manifest.json");
let mut manifest = Manifest::new(manifest_path.as_path());
let mut manager = AccountManager::new(manifest_path.as_path());
let mut account = SteamGuardAccount::new();
account.account_name = "asdf1234".into();
account.revocation_code = "R12345".into();
account.revocation_code = String::from("R12345").into();
account.shared_secret = steamguard::token::TwoFactorSecret::parse_shared_secret(
"zvIayp3JPvtvX/QGHqsqKBk/44s=".into(),
)
.unwrap();
account.uri = "otpauth://;laksdjf;lkasdjf;lkasdj;flkasdjlkf;asjdlkfjslk;adjfl;kasdjf;lksdjflk;asjd;lfajs;ldkfjaslk;djf;lsakdjf;lksdj".into();
account.uri = String::from("otpauth://;laksdjf;lkasdjf;lkasdj;flkasdjlkf;asjdlkfjslk;adjfl;kasdjf;lksdjflk;asjd;lfajs;ldkfjaslk;djf;lsakdjf;lksdj").into();
account.token_gid = "asdf1234".into();
manifest.add_account(account);
manifest.entries[0].encryption = Some(EntryEncryptionParams::generate());
manifest.save(&passkey)?;
manager.add_account(account);
manager.submit_passkey(passkey.clone());
manager.manifest.entries[0].encryption = Some(EncryptionScheme::generate());
manager.save()?;
let mut loaded_manifest = Manifest::load(manifest_path.as_path())?;
assert_eq!(loaded_manifest.entries.len(), 1);
assert_eq!(loaded_manifest.entries[0].filename, "asdf1234.maFile");
loaded_manifest.load_accounts(&passkey)?;
let mut loaded_manager = AccountManager::load(manifest_path.as_path())?;
loaded_manager.submit_passkey(passkey);
assert_eq!(loaded_manager.manifest.entries.len(), 1);
assert_eq!(
loaded_manifest.entries.len(),
loaded_manifest.accounts.len()
loaded_manager.manifest.entries[0].filename,
"asdf1234.maFile"
);
loaded_manager.load_accounts()?;
assert_eq!(
loaded_manifest.accounts[0].lock().unwrap().account_name,
"asdf1234"
loaded_manager.manifest.entries.len(),
loaded_manager.accounts.len()
);
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!(
loaded_manifest.accounts[0].lock().unwrap().revocation_code,
"R12345"
);
assert_eq!(
loaded_manifest.accounts[0].lock().unwrap().shared_secret,
account.shared_secret,
steamguard::token::TwoFactorSecret::parse_shared_secret(
"zvIayp3JPvtvX/QGHqsqKBk/44s=".into()
)
.unwrap(),
);
return Ok(());
Ok(())
}
#[test]
fn test_should_import() {
let tmp_dir = TempDir::new("steamguard-cli-test").unwrap();
fn test_should_import() -> anyhow::Result<()> {
let tmp_dir = TempDir::new()?;
let manifest_path = tmp_dir.path().join("manifest.json");
let mut manifest = Manifest::new(manifest_path.as_path());
let mut manager = AccountManager::new(manifest_path.as_path());
let mut account = SteamGuardAccount::new();
account.account_name = "asdf1234".into();
account.revocation_code = "R12345".into();
account.revocation_code = String::from("R12345").into();
account.shared_secret = steamguard::token::TwoFactorSecret::parse_shared_secret(
"zvIayp3JPvtvX/QGHqsqKBk/44s=".into(),
)
.unwrap();
manifest.add_account(account);
assert!(matches!(manifest.save(&None), Ok(_)));
std::fs::remove_file(&manifest_path).unwrap();
manager.add_account(account);
manager.save()?;
std::fs::remove_file(&manifest_path)?;
let mut loaded_manifest = Manifest::new(manifest_path.as_path());
assert!(matches!(
loaded_manifest.import_account(
tmp_dir
let mut loaded_manager = AccountManager::new(manifest_path.as_path());
assert!(loaded_manager
.import_account(
&tmp_dir
.path()
.join("asdf1234.maFile")
.into_os_string()
.into_string()
.unwrap()
),
Ok(_)
));
)
.is_ok());
assert_eq!(
loaded_manifest.entries.len(),
loaded_manifest.accounts.len()
loaded_manager.manifest.entries.len(),
loaded_manager.accounts.len()
);
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!(
loaded_manifest.accounts[0].lock().unwrap().account_name,
"asdf1234"
);
assert_eq!(
loaded_manifest.accounts[0].lock().unwrap().revocation_code,
"R12345"
);
assert_eq!(
loaded_manifest.accounts[0].lock().unwrap().shared_secret,
account.shared_secret,
steamguard::token::TwoFactorSecret::parse_shared_secret(
"zvIayp3JPvtvX/QGHqsqKBk/44s=".into()
)
.unwrap(),
);
Ok(())
}
#[test]
fn test_sda_compatibility_1() {
let path = Path::new("src/fixtures/maFiles/compat/1-account/manifest.json");
assert!(path.is_file());
let result = Manifest::load(path);
assert!(matches!(result, Ok(_)));
let mut manifest = result.unwrap();
assert!(matches!(manifest.entries.last().unwrap().encryption, None));
assert!(matches!(manifest.load_accounts(&None), Ok(_)));
assert_eq!(
manifest.entries.last().unwrap().account_name,
manifest
.accounts
.last()
.unwrap()
.lock()
.unwrap()
.account_name
);
fn should_load_manifest_v1() -> anyhow::Result<()> {
#[derive(Debug)]
struct Test {
manifest: &'static str,
passkey: Option<SecretString>,
}
#[test]
fn test_sda_compatibility_1_encrypted() {
let path = Path::new("src/fixtures/maFiles/compat/1-account-encrypted/manifest.json");
assert!(path.is_file());
let result = Manifest::load(path);
assert!(matches!(result, Ok(_)));
let mut manifest = result.unwrap();
assert!(matches!(
manifest.entries.last().unwrap().encryption,
Some(_)
));
let result = manifest.load_accounts(&Some("password".into()));
assert!(
matches!(result, Ok(_)),
"error when loading accounts: {:?}",
result.unwrap_err()
);
assert_eq!(
manifest.entries.last().unwrap().account_name,
manifest
.accounts
.last()
.unwrap()
.lock()
.unwrap()
.account_name
);
let cases = vec![
Test {
manifest: "src/fixtures/maFiles/manifest-v1/1-account/manifest.json",
passkey: None,
},
Test {
manifest: "src/fixtures/maFiles/manifest-v1/1-account-encrypted/manifest.json",
passkey: Some(SecretString::new("password".into())),
},
Test {
manifest: "src/fixtures/maFiles/manifest-v1/2-account/manifest.json",
passkey: None,
},
Test {
manifest: "src/fixtures/maFiles/manifest-v1/missing-account-name/manifest.json",
passkey: None,
},
];
for case in cases {
eprintln!("testing: {:?}", case);
let mut manager = AccountManager::load(Path::new(case.manifest))?;
manager.submit_passkey(case.passkey.clone());
manager.load_accounts()?;
assert_eq!(manager.manifest.version, CURRENT_MANIFEST_VERSION);
assert_eq!(manager.manifest.entries[0].account_name, "example");
assert_eq!(manager.manifest.entries[0].steam_id, 1234);
let account = manager.get_account("example").unwrap();
let account = account.lock().unwrap();
assert_eq!(account.account_name, "example");
assert_eq!(account.steam_id, 1234);
}
Ok(())
}
}

View file

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

View file

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

View file

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

View file

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

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

236
src/commands.rs Normal file
View file

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

50
src/commands/code.rs Normal file
View file

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

View file

@ -0,0 +1,23 @@
use clap::CommandFactory;
use super::*;
#[derive(Debug, Clone, Parser)]
#[clap(about = "Generate shell completions")]
pub struct CompletionsCommand {
#[clap(
short,
long,
value_enum,
help = "The shell to generate completions for."
)]
pub shell: Shell,
}
impl ConstCommand for CompletionsCommand {
fn execute(&self) -> anyhow::Result<()> {
let mut app = Args::command_for_update();
clap_complete::generate(self.shell, &mut app, "steamguard", &mut std::io::stdout());
Ok(())
}
}

168
src/commands/confirm.rs Normal file
View 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(())
}
}

115
src/commands/debug.rs Normal file
View file

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

62
src/commands/decrypt.rs Normal file
View file

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

75
src/commands/encrypt.rs Normal file
View file

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

71
src/commands/import.rs Normal file
View file

@ -0,0 +1,71 @@
use std::path::Path;
use log::*;
use crate::{accountmanager::ManifestAccountImportError, AccountManager};
use super::*;
#[derive(Debug, Clone, Parser, Default)]
#[clap(
about = "Import an account with steamguard already set up. It must not be encrypted. If you haven't used steamguard-cli before, you probably don't need to use this command."
)]
pub struct ImportCommand {
#[clap(long, help = "Paths to one or more maFiles, eg. \"./gaben.maFile\"")]
pub files: Vec<String>,
}
impl<T> ManifestCommand<T> for ImportCommand
where
T: Transport,
{
fn execute(
&self,
_transport: T,
manager: &mut AccountManager,
_args: &GlobalArgs,
) -> anyhow::Result<()> {
let mut accounts_added = 0;
for file_path in self.files.iter() {
debug!("loading entry: {:?}", file_path);
match manager.import_account(file_path) {
Ok(_) => {
info!("Imported account: {}", &file_path);
}
Err(ManifestAccountImportError::AlreadyExists { .. }) => {
warn!("Account already exists: {} -- Ignoring", &file_path);
}
Err(ManifestAccountImportError::DeserializationFailed(orig_err)) => {
debug!("Falling back to external account import",);
let path = Path::new(&file_path);
let accounts =
match crate::accountmanager::migrate::load_and_upgrade_external_accounts(
path,
) {
Ok(accounts) => accounts,
Err(err) => {
error!("Failed to import account: {} {}", &file_path, err);
error!("The original error was: {}", orig_err);
continue;
}
};
for account in accounts {
manager.add_account(account);
info!("Imported account: {}", &file_path);
accounts_added += 1;
}
}
Err(err) => {
bail!("Failed to import account: {} {}", &file_path, err);
}
}
}
if accounts_added > 0 {
info!("Imported {} accounts", accounts_added);
}
manager.save()?;
Ok(())
}
}

60
src/commands/qr.rs Normal file
View file

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

128
src/commands/qr_login.rs Normal file
View 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");
}
}

102
src/commands/remove.rs Normal file
View file

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

309
src/commands/setup.rs Normal file
View file

@ -0,0 +1,309 @@
use log::*;
use phonenumber::PhoneNumber;
use secrecy::ExposeSecret;
use steamguard::{
accountlinker::{AccountLinkConfirmType, AccountLinkSuccess, RemoveAuthenticatorError},
phonelinker::PhoneLinker,
steamapi::PhoneClient,
token::Tokens,
AccountLinkError, AccountLinker, FinalizeLinkError,
};
use crate::{tui, AccountManager};
use super::*;
#[derive(Debug, Clone, Parser)]
#[clap(about = "Set up a new account with steamguard-cli")]
pub struct SetupCommand;
impl<T> ManifestCommand<T> for SetupCommand
where
T: Transport + Clone,
{
fn execute(
&self,
transport: T,
manager: &mut AccountManager,
args: &GlobalArgs,
) -> anyhow::Result<()> {
eprintln!("Log in to the account that you want to link to steamguard-cli");
eprint!("Username: ");
let username = tui::prompt().to_lowercase();
let account_name = username.clone();
if manager.account_exists(&username) {
bail!(
"Account {} already exists in manifest, remove it first",
username
);
}
info!("Logging in to {}", username);
let tokens = crate::do_login_raw(transport.clone(), username, args.password.clone())
.expect("Failed to log in. Account has not been linked.");
info!("Adding authenticator...");
let mut linker = AccountLinker::new(transport.clone(), tokens);
loop {
match linker.link() {
Ok(link) => {
return Self::add_new_account(link, manager, account_name, linker);
}
Err(AccountLinkError::MustProvidePhoneNumber) => {
// As of Dec 12, 2023, Steam no longer appears to require a phone number to add an authenticator. Keeping this code here just in case.
eprintln!("Looks like you don't have a phone number on this account.");
do_add_phone_number(transport.clone(), linker.tokens())?;
}
Err(AccountLinkError::MustConfirmEmail) => {
println!("Check your email and click the link.");
tui::pause();
}
Err(AccountLinkError::AuthenticatorPresent) => {
eprintln!("It looks like there's already an authenticator on this account. If you want to link it to steamguard-cli, you'll need to remove it first. If you remove it using your revocation code (R#####), you'll get a 15 day trade ban.");
eprintln!("However, you can \"transfer\" the authenticator to steamguard-cli if you have access to the phone number associated with your account. This will cause you to get only a 2 day trade ban.");
eprintln!("If you were using SDA or WinAuth, you can import it into steamguard-cli with the `import` command, and have no trade ban.");
eprintln!("You can't have the same authenticator on steamguard-cli and the steam mobile app at the same time.");
eprintln!("\nHere are your options:");
eprintln!("[T] Transfer authenticator to steamguard-cli (2 day trade ban)");
eprintln!("[R] Revoke authenticator with revocation code (15 day trade ban)");
eprintln!("[A] Abort setup");
let answer = tui::prompt_char("What would you like to do?", "Tra");
match answer {
't' => return Self::transfer_new_account(linker, manager),
'r' => {
loop {
let revocation_code =
tui::prompt_non_empty("Enter your revocation code (R#####): ");
match linker.remove_authenticator(Some(&revocation_code)) {
Ok(_) => break,
Err(RemoveAuthenticatorError::IncorrectRevocationCode {
attempts_remaining,
}) => {
error!(
"Revocation code was incorrect ({} attempts remaining)",
attempts_remaining
);
if attempts_remaining == 0 {
error!("No attempts remaining, aborting!");
bail!("Failed to remove authenticator: no attempts remaining")
}
}
Err(err) => {
error!("Failed to remove authenticator: {}", err);
}
}
}
}
_ => {
info!("Aborting account linking.");
return Err(AccountLinkError::AuthenticatorPresent.into());
}
}
}
Err(err) => {
error!(
"Failed to link authenticator. Account has not been linked. {}",
err
);
return Err(err.into());
}
}
}
}
}
impl SetupCommand {
/// Add a new account to the manifest after linking has started.
fn add_new_account<T>(
link: AccountLinkSuccess,
manager: &mut AccountManager,
account_name: String,
mut linker: AccountLinker<T>,
) -> Result<(), anyhow::Error>
where
T: Transport + Clone,
{
let mut server_time = link.server_time();
let phone_number_hint = link.phone_number_hint().to_owned();
let confirm_type = link.confirm_type();
manager.add_account(link.into_account());
match manager.save() {
Ok(_) => {}
Err(err) => {
error!("Aborting the account linking process because we failed to save the manifest. This is really bad. Here is the error: {}", err);
eprintln!(
"Just in case, here is the account info. Save it somewhere just in case!\n{:#?}",
manager.get_account(&account_name).unwrap().lock().unwrap()
);
return Err(err);
}
}
let account_arc = manager
.get_account(&account_name)
.expect("account was not present in manifest");
let mut account = account_arc.lock().unwrap();
eprintln!("Authenticator has not yet been linked. Before continuing with finalization, please take the time to write down your revocation code: {}", account.revocation_code.expose_secret());
tui::pause();
debug!("attempting link finalization");
let confirm_code = match confirm_type {
AccountLinkConfirmType::Email => {
eprintln!(
"A code has been sent to the email address associated with this account."
);
tui::prompt_non_empty("Enter email code: ")
}
AccountLinkConfirmType::SMS => {
eprintln!(
"A code has been sent to your phone number ending in {}.",
phone_number_hint
);
tui::prompt_non_empty("Enter SMS code: ")
}
AccountLinkConfirmType::Unknown(t) => {
error!("Unknown link confirm type: {}", t);
bail!("Unknown link confirm type: {}", t);
}
};
let mut tries = 0;
loop {
match linker.finalize(server_time, &mut account, confirm_code.clone()) {
Ok(_) => break,
Err(FinalizeLinkError::WantMore { server_time: s }) => {
server_time = s;
debug!("steam wants more 2fa codes (tries: {})", tries);
tries += 1;
if tries >= 30 {
error!("Failed to finalize: unable to generate valid 2fa codes");
bail!("Failed to finalize: unable to generate valid 2fa codes");
}
}
Err(err) => {
error!("Failed to finalize: {}", err);
return Err(err.into());
}
}
}
let revocation_code = account.revocation_code.clone();
drop(account);
info!("Verifying authenticator status...");
let status =
linker.query_status(&manager.get_account(&account_name).unwrap().lock().unwrap())?;
if status.state() == 0 {
debug!(
"authenticator state: {} -- did not actually finalize",
status.state()
);
debug!("full status: {:#?}", status);
manager.remove_account(&account_name);
manager.save()?;
bail!("Authenticator finalization was unsuccessful. You may have entered the wrong confirm code in the previous step. Try again.");
}
info!("Authenticator finalized.");
match manager.save() {
Ok(_) => {}
Err(err) => {
error!(
"Failed to save manifest, but we were able to save it before. {}",
err
);
return Err(err);
}
}
eprintln!(
"Authenticator has been finalized. Please actually write down your revocation code: {}",
revocation_code.expose_secret()
);
Ok(())
}
/// Transfer an existing authenticator to steamguard-cli.
fn transfer_new_account<T>(
mut linker: AccountLinker<T>,
manager: &mut AccountManager,
) -> anyhow::Result<()>
where
T: Transport + Clone,
{
info!("Transferring authenticator to steamguard-cli");
linker.transfer_start()?;
let account: SteamGuardAccount;
loop {
let sms_code = tui::prompt_non_empty("Enter SMS code: ");
match linker.transfer_finish(sms_code) {
Ok(acc) => {
account = acc;
break;
}
Err(err) => {
error!("Failed to transfer authenticator: {}", err);
}
}
}
info!("Transfer successful, adding account to manifest");
let revocation_code = account.revocation_code.clone();
eprintln!(
"Take a moment to write down your revocation code: {}",
revocation_code.expose_secret()
);
manager.add_account(account);
manager.save()?;
eprintln!(
"Make sure you have your revocation code written down: {}",
revocation_code.expose_secret()
);
Ok(())
}
}
pub fn do_add_phone_number<T: Transport>(transport: T, tokens: &Tokens) -> anyhow::Result<()> {
let client = PhoneClient::new(transport);
let linker = PhoneLinker::new(client, tokens.clone());
let phone_number: PhoneNumber;
loop {
eprintln!("Enter your phone number, including country code, in this format: +1 1234567890");
eprint!("Phone number: ");
let number = tui::prompt();
match phonenumber::parse(None, &number) {
Ok(p) => {
phone_number = p;
break;
}
Err(err) => {
error!("Failed to parse phone number: {}", err);
}
}
}
let resp = linker.set_account_phone_number(phone_number)?;
eprintln!(
"Please click the link in the email sent to {}",
resp.confirmation_email_address()
);
tui::pause();
debug!("sending phone verification code");
linker.send_phone_verification_code(0)?;
loop {
eprint!("Enter the code sent to your phone: ");
let code = tui::prompt();
match linker.verify_account_phone_with_code(code) {
Ok(_) => break,
Err(err) => {
error!("Failed to verify phone number: {}", err);
}
}
}
info!("Successfully added phone number to account");
Ok(())
}

27
src/debug.rs Normal file
View 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,
}
}

View file

@ -1,38 +0,0 @@
use crate::tui;
use log::*;
use steamguard::{Confirmation, ConfirmationType};
pub fn demo_confirmation_menu() {
info!("showing demo menu");
let (accept, deny) = tui::prompt_confirmation_menu(vec![
Confirmation {
id: 1234,
key: 12345,
conf_type: ConfirmationType::Trade,
creator: 09870987,
description: "example confirmation".into(),
},
Confirmation {
id: 1234,
key: 12345,
conf_type: ConfirmationType::MarketSell,
creator: 09870987,
description: "example confirmation".into(),
},
Confirmation {
id: 1234,
key: 12345,
conf_type: ConfirmationType::AccountRecovery,
creator: 09870987,
description: "example confirmation".into(),
},
Confirmation {
id: 1234,
key: 12345,
conf_type: ConfirmationType::Trade,
creator: 09870987,
description: "example confirmation".into(),
},
]);
println!("accept: {}, deny: {}", accept.len(), deny.len());
}

View file

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

View 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
View 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
View 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(), &params, orig.clone()).unwrap();
// let result = LegacySdaCompatible::decrypt(&passkey.into(), &params, encrypted).unwrap();
// prop_assert_eq!(orig, result.to_vec());
// }
// }
}

7
src/errors.rs Normal file
View file

@ -0,0 +1,7 @@
use thiserror::Error;
#[derive(Debug, Error)]
pub(crate) enum UserError {
#[error("User aborted the operation.")]
Aborted,
}

View file

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

View file

@ -0,0 +1 @@
{"shared_secret":"zvIayp3JPvtvX/QGHqsqKBk/44s=","serial_number":"kljasfhds","revocation_code":"R56789","uri":"otpauth://totp/Steam:example?secret=ASDF&issuer=Steam","server_time":1602522478,"account_name":"example2","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":5678}}

View file

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

View file

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

View 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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -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":null,"OAuthToken":"asdk;lf;dsjlkfd","SteamID":1234}}

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

View file

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

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

View 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

View file

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

View file

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

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

View file

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

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

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

View 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}]}

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

View file

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

219
src/login.rs Normal file
View 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,
}
}

View file

@ -1,18 +1,19 @@
extern crate rpassword;
use clap::{crate_version, App, Arg, Shell};
use clap::Parser;
use log::*;
use std::str::FromStr;
use secrecy::SecretString;
use std::{
io::{stdout, Write},
path::Path,
sync::{Arc, Mutex},
};
use steamguard::{
steamapi, AccountLinkError, AccountLinker, Confirmation, FinalizeLinkError, LoginError,
SteamGuardAccount, UserLogin,
};
use steamguard::transport::WebApiTransport;
use steamguard::SteamGuardAccount;
use crate::accountmanager::migrate::{load_and_migrate, MigrationError};
pub use crate::accountmanager::{AccountManager, ManifestAccountLoadError, ManifestLoadError};
use crate::commands::{CommandType, Subcommands};
pub use login::*;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate anyhow;
@ -20,350 +21,241 @@ extern crate base64;
extern crate dirs;
#[cfg(test)]
extern crate proptest;
extern crate ring;
mod accountmanager;
mod demos;
mod commands;
mod debug;
mod encryption;
mod tui;
mod errors;
mod login;
mod secret_string;
pub(crate) mod tui;
fn cli() -> App<'static, 'static> {
App::new("steamguard-cli")
.version(crate_version!())
.bin_name("steamguard")
.author("dyc3 (Carson McManus)")
.about("Generate Steam 2FA codes and confirm Steam trades from the command line.")
.arg(
Arg::with_name("username")
.long("username")
.short("u")
.takes_value(true)
.help("Select the account you want by steam username. By default, the first account in the manifest is selected.")
.conflicts_with("all")
)
.arg(
Arg::with_name("all")
.long("all")
.short("a")
.takes_value(false)
.help("Select all accounts in the manifest.")
.conflicts_with("username")
)
.arg(
Arg::with_name("mafiles-path")
.long("mafiles-path")
.short("m")
.default_value("~/maFiles")
.help("Specify which folder your maFiles are in. This should be a path to a folder that contains manifest.json.")
)
.arg(
Arg::with_name("passkey")
.long("passkey")
.short("p")
.help("Specify your encryption passkey.")
.takes_value(true)
)
.arg(
Arg::with_name("verbosity")
.short("v")
.help("Log what is going on verbosely.")
.takes_value(false)
.multiple(true)
)
.subcommand(
App::new("completion")
.about("Generate shell completions")
.arg(
Arg::with_name("shell")
.long("shell")
.takes_value(true)
.possible_values(&Shell::variants())
)
)
.subcommand(
App::new("trade")
.about("Interactive interface for trade confirmations")
.arg(
Arg::with_name("accept-all")
.short("a")
.long("accept-all")
.takes_value(false)
.help("Accept all open trade confirmations. Does not open interactive interface.")
)
)
.subcommand(
App::new("setup")
.about("Set up a new account with steamguard-cli")
)
.subcommand(
App::new("import")
.about("Import an account with steamguard already set up")
.arg(
Arg::with_name("files")
.required(true)
.multiple(true)
)
)
.subcommand(
App::new("remove")
.about("Remove the authenticator from an account.")
)
.subcommand(
App::new("encrypt")
.about("Encrypt maFiles.")
)
.subcommand(
App::new("decrypt")
.about("Decrypt maFiles.")
)
.subcommand(
App::new("debug")
.arg(
Arg::with_name("demo-conf-menu")
.help("Show an example confirmation menu using dummy data.")
.takes_value(false)
)
)
}
#[cfg(feature = "updater")]
mod updater;
fn main() {
let matches = cli().get_matches();
let args = commands::Args::parse();
let verbosity = matches.occurrences_of("verbosity") as usize + 2;
stderrlog::new()
.verbosity(verbosity)
.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;
if let Some(demo_matches) = matches.subcommand_matches("debug") {
if demo_matches.is_present("demo-conf-menu") {
demos::demo_confirmation_menu();
let exit_code = match run(args) {
Ok(_) => 0,
Err(e) => {
error!("{:?}", e);
255
}
return;
}
if let Some(completion_matches) = matches.subcommand_matches("completion") {
cli().gen_completions_to(
"steamguard",
Shell::from_str(completion_matches.value_of("shell").unwrap()).unwrap(),
&mut std::io::stdout(),
};
#[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
);
return;
}
Ok(None) => {
debug!("No update available");
}
Err(e) => {
warn!("Failed to check for updates: {}", e);
}
}
}
let mafiles_dir = if matches.occurrences_of("mafiles-path") > 0 {
matches.value_of("mafiles-path").unwrap().into()
std::process::exit(exit_code);
}
fn run(args: commands::Args) -> anyhow::Result<()> {
let globalargs = args.global;
let cmd: CommandType<WebApiTransport> = match args.sub.unwrap_or(Subcommands::Code(args.code)) {
Subcommands::Debug(args) => CommandType::Const(Box::new(args)),
Subcommands::Completion(args) => CommandType::Const(Box::new(args)),
Subcommands::Setup(args) => CommandType::Manifest(Box::new(args)),
Subcommands::Import(args) => CommandType::Manifest(Box::new(args)),
Subcommands::Encrypt(args) => CommandType::Manifest(Box::new(args)),
Subcommands::Decrypt(args) => CommandType::Manifest(Box::new(args)),
Subcommands::Confirm(args) => CommandType::Account(Box::new(args)),
Subcommands::Remove(args) => CommandType::Account(Box::new(args)),
Subcommands::Code(args) => CommandType::Account(Box::new(args)),
#[cfg(feature = "qr")]
Subcommands::Qr(args) => CommandType::Account(Box::new(args)),
Subcommands::QrLogin(args) => CommandType::Account(Box::new(args)),
};
if let CommandType::Const(cmd) = cmd {
return cmd.execute();
}
let mafiles_dir = if let Some(mafiles_path) = &globalargs.mafiles_path {
mafiles_path.clone()
} else {
get_mafiles_dir()
};
info!("reading manifest from {}", mafiles_dir);
let path = Path::new(&mafiles_dir).join("manifest.json");
let mut manifest: accountmanager::Manifest;
let mut passkey = globalargs.passkey.clone();
let mut manager: accountmanager::AccountManager;
if !path.exists() {
error!("Did not find manifest in {}", mafiles_dir);
match tui::prompt_char(
if tui::prompt_char(
format!("Would you like to create a manifest in {} ?", mafiles_dir).as_str(),
"Yn",
) {
'n' => {
) == 'n'
{
info!("Aborting!");
return;
return Err(errors::UserError::Aborted.into());
}
_ => {}
}
std::fs::create_dir_all(mafiles_dir).expect("failed to create directory");
std::fs::create_dir_all(mafiles_dir)?;
manifest = accountmanager::Manifest::new(path.as_path());
manager = accountmanager::AccountManager::new(path.as_path());
manager.save()?;
} else {
match accountmanager::Manifest::load(path.as_path()) {
Ok(m) => {
manager = match accountmanager::AccountManager::load(path.as_path()) {
Ok(m) => m,
Err(ManifestLoadError::MigrationNeeded) => {
info!("Migrating manifest");
let manifest;
let accounts;
loop {
match load_and_migrate(path.as_path(), passkey.as_ref()) {
Ok((m, a)) => {
manifest = m;
accounts = a;
break;
}
Err(MigrationError::MissingPasskey { keyring_id }) => {
if passkey.is_some() {
error!("Incorrect passkey");
}
#[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!("Could not load manifest: {}", e);
return;
error!("Failed to migrate manifest: {}", e);
return Err(e.into());
}
}
}
let mut manager = AccountManager::from_manifest(manifest, mafiles_dir);
manager.register_accounts(accounts);
manager.submit_passkey(passkey.clone());
manager.save()?;
manager
}
Err(err) => {
error!("Failed to load manifest: {}", err);
return Err(err.into());
}
}
}
let mut passkey: Option<String> = matches.value_of("passkey").map(|s| s.into());
#[cfg(feature = "keyring")]
if let Some(keyring_id) = manager.keyring_id() {
if passkey.is_none() {
info!("Attempting to load encryption passkey from keyring");
match encryption::try_passkey_from_keyring(keyring_id.clone()) {
Ok(k) => passkey = k,
Err(e) => {
warn!("Failed to load encryption passkey from keyring: {}", e);
}
}
}
}
manager.submit_passkey(passkey);
loop {
match manifest.load_accounts(&passkey) {
Ok(_) => break,
match manager.auto_upgrade() {
Ok(upgraded) => {
if upgraded {
info!("Manifest auto-upgraded");
manager.save()?;
} else {
debug!("Manifest is up to date");
}
break;
}
Err(
accountmanager::ManifestAccountLoadError::MissingPasskey
| accountmanager::ManifestAccountLoadError::IncorrectPasskey,
) => {
if passkey.is_some() {
if manager.has_passkey() {
error!("Incorrect passkey");
}
passkey = rpassword::prompt_password_stdout("Enter encryption passkey: ").ok();
passkey = Some(tui::prompt_passkey()?);
manager.submit_passkey(passkey);
}
Err(e) => {
error!("Could not load accounts: {}", e);
return;
return Err(e.into());
}
}
}
if matches.is_present("setup") {
println!("Log in to the account that you want to link to steamguard-cli");
let session = do_login_raw().expect("Failed to log in. Account has not been linked.");
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);
let mut linker = AccountLinker::new(session);
let account: SteamGuardAccount;
if let CommandType::Manifest(cmd) = cmd {
cmd.execute(transport, &mut manager, &globalargs)?;
return Ok(());
}
let selected_accounts: Vec<Arc<Mutex<SteamGuardAccount>>>;
loop {
match linker.link() {
Ok(a) => {
account = a;
match get_selected_accounts(&globalargs, &mut manager) {
Ok(accounts) => {
selected_accounts = accounts;
break;
}
Err(AccountLinkError::MustRemovePhoneNumber) => {
println!("There is already a phone number on this account, please remove it and try again.");
return;
Err(
accountmanager::ManifestAccountLoadError::MissingPasskey { .. }
| accountmanager::ManifestAccountLoadError::IncorrectPasskey,
) => {
if manager.has_passkey() {
error!("Incorrect passkey");
}
Err(AccountLinkError::MustProvidePhoneNumber) => {
println!("Enter your phone number in the following format: +1 123-456-7890");
print!("Phone number: ");
linker.phone_number = tui::prompt().replace(&['(', ')', '-'][..], "");
passkey = Some(tui::prompt_passkey()?);
manager.submit_passkey(passkey);
}
Err(AccountLinkError::AuthenticatorPresent) => {
println!("An authenticator is already present on this account.");
return;
}
Err(AccountLinkError::MustConfirmEmail) => {
println!("Check your email and click the link.");
tui::pause();
}
Err(err) => {
error!(
"Failed to link authenticator. Account has not been linked. {}",
err
);
return;
}
}
}
manifest.add_account(account);
match manifest.save(&passkey) {
Ok(_) => {}
Err(err) => {
error!("Aborting the account linking process because we failed to save the manifest. This is really bad. Here is the error: {}", err);
println!(
"Just in case, here is the account info. Save it somewhere just in case!\n{:?}",
manifest.accounts.last().unwrap().lock().unwrap()
);
return;
}
}
let mut account = manifest
.accounts
.last()
.as_ref()
.unwrap()
.clone()
.lock()
.unwrap();
println!("Authenticator has not yet been linked. Before continuing with finalization, please take the time to write down your revocation code: {}", account.revocation_code);
tui::pause();
debug!("attempting link finalization");
print!("Enter SMS code: ");
let sms_code = tui::prompt();
let mut tries = 0;
loop {
match linker.finalize(&mut account, sms_code.clone()) {
Ok(_) => break,
Err(FinalizeLinkError::WantMore) => {
debug!("steam wants more 2fa codes (tries: {})", tries);
tries += 1;
if tries >= 30 {
error!("Failed to finalize: unable to generate valid 2fa codes");
return;
}
}
Err(err) => {
error!("Failed to finalize: {}", err);
return;
}
}
}
println!("Authenticator finalized.");
match manifest.save(&None) {
Ok(_) => {}
Err(err) => {
println!(
"Failed to save manifest, but we were able to save it before. {}",
err
);
return;
}
}
println!(
"Authenticator has been finalized. Please actually write down your revocation code: {}",
account.revocation_code
);
return;
} else if let Some(import_matches) = matches.subcommand_matches("import") {
for file_path in import_matches.values_of("files").unwrap() {
match manifest.import_account(file_path.into()) {
Ok(_) => {
info!("Imported account: {}", file_path);
}
Err(err) => {
error!("Failed to import account: {} {}", file_path, err);
}
}
}
manifest.save(&passkey).expect("Failed to save manifest.");
return;
} else if matches.is_present("encrypt") {
if passkey.is_none() {
loop {
passkey = rpassword::prompt_password_stdout("Enter encryption passkey: ").ok();
let passkey_confirm =
rpassword::prompt_password_stdout("Confirm encryption passkey: ").ok();
if passkey == passkey_confirm {
break;
}
error!("Passkeys do not match, try again.");
}
}
for entry in &mut manifest.entries {
entry.encryption = Some(accountmanager::EntryEncryptionParams::generate());
}
manifest.save(&passkey).expect("Failed to save manifest.");
return;
} else if matches.is_present("decrypt") {
for entry in &mut manifest.entries {
entry.encryption = None;
}
manifest.save(&passkey).expect("Failed to save manifest.");
return;
}
let mut selected_accounts: Vec<Arc<Mutex<SteamGuardAccount>>> = vec![];
if matches.is_present("all") {
// manifest.accounts.iter().map(|a| selected_accounts.push(a.b));
for account in &manifest.accounts {
selected_accounts.push(account.clone());
}
} else {
for account in &manifest.accounts {
if !matches.is_present("username") {
selected_accounts.push(account.clone());
break;
}
if matches.value_of("username").unwrap() == account.lock().unwrap().account_name {
selected_accounts.push(account.clone());
break;
Err(e) => {
error!("Could not load accounts: {}", e);
return Err(e.into());
}
}
}
@ -376,196 +268,49 @@ fn main() {
.collect::<Vec<String>>()
);
if let Some(trade_matches) = matches.subcommand_matches("trade") {
info!("trade");
for a in selected_accounts.iter_mut() {
let mut account = a.lock().unwrap();
info!("Checking for trade confirmations");
let confirmations: Vec<Confirmation>;
loop {
match account.get_trade_confirmations() {
Ok(confs) => {
confirmations = confs;
break;
}
Err(_) => {
info!("failed to get trade confirmations, asking user to log in");
do_login(&mut account).expect("Failed to log in");
}
}
if let CommandType::Account(cmd) = cmd {
return cmd.execute(transport, &mut manager, selected_accounts, &globalargs);
}
if trade_matches.is_present("accept-all") {
info!("accepting all confirmations");
for conf in &confirmations {
let result = account.accept_confirmation(conf);
debug!("accept confirmation result: {:?}", result);
Ok(())
}
fn get_selected_accounts(
args: &commands::GlobalArgs,
manifest: &mut accountmanager::AccountManager,
) -> anyhow::Result<Vec<Arc<Mutex<SteamGuardAccount>>>, ManifestAccountLoadError> {
let mut selected_accounts: Vec<Arc<Mutex<SteamGuardAccount>>> = vec![];
if args.all {
manifest.load_accounts()?;
for entry in manifest.iter() {
selected_accounts.push(manifest.get_account(&entry.account_name).unwrap().clone());
}
} else {
if termion::is_tty(&stdout()) {
let (accept, deny) = tui::prompt_confirmation_menu(confirmations);
for conf in &accept {
let result = account.accept_confirmation(conf);
debug!("accept confirmation result: {:?}", result);
}
for conf in &deny {
let result = account.deny_confirmation(conf);
debug!("deny confirmation result: {:?}", result);
}
let entry = if let Some(username) = &args.username {
manifest.get_entry(username)
} else {
warn!("not a tty, not showing menu");
for conf in &confirmations {
println!("{}", conf.description());
}
}
}
}
manifest.save(&passkey).expect("Failed to save manifest");
} else if let Some(_) = matches.subcommand_matches("remove") {
println!(
"This will remove the mobile authenticator from {} accounts: {}",
selected_accounts.len(),
selected_accounts
manifest
.iter()
.map(|a| a.lock().unwrap().account_name.clone())
.collect::<Vec<String>>()
.join(", ")
);
.next()
.ok_or(ManifestAccountLoadError::MissingManifestEntry)
}?;
match tui::prompt_char("Do you want to continue?", "yN") {
'y' => {}
_ => {
info!("Aborting!");
return;
}
}
let mut successful = vec![];
for a in selected_accounts {
let account = a.lock().unwrap();
match account.remove_authenticator(None) {
Ok(success) => {
if success {
println!("Removed authenticator from {}", account.account_name);
successful.push(account.account_name.clone());
} else {
println!(
"Failed to remove authenticator from {}",
account.account_name
);
}
}
Err(err) => {
println!(
"Unexpected error when removing authenticator from {}: {}",
account.account_name, err
);
}
}
}
for account_name in successful {
manifest.remove_account(account_name);
}
manifest.save(&passkey).expect("Failed to save manifest.");
} else {
let server_time = steamapi::get_server_time();
for account in selected_accounts {
trace!("{:?}", account);
let code = account.lock().unwrap().generate_code(server_time);
println!("{}", code);
}
}
}
fn do_login(account: &mut SteamGuardAccount) -> anyhow::Result<()> {
if account.account_name.len() > 0 {
println!("Username: {}", account.account_name);
} else {
print!("Username: ");
account.account_name = tui::prompt();
}
let _ = std::io::stdout().flush();
let password = rpassword::prompt_password_stdout("Password: ").unwrap();
if password.len() > 0 {
debug!("password is present");
} else {
debug!("password is empty");
}
account.session = Some(do_login_impl(
account.account_name.clone(),
password,
Some(account),
)?);
return Ok(());
}
fn do_login_raw() -> anyhow::Result<steamapi::Session> {
print!("Username: ");
let username = tui::prompt();
let _ = std::io::stdout().flush();
let password = rpassword::prompt_password_stdout("Password: ").unwrap();
if password.len() > 0 {
debug!("password is present");
} else {
debug!("password is empty");
}
return do_login_impl(username, password, None);
}
fn do_login_impl(
username: String,
password: String,
account: Option<&SteamGuardAccount>,
) -> anyhow::Result<steamapi::Session> {
// TODO: reprompt if password is empty
let mut login = UserLogin::new(username, password);
let mut loops = 0;
loop {
match login.login() {
Ok(s) => {
return Ok(s);
}
Err(LoginError::Need2FA) => match account {
Some(a) => {
let server_time = steamapi::get_server_time();
login.twofactor_code = a.generate_code(server_time);
}
None => {
print!("Enter 2fa code: ");
login.twofactor_code = tui::prompt();
}
},
Err(LoginError::NeedCaptcha { captcha_gid }) => {
debug!("need captcha to log in");
login.captcha_text = tui::prompt_captcha_text(&captcha_gid);
}
Err(LoginError::NeedEmail) => {
println!("You should have received an email with a code.");
print!("Enter code: ");
login.email_code = tui::prompt();
}
Err(r) => {
error!("Fatal login result: {:?}", r);
bail!(r);
}
}
loops += 1;
if loops > 2 {
error!("Too many loops. Aborting login process, to avoid getting rate limited.");
bail!("Too many loops. Login process aborted to avoid getting rate limited.");
}
let account_name = entry.account_name.clone();
let account = manifest.get_or_load_account(&account_name)?;
selected_accounts.push(account);
}
Ok(selected_accounts)
}
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::home_dir().unwrap()).join("maFiles"),
];
if let Ok(current_exe) = std::env::current_exe() {
paths.push(current_exe.parent().unwrap().join("maFiles"));
}
for path in &paths {
if path.join("manifest.json").is_file() {

30
src/secret_string.rs Normal file
View file

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

View file

@ -1,74 +1,65 @@
use log::*;
use regex::Regex;
use std::collections::HashSet;
use std::io::{Read, Write};
use steamguard::Confirmation;
use termion::{
event::{Event, Key},
input::TermRead,
raw::IntoRawMode,
screen::AlternateScreen,
use anyhow::Context;
use crossterm::{
cursor,
event::{Event, KeyCode, KeyEvent, KeyModifiers},
execute,
style::{Color, Print, PrintStyledContent, SetForegroundColor, Stylize},
terminal::{Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen},
QueueableCommand,
};
lazy_static! {
static ref CAPTCHA_VALID_CHARS: Regex =
Regex::new("^([A-H]|[J-N]|[P-R]|[T-Z]|[2-4]|[7-9]|[@%&])+$").unwrap();
}
pub fn validate_captcha_text(text: &String) -> bool {
return CAPTCHA_VALID_CHARS.is_match(text);
}
#[test]
fn test_validate_captcha_text() {
assert!(validate_captcha_text(&String::from("2WWUA@")));
assert!(validate_captcha_text(&String::from("3G8HT2")));
assert!(validate_captcha_text(&String::from("3J%@X3")));
assert!(validate_captcha_text(&String::from("2GCZ4A")));
assert!(validate_captcha_text(&String::from("3G8HT2")));
assert!(!validate_captcha_text(&String::from("asd823")));
assert!(!validate_captcha_text(&String::from("!PQ4RD")));
assert!(!validate_captcha_text(&String::from("1GQ4XZ")));
assert!(!validate_captcha_text(&String::from("8GO4XZ")));
assert!(!validate_captcha_text(&String::from("IPQ4RD")));
assert!(!validate_captcha_text(&String::from("0PT4RD")));
assert!(!validate_captcha_text(&String::from("APTSRD")));
assert!(!validate_captcha_text(&String::from("AP5TRD")));
assert!(!validate_captcha_text(&String::from("AP6TRD")));
}
use log::debug;
use secrecy::SecretString;
use std::collections::HashSet;
use std::io::{stderr, stdout, Write};
use steamguard::Confirmation;
/// Prompt the user for text input.
pub fn prompt() -> String {
let mut text = String::new();
let _ = std::io::stdout().flush();
std::io::stdin()
.read_line(&mut text)
.expect("Did not enter a correct string");
return String::from(text.strip_suffix('\n').unwrap());
}
pub(crate) fn prompt() -> String {
stdout().flush().expect("failed to flush stdout");
stderr().flush().expect("failed to flush stderr");
pub fn prompt_captcha_text(captcha_gid: &String) -> String {
println!("Captcha required. Open this link in your web browser: https://steamcommunity.com/public/captcha.php?gid={}", captcha_gid);
let mut captcha_text;
loop {
print!("Enter captcha text: ");
captcha_text = prompt();
if captcha_text.len() > 0 && validate_captcha_text(&captcha_text) {
let mut line = String::new();
while let Event::Key(KeyEvent { code, .. }) = crossterm::event::read().unwrap() {
match code {
KeyCode::Enter => {
break;
}
warn!("Invalid chars for captcha text found in user's input. Prompting again...");
KeyCode::Char(c) => {
line.push(c);
}
_ => {}
}
}
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;
}
}
return captcha_text;
}
/// Prompt the user for a single character response. Useful for asking yes or no questions.
///
/// `chars` should be all lowercase characters, with at most 1 uppercase character. The uppercase character is the default answer if no answer is provided.
pub fn prompt_char(text: &str, chars: &str) -> char {
return prompt_char_impl(&mut std::io::stdin(), text, chars);
/// The selected character returned will always be lowercase.
pub(crate) fn prompt_char(text: &str, chars: &str) -> char {
loop {
let _ = stderr().queue(Print(format!("{} [{}] ", text, chars)));
let _ = stderr().flush();
let input = prompt();
if let Ok(c) = prompt_char_impl(input, chars) {
return c;
}
}
}
fn prompt_char_impl(input: &mut impl Read, text: &str, chars: &str) -> char {
fn prompt_char_impl(input: impl Into<String>, chars: &str) -> anyhow::Result<char> {
let uppers = chars.replace(char::is_lowercase, "");
if uppers.len() > 1 {
panic!("Invalid chars for prompt_char. Maximum 1 uppercase letter is allowed.");
@ -79,140 +70,166 @@ fn prompt_char_impl(input: &mut impl Read, text: &str, chars: &str) -> char {
None
};
loop {
print!("{} [{}] ", text, chars);
let answer = input
.read_line()
.expect("Unable to read input")
.unwrap()
.to_ascii_lowercase();
if answer.len() == 0 {
let answer: String = input.into().to_ascii_lowercase();
if answer.is_empty() {
if let Some(a) = default_answer {
return a;
return Ok(a);
} else {
bail!("no valid answer")
}
} else if answer.len() > 1 {
continue;
bail!("answer too long")
}
let answer_char = answer.chars().collect::<Vec<char>>()[0];
if chars.contains(answer_char) {
return answer_char;
}
if chars.to_ascii_lowercase().contains(answer_char) {
return Ok(answer_char);
}
bail!("no valid answer")
}
/// Returns a tuple of (accepted, denied). Ignored confirmations are not included.
pub fn prompt_confirmation_menu(
pub(crate) fn prompt_confirmation_menu(
confirmations: Vec<Confirmation>,
) -> (Vec<Confirmation>, Vec<Confirmation>) {
println!("press a key other than enter to show the menu.");
) -> anyhow::Result<(Vec<Confirmation>, Vec<Confirmation>)> {
if confirmations.is_empty() {
return Ok((vec![], vec![]));
}
let mut to_accept_idx: HashSet<usize> = HashSet::new();
let mut to_deny_idx: HashSet<usize> = HashSet::new();
let mut screen = AlternateScreen::from(std::io::stdout().into_raw_mode().unwrap());
let stdin = std::io::stdin();
execute!(stdout(), EnterAlternateScreen)?;
crossterm::terminal::enable_raw_mode()?;
let mut selected_idx = 0;
for c in stdin.events() {
match c.expect("could not get events") {
Event::Key(Key::Char('a')) => {
loop {
execute!(
stdout(),
Clear(ClearType::All),
cursor::MoveTo(1, 1),
PrintStyledContent(
"arrow keys to select, [a]ccept, [d]eny, [i]gnore, [enter] confirm choices\n\n"
.white()
),
)?;
for (i, conf) in confirmations.iter().enumerate() {
stdout().queue(Print("\r"))?;
if selected_idx == i {
stdout().queue(SetForegroundColor(Color::Yellow))?;
stdout().queue(Print(" >"))?;
} else {
stdout().queue(SetForegroundColor(Color::White))?;
stdout().queue(Print(" "))?;
}
if to_accept_idx.contains(&i) {
stdout().queue(SetForegroundColor(Color::Green))?;
stdout().queue(Print("[a]"))?;
} else if to_deny_idx.contains(&i) {
stdout().queue(SetForegroundColor(Color::Red))?;
stdout().queue(Print("[d]"))?;
} else {
stdout().queue(Print("[ ]"))?;
}
if selected_idx == i {
stdout().queue(SetForegroundColor(Color::Yellow))?;
}
stdout().queue(Print(format!(" {}\n", conf.description())))?;
}
stdout().flush()?;
match crossterm::event::read()? {
Event::Resize(_, _) => continue,
Event::Key(KeyEvent {
code: KeyCode::Char('a'),
..
}) => {
to_accept_idx.insert(selected_idx);
to_deny_idx.remove(&selected_idx);
}
Event::Key(Key::Char('d')) => {
Event::Key(KeyEvent {
code: KeyCode::Char('d'),
..
}) => {
to_accept_idx.remove(&selected_idx);
to_deny_idx.insert(selected_idx);
}
Event::Key(Key::Char('i')) => {
Event::Key(KeyEvent {
code: KeyCode::Char('i'),
..
}) => {
to_accept_idx.remove(&selected_idx);
to_deny_idx.remove(&selected_idx);
}
Event::Key(Key::Char('A')) => {
Event::Key(KeyEvent {
code: KeyCode::Char('A'),
..
}) => {
(0..confirmations.len()).for_each(|i| {
to_accept_idx.insert(i);
to_deny_idx.remove(&i);
});
}
Event::Key(Key::Char('D')) => {
Event::Key(KeyEvent {
code: KeyCode::Char('D'),
..
}) => {
(0..confirmations.len()).for_each(|i| {
to_accept_idx.remove(&i);
to_deny_idx.insert(i);
});
}
Event::Key(Key::Char('I')) => {
Event::Key(KeyEvent {
code: KeyCode::Char('I'),
..
}) => {
(0..confirmations.len()).for_each(|i| {
to_accept_idx.remove(&i);
to_deny_idx.remove(&i);
});
}
Event::Key(Key::Up) if selected_idx > 0 => {
Event::Key(KeyEvent {
code: KeyCode::Up, ..
}) if selected_idx > 0 => {
selected_idx -= 1;
}
Event::Key(Key::Down) if selected_idx < confirmations.len() - 1 => {
Event::Key(KeyEvent {
code: KeyCode::Down,
..
}) if selected_idx < confirmations.len() - 1 => {
selected_idx += 1;
}
Event::Key(Key::Char('\n')) => {
Event::Key(KeyEvent {
code: KeyCode::Enter,
..
}) => {
break;
}
Event::Key(Key::Esc) | Event::Key(Key::Ctrl('c')) => {
return (vec![], vec![]);
Event::Key(KeyEvent {
code: KeyCode::Esc, ..
})
| Event::Key(KeyEvent {
code: KeyCode::Char('c'),
modifiers: KeyModifiers::CONTROL,
}) => {
return Ok((vec![], vec![]));
}
_ => {}
}
write!(
screen,
"{}{}{}arrow keys to select, [a]ccept, [d]eny, [i]gnore, [enter] confirm choices\n\n",
termion::clear::All,
termion::cursor::Goto(1, 1),
termion::color::Fg(termion::color::White)
)
.unwrap();
for i in 0..confirmations.len() {
if selected_idx == i {
write!(
screen,
"\r{} >",
termion::color::Fg(termion::color::LightYellow)
)
.unwrap();
} else {
write!(screen, "\r{} ", termion::color::Fg(termion::color::White)).unwrap();
}
if to_accept_idx.contains(&i) {
write!(
screen,
"{}[a]",
termion::color::Fg(termion::color::LightGreen)
)
.unwrap();
} else if to_deny_idx.contains(&i) {
write!(
screen,
"{}[d]",
termion::color::Fg(termion::color::LightRed)
)
.unwrap();
} else {
write!(screen, "[ ]").unwrap();
}
execute!(stdout(), LeaveAlternateScreen)?;
crossterm::terminal::disable_raw_mode()?;
if selected_idx == i {
write!(
screen,
"{}",
termion::color::Fg(termion::color::LightYellow)
)
.unwrap();
}
write!(screen, " {}\n", confirmations[i].description()).unwrap();
}
}
return (
return Ok((
to_accept_idx
.iter()
.map(|i| confirmations[*i].clone())
@ -221,14 +238,42 @@ pub fn prompt_confirmation_menu(
.iter()
.map(|i| confirmations[*i].clone())
.collect(),
);
));
}
pub fn pause() {
println!("Press any key to continue...");
let mut stdout = std::io::stdout().into_raw_mode().unwrap();
stdout.flush().unwrap();
std::io::stdin().events().next();
pub(crate) fn pause() {
let _ = write!(stderr(), "Press enter to continue...");
let _ = stderr().flush();
loop {
match crossterm::event::read().expect("could not read terminal events") {
Event::Key(KeyEvent {
code: KeyCode::Enter,
..
}) => break,
_ => continue,
}
}
}
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)]
@ -237,36 +282,33 @@ mod prompt_char_tests {
#[test]
fn test_gives_answer() {
let inputs = ['y', '\n'].iter().collect::<String>();
let answer = prompt_char_impl(&mut inputs.as_bytes(), "ligma balls", "yn");
let answer = prompt_char_impl("y", "yn").unwrap();
assert_eq!(answer, 'y');
}
#[test]
fn test_gives_default() {
let inputs = ['\n'].iter().collect::<String>();
let answer = prompt_char_impl(&mut inputs.as_bytes(), "ligma balls", "Yn");
let answer = prompt_char_impl("", "Yn").unwrap();
assert_eq!(answer, 'y');
}
#[test]
fn test_should_not_give_default() {
let inputs = ['n', '\n'].iter().collect::<String>();
let answer = prompt_char_impl(&mut inputs.as_bytes(), "ligma balls", "Yn");
let answer = prompt_char_impl("n", "Yn").unwrap();
assert_eq!(answer, 'n');
}
#[test]
fn test_should_not_give_invalid() {
let inputs = ['g', '\n', 'n', '\n'].iter().collect::<String>();
let answer = prompt_char_impl(&mut inputs.as_bytes(), "ligma balls", "yn");
let answer = prompt_char_impl("g", "yn");
assert!(answer.is_err());
let answer = prompt_char_impl("n", "yn").unwrap();
assert_eq!(answer, 'n');
}
#[test]
fn test_should_not_give_multichar() {
let inputs = ['y', 'y', '\n', 'n', '\n'].iter().collect::<String>();
let answer = prompt_char_impl(&mut inputs.as_bytes(), "ligma balls", "yn");
assert_eq!(answer, 'n');
let answer = prompt_char_impl("yy", "yn");
assert!(answer.is_err());
}
}

46
src/updater.rs Normal file
View 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)
}
}

View file

@ -1,67 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>12E8E57D-A11A-4FDF-BAEC-AAFDE916E732</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>steamguard_cli</RootNamespace>
<AssemblyName>steamguard-cli</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Content Include=".\makefile">
<Link>makefile</Link>
</Content>
</ItemGroup>
<ItemGroup>
<Compile Include=".\Manifest.cs">
<Link>Manifest.cs</Link>
</Compile>
<Compile Include=".\Program.cs">
<Link>Program.cs</Link>
</Compile>
<Compile Include="AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<Reference Include="Newtonsoft.Json, Version=7.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed">
<HintPath>.\build\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="SteamAuth, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
<HintPath>.\build\SteamAuth.dll</HintPath>
</Reference>
<Reference Include="System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<HintPath>..\..\..\..\..\usr\lib\mono\4.5\System.dll</HintPath>
</Reference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

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