Skip to content

Play your Steam library's Windows games on a jailbroken PS5.

C++

Sign in to Steam with an account name and password

Leonardo Lobato1b2da3cd37a4
diff --git a/README.md b/README.md
index 55ad67a..acbaccb 100644
--- a/README.md
+++ b/README.md
@@ -5,7 +5,7 @@
**Play your Steam library's Windows games on a jailbroken PS5.**
Playden is a launcher that runs on the PS5, adapted from [Playden for macOS](https://github.com/leolobato/playden).
-You sign in to Steam with a QR code, browse your library, download games, and play them. The Windows games run through
+You sign in to Steam with a QR code or your account name and password, browse your library, download games, and play them. The Windows games run through
[prospero-win](https://github.com/mpereiraesaa/prospero-win), a port of Wine to the PS5. Each game gets its own
private Windows environment and its own tile on the PS5 Home screen.
@@ -18,7 +18,9 @@ private Windows environment and its own tile on the PS5 Home screen.
## Features
-- **Steam sign-in with a QR code.** Approve the sign-in in the Steam mobile app. No password typed on the console.
+- **Steam sign-in with a QR code** (approve it in the Steam mobile app), **or with your account name and password.**
+ Steam Guard email codes, Steam Mobile app codes and approval in the app are supported. The sign-in screen opens on
+ the method you used last.
- **Your whole Steam library.** Search, sort, favorites, collections, ratings and notes, with cover art and store
details. The library works offline from a cache.
- **Downloads from Steam.** Queue games and watch progress.
@@ -58,7 +60,8 @@ you sign in:
does not support third-party clients. We know of no account problems from this, but the risk is yours to accept.
- **Your Steam session stays on the console.** Playden stores a Steam sign-in token on the PS5, **without encryption**.
On a jailbroken console, anyone with file access (for example through FTP) can read it. Signing out in Playden
- deletes the token from the console.
+ deletes the token from the console. If you sign in with your password, Playden sends it to Steam encrypted with
+ Steam's key and never saves it; only the token stays.
- **It writes to your Steam Cloud saves.** Playden uploads saves after you play. A bug can overwrite good saves with
older or broken ones. Back up saves you care about. When Playden shows a conflict, read it before you choose.
- **It needs a jailbroken console with root-level helpers.** A running game can get elevated rights on the console.
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 68b401c..b0b4c74 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -13,6 +13,7 @@ These are compiled into Playden's PS5 package (`FAKE77031`) or copied into it.
| ps5-homebrew-ui | fork `0a6fb4b` | GPL-3.0 | [blackbearreloaded/ps5-homebrew-ui](https://github.com/blackbearreloaded/ps5-homebrew-ui), our fork in `third_party/ps5-homebrew-ui` |
| ps5-opengl (`libPS5OpenGL`) | 1.0.0, fork `7234923` | GPL-3.0 | [blackbearreloaded/ps5-opengl](https://github.com/blackbearreloaded/ps5-opengl), our fork in `third_party/ps5-opengl` |
| ps5-native-app-boilerplate (build tools and `libc.prx`) | `f98de73` | GPL-3.0 | [blackbearreloaded/ps5-native-app-boilerplate](https://github.com/blackbearreloaded/ps5-native-app-boilerplate) |
+| ProsperoStore's system keyboard (adapted in `src/platform/ps5/system_keyboard.cpp` and `common_dialog_stub.cpp`) | `f73ec17` | GPL-3.0 | [blackbearreloaded/ProsperoStore](https://github.com/blackbearreloaded/ProsperoStore) |
| ps5-payload-sdk | v0.43 (v0.42 for the root helper) | GPL-3.0 | [ps5-payload-dev/sdk](https://github.com/ps5-payload-dev/sdk) |
| PS5-Lapy-JB-Daemon (root helper, `lapy.elf`) | fork `66ab4f1` | MIT, Copyright (c) 2026 Arksama (Team PHU) | [mpereiraesaa/PS5-Lapy-JB-Daemon](https://github.com/mpereiraesaa/PS5-Lapy-JB-Daemon), our fork in `third_party/PS5-Lapy-JB-Daemon` |
| curl | 8.22.0, with a PS5 non-blocking patch | curl license (MIT-style) | [curl.se](https://curl.se/) |
diff --git a/cmake/HomebrewPS5.cmake b/cmake/HomebrewPS5.cmake
index e52e0d8..7ac0d20 100644
--- a/cmake/HomebrewPS5.cmake
+++ b/cmake/HomebrewPS5.cmake
@@ -58,6 +58,16 @@ function(playden_add_homebrew_ps5_title)
file(COPY_FILE "${gl_sdk}/lib/${name}" "${out}/stubs/${name}" ONLY_IF_DIFFERENT)
list(APPEND link_stubs "${out}/stubs/${name}")
endforeach()
+ # The system keyboard needs sceCommonDialogInitialize, which the SDK has no stub for: a
+ # link-only library named after the system module turns it into an import.
+ set(common_dialog_stub "${out}/stubs/libSceCommonDialog.so")
+ add_custom_command(OUTPUT "${common_dialog_stub}"
+ COMMAND "${CMAKE_CXX_COMPILER}" -O2 -fPIC -fno-exceptions -fno-rtti
+ -c "${CMAKE_SOURCE_DIR}/src/platform/ps5/common_dialog_stub.cpp" -o "${out}/common_dialog_stub.o"
+ COMMAND "${sdk}/bin/prospero-lld" --shared -soname libSceCommonDialog.sprx
+ -o "${common_dialog_stub}" "${out}/common_dialog_stub.o"
+ DEPENDS "${CMAKE_SOURCE_DIR}/src/platform/ps5/common_dialog_stub.cpp" VERBATIM)
+ list(APPEND link_stubs "${common_dialog_stub}")
add_library(playden_ps5_runtime OBJECT
"${boilerplate}/tooling/native/app_crt.cpp"
@@ -76,7 +86,7 @@ function(playden_add_homebrew_ps5_title)
--wrap=openat --wrap=mkdirat)
add_library(playden_ps5_app OBJECT src/homebrew/ps5.cpp src/homebrew/usb_keyboard.cpp src/platform/ps5/title_runtime.cpp
- src/platform/ps5/native_startup.cpp src/platform/ps5/console_services.cpp
+ src/platform/ps5/native_startup.cpp src/platform/ps5/console_services.cpp src/platform/ps5/system_keyboard.cpp
"${PLAYDEN_HUI_SOURCE_DIR}/src/platform/ps5/display_egl.cpp"
"${PLAYDEN_HUI_SOURCE_DIR}/src/platform/ps5/pad.cpp"
"${PLAYDEN_HUI_SOURCE_DIR}/src/platform/ps5/system.cpp")
@@ -151,7 +161,7 @@ function(playden_add_homebrew_ps5_title)
${PLAYDEN_STEAM_LINK_ARCHIVES} ${title_database_archives}
--end-group --as-needed ${link_stubs}
WORKING_DIRECTORY "${out}/link"
- DEPENDS playden_ps5_runtime playden_ps5_shims playden_ps5_app playden_hui playden_homebrew_ui playden_homebrew_model ${title_database_targets}
+ DEPENDS "${common_dialog_stub}" playden_ps5_runtime playden_ps5_shims playden_ps5_app playden_hui playden_homebrew_ui playden_homebrew_model ${title_database_targets}
playden_homebrew_qr playden_homebrew_controller playden_local_session_repository playden_auth_diagnostics
playden_homebrew_artwork_cache playden_homebrew_artwork playden_persistence_controller playden_persistence_service playden_preferences playden_library_controller playden_library_service playden_steam_library playden_steam_cm playden_steam_cm_codec playden_depot_codec
playden_library playden_self_update playden_miniz playden_steam_auth playden_steam_http playden_steam_protocol playden_steam_core playden_diagnostic_log playden_storage playden_native_access playden_managed_directory playden_runtime_steamworks playden_runtime_artifact_hash playden_runtime_settings_storage playden_runtime_private_directories playden_runtime_session_reconciler playden_runtime_launch_service playden_runtime_install_service playden_runtime_installs playden_game_paths
diff --git a/cmake/SteamBackend.cmake b/cmake/SteamBackend.cmake
index 06a28ec..9453b4d 100644
--- a/cmake/SteamBackend.cmake
+++ b/cmake/SteamBackend.cmake
@@ -17,7 +17,8 @@ else()
endif()
add_library(playden_steam_auth STATIC
- "${CMAKE_SOURCE_DIR}/src/steam/backend/auth_client.cpp")
+ "${CMAKE_SOURCE_DIR}/src/steam/backend/auth_client.cpp"
+ "${CMAKE_SOURCE_DIR}/src/steam/backend/password_crypto.cpp")
target_include_directories(playden_steam_auth PUBLIC "${CMAKE_SOURCE_DIR}/src")
target_compile_features(playden_steam_auth PUBLIC cxx_std_17)
target_link_libraries(playden_steam_auth PUBLIC
@@ -229,6 +230,9 @@ function(playden_register_steam_backend_tests)
add_executable(auth_client_test "${CMAKE_SOURCE_DIR}/tests/auth_client_test.cpp")
target_link_libraries(auth_client_test PRIVATE playden_steam_auth)
add_test(NAME auth_client COMMAND auth_client_test)
+ add_executable(password_crypto_test "${CMAKE_SOURCE_DIR}/tests/password_crypto_test.cpp")
+ target_link_libraries(password_crypto_test PRIVATE playden_steam_auth)
+ add_test(NAME password_crypto COMMAND password_crypto_test)
foreach(test_name cm_messages cm_client)
add_executable(${test_name}_test "${CMAKE_SOURCE_DIR}/tests/${test_name}_test.cpp")
diff --git a/fixtures/steam/auth/README.md b/fixtures/steam/auth/README.md
index 656f4fe..df39c6a 100644
--- a/fixtures/steam/auth/README.md
+++ b/fixtures/steam/auth/README.md
@@ -3,3 +3,5 @@
These protobuf frames contain deterministic synthetic values only. They were encoded and decoded by the pinned SwiftProtobuf reference harness described in `../proto/auth_fixture_manifest.json`; the reduced C++ implementation cross-decodes every response and must reproduce every request byte-for-byte.
The `.textproto` files are readable descriptions of the matching `.pb` frames. They are not captured service traffic and contain no real account IDs, request IDs, tokens, QR challenges, guard data, or endpoints.
+
+The credential sign-in frames (`rsa_key_*`, `credentials_*`, `guard_code_request`) were encoded from their `.textproto` files with `protoc --encode` against `../proto/steammessages_auth.steamclient.proto` (protoc 35.1). The same command reproduces `begin_request.pb` byte for byte.
diff --git a/fixtures/steam/auth/credentials_request.pb b/fixtures/steam/auth/credentials_request.pb
new file mode 100644
index 0000000..07cb2d9
Binary files /dev/null and b/fixtures/steam/auth/credentials_request.pb differ
diff --git a/fixtures/steam/auth/credentials_request.textproto b/fixtures/steam/auth/credentials_request.textproto
new file mode 100644
index 0000000..377403f
--- /dev/null
+++ b/fixtures/steam/auth/credentials_request.textproto
@@ -0,0 +1,13 @@
+device_friendly_name: "Playden Synthetic Device"
+account_name: "synthetic_account"
+encrypted_password: "c3ludGhldGlj"
+encryption_timestamp: 1700000000000000
+remember_login: true
+platform_type: k_EAuthTokenPlatformType_SteamClient
+persistence: k_ESessionPersistence_Persistent
+website_id: "Client"
+device_details {
+ device_friendly_name: "Playden Synthetic Device"
+ platform_type: k_EAuthTokenPlatformType_SteamClient
+ os_type: 0
+}
diff --git a/fixtures/steam/auth/credentials_response.pb b/fixtures/steam/auth/credentials_response.pb
new file mode 100644
index 0000000..0c7c2be
--- /dev/null
+++ b/fixtures/steam/auth/credentials_response.pb
@@ -0,0 +1 @@
+�������� 0@P���=""example.invalid(��������2synthetic.weak.tokenBsynthetic extended error
\ No newline at end of file
diff --git a/fixtures/steam/auth/credentials_response.textproto b/fixtures/steam/auth/credentials_response.textproto
new file mode 100644
index 0000000..b7910a3
--- /dev/null
+++ b/fixtures/steam/auth/credentials_response.textproto
@@ -0,0 +1,13 @@
+client_id: 72623859790382856
+request_id: "\020 0@P"
+interval: 0.1
+allowed_confirmations {
+ confirmation_type: k_EAuthSessionGuardType_DeviceConfirmation
+}
+allowed_confirmations {
+ confirmation_type: k_EAuthSessionGuardType_EmailCode
+ associated_message: "example.invalid"
+}
+steamid: 76561197960287930
+weak_token: "synthetic.weak.token"
+extended_error_message: "synthetic extended error"
diff --git a/fixtures/steam/auth/guard_code_request.pb b/fixtures/steam/auth/guard_code_request.pb
new file mode 100644
index 0000000..5bf38b0
Binary files /dev/null and b/fixtures/steam/auth/guard_code_request.pb differ
diff --git a/fixtures/steam/auth/guard_code_request.textproto b/fixtures/steam/auth/guard_code_request.textproto
new file mode 100644
index 0000000..0fe410b
--- /dev/null
+++ b/fixtures/steam/auth/guard_code_request.textproto
@@ -0,0 +1,4 @@
+client_id: 72623859790382856
+steamid: 76561197960287930
+code: "AB12C"
+code_type: k_EAuthSessionGuardType_EmailCode
diff --git a/fixtures/steam/auth/rsa_key_request.pb b/fixtures/steam/auth/rsa_key_request.pb
new file mode 100644
index 0000000..fa9a878
--- /dev/null
+++ b/fixtures/steam/auth/rsa_key_request.pb
@@ -0,0 +1,2 @@
+
+synthetic_account
\ No newline at end of file
diff --git a/fixtures/steam/auth/rsa_key_request.textproto b/fixtures/steam/auth/rsa_key_request.textproto
new file mode 100644
index 0000000..37dedf4
--- /dev/null
+++ b/fixtures/steam/auth/rsa_key_request.textproto
@@ -0,0 +1 @@
+account_name: "synthetic_account"
diff --git a/fixtures/steam/auth/rsa_key_response.pb b/fixtures/steam/auth/rsa_key_response.pb
new file mode 100644
index 0000000..f9e6867
--- /dev/null
+++ b/fixtures/steam/auth/rsa_key_response.pb
@@ -0,0 +1,2 @@
+
+c3a1f0010001�����Ă
\ No newline at end of file
diff --git a/fixtures/steam/auth/rsa_key_response.textproto b/fixtures/steam/auth/rsa_key_response.textproto
new file mode 100644
index 0000000..d33e66f
--- /dev/null
+++ b/fixtures/steam/auth/rsa_key_response.textproto
@@ -0,0 +1,3 @@
+publickey_mod: "c3a1f0"
+publickey_exp: "010001"
+timestamp: 1700000000000000
diff --git a/src/app/preferences.cpp b/src/app/preferences.cpp
index ccad65d..b0d2714 100644
--- a/src/app/preferences.cpp
+++ b/src/app/preferences.cpp
@@ -32,7 +32,8 @@ PreferencesLoadResult PreferencesStore::Load() const {
}
const std::string serialized = ToString(read.value());
- // Version 1 holds only reduce_motion; version 2 adds title_store_suffix; version 3 cloud_saves_auto.
+ // Version 1 holds only reduce_motion; version 2 adds title_store_suffix; version 3 cloud_saves_auto;
+ // version 4 steam_sign_in_password.
for (const int motion : {0, 1}) {
if (serialized == std::string("version=1\nreduce_motion=") + char('0' + motion) + "\n") {
Preferences preferences;
@@ -57,6 +58,19 @@ PreferencesLoadResult PreferencesStore::Load() const {
preferences.cloud_saves_auto = cloud == 1;
return PreferencesLoadResult{preferences, PreferencesLoadStatus::kLoaded, std::string()};
}
+ for (const int suffix : {0, 1})
+ for (const int cloud : {0, 1})
+ for (const int password : {0, 1})
+ if (serialized == std::string("version=4\nreduce_motion=") + char('0' + motion) +
+ "\ntitle_store_suffix=" + char('0' + suffix) + "\ncloud_saves_auto=" + char('0' + cloud) +
+ "\nsteam_sign_in_password=" + char('0' + password) + "\n") {
+ Preferences preferences;
+ preferences.reduce_motion = motion == 1;
+ preferences.title_store_suffix = suffix == 1;
+ preferences.cloud_saves_auto = cloud == 1;
+ preferences.steam_sign_in_password = password == 1;
+ return PreferencesLoadResult{preferences, PreferencesLoadStatus::kLoaded, std::string()};
+ }
}
return PreferencesLoadResult{
Preferences{}, PreferencesLoadStatus::kDefaultCorrupt,
@@ -66,9 +80,10 @@ PreferencesLoadResult PreferencesStore::Load() const {
Result<void> PreferencesStore::Save(const Preferences& preferences) const {
const auto ready=storage_.EnsureRootDirectory();
if(!ready.ok()) return ready;
- const std::string text = std::string("version=3\nreduce_motion=") + (preferences.reduce_motion ? "1" : "0") +
+ const std::string text = std::string("version=4\nreduce_motion=") + (preferences.reduce_motion ? "1" : "0") +
"\ntitle_store_suffix=" + (preferences.title_store_suffix ? "1" : "0") +
- "\ncloud_saves_auto=" + (preferences.cloud_saves_auto ? "1" : "0") + "\n";
+ "\ncloud_saves_auto=" + (preferences.cloud_saves_auto ? "1" : "0") +
+ "\nsteam_sign_in_password=" + (preferences.steam_sign_in_password ? "1" : "0") + "\n";
return storage_.WriteAtomic(kPreferencesPath, Bytes(text.begin(), text.end()));
}
diff --git a/src/app/preferences.h b/src/app/preferences.h
index d91ae36..3d94148 100644
--- a/src/app/preferences.h
+++ b/src/app/preferences.h
@@ -14,6 +14,8 @@ struct Preferences {
// uninstall. Off (the default, so a fresh install never changes Cloud saves unasked) leaves only
// the Sync actions the player chooses.
bool cloud_saves_auto = false;
+ // The sign-in screen opens on the account name and password form: the last sign-in used it.
+ bool steam_sign_in_password = false;
};
enum class PreferencesLoadStatus {
diff --git a/src/diagnostics/redaction.cpp b/src/diagnostics/redaction.cpp
index f968ed9..0b08dcf 100644
--- a/src/diagnostics/redaction.cpp
+++ b/src/diagnostics/redaction.cpp
@@ -11,6 +11,12 @@ const char* AuthMessage(steam::AuthError error) {
case steam::AuthError::kCredentialsRevoked: return "The saved Steam session is no longer valid. Sign in again.";
case steam::AuthError::kPersistence: return "Account storage is unavailable. Retry when storage is available.";
case steam::AuthError::kNoSession: return "Sign in to Steam to connect your library.";
+ case steam::AuthError::kInvalidPassword:
+ return "Steam did not accept the account name or password. Check them and try again.";
+ case steam::AuthError::kRateLimited:
+ return "Steam is limiting sign-in attempts. Wait a while before you try again, or use the QR code.";
+ case steam::AuthError::kSignInRefused: return "Steam did not allow this sign-in. Try the QR code instead.";
+ case steam::AuthError::kSignInTimedOut: return "The sign-in timed out. Try again.";
}
return "Steam sign-in failed.";
}
@@ -19,6 +25,9 @@ std::string AuthRecord(const steam::SteamEvent& event) {
switch (event.kind) {
case steam::SteamEventKind::kChallenge: kind="challenge"; break;
case steam::SteamEventKind::kAwaitingApproval: kind="awaiting-approval"; break;
+ case steam::SteamEventKind::kNeedsEmailCode: kind="needs-email-code"; break;
+ case steam::SteamEventKind::kNeedsAuthenticatorCode: kind="needs-authenticator-code"; break;
+ case steam::SteamEventKind::kCodeRejected: kind="code-rejected"; break;
case steam::SteamEventKind::kAuthenticated: kind="authenticated"; break;
case steam::SteamEventKind::kOfflineSession: kind="offline-session"; break;
case steam::SteamEventKind::kSignedOut: kind="signed-out"; break;
diff --git a/src/homebrew/controller.cpp b/src/homebrew/controller.cpp
index a9adc15..bfe49ba 100644
--- a/src/homebrew/controller.cpp
+++ b/src/homebrew/controller.cpp
@@ -1,6 +1,7 @@
#include "homebrew/controller.hpp"
#include "diagnostics/redaction.h"
#include "steam/install_volumes.h"
+#include "steam/secret.h"
#include <chrono>
namespace playden::homebrew {
@@ -51,32 +52,91 @@ void Controller::Shutdown() {
phase_ = Phase::Idle;
Update(AuthState::SignedOut,{},true);
}
-void Controller::Update(AuthState state,const std::string& error,bool clear,const std::string& challenge) {
+void Controller::Update(AuthState state,const std::string& error,bool clear,const std::string& challenge,
+ SignInStep step,const steam::SteamEvent* prompt) {
AccountUpdate update;
update.authentication = state;
update.id = clear ? std::string{} : model_.state().account.id;
update.display_name = clear ? std::string{} : model_.state().account.display_name;
update.error = error; update.challenge_url = challenge; update.clear_library = clear;
+ update.sign_in = step;
+ if (prompt) {
+ update.email_domain = prompt->email_domain;
+ update.code_allowed = prompt->code_allowed;
+ update.code_is_email = prompt->code_is_email;
+ update.code_rejected = prompt->kind == steam::SteamEventKind::kCodeRejected;
+ }
model_.UpdateAccount(std::move(update));
}
-void Controller::Begin() {
+void Controller::Begin() { Begin(model_.state().sign_in_password); }
+void Controller::Begin(bool password) {
if (retry_saved_session_) {
if (phase_ == Phase::Idle) Restore();
return;
}
- if (phase_ == Phase::SignOut || phase_==Phase::ClearLibrary || phase_==Phase::ClearOrganization) { begin_after_clear_ = true; return; }
+ if (phase_ == Phase::SignOut || phase_==Phase::ClearLibrary || phase_==Phase::ClearOrganization) {
+ begin_after_clear_ = true; begin_password_after_clear_ = password; return;
+ }
if(!model_.state().account.id.empty() && established_auth_==AuthState::Offline) { Restore();return; }
- if(!model_.state().account.id.empty() && established_auth_==AuthState::SignedIn) { SignOut(true);return; }
+ if(!model_.state().account.id.empty() && established_auth_==AuthState::SignedIn) {
+ SignOut(true); begin_password_after_clear_ = password; return;
+ }
if(library_) library_->Reset();
if(persistence_) persistence_->Reset();
phase_ = Phase::SignIn;
+ password_sign_in_ = password;
+ if (password) {
+ // The form waits for the player; nothing runs until Sign in.
+ if (request_) service_->Cancel(request_);
+ request_ = 0;
+ Update(AuthState::Waiting,{},true,{},SignInStep::Password);
+ return;
+ }
request_ = service_->BeginQrSignIn();
Update(AuthState::Waiting,{},true);
}
+void Controller::UseMethod(bool password) {
+ if (phase_ != Phase::SignIn) { Begin(password); return; }
+ password_sign_in_ = password;
+ if (password) {
+ if (request_) service_->Cancel(request_);
+ request_ = 0;
+ Update(AuthState::Waiting,{},!reauthenticating_,{},SignInStep::Password);
+ } else {
+ request_ = service_->BeginQrSignIn();
+ Update(AuthState::Waiting,{},!reauthenticating_);
+ }
+}
+void Controller::BeginPassword() {
+ auto credentials = model_.TakeSignInCredentials();
+ if (!credentials) return;
+ const bool ready = phase_ == Phase::SignIn || (phase_ == Phase::Idle && model_.state().account.id.empty());
+ if (!ready || credentials->account_name.empty() || credentials->password.empty()) {
+ steam::ZeroizeSecret(credentials->password);
+ Update(model_.state().account.authentication == AuthState::Failed ? AuthState::Failed : AuthState::Waiting,
+ {},false,{},SignInStep::Password);
+ return;
+ }
+ if (phase_ == Phase::Idle) {
+ if(library_) library_->Reset();
+ if(persistence_) persistence_->Reset();
+ }
+ phase_ = Phase::SignIn;
+ password_sign_in_ = true;
+ request_ = service_->BeginCredentialSignIn(std::move(credentials->account_name), std::move(credentials->password));
+ steam::ZeroizeSecret(credentials->password);
+ Update(AuthState::Waiting,{},!reauthenticating_,{},SignInStep::Submitting);
+}
void Controller::Reauthenticate() {
if (phase_ != Phase::Idle || model_.state().account.id.empty()) return;
reauthenticating_ = true;
phase_ = Phase::SignIn;
+ password_sign_in_ = model_.state().sign_in_password;
+ if (password_sign_in_) {
+ request_ = 0;
+ Update(AuthState::Waiting,{},false,{},SignInStep::Password);
+ return;
+ }
request_ = service_->BeginQrSignIn();
Update(AuthState::Waiting);
}
@@ -89,6 +149,7 @@ void Controller::SignOut(bool switch_account) {
if(phase_==Phase::ClearLibrary || phase_==Phase::ClearOrganization || phase_==Phase::SignOut) return;
retry_saved_session_ = false;
begin_after_clear_ = switch_account;
+ begin_password_after_clear_ = model_.state().sign_in_password;
request_ = 0;
if(library_) { phase_=Phase::ClearLibrary;library_->Clear(); }
else BeginOrganizationClear();
@@ -127,8 +188,17 @@ void Controller::Tick() {
std::chrono::system_clock::now().time_since_epoch()).count());
for (const auto action : model_.TakeServiceActions()) {
switch (action) {
- case ServiceAction::BeginQr: Begin(); break;
+ case ServiceAction::BeginQr: Begin(false); break;
case ServiceAction::Reauthenticate: Reauthenticate(); break;
+ case ServiceAction::UsePassword: UseMethod(true); break;
+ case ServiceAction::UseQr: UseMethod(false); break;
+ case ServiceAction::BeginPassword: BeginPassword(); break;
+ case ServiceAction::SubmitCode:
+ if (auto code = model_.TakeGuardCode()) {
+ if (phase_ == Phase::SignIn && password_sign_in_ && request_) service_->SubmitGuardCode(std::move(*code));
+ steam::ZeroizeSecret(*code);
+ }
+ break;
case ServiceAction::CancelQr:
// Stop automatic retries while preserving the need to restore the
// saved account when the user chooses Connect again.
@@ -140,6 +210,14 @@ void Controller::Tick() {
Restore();
break;
}
+ if (phase_ == Phase::SignIn && !request_) {
+ // The password form, with nothing sent to Steam yet.
+ phase_ = Phase::Idle;
+ if(library_) library_->Reset();
+ if(persistence_) persistence_->Reset();
+ Update(AuthState::Cancelled,{},!retry_saved_session_);
+ break;
+ }
if (phase_ == Phase::SignIn || phase_ == Phase::Restore) {
service_->Cancel(request_);
if(library_) library_->Reset();
@@ -1227,9 +1305,22 @@ void Controller::Apply(const steam::SteamEvent& event) {
if (phase_ == Phase::SignIn) Update(AuthState::Waiting,{},false,event.challenge_url);
break;
case steam::SteamEventKind::kAwaitingApproval:
- break; // The preceding challenge remains on screen; do not erase it.
+ // QR: the preceding challenge remains on screen; do not erase it.
+ if (phase_ == Phase::SignIn && password_sign_in_) Update(AuthState::Waiting,{},false,{},SignInStep::Approval,&event);
+ break;
+ case steam::SteamEventKind::kNeedsEmailCode:
+ case steam::SteamEventKind::kNeedsAuthenticatorCode:
+ case steam::SteamEventKind::kCodeRejected:
+ if (phase_ == Phase::SignIn && password_sign_in_)
+ Update(AuthState::Waiting,{},false,{},
+ event.kind == steam::SteamEventKind::kNeedsEmailCode ||
+ (event.kind == steam::SteamEventKind::kCodeRejected && event.code_is_email)
+ ? SignInStep::EmailCode : SignInStep::AuthenticatorCode,
+ &event);
+ break;
case steam::SteamEventKind::kOfflineSession:
case steam::SteamEventKind::kAuthenticated: {
+ const bool signed_in = phase_ == Phase::SignIn && event.kind == steam::SteamEventKind::kAuthenticated;
phase_ = Phase::Idle;
retry_saved_session_ = false;
reauthenticating_ = false;
@@ -1240,6 +1331,7 @@ void Controller::Apply(const steam::SteamEvent& event) {
update.id = std::to_string(event.steam_id); update.display_name = event.account_name;
update.clear_library = model_.state().account.id!=update.id;
if(!library_) update.error = "Library sync is unavailable. Try again later.";
+ if (signed_in) update.signed_in_with_password = password_sign_in_;
model_.UpdateAccount(std::move(update));
if(persistence_) persistence_->Activate(event.steam_id);
if(runtime_) runtime_->SetSteamAccount(event.account_name, event.steam_id);
@@ -1254,7 +1346,7 @@ void Controller::Apply(const steam::SteamEvent& event) {
if(runtime_) runtime_->SetSteamAccount({}, 0);
const bool begin = begin_after_clear_; begin_after_clear_ = false;
Update(AuthState::SignedOut,{},true);
- if (begin) Begin();
+ if (begin) Begin(begin_password_after_clear_);
break;
}
case steam::SteamEventKind::kCanceled:
@@ -1262,6 +1354,12 @@ void Controller::Apply(const steam::SteamEvent& event) {
if (reauthenticating_) { reauthenticating_ = false; Restore(); break; }
Update(AuthState::Cancelled,{},!retry_saved_session_); break;
case steam::SteamEventKind::kFailure: {
+ if (reauthenticating_ && phase_ == Phase::SignIn && password_sign_in_ && event.error != steam::AuthError::kCanceled) {
+ // A refused password (or code) is worth showing: the form stays, and Cancel returns to the saved sign-in.
+ request_ = 0;
+ Update(AuthState::Failed,diagnostics::AuthMessage(event.error),false,{},SignInStep::Password);
+ break;
+ }
if (reauthenticating_ && phase_ == Phase::SignIn) {
// The new QR sign-in failed or expired: keep using the saved one.
reauthenticating_ = false;
@@ -1271,6 +1369,7 @@ void Controller::Apply(const steam::SteamEvent& event) {
}
const bool restoring = phase_ == Phase::Restore;
const bool clearing = phase_ == Phase::SignOut;
+ const bool password = phase_ == Phase::SignIn && password_sign_in_;
phase_ = Phase::Idle; begin_after_clear_ = false;
if (restoring && event.error == steam::AuthError::kPersistence) {
// A busy/private storage probe is not a revoked Steam credential. Keep
@@ -1293,7 +1392,8 @@ void Controller::Apply(const steam::SteamEvent& event) {
}
else if (event.error == steam::AuthError::kCanceled) Update(AuthState::Cancelled,{},true);
else if (event.error == steam::AuthError::kExpired) Update(AuthState::Expired,diagnostics::AuthMessage(event.error),true);
- else Update(AuthState::Failed,diagnostics::AuthMessage(event.error),true);
+ else Update(AuthState::Failed,diagnostics::AuthMessage(event.error),true,{},
+ password ? SignInStep::Password : SignInStep::Qr);
break;
}
}
diff --git a/src/homebrew/controller.hpp b/src/homebrew/controller.hpp
index 5b15241..279c44c 100644
--- a/src/homebrew/controller.hpp
+++ b/src/homebrew/controller.hpp
@@ -41,7 +41,12 @@ class Controller {
Controller& operator=(const Controller&) = delete;
private:
enum class Phase { Idle, Restore, SignIn, ClearLibrary, ClearOrganization, SignOut };
+ // A new sign-in in the given method; without one, in the method the last sign-in used.
void Begin();
+ void Begin(bool password);
+ // The sign-in screen's method changed: a QR sign-in starts, or the password form waits for input.
+ void UseMethod(bool password);
+ void BeginPassword();
void SignOut(bool switch_account);
void Reauthenticate();
void Restore();
@@ -50,7 +55,8 @@ class Controller {
void AdvanceOrganizationClear();
void Apply(const steam::SteamEvent& event);
void Update(AuthState state, const std::string& error = {}, bool clear = false,
- const std::string& challenge = {});
+ const std::string& challenge = {}, SignInStep step = SignInStep::Qr,
+ const steam::SteamEvent* prompt = nullptr);
void TickAppDetails();
void TickStoreDetails();
steam::StoreDetailsService* store_details_ = nullptr;
@@ -207,6 +213,9 @@ class Controller {
// A QR sign-in for an account that is already signed in: its library and organization stay, and
// a cancel or failure goes back to the saved sign-in.
bool reauthenticating_ = false;
+ // The current sign-in uses the account name and password (the form, or its request).
+ bool password_sign_in_ = false;
+ bool begin_password_after_clear_ = false;
std::array<std::int64_t, 9> tick_us_{};
};
}
diff --git a/src/homebrew/ps5.cpp b/src/homebrew/ps5.cpp
index e3b2f27..3938a39 100644
--- a/src/homebrew/ps5.cpp
+++ b/src/homebrew/ps5.cpp
@@ -15,6 +15,7 @@
#include "homebrew/title_icon.hpp"
#include "platform/ps5/title_allow_list.h"
#include "platform/ps5/console_services.h"
+#include "platform/ps5/system_keyboard.h"
#include "runtime/artifact_hash.h"
#include "runtime/kit_admission.h"
#include "runtime/kit_trust.h"
@@ -172,6 +173,7 @@ std::vector<playden::steam::InstallRequest> take_install_requests(bool runtime_r
int main() {
// Before the title's /data grant: a title whose credentials changed may fail to load system modules.
const int keyboard_module = sceSysmoduleLoadModule(kKeyboardModule);
+ const int system_keyboard_module = playden::ps5::SystemKeyboard::Preload();
const auto native_access = playden::ps5::PrepareNativeStartup(PLAYDEN_PS5_TITLE_ID);
hui::ps5::Display display;
if (display.width() <= 0 && !display.open(3840, 2160)) {
@@ -503,8 +505,17 @@ int main() {
int keyboard_user = -1;
sceUserServiceGetInitialUser(&keyboard_user);
playden::app::AppendLogLine(log_root, "launch.log", "keyboard preload status=" + std::to_string(keyboard_module));
+ char system_keyboard_line[64];
+ std::snprintf(system_keyboard_line, sizeof(system_keyboard_line), "system keyboard preload status=0x%08x",
+ unsigned(system_keyboard_module));
+ playden::app::AppendLogLine(log_root, "launch.log", system_keyboard_line);
UsbKeyboard keyboard;
playden::homebrew::KeyboardInput keyboard_input;
+ // Text fields open the system keyboard, so Remote Play's keyboard can type into them;
+ // Playden's own keyboard stays for a field the system keyboard refused.
+ playden::ps5::SystemKeyboard system_keyboard;
+ std::uint64_t offered_editor = 0;
+ simulation.SetSystemKeyboardAvailable(system_keyboard_module == 0);
hui::InputTracker tracker;
std::array<hui::PadSample, 64> samples{};
bool presented = false;
@@ -519,12 +530,50 @@ int main() {
simulation.SetControllerConnected(input.connected);
was_connected = input.connected;
}
- dispatch(simulation, input);
- // A USB keyboard types into the open text box and also moves around Playden.
+ const auto& editor = simulation.state().editor;
+ // The frame the dialog closes in carries the press that closed it (Done, Enter, Escape): it
+ // does not reach Playden, or it would also press the row under the field.
+ bool dialog_closed = false;
+ if (system_keyboard.active()) {
+ // The field went away (a sign-in finished, for example): so does the dialog.
+ if (!editor.active || editor.serial != offered_editor) system_keyboard.Close();
+ const auto state = system_keyboard.Poll();
+ dialog_closed = state != playden::ps5::SystemKeyboard::State::kOpen;
+ if (dialog_closed) simulation.SetSystemKeyboardOpen(false);
+ if (state == playden::ps5::SystemKeyboard::State::kAccepted) {
+ simulation.SubmitEditorText(system_keyboard.Take());
+ // A value the field refused (a duplicate name, say) leaves it open: offer it again.
+ if (simulation.state().editor.active) {
+ offered_editor = 0;
+ simulation.SetSystemKeyboardOpen(true);
+ }
+ }
+ else if (state == playden::ps5::SystemKeyboard::State::kCancelled && editor.active) simulation.action("circle");
+ if (state != playden::ps5::SystemKeyboard::State::kOpen)
+ playden::app::AppendLogLine(log_root, "launch.log", "system keyboard closed state=" + std::to_string(static_cast<int>(state)));
+ } else if (editor.active && editor.serial != offered_editor && !input.is_held(hui::Action::confirm) &&
+ !input.is_held(hui::Action::menu)) {
+ offered_editor = editor.serial;
+ std::string refused;
+ const bool opened = system_keyboard.Open(editor.purpose, editor.value, editor.secret, &refused);
+ simulation.SetSystemKeyboardOpen(opened);
+ playden::app::AppendLogLine(log_root, "launch.log", (opened ? std::string("system keyboard open") : "system keyboard refused") +
+ (refused.empty() ? std::string() : " " + refused));
+ }
keyboard.open(keyboard_user, now, log_root);
- for (const auto& command : keyboard_input.Update(keyboard.read(), simulation.state().editor.active, now)) {
- if (!command.text.empty()) simulation.text(command.text);
- else simulation.action(command.action);
+ // A field waiting for the button that opened it to come up already belongs to the system keyboard.
+ const bool awaiting_dialog = editor.active && editor.system_keyboard && editor.serial != offered_editor;
+ if (system_keyboard.active() || awaiting_dialog || dialog_closed) {
+ // The dialog owns input; keys typed meanwhile go to it, not to Playden. The USB keyboard's
+ // state is still followed, so a key held across the close is not read as a new press.
+ keyboard_input.Follow(keyboard.read());
+ } else {
+ dispatch(simulation, input);
+ // A USB keyboard types into the open text box and also moves around Playden.
+ for (const auto& command : keyboard_input.Update(keyboard.read(), simulation.state().editor.active, now)) {
+ if (!command.text.empty()) simulation.text(command.text);
+ else simulation.action(command.action);
+ }
}
simulation.controller_sample(playden::homebrew::diagnostic_sample(input));
const auto dispatched = hui::sys::monotonic_us();
diff --git a/src/homebrew/simulation.cpp b/src/homebrew/simulation.cpp
index 9c54e77..23906f4 100644
--- a/src/homebrew/simulation.cpp
+++ b/src/homebrew/simulation.cpp
@@ -12,6 +12,7 @@
#include "homebrew/storage_sim.hpp"
#include "steam/install_volumes.h"
#include "steam/backend/json.h"
+#include "steam/secret.h"
#include <cstring>
#include <algorithm>
@@ -678,6 +679,25 @@ bool Simulation::live_notices_visible() const noexcept {
state_.navigation.route != Route::Startup && state_.navigation.route != Route::SignIn;
}
+std::string mask_secret(std::string_view value) {
+ std::string masked;
+ for (const char c : value)
+ if ((static_cast<unsigned char>(c) & 0xC0) != 0x80) masked += "\u2022";
+ return masked;
+}
+
+std::optional<SignInCredentials> Simulation::TakeSignInCredentials() {
+ auto credentials = std::move(pending_credentials_);
+ pending_credentials_.reset();
+ return credentials;
+}
+
+std::optional<std::string> Simulation::TakeGuardCode() {
+ auto code = std::move(pending_guard_code_);
+ pending_guard_code_.reset();
+ return code;
+}
+
std::vector<ServiceAction> Simulation::TakeServiceActions() {
auto actions = std::move(pending_service_actions_);
pending_service_actions_.clear();
@@ -1501,10 +1521,51 @@ void Simulation::UpdateAccount(AccountUpdate update) {
state_.account.challenge_expiry = 0;
state_.library_syncing = update.authentication == AuthState::Syncing;
+ if (update.signed_in_with_password && *update.signed_in_with_password != state_.sign_in_password) {
+ state_.sign_in_password = *update.signed_in_with_password;
+ save_profile();
+ }
if (update.authentication == AuthState::Waiting || update.authentication == AuthState::Expired || update.authentication == AuthState::Failed) {
state_.navigation.route = Route::SignIn;
- state_.navigation.focus_key = update.authentication == AuthState::Expired ? "qr-refresh"
- : update.authentication == AuthState::Failed ? "qr-retry" : "qr-cancel";
+ auto& form = state_.sign_in;
+ if (update.sign_in == SignInStep::Qr) {
+ if (form.step != SignInStep::Qr) clear_sign_in_secrets();
+ form.step = SignInStep::Qr;
+ form.error.clear();
+ set_route_focus(update.authentication == AuthState::Expired ? "qr-refresh"
+ : update.authentication == AuthState::Failed ? "qr-retry" : "qr-cancel");
+ } else if (update.authentication != AuthState::Waiting) {
+ // A failed password sign-in returns to the form, with the reason and the account name kept.
+ clear_sign_in_secrets();
+ form.step = SignInStep::Password;
+ form.code_entry = false;
+ form.error = state_.account.error;
+ state_.account.error.clear();
+ set_route_focus(form.account_name.empty() ? "signin-account" : "signin-password");
+ } else {
+ // A code typed instead of approving was wrong: approval in the app still works, so say both.
+ const bool approval = update.code_rejected && form.step == SignInStep::Approval && form.code_entry;
+ form.step = approval ? SignInStep::Approval : update.sign_in;
+ form.error.clear();
+ if (form.step == SignInStep::Password) {
+ const auto& focus = state_.editor.active ? state_.editor.opener_focus_key : state_.navigation.focus_key;
+ if (focus.rfind("signin-", 0) != 0 || focus == "signin-cancel")
+ set_route_focus(form.account_name.empty() ? "signin-account" : "signin-password");
+ } else if (form.step == SignInStep::Submitting) {
+ set_route_focus("signin-cancel");
+ } else {
+ steam::ZeroizeSecret(form.code);
+ form.email_domain = update.email_domain;
+ form.code_allowed = update.code_allowed;
+ form.code_is_email = update.code_is_email;
+ form.code_allowed = form.code_allowed || approval;
+ form.code_entry = approval;
+ form.code_sent = false;
+ form.code_rejected = update.code_rejected;
+ set_route_focus(form.step == SignInStep::Approval && !form.code_entry
+ ? (form.code_allowed ? "guard-use-code" : "guard-cancel") : "guard-code");
+ }
+ }
} else if (update.authentication == AuthState::SignedIn || update.authentication == AuthState::Offline) {
if (state_.navigation.route == Route::Startup || state_.navigation.route == Route::SignIn) state_.navigation.route = Route::Home;
state_.navigation.focus_key = state_.games.empty() ? "home-library" : game_key(state_.games.front().id);
@@ -1515,6 +1576,12 @@ void Simulation::UpdateAccount(AccountUpdate update) {
state_.navigation.route = Route::Startup;
state_.navigation.focus_key = "startup-loading";
}
+ if (state_.navigation.route != Route::SignIn) {
+ // Leaving the sign-in screen: a sign-in field still open closes, and nothing secret stays.
+ if (state_.editor.active && state_.editor.opener_focus_key.rfind("signin-", 0) == 0) state_.editor.active = false;
+ if (state_.editor.active && state_.editor.opener_focus_key.rfind("guard-", 0) == 0) state_.editor.active = false;
+ clear_sign_in_secrets();
+ }
rebuild_view();
}
@@ -1716,7 +1783,7 @@ playden::OrganizationSnapshot Simulation::ExportOrganization() const {
}
playden::Preferences Simulation::ExportPreferences() const {
- return {state_.reduced_motion, state_.title_store_suffix, state_.cloud_saves_auto};
+ return {state_.reduced_motion, state_.title_store_suffix, state_.cloud_saves_auto, state_.sign_in_password};
}
void Simulation::apply_organization_snapshot(const playden::OrganizationSnapshot& snapshot) {
@@ -1940,6 +2007,7 @@ bool Simulation::ApplyPreferences(PersistenceLoadToken token,
state_.reduced_motion = loaded.preferences.reduce_motion;
state_.title_store_suffix = loaded.preferences.title_store_suffix;
state_.cloud_saves_auto = loaded.preferences.cloud_saves_auto;
+ state_.sign_in_password = loaded.preferences.steam_sign_in_password;
captured_preferences_ = loaded.preferences;
preferences_saved_revision_ = preferences_revision_;
}
@@ -2015,7 +2083,8 @@ bool Simulation::record_live_persistence() {
const bool preferences_changed = force_preferences_reset_ ||
(after_preferences.reduce_motion != captured_preferences_.reduce_motion ||
after_preferences.title_store_suffix != captured_preferences_.title_store_suffix ||
- after_preferences.cloud_saves_auto != captured_preferences_.cloud_saves_auto);
+ after_preferences.cloud_saves_auto != captured_preferences_.cloud_saves_auto ||
+ after_preferences.steam_sign_in_password != captured_preferences_.steam_sign_in_password);
if (organization_changed && !snapshot_within_model_bounds(after_organization)) {
apply_organization_snapshot(captured_organization_);
@@ -2036,6 +2105,7 @@ bool Simulation::record_live_persistence() {
state_.reduced_motion = captured_preferences_.reduce_motion;
state_.title_store_suffix = captured_preferences_.title_store_suffix;
state_.cloud_saves_auto = captured_preferences_.cloud_saves_auto;
+ state_.sign_in_password = captured_preferences_.steam_sign_in_password;
organization_journal_full_ = true;
force_organization_reset_ = false;
force_organization_selection_ = false;
@@ -2519,6 +2589,9 @@ bool Simulation::scenario(const std::string& name) {
} else if (name == "qr-approved") {
if (state_.account.authentication != AuthState::Cancelled && challenge_generation_ != cancelled_challenge_generation_) {
if (state_.account.id.empty()) { state_.account.id = "fixture-connected"; state_.account.display_name = "Connected fixture account"; }
+ if (state_.sign_in.step != SignInStep::Qr) state_.sign_in_password = true;
+ clear_sign_in_secrets();
+ state_.sign_in.step = SignInStep::Qr;
state_.account.authentication = AuthState::Syncing;
state_.navigation.route = Route::SignIn;
state_.navigation.focus_key = "sync-status";
@@ -2667,7 +2740,8 @@ void Simulation::rebuild_view() {
if (!rebuilding_overlay_ && uninstall_batch_ && !installed_list_open()) uninstall_batch_.reset();
const bool has_overlay = state_.editor.active || !state_.navigation.modals.empty();
if (has_overlay) {
- const auto editor = state_.editor;
+ // Only the flag is set aside: a copy of the editor would keep a password in memory.
+ const bool editor_active = state_.editor.active;
const auto modals = state_.navigation.modals;
const auto focus = state_.navigation.focus_key;
const int selected_index = state_.navigation.selected_index;
@@ -2682,7 +2756,7 @@ void Simulation::rebuild_view() {
rebuild_view();
rebuilding_overlay_ = false;
route_view_ = view_;
- state_.editor = editor;
+ state_.editor.active = editor_active;
state_.navigation.modals = modals;
state_.navigation.focus_key = focus;
state_.navigation.selected_index = selected_index;
@@ -2703,7 +2777,7 @@ void Simulation::rebuild_view() {
if (state_.editor.active) {
view_.title = state_.editor.purpose;
- view_.subtitle = state_.editor.value;
+ view_.subtitle = state_.editor.secret && !state_.editor.revealed ? mask_secret(state_.editor.value) : state_.editor.value;
if (state_.editor.purpose == "Search") view_.subtitle += " · " + std::to_string(visible_games().size()) + " results";
row("keyboard-done", RowKind::Action, "Done", "editor-done");
row("keyboard-cancel", RowKind::Action, "Cancel", "editor-cancel");
@@ -3305,6 +3379,42 @@ void Simulation::rebuild_view() {
row("startup-connect", RowKind::Action, "Connect Steam", "connect");
row("startup-skip", RowKind::Action, "Skip for now", "skip");
}
+ } else if (state_.navigation.route == Route::SignIn && state_.sign_in.step != SignInStep::Qr &&
+ state_.account.authentication != AuthState::Syncing) {
+ view_.title = "Connect Steam";
+ const auto& form = state_.sign_in;
+ const bool code_step = form.step == SignInStep::EmailCode || form.step == SignInStep::AuthenticatorCode ||
+ (form.step == SignInStep::Approval && form.code_entry);
+ if (form.step == SignInStep::Password) {
+ view_.subtitle = form.error.empty() ? "Sign in with your Steam account name and password." : form.error;
+ row("signin-account", RowKind::Action, "Account name", "signin-account").value = form.account_name;
+ row("signin-password", RowKind::Action, "Password", "signin-password").value = mask_secret(form.password);
+ row("signin-submit", RowKind::Action, "Sign in", "signin-submit").enabled =
+ !form.account_name.empty() && !form.password.empty();
+ row("signin-qr-mode", RowKind::Action, "Use QR code instead", "signin-qr-mode");
+ } else if (form.step == SignInStep::Submitting) {
+ view_.subtitle = "Signing in to Steam…";
+ row("signin-cancel", RowKind::Action, "Cancel", "signin-cancel");
+ } else if (code_step) {
+ const bool email = form.step == SignInStep::EmailCode || (form.step == SignInStep::Approval && form.code_is_email);
+ const std::string prompt = !email ? "Enter the code from the Steam Mobile app."
+ : form.email_domain.empty() ? "Enter the code Steam sent to your email."
+ : "Enter the code sent to …@" + form.email_domain + ".";
+ view_.subtitle = form.code_sent ? "Checking the code…" : form.code_rejected ? "That code was not right. " + prompt : prompt;
+ if (form.step == SignInStep::Approval && !form.code_sent)
+ view_.subtitle += " You can also approve the sign-in in the Steam Mobile app.";
+ row("guard-code", RowKind::Action, "Code", "guard-code").value = form.code;
+ row("guard-submit", RowKind::Action, "Submit", "guard-submit").enabled = form.code.size() == 5 && !form.code_sent;
+ row("guard-cancel", RowKind::Action, "Cancel", "guard-cancel");
+ } else {
+ view_.subtitle = !form.email_domain.empty() && !form.code_allowed
+ ? "Approve the sign-in from the email Steam sent to …@" + form.email_domain + "."
+ : "Approve the sign-in in the Steam Mobile app.";
+ if (form.code_allowed) row("guard-use-code", RowKind::Action, "Type a code instead", "guard-use-code");
+ row("guard-cancel", RowKind::Action, "Cancel", "guard-cancel");
+ }
+ if (!live() && (form.step == SignInStep::Approval || form.step == SignInStep::Submitting))
+ row("qr-fixture-controls", RowKind::Action, "QR fixture controls", "qr-fixture-controls");
} else if (state_.navigation.route == Route::SignIn) {
view_.title = "Connect Steam";
view_.subtitle = state_.account.authentication == AuthState::Waiting
@@ -3317,6 +3427,8 @@ void Simulation::rebuild_view() {
else if (state_.account.authentication == AuthState::Expired) row("qr-refresh", RowKind::Action, "Refresh code", "qr-refresh");
else if (state_.account.authentication == AuthState::Failed) row("qr-retry", RowKind::Action, "Retry", "qr-retry");
else row("qr-cancel", RowKind::Action, "Cancel", "qr-cancel");
+ if (state_.account.authentication != AuthState::Syncing)
+ row("signin-password-mode", RowKind::Action, "Sign in with account name and password", "signin-password-mode");
if (!live() && state_.account.authentication != AuthState::Syncing) row("qr-fixture-controls", RowKind::Action, "QR fixture controls", "qr-fixture-controls");
} else if (state_.navigation.route == Route::Home) {
view_.title = "Home";
@@ -4005,12 +4117,15 @@ std::string Simulation::next_job_id() {
}
}
-void Simulation::start_editor(std::string purpose, std::string value) {
+void Simulation::start_editor(std::string purpose, std::string value, bool secret) {
const auto opener = state_.navigation.focus_key;
editing_setting_id_.clear();
editing_append_ = false;
state_.editor = {};
state_.editor.active = true;
+ state_.editor.secret = secret;
+ state_.editor.serial = ++editor_serial_;
+ state_.editor.system_keyboard = system_keyboard_available_;
state_.editor.purpose = std::move(purpose);
state_.editor.value = value;
state_.editor.original = std::move(value);
@@ -4019,7 +4134,168 @@ void Simulation::start_editor(std::string purpose, std::string value) {
state_.navigation.focus_key = "keyboard-done";
}
+void Simulation::set_route_focus(std::string key) {
+ if (state_.editor.active) state_.editor.opener_focus_key = std::move(key);
+ else state_.navigation.focus_key = std::move(key);
+}
+
+void Simulation::clear_sign_in_secrets() {
+ steam::ZeroizeSecret(state_.sign_in.password);
+ steam::ZeroizeSecret(state_.sign_in.code);
+ if (state_.editor.secret) {
+ steam::ZeroizeSecret(state_.editor.value);
+ steam::ZeroizeSecret(state_.editor.original);
+ state_.editor.caret = 0;
+ }
+}
+
+void Simulation::normalize_editor() {
+ if (state_.editor.purpose != "Steam Guard code") return;
+ std::string code;
+ for (const char c : state_.editor.value) {
+ if (std::isalnum(static_cast<unsigned char>(c)) && code.size() < 5)
+ code += static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
+ }
+ state_.editor.value = std::move(code);
+ state_.editor.caret = std::min(state_.editor.caret, state_.editor.value.size());
+}
+
+void Simulation::open_sign_in(bool reauthenticate) {
+ const bool password = state_.sign_in_password;
+ clear_sign_in_secrets();
+ const auto name = state_.sign_in.account_name;
+ state_.sign_in = {};
+ state_.sign_in.account_name = name;
+ state_.sign_in.step = password ? SignInStep::Password : SignInStep::Qr;
+ state_.account.authentication = AuthState::Waiting;
+ state_.account.challenge_url.clear();
+ state_.account.error.clear();
+ state_.navigation.route = Route::SignIn;
+ state_.navigation.focus_key = password ? (name.empty() ? "signin-account" : "signin-password") : "qr-cancel";
+ if (live()) queue_service_action(reauthenticate ? ServiceAction::Reauthenticate
+ : password ? ServiceAction::UsePassword : ServiceAction::BeginQr);
+ else if (!password) scenario("qr-waiting");
+}
+
+bool Simulation::sign_in_action(const std::string& action_name) {
+ auto& form = state_.sign_in;
+ if (action_name == "signin-password-mode" || action_name == "signin-qr-mode") {
+ const bool password = action_name == "signin-password-mode";
+ clear_sign_in_secrets();
+ const auto name = form.account_name;
+ form = {};
+ form.account_name = name;
+ form.step = password ? SignInStep::Password : SignInStep::Qr;
+ state_.account.authentication = AuthState::Waiting;
+ state_.account.challenge_url.clear();
+ state_.account.error.clear();
+ state_.navigation.focus_key = password ? (name.empty() ? "signin-account" : "signin-password") : "qr-cancel";
+ if (live()) queue_service_action(password ? ServiceAction::UsePassword : ServiceAction::UseQr);
+ else if (!password) scenario("qr-waiting");
+ } else if (action_name == "signin-account") {
+ start_editor("Account name", form.account_name);
+ } else if (action_name == "signin-password") {
+ start_editor("Password", form.password, true);
+ } else if (action_name == "signin-submit") {
+ if (form.step != SignInStep::Password || form.account_name.empty() || form.password.empty()) return true;
+ form.error.clear();
+ if (!live()) { submit_fixture_sign_in(); return true; }
+ if (pending_credentials_) steam::ZeroizeSecret(pending_credentials_->password);
+ pending_credentials_ = SignInCredentials{form.account_name, form.password};
+ steam::ZeroizeSecret(form.password);
+ form.step = SignInStep::Submitting;
+ state_.account.authentication = AuthState::Waiting;
+ state_.account.error.clear();
+ state_.navigation.focus_key = "signin-cancel";
+ queue_service_action(ServiceAction::BeginPassword);
+ } else if (action_name == "guard-code") {
+ start_editor("Steam Guard code", form.code);
+ } else if (action_name == "guard-use-code") {
+ form.code_entry = true;
+ steam::ZeroizeSecret(form.code);
+ state_.navigation.focus_key = "guard-code";
+ } else if (action_name == "guard-submit") {
+ if (form.code.size() != 5 || form.code_sent) return true;
+ form.code_rejected = false;
+ if (!live()) { submit_fixture_sign_in(); return true; }
+ if (pending_guard_code_) steam::ZeroizeSecret(*pending_guard_code_);
+ pending_guard_code_ = form.code;
+ form.code_sent = true;
+ state_.navigation.focus_key = "guard-cancel";
+ queue_service_action(ServiceAction::SubmitCode);
+ } else if (action_name == "signin-cancel" || action_name == "guard-cancel") {
+ cancel();
+ } else {
+ return false;
+ }
+ return true;
+}
+
+// Fixture mode scripts Steam's answers by account name: "wrong" (password refused), "limited" (rate
+// limit), "email" and "mobile" (a code; 00000 is refused), "approve" (approval in the app, or a code);
+// any other name signs in.
+void Simulation::submit_fixture_sign_in() {
+ auto& form = state_.sign_in;
+ auto succeed = [this] {
+ clear_sign_in_secrets();
+ state_.sign_in_password = true;
+ scenario("qr-approved");
+ };
+ if (form.step == SignInStep::Password) {
+ const auto& name = form.account_name;
+ if (name == "wrong" || name == "limited") {
+ clear_sign_in_secrets();
+ state_.account.authentication = AuthState::Failed;
+ form.error = name == "wrong" ? "Steam did not accept the account name or password. Check them and try again."
+ : "Steam is limiting sign-in attempts. Wait a while before you try again, or use the QR code.";
+ state_.navigation.focus_key = "signin-password";
+ } else if (name == "email" || name == "mobile" || name == "approve") {
+ steam::ZeroizeSecret(form.password);
+ form.step = name == "email" ? SignInStep::EmailCode : name == "mobile" ? SignInStep::AuthenticatorCode : SignInStep::Approval;
+ form.email_domain = name == "email" ? "example.invalid" : "";
+ form.code_allowed = true;
+ form.code_is_email = name == "email";
+ state_.navigation.focus_key = form.step == SignInStep::Approval ? "guard-use-code" : "guard-code";
+ } else {
+ succeed();
+ }
+ return;
+ }
+ if (form.code == "00000") {
+ steam::ZeroizeSecret(form.code);
+ form.code_rejected = true;
+ if (form.step == SignInStep::Approval) form.step = form.code_is_email ? SignInStep::EmailCode : SignInStep::AuthenticatorCode;
+ form.code_entry = false;
+ state_.navigation.focus_key = "guard-code";
+ return;
+ }
+ succeed();
+}
+
void Simulation::commit_editor() {
+ if (state_.navigation.route == Route::SignIn &&
+ (state_.editor.purpose == "Account name" || state_.editor.purpose == "Password" ||
+ state_.editor.purpose == "Steam Guard code")) {
+ auto& form = state_.sign_in;
+ std::string next;
+ if (state_.editor.purpose == "Account name") {
+ form.account_name = trimmed(state_.editor.value);
+ next = form.account_name.empty() ? "signin-account" : "signin-password";
+ } else if (state_.editor.purpose == "Password") {
+ steam::ZeroizeSecret(form.password);
+ form.password = state_.editor.value;
+ next = form.password.empty() ? "signin-password" : form.account_name.empty() ? "signin-account" : "signin-submit";
+ } else {
+ form.code = state_.editor.value;
+ next = form.code.size() == 5 ? "guard-submit" : "guard-code";
+ }
+ if (state_.editor.secret) { steam::ZeroizeSecret(state_.editor.value); steam::ZeroizeSecret(state_.editor.original); }
+ state_.editor.active = false;
+ state_.editor.secret = false;
+ state_.editor.revealed = false;
+ state_.navigation.focus_key = next;
+ return;
+ }
if (state_.editor.purpose == "Search") { state_.library.query = state_.editor.value; reconcile_library_selection(state_); }
else if (!editing_setting_id_.empty()) {
if (!can_change_game_settings()) return;
@@ -4102,7 +4378,13 @@ void Simulation::cancel() {
state_.navigation.settings_rail_focused = false;
return;
}
- if (state_.editor.active) { state_.editor.active = false; state_.navigation.focus_key = state_.editor.opener_focus_key; return; }
+ if (state_.editor.active) {
+ if (state_.editor.secret) { steam::ZeroizeSecret(state_.editor.value); steam::ZeroizeSecret(state_.editor.original); }
+ state_.editor.active = false;
+ state_.editor.revealed = false;
+ state_.navigation.focus_key = state_.editor.opener_focus_key;
+ return;
+ }
// An applied search is undone before Circle leaves the Library.
if (state_.navigation.route == Route::Library && state_.navigation.modals.empty() && !state_.library.query.empty()) {
state_.library.query.clear();
@@ -4124,6 +4406,12 @@ void Simulation::cancel() {
}
if (state_.navigation.route == Route::SignIn) {
if (live()) queue_service_action(ServiceAction::CancelQr);
+ clear_sign_in_secrets();
+ if (pending_credentials_) steam::ZeroizeSecret(pending_credentials_->password);
+ pending_credentials_.reset();
+ if (pending_guard_code_) steam::ZeroizeSecret(*pending_guard_code_);
+ pending_guard_code_.reset();
+ state_.sign_in.error.clear();
cancelled_challenge_generation_ = challenge_generation_;
state_.account.authentication = AuthState::Cancelled;
state_.navigation.route = Route::Startup;
@@ -4149,7 +4437,8 @@ int route_tab(Route route) {
void Simulation::move(int delta_x, int delta_y) {
if (state_.editor.active) {
state_.editor.focus_row = std::clamp(state_.editor.focus_row + delta_y, 0, 4);
- const int max_key = state_.editor.focus_row == 4 ? (state_.editor.symbols ? 3 : 4) : 9;
+ // A password's bottom row has a Show key between space and backspace.
+ const int max_key = state_.editor.focus_row == 4 ? (state_.editor.symbols ? 3 : 4) + (state_.editor.secret ? 1 : 0) : 9;
state_.editor.focus_key = std::clamp(state_.editor.focus_key + delta_x, 0, max_key);
return;
}
@@ -4270,6 +4559,8 @@ bool Simulation::move_settings(int delta_x, int delta_y) {
void Simulation::change_route(int delta) {
if (state_.editor.active || !state_.navigation.modals.empty()) return;
+ // The password form and its Steam Guard steps are left with Cancel, which stops the sign-in and wipes them.
+ if (state_.navigation.route == Route::SignIn && state_.sign_in.step != SignInStep::Qr) return;
constexpr Route routes[] = {Route::Home, Route::Library, Route::Downloads, Route::Saves, Route::Settings};
constexpr int count = static_cast<int>(std::size(routes));
auto found = std::find(std::begin(routes), std::end(routes), state_.navigation.route);
@@ -4485,12 +4776,15 @@ void Simulation::activate() {
}
state_.editor.value.insert(state_.editor.caret, 1, inserted); ++state_.editor.caret;
if (state_.editor.shifted) state_.editor.shifted = false;
+ normalize_editor();
} else if ((!state_.editor.symbols && state_.editor.focus_key == 0)) state_.editor.shifted = !state_.editor.shifted;
else {
const int offset = state_.editor.symbols ? 0 : 1;
- const int special = state_.editor.focus_key - offset;
+ int special = state_.editor.focus_key - offset;
+ if (state_.editor.secret && special == 2) { state_.editor.revealed = !state_.editor.revealed; return; }
+ if (state_.editor.secret && special > 2) --special;
if (special == 0) state_.editor.symbols = !state_.editor.symbols;
- else if (special == 1) { state_.editor.value.insert(state_.editor.caret, " "); ++state_.editor.caret; }
+ else if (special == 1) { state_.editor.value.insert(state_.editor.caret, " "); ++state_.editor.caret; normalize_editor(); }
else if (special == 2 && state_.editor.caret > 0) {
const auto prior = previous_caret(state_.editor.value, state_.editor.caret);
state_.editor.value.erase(prior, state_.editor.caret - prior); state_.editor.caret = prior;
@@ -4564,7 +4858,10 @@ void Simulation::activate() {
action_name.rfind("override-remove-", 0) == 0 || action_name == "value-reset" ||
action_name == "unlock-setting" || action_name == "reset-settings";
if (edits_settings && !can_change_game_settings()) return;
- if (action_name == "connect" || action_name == "qr-retry" || action_name == "qr-refresh") {
+ if (sign_in_action(action_name)) return;
+ if (action_name == "connect") open_sign_in();
+ else if (action_name == "qr-retry" || action_name == "qr-refresh") {
+ state_.sign_in.step = SignInStep::Qr;
if (live()) {
queue_service_action(ServiceAction::BeginQr);
state_.account.authentication = AuthState::Waiting;
@@ -5613,12 +5910,11 @@ void Simulation::activate() {
}
else if (action_name == "account-recover") {
state_.navigation.modals.clear();
- if (live()) { queue_service_action(ServiceAction::BeginQr); state_.account.authentication = AuthState::Waiting; state_.account.challenge_url.clear(); state_.account.error.clear(); state_.navigation.route = Route::SignIn; state_.navigation.focus_key = "qr-cancel"; }
- else scenario("qr-waiting");
+ open_sign_in();
}
else if (action_name == "account-reauth") {
state_.navigation.modals.clear();
- if (live()) { queue_service_action(ServiceAction::Reauthenticate); state_.account.authentication = AuthState::Waiting; state_.account.challenge_url.clear(); state_.account.error.clear(); state_.navigation.route = Route::SignIn; state_.navigation.focus_key = "qr-cancel"; }
+ if (live()) open_sign_in(true);
}
else if (action_name == "account-switch") { pending_destructive_action_ = "account-switch"; open_modal({"confirmation", "Switch account? Current account cache will be cleared.", state_.navigation.focus_key, {"cancel", "confirm-destructive"}, 0, true}); }
}
@@ -5641,7 +5937,9 @@ bool Simulation::action(const std::string& logical_action) {
else if (logical_action == "r2") state_.controller.r2 = 1.0F;
else if (logical_action == "options") state_.controller.options = true;
if (live()) {
- if (logical_action == "connect" || logical_action == "qr-retry" || logical_action == "qr-refresh") {
+ if (logical_action == "connect") { open_sign_in(); rebuild_view(); return true; }
+ if (logical_action == "qr-retry" || logical_action == "qr-refresh") {
+ state_.sign_in.step = SignInStep::Qr;
queue_service_action(ServiceAction::BeginQr);
state_.account.authentication = AuthState::Waiting;
state_.account.challenge_url.clear(); state_.account.error.clear();
@@ -5777,6 +6075,7 @@ bool Simulation::action(const std::string& logical_action) {
else if (route == "settings") state_.navigation.route = Route::Settings;
else if (route == "saves") state_.navigation.route = Route::Saves;
else { last_error_ = "Unknown route: " + route; return false; }
+ clear_sign_in_secrets();
state_.navigation.modals.clear(); state_.editor.active = false; state_.navigation.focus_key.clear(); rebuild_view(); return true;
}
if (logical_action.rfind("select:", 0) == 0 || logical_action.rfind("details:", 0) == 0) {
@@ -5828,15 +6127,16 @@ bool Simulation::action(const std::string& logical_action) {
if (state_.editor.active && state_.editor.caret > 0) { const auto prior = previous_caret(state_.editor.value, state_.editor.caret); state_.editor.value.erase(prior, state_.editor.caret - prior); state_.editor.caret = prior; }
rebuild_view(); return true;
}
- if (logical_action == "clear") { if (state_.editor.active) { state_.editor.value.clear(); state_.editor.caret = 0; } rebuild_view(); return true; }
- if (logical_action == "space") { if (state_.editor.active) { state_.editor.value.insert(state_.editor.caret, " "); ++state_.editor.caret; } rebuild_view(); return true; }
+ if (logical_action == "clear") { if (state_.editor.active) { steam::ZeroizeSecret(state_.editor.value); state_.editor.caret = 0; } rebuild_view(); return true; }
+ if (logical_action == "space") { if (state_.editor.active) { state_.editor.value.insert(state_.editor.caret, " "); ++state_.editor.caret; normalize_editor(); } rebuild_view(); return true; }
+ if (logical_action == "reveal") { if (state_.editor.active && state_.editor.secret) state_.editor.revealed = !state_.editor.revealed; rebuild_view(); return true; }
if (logical_action == "shift") { if (state_.editor.active) state_.editor.shifted = !state_.editor.shifted; rebuild_view(); return true; }
if (logical_action == "symbols") { if (state_.editor.active) state_.editor.symbols = !state_.editor.symbols; rebuild_view(); return true; }
if (logical_action == "caret-left") { if (state_.editor.active) state_.editor.caret = previous_caret(state_.editor.value, state_.editor.caret); rebuild_view(); return true; }
if (logical_action == "caret-right") { if (state_.editor.active) state_.editor.caret = next_caret(state_.editor.value, state_.editor.caret); rebuild_view(); return true; }
if (state_.editor.active && logical_action == "l1") { state_.editor.caret = previous_caret(state_.editor.value, state_.editor.caret); rebuild_view(); return true; }
if (state_.editor.active && logical_action == "r1") { state_.editor.caret = next_caret(state_.editor.value, state_.editor.caret); rebuild_view(); return true; }
- if (state_.editor.active && logical_action == "triangle") { state_.editor.value.clear(); state_.editor.caret = 0; rebuild_view(); return true; }
+ if (state_.editor.active && logical_action == "triangle") { steam::ZeroizeSecret(state_.editor.value); state_.editor.caret = 0; rebuild_view(); return true; }
// Options presses Done, so a game controller or a USB keyboard's Options key can finish the text without moving to Done.
if (state_.editor.active && logical_action == "options") { commit_editor(); rebuild_view(); return true; }
if (state_.editor.active && (logical_action == "l2" || logical_action == "r2" || logical_action == "search")) return true;
@@ -6046,9 +6346,21 @@ void Simulation::text(const std::string& utf8) {
if (!state_.editor.active) return;
state_.editor.value.insert(state_.editor.caret, utf8);
state_.editor.caret += utf8.size();
+ normalize_editor();
rebuild_view();
}
+void Simulation::SubmitEditorText(std::string utf8) {
+ if (state_.editor.active) {
+ if (state_.editor.secret) steam::ZeroizeSecret(state_.editor.value);
+ state_.editor.value = utf8;
+ state_.editor.caret = state_.editor.value.size();
+ normalize_editor();
+ action("done");
+ }
+ steam::ZeroizeSecret(utf8);
+}
+
void Simulation::controller_sample(ControllerState sample) {
state_.controller = sample;
}
@@ -6142,7 +6454,8 @@ std::string Simulation::snapshot() const {
<< "\",\"context\":\"" << json::escape(state_.log_context) << "\",\"count\":" << state_.log_lines.size()
<< ",\"offset\":" << state_.log_offset << "}"
<< ",\"editor\":{\"active\":" << (state_.editor.active ? "true" : "false") << ",\"value\":\""
- << json::escape(state_.editor.value) << "\",\"original\":\"" << json::escape(state_.editor.original)
+ << (state_.editor.secret ? std::string("<redacted>") : json::escape(state_.editor.value)) << "\",\"original\":\""
+ << (state_.editor.secret ? std::string("<redacted>") : json::escape(state_.editor.original))
<< "\",\"caret\":" << state_.editor.caret << "},\"scroll_offsets\":{";
bool first = true;
for (const auto& [key, value] : state_.navigation.scroll_offsets) {
diff --git a/src/homebrew/simulation.hpp b/src/homebrew/simulation.hpp
index 825ffca..1405cf8 100644
--- a/src/homebrew/simulation.hpp
+++ b/src/homebrew/simulation.hpp
@@ -23,7 +23,10 @@ using GameId = playden::GameId;
enum class Route { Startup, SignIn, Home, Library, Downloads, Settings, Details, Session, Saves, SaveDetails };
enum class ModelMode { Simulation, Live };
-enum class ServiceAction { BeginQr, CancelQr, SignOut, SwitchAccount, RefreshLibrary, Reauthenticate };
+// UsePassword/UseQr switch the sign-in screen's method; BeginPassword and SubmitCode carry the form's
+// secrets, which the controller takes with TakeSignInCredentials and TakeGuardCode.
+enum class ServiceAction { BeginQr, CancelQr, SignOut, SwitchAccount, RefreshLibrary, Reauthenticate,
+ UsePassword, UseQr, BeginPassword, SubmitCode };
enum class AuthState { SignedOut, Restoring, Waiting, Expired, Failed, Cancelled, Syncing, SigningOut, SignedIn, Offline };
enum class JobState { Queued, Downloading, Pausing, Paused, Verifying, Downloaded, Failed, Cancelled, Interrupted };
enum class JobStage { Download, Verify, Install, Uninstall };
@@ -206,6 +209,28 @@ struct CloudRequest {
enum class Compatibility { Untested, Works, Playable, Broken };
enum class RowKind { Heading, Action, Toggle, Choice, Text, Game, Job, Volume, Profile, Status, Separator };
+// The sign-in screen: the QR code, or the account name and password form and its Steam Guard steps.
+enum class SignInStep { Qr, Password, Submitting, Approval, EmailCode, AuthenticatorCode };
+struct SignInForm {
+ SignInStep step = SignInStep::Qr;
+ std::string account_name;
+ std::string password; // never saved, shown or snapshotted; cleared after submit, cancel or leaving
+ std::string code; // the Steam Guard code being typed
+ std::string email_domain; // where Steam sent the email code or approval
+ bool code_allowed = false; // Approval: a typed code works too
+ bool code_is_email = false; // the code Steam takes is the emailed one
+ bool code_entry = false; // Approval: the player chose to type a code
+ bool code_rejected = false; // the last code was wrong
+ bool code_sent = false; // waiting for Steam to check the code
+ std::string error; // why the last password sign-in failed
+};
+// A password as the screen shows it: one dot per character.
+std::string mask_secret(std::string_view value);
+struct SignInCredentials {
+ std::string account_name;
+ std::string password;
+};
+
struct Account {
std::string id;
std::string display_name;
@@ -224,6 +249,14 @@ struct AccountUpdate {
std::string challenge_url;
std::string error;
bool clear_library = false;
+ // Waiting and Failed: the sign-in screen's step and its Steam Guard prompt.
+ SignInStep sign_in = SignInStep::Qr;
+ std::string email_domain;
+ bool code_allowed = false;
+ bool code_is_email = false;
+ bool code_rejected = false;
+ // Authenticated by a sign-in (not a restore): whether it used the password, remembered for next time.
+ std::optional<bool> signed_in_with_password;
};
struct LibraryUpdate {
@@ -380,6 +413,10 @@ struct EditorState {
std::size_t caret = 0;
bool shifted = false;
bool symbols = false;
+ bool secret = false; // a password: shown as dots, never snapshotted
+ bool revealed = false; // the keyboard's Show key; reset each time the editor opens
+ std::uint64_t serial = 0; // tells each opened editor apart (the PS5 offers each one to its system keyboard)
+ bool system_keyboard = false; // the PS5's keyboard is (about to be) open for it: Playden's own is not drawn
int focus_row = 0;
int focus_key = 0;
};
@@ -430,6 +467,8 @@ struct State {
std::map<GameId, std::uint64_t> save_sizes; // live: Windows user folders of games without Steam Cloud
Navigation navigation;
EditorState editor;
+ SignInForm sign_in;
+ bool sign_in_password = false; // preference: the last sign-in used the account name and password
std::vector<Notice> notices;
// Per-game settings: preset and player overrides (see runtime/game_settings.h).
std::map<GameId, playden::runtime::GameSettingsRecord> game_settings;
@@ -530,6 +569,12 @@ public:
bool action(const std::string& logical_action);
void controller_sample(ControllerState sample);
void text(const std::string& utf8);
+ // The PS5 system keyboard's accepted text replaces the open editor's value and commits it, as Done does.
+ void SubmitEditorText(std::string utf8);
+ void SetSystemKeyboardOpen(bool open) { state_.editor.system_keyboard = open && state_.editor.active; }
+ // The PS5 offers every field to its system keyboard: fields open with Playden's keyboard hidden
+ // until that one is refused (SetSystemKeyboardOpen(false)).
+ void SetSystemKeyboardAvailable(bool available) { system_keyboard_available_ = available; }
void tick(int ticks = 1);
void SetControllerConnected(bool connected);
void SetWallClock(std::int64_t unix_seconds);
@@ -614,6 +659,9 @@ public:
void PreferencesSaveResult(std::uint64_t revision, playden::StorageError error);
bool TakePersistenceRetryRequest();
[[nodiscard]] std::vector<ServiceAction> TakeServiceActions();
+ // The password sign-in's secrets, handed over once; the form keeps no copy of the password.
+ [[nodiscard]] std::optional<SignInCredentials> TakeSignInCredentials();
+ [[nodiscard]] std::optional<std::string> TakeGuardCode();
// Presets and recipes for the Game settings sheet (runtime/presets.json, runtime/recipes/).
void SetSettingsData(std::vector<playden::runtime::SettingsPreset> presets,
std::vector<playden::runtime::GameRecipe> recipes);
@@ -695,6 +743,10 @@ private:
std::uint64_t next_collection_serial_ = 1;
std::uint64_t next_job_serial_ = 1;
std::vector<ServiceAction> pending_service_actions_;
+ std::optional<SignInCredentials> pending_credentials_;
+ std::optional<std::string> pending_guard_code_;
+ std::uint64_t editor_serial_ = 0;
+ bool system_keyboard_available_ = false;
std::vector<InstallRequest> pending_install_requests_;
std::vector<GameId> pending_runtime_prepare_requests_;
std::vector<GameId> pending_runtime_play_requests_;
@@ -806,7 +858,15 @@ private:
void change_route(int delta);
void open_modal(ModalEntry modal);
void close_modal();
- void start_editor(std::string purpose, std::string value);
+ void start_editor(std::string purpose, std::string value, bool secret = false);
+ // Sign-in screen: opened in the remembered method, its actions, and the form's secrets wiped.
+ void open_sign_in(bool reauthenticate = false);
+ bool sign_in_action(const std::string& action_name);
+ void submit_fixture_sign_in();
+ void clear_sign_in_secrets();
+ void set_route_focus(std::string key);
+ // Steam Guard codes: five characters, uppercase.
+ void normalize_editor();
void commit_editor();
void advance_jobs();
[[nodiscard]] std::vector<std::string> game_settings_actions() const;
diff --git a/src/homebrew/usb_keyboard.cpp b/src/homebrew/usb_keyboard.cpp
index 045b501..49c0939 100644
--- a/src/homebrew/usb_keyboard.cpp
+++ b/src/homebrew/usb_keyboard.cpp
@@ -130,4 +130,9 @@ std::vector<KeyboardCommand> KeyboardInput::Update(const KeyboardReport& report,
return commands;
}
+void KeyboardInput::Follow(const KeyboardReport& report) {
+ held_ = report.connected ? report.keys : std::vector<std::uint16_t>{};
+ repeating_ = 0;
+}
+
} // namespace playden::homebrew
diff --git a/src/homebrew/usb_keyboard.hpp b/src/homebrew/usb_keyboard.hpp
index 407ec8c..c1459fa 100644
--- a/src/homebrew/usb_keyboard.hpp
+++ b/src/homebrew/usb_keyboard.hpp
@@ -35,6 +35,9 @@ struct KeyboardCommand {
class KeyboardInput {
public:
std::vector<KeyboardCommand> Update(const KeyboardReport& report, bool editing, std::uint64_t now_us);
+ // Another owner (the system keyboard) reads the keys: remember which are down, so none of them
+ // reads as a new press afterwards, and stop any repeat.
+ void Follow(const KeyboardReport& report);
private:
std::vector<std::uint16_t> held_;
diff --git a/src/homebrew/view.cpp b/src/homebrew/view.cpp
index 94edb74..839462a 100644
--- a/src/homebrew/view.cpp
+++ b/src/homebrew/view.cpp
@@ -1192,6 +1192,42 @@ class Render::Impl
20.0F, kBackground.with_alpha(0.78F), gfx::Align::center);
}
+ // Beside the account name and password form: what the current step waits for, and what Playden keeps.
+ void draw_password_panel(const State &state)
+ {
+ const SignInForm &form = state.sign_in;
+ const gfx::Rect panel{1036.0F, 224.0F, 640.0F, 430.0F};
+ scene_.rounded_rect(panel, 14.0F, kPanel);
+ const char *title = "Account name and password";
+ const char *detail = "Playden sends your password to Steam, encrypted, and keeps only Steam's sign-in token. "
+ "It never saves your password.";
+ if (form.step == SignInStep::Submitting)
+ {
+ title = "Signing in";
+ detail = "Waiting for Steam to check your account name and password.";
+ }
+ else if (form.step == SignInStep::Approval && !form.code_entry)
+ {
+ title = "Check your phone";
+ detail = form.code_allowed ? "Approve the sign-in in the Steam Mobile app, or type its code instead."
+ : "Approve the sign-in when Steam asks you to.";
+ }
+ else if (form.step != SignInStep::Password)
+ {
+ title = "Steam Guard";
+ detail = "Steam asks for a code to confirm that it is you. Codes have five letters or digits.";
+ }
+ ui::text(scene_, fonts_.display, title, panel.x + 48.0F, panel.y + 96.0F, 40.0F, kText);
+ ui::paragraph(scene_, fonts_.regular, detail, panel.x + 48.0F, panel.y + 156.0F, 25.0F,
+ panel.w - 96.0F, 36.0F, kSecondary, 6);
+ if (state.simulation_mode)
+ {
+ scene_.rounded_rect({1185.0F, 678.0F, 292.0F, 42.0F}, 21.0F, kAmber.with_alpha(0.18F));
+ ui::text(scene_, fonts_.semibold, "SIMULATED SIGN-IN", 1331.0F, 706.0F, 18.0F, kAmber,
+ gfx::Align::center);
+ }
+ }
+
void draw_sign_in(ui::Canvas &, const ViewData &view, const State &state)
{
section_label("Connect Steam", 96.0F, 78.0F);
@@ -1200,6 +1236,11 @@ class Render::Impl
constexpr float qr_x = 1116.0F;
constexpr float qr_y = 224.0F;
constexpr int qr_side = 430;
+ if (state.sign_in.step != SignInStep::Qr && state.account.authentication != AuthState::Syncing)
+ {
+ draw_password_panel(state);
+ return;
+ }
if (state.simulation_mode && state.account.challenge_url.empty()) {
draw_simulated_qr(qr_x, qr_y, static_cast<float>(qr_side));
} else if (state.account.authentication == AuthState::Waiting &&
@@ -2918,7 +2959,9 @@ class Render::Impl
ui::Canvas overlay{overlay_, fonts_, renderer_.glass_texture(), clock_};
if (state.editor.active)
{
- draw_editor_overlay(overlay, state);
+ // The PS5's own keyboard is on screen instead.
+ if (!state.editor.system_keyboard)
+ draw_editor_overlay(overlay, state);
return;
}
if (!state.navigation.modals.empty())
@@ -2957,6 +3000,29 @@ class Render::Impl
}
}
+ // A password's keyboard: the bottom row gains a Show (or Hide) key between space and backspace,
+ // where the simulation expects it.
+ static std::vector<ui::KeyboardLayout> secret_layouts(bool revealed)
+ {
+ const auto key = [](ui::KeyKind kind, int span) {
+ ui::KeyboardKey result;
+ result.kind = kind;
+ result.span = span;
+ if (kind == ui::KeyKind::space)
+ result.text = " ";
+ return result;
+ };
+ ui::KeyboardKey show;
+ show.label = revealed ? "Hide" : "Show";
+ ui::KeyboardLayout letters = ui::KeyboardLayout::letters();
+ letters.rows.back() = {key(ui::KeyKind::shift, 2), key(ui::KeyKind::layout, 1), key(ui::KeyKind::space, 2), show,
+ key(ui::KeyKind::backspace, 2), key(ui::KeyKind::done, 2)};
+ ui::KeyboardLayout symbols = ui::KeyboardLayout::symbols();
+ symbols.rows.back() = {key(ui::KeyKind::layout, 2), key(ui::KeyKind::space, 3), show,
+ key(ui::KeyKind::backspace, 2), key(ui::KeyKind::done, 2)};
+ return {letters, symbols};
+ }
+
void draw_editor_overlay(ui::Canvas &canvas, const State &state)
{
overlay_.rounded_rect({0.0F, 0.0F, kWidth, kHeight}, 0.0F, gfx::Color::rgb(0x000000, 0.68F));
@@ -2966,16 +3032,25 @@ class Render::Impl
476.0F, 188.0F, 46.0F, kText);
ui::Painter painter(overlay_, fonts_, theme_, renderer_.glass_texture());
const gfx::Rect field{476.0F, 232.0F, 968.0F, 76.0F};
- painter.field(field, state.editor.value, false,
+ const bool masked = state.editor.secret && !state.editor.revealed;
+ const std::string shown = masked ? mask_secret(state.editor.value) : state.editor.value;
+ painter.field(field, shown, false,
{0.0F, 0.0F, false});
const std::size_t caret = std::min(state.editor.caret, state.editor.value.size());
+ const std::string_view typed = std::string_view(state.editor.value).substr(0, caret);
const float caret_x = field.x + 22.0F +
- fonts_.regular.measure(std::string_view(state.editor.value).substr(0, caret),
- 24.0F);
+ (masked ? fonts_.regular.measure(mask_secret(typed), 24.0F) : fonts_.regular.measure(typed, 24.0F));
overlay_.rounded_rect({std::min(caret_x, field.x + field.w - 24.0F), field.y + 18.0F,
2.0F, field.h - 36.0F},
1.0F, kAccent);
keyboard_.style.reduced_motion = state.reduced_motion;
+ const int layouts = !state.editor.secret ? 0 : state.editor.revealed ? 2 : 1;
+ if (layouts != keyboard_layouts_)
+ {
+ keyboard_layouts_ = layouts;
+ keyboard_.set_layouts(layouts == 0 ? std::vector<ui::KeyboardLayout>{ui::KeyboardLayout::letters(), ui::KeyboardLayout::symbols()}
+ : secret_layouts(layouts == 2));
+ }
keyboard_.set_length(static_cast<int>(state.editor.value.size()));
keyboard_.set_shift(state.editor.shifted ? ui::KeyboardShift::lock : ui::KeyboardShift::off);
keyboard_.set_layout(state.editor.symbols ? 1 : 0);
@@ -3769,6 +3844,7 @@ class Render::Impl
ui::GridView grid_;
ui::ListView list_;
ui::Keyboard keyboard_;
+ int keyboard_layouts_ = 0; // 0 the default layouts, 1 a password's (Show), 2 a revealed password's (Hide)
std::array<std::uint32_t, 8> art_{};
std::uint32_t hero_ = 0;
std::string cached_qr_url_;
diff --git a/src/platform/ps5/common_dialog_stub.cpp b/src/platform/ps5/common_dialog_stub.cpp
new file mode 100644
index 0000000..bf52b9f
--- /dev/null
+++ b/src/platform/ps5/common_dialog_stub.cpp
@@ -0,0 +1,8 @@
+// common_dialog_stub.cpp - Link-only import of libSceCommonDialog for the system keyboard.
+// From ps5-native-app-boilerplate's system-keyboard example (BlackBearReloaded, GPL-3.0-or-later).
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+// The payload SDK has no stub for this module. Linked as a shared library named
+// libSceCommonDialog.sprx, this symbol becomes a system import; the body is never
+// linked into or shipped with Playden.
+extern "C" int sceCommonDialogInitialize() { return 0; }
diff --git a/src/platform/ps5/system_keyboard.cpp b/src/platform/ps5/system_keyboard.cpp
new file mode 100644
index 0000000..344af5c
--- /dev/null
+++ b/src/platform/ps5/system_keyboard.cpp
@@ -0,0 +1,238 @@
+// system_keyboard.cpp - The PS5's own keyboard (the IME dialog) for Playden's text fields.
+// Adapted from ProsperoStore's platform/ps5/ime (BlackBearReloaded, GPL-3.0-or-later).
+// Copyright (c) 2026 Playden contributors
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "platform/ps5/system_keyboard.h"
+
+#include <cstddef>
+#include <cstdio>
+#include <span>
+#include <string>
+#include <time.h>
+
+namespace {
+struct ImeParam {
+ std::int32_t user_id, type;
+ std::uint64_t supported_languages;
+ std::int32_t enter_label, input_method;
+ void* filter;
+ std::uint32_t option, max_text_length;
+ std::uint16_t* input_text_buffer;
+ float pos_x, pos_y;
+ std::int32_t horizontal_alignment, vertical_alignment;
+ const std::uint16_t *placeholder, *title;
+ std::int8_t reserved[16];
+};
+struct ImeResult {
+ std::int32_t outcome; // 0 accepted, 1 cancelled, 2 aborted
+ std::int8_t reserved[12];
+};
+static_assert(sizeof(ImeParam) == 96);
+static_assert(offsetof(ImeParam, input_text_buffer) == 40);
+static_assert(offsetof(ImeParam, title) == 72);
+static_assert(sizeof(ImeResult) == 16);
+
+constexpr std::uint16_t kImeDialogModule = 0x0096;
+constexpr std::uint32_t kOptionPassword = 0x4;
+constexpr std::uint32_t kAlreadyInitialized = 0x80b80002u;
+} // namespace
+
+// The payload SDK has no libSceCommonDialog stub: the build links a link-only one (cmake/HomebrewPS5.cmake).
+extern "C" {
+int sceCommonDialogInitialize();
+int sceImeDialogAbort();
+int sceImeDialogGetResult(ImeResult* result);
+int sceImeDialogGetStatus();
+int sceImeDialogInit(const ImeParam* param, const void* extended);
+int sceImeDialogTerm();
+int sceSysmoduleLoadModule(std::uint16_t id);
+int sceUserServiceGetForegroundUser(std::int32_t* user_id);
+}
+
+namespace playden::ps5 {
+namespace {
+std::int64_t MonotonicUs() {
+ timespec now{};
+ clock_gettime(CLOCK_MONOTONIC, &now);
+ return static_cast<std::int64_t>(now.tv_sec) * 1000000 + now.tv_nsec / 1000;
+}
+
+// UTF-8 into a zero-terminated UTF-16 buffer, cut at a whole character when it does not fit.
+void ToUtf16(std::string_view source, std::span<std::uint16_t> out) {
+ std::size_t written = 0, index = 0;
+ while (index < source.size() && written + 1 < out.size()) {
+ const auto lead = static_cast<unsigned char>(source[index]);
+ const unsigned length = lead < 0x80 ? 1 : (lead >> 5) == 6 ? 2 : (lead >> 4) == 14 ? 3 : (lead >> 3) == 30 ? 4 : 0;
+ std::uint32_t point = 0xfffd;
+ if (length == 0 || index + length > source.size()) {
+ ++index;
+ } else {
+ point = length == 1 ? lead : lead & (0x7f >> length);
+ for (unsigned i = 1; i < length; ++i) point = (point << 6) | (static_cast<unsigned char>(source[index + i]) & 0x3f);
+ index += length;
+ }
+ if (point >= 0x10000) {
+ if (written + 2 >= out.size()) break;
+ point -= 0x10000;
+ out[written++] = static_cast<std::uint16_t>(0xd800 | (point >> 10));
+ out[written++] = static_cast<std::uint16_t>(0xdc00 | (point & 0x3ff));
+ } else {
+ out[written++] = static_cast<std::uint16_t>(point);
+ }
+ }
+ out[written] = 0;
+}
+
+std::string ToUtf8(std::span<const std::uint16_t> source) {
+ std::string out;
+ for (std::size_t i = 0; i < source.size() && source[i] != 0; ++i) {
+ std::uint32_t point = source[i];
+ if (point >= 0xd800 && point <= 0xdbff && i + 1 < source.size() && source[i + 1] >= 0xdc00 &&
+ source[i + 1] <= 0xdfff)
+ point = 0x10000 + ((point - 0xd800) << 10) + (source[++i] - 0xdc00);
+ else if (point >= 0xd800 && point <= 0xdfff)
+ point = 0xfffd;
+ if (point < 0x80) {
+ out.push_back(static_cast<char>(point));
+ } else if (point < 0x800) {
+ out.push_back(static_cast<char>(0xc0 | (point >> 6)));
+ out.push_back(static_cast<char>(0x80 | (point & 0x3f)));
+ } else if (point < 0x10000) {
+ out.push_back(static_cast<char>(0xe0 | (point >> 12)));
+ out.push_back(static_cast<char>(0x80 | ((point >> 6) & 0x3f)));
+ out.push_back(static_cast<char>(0x80 | (point & 0x3f)));
+ } else {
+ out.push_back(static_cast<char>(0xf0 | (point >> 18)));
+ out.push_back(static_cast<char>(0x80 | ((point >> 12) & 0x3f)));
+ out.push_back(static_cast<char>(0x80 | ((point >> 6) & 0x3f)));
+ out.push_back(static_cast<char>(0x80 | (point & 0x3f)));
+ }
+ }
+ return out;
+}
+
+// Set by Preload: the dialog is initialized and its module loaded.
+bool g_loaded = false;
+int g_preload_result = 0;
+
+std::string Refused(const char* step, int result) {
+ char text[64];
+ std::snprintf(text, sizeof(text), "%s=0x%08x", step, static_cast<unsigned>(result));
+ return text;
+}
+} // namespace
+
+SystemKeyboard::~SystemKeyboard() {
+ Close();
+ Wipe();
+}
+
+int SystemKeyboard::Preload() {
+ if (g_loaded) return 0;
+ const int initialized = sceCommonDialogInitialize();
+ if (initialized < 0 && static_cast<std::uint32_t>(initialized) != kAlreadyInitialized) return g_preload_result = initialized;
+ if (const int loaded = sceSysmoduleLoadModule(kImeDialogModule); loaded < 0) return g_preload_result = loaded;
+ g_loaded = true;
+ return g_preload_result = 0;
+}
+
+void SystemKeyboard::Wipe() {
+ volatile std::uint16_t* units = buffer_.data();
+ for (std::size_t i = 0; i < buffer_.size(); ++i) units[i] = 0;
+ volatile char* bytes = text_.data();
+ for (std::size_t i = 0; i < text_.size(); ++i) bytes[i] = 0;
+ text_.clear();
+}
+
+bool SystemKeyboard::Open(std::string_view title, std::string_view value, bool secret, std::string* error) {
+ if (active_) return false;
+ if (!g_loaded) {
+ if (error) *error = Refused("preload", g_preload_result);
+ return false;
+ }
+ ImeParam param{};
+ if (const int user = sceUserServiceGetForegroundUser(&param.user_id); user < 0) {
+ if (error) *error = Refused("user", user);
+ return false;
+ }
+ // A value longer than the dialog holds would come back cut: Playden's own keyboard edits it.
+ std::size_t units = 0;
+ for (std::size_t i = 0; i < value.size(); ++i) {
+ const auto byte = static_cast<unsigned char>(value[i]);
+ if ((byte & 0xc0) != 0x80) units += byte >= 0xf0 ? 2 : 1;
+ }
+ if (units > (secret ? 64u : 511u)) {
+ if (error) *error = "value-too-long units=" + std::to_string(units);
+ return false;
+ }
+ Wipe();
+ ToUtf16(title, title_);
+ // A password dialog takes only the basic Latin type (1); the default type is refused with
+ // 0x80bc0030 (console, 2026-10-17). Settings are tried in turn and every refusal is logged.
+ struct Attempt { std::int32_t type; std::uint32_t max_length; bool placeholder; };
+ static constexpr Attempt kPlain[] = {{0, 511, true}};
+ static constexpr Attempt kSecret[] = {{1, 128, true}, {1, 64, false}};
+ std::string refusals;
+ bool opened = false;
+ for (const auto& attempt : secret ? std::span<const Attempt>(kSecret) : std::span<const Attempt>(kPlain)) {
+ ToUtf16(value, std::span<std::uint16_t>(buffer_.data(), attempt.max_length + 1));
+ param.type = attempt.type;
+ param.option = secret ? kOptionPassword : 0;
+ param.max_text_length = attempt.max_length;
+ param.input_text_buffer = buffer_.data();
+ param.pos_x = 960.0F; // the middle of the 1920x1080 screen
+ param.pos_y = 540.0F;
+ param.horizontal_alignment = param.vertical_alignment = 1; // centred on that point
+ param.placeholder = attempt.placeholder ? title_.data() : nullptr;
+ param.title = title_.data();
+ const int result = sceImeDialogInit(&param, nullptr);
+ if (result == 0) { opened = true; break; }
+ char refusal[80];
+ std::snprintf(refusal, sizeof(refusal), "%sinit(type=%d max=%u placeholder=%d)=0x%08x", refusals.empty() ? "" : " ",
+ int(attempt.type), unsigned(attempt.max_length), attempt.placeholder ? 1 : 0, unsigned(result));
+ refusals += refusal;
+ }
+ if (error) *error = refusals;
+ if (!opened) {
+ Wipe();
+ return false;
+ }
+ active_ = true;
+ started_us_ = MonotonicUs();
+ return true;
+}
+
+SystemKeyboard::State SystemKeyboard::Poll() {
+ if (!active_) return State::kIdle;
+ // The status can read "none" for a moment after Init.
+ const int status = sceImeDialogGetStatus();
+ if (status == 1 || (status == 0 && MonotonicUs() - started_us_ < 1000000)) return State::kOpen;
+ State state = State::kFailed;
+ if (status == 2) {
+ ImeResult result{};
+ if (sceImeDialogGetResult(&result) >= 0) {
+ state = result.outcome == 0 ? State::kAccepted : State::kCancelled;
+ if (state == State::kAccepted) text_ = ToUtf8(buffer_);
+ }
+ }
+ volatile std::uint16_t* units = buffer_.data();
+ for (std::size_t i = 0; i < buffer_.size(); ++i) units[i] = 0;
+ // Focus stays with the system while it still owns the dialog.
+ if (sceImeDialogTerm() < 0) return State::kOpen;
+ active_ = false;
+ return state;
+}
+
+void SystemKeyboard::Close() {
+ if (!active_) return;
+ sceImeDialogAbort();
+ active_ = sceImeDialogTerm() < 0;
+ if (!active_) Wipe();
+}
+
+std::string SystemKeyboard::Take() {
+ std::string text = std::move(text_);
+ Wipe();
+ return text;
+}
+} // namespace playden::ps5
diff --git a/src/platform/ps5/system_keyboard.h b/src/platform/ps5/system_keyboard.h
new file mode 100644
index 0000000..6692499
--- /dev/null
+++ b/src/platform/ps5/system_keyboard.h
@@ -0,0 +1,42 @@
+#pragma once
+// system_keyboard.h - The PS5's own keyboard (the IME dialog) for Playden's text fields.
+// Adapted from ProsperoStore's platform/ps5/ime (BlackBearReloaded, GPL-3.0-or-later).
+// Copyright (c) 2026 Playden contributors
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include <array>
+#include <cstdint>
+#include <string>
+#include <string_view>
+
+namespace playden::ps5 {
+// Remote Play's keyboard, a USB keyboard and the controller all type into the system keyboard.
+// It owns input while open: the app passes nothing on until Poll() stops returning kOpen.
+// Open it once the button that asked for it is released, so that press cannot reach the dialog.
+class SystemKeyboard {
+ public:
+ enum class State { kIdle, kOpen, kAccepted, kCancelled, kFailed };
+ SystemKeyboard() = default;
+ SystemKeyboard(const SystemKeyboard&) = delete;
+ SystemKeyboard& operator=(const SystemKeyboard&) = delete;
+ ~SystemKeyboard();
+ // Loads the dialog's module. Call it first thing in main: once the title's credentials change
+ // (the /data grant), loading system modules fails with 0x80020063. Returns the first failure, or 0.
+ static int Preload();
+ // secret: the dialog hides the text (a password). On failure, error names the refused step and
+ // its result code, for the log; Playden's own keyboard is used instead.
+ bool Open(std::string_view title, std::string_view value, bool secret, std::string* error);
+ State Poll();
+ void Close();
+ // The accepted text; Take() hands it over and wipes Playden's copies.
+ std::string Take();
+ bool active() const { return active_; }
+
+ private:
+ void Wipe();
+ std::array<std::uint16_t, 512> buffer_{};
+ std::array<std::uint16_t, 64> title_{};
+ std::string text_;
+ std::int64_t started_us_ = 0;
+ bool active_ = false;
+};
+} // namespace playden::ps5
diff --git a/src/steam/auth_backend.h b/src/steam/auth_backend.h
index 3446059..e41c9e6 100644
--- a/src/steam/auth_backend.h
+++ b/src/steam/auth_backend.h
@@ -1,5 +1,6 @@
#pragma once
+#include "steam/secret.h"
#include "steam/session_store.h"
#include <atomic>
#include <functional>
@@ -10,7 +11,12 @@ namespace playden::steam {
enum class AuthError {
kNone, kCanceled, kExpired, kRejected, kNetwork, kProtocol,
- kCredentialsRevoked, kPersistence, kNoSession
+ kCredentialsRevoked, kPersistence, kNoSession,
+ // Account name and password sign-in only.
+ kInvalidPassword, // EResult 5: Steam does not say whether the name or the password was wrong
+ kRateLimited, // EResult 84: too many attempts
+ kSignInRefused, // any other refusal; the QR code may still work
+ kSignInTimedOut
};
struct AuthResult {
@@ -22,6 +28,29 @@ struct AuthResult {
// presentation data; neither they nor credentials belong in diagnostics.
using ChallengeCallback = std::function<void(const std::string&)>;
+// Steam Guard follow-ups of an account name and password sign-in.
+enum class GuardPromptKind {
+ kApproval, // approve in the Steam Mobile app (or, with email_domain, from Steam's email)
+ kEmailCode, // type the code Steam emailed to …@email_domain
+ kAuthenticatorCode, // type the code from the Steam Mobile app
+};
+struct GuardPrompt {
+ GuardPromptKind kind = GuardPromptKind::kApproval;
+ std::string email_domain;
+ bool code_allowed = false; // kApproval: a typed code works too (code_kind says which)
+ GuardPromptKind code_kind = GuardPromptKind::kAuthenticatorCode;
+ bool code_rejected = false; // the last code was wrong; the same sign-in waits for another
+};
+using GuardPromptCallback = std::function<void(const GuardPrompt&)>;
+// Returns the code the player submitted since the last call, if any. Called on the service worker.
+using GuardCodeSource = std::function<std::optional<std::string>()>;
+
+// The password is cleared (overwritten) as soon as it is encrypted, and on every failure.
+struct Credentials {
+ std::string account_name;
+ std::string password;
+};
+
class AuthBackend {
public:
virtual ~AuthBackend() = default;
@@ -29,6 +58,15 @@ class AuthBackend {
const ChallengeCallback& challenge) = 0;
virtual AuthResult Restore(const StoredSession& session,
const std::atomic<bool>& cancel) = 0;
+ // Backends without password sign-in refuse it.
+ virtual AuthResult AuthenticateCredentials(Credentials& credentials, const std::atomic<bool>& cancel,
+ const GuardPromptCallback& prompt, const GuardCodeSource& code);
};
+inline AuthResult AuthBackend::AuthenticateCredentials(Credentials& credentials, const std::atomic<bool>&,
+ const GuardPromptCallback&, const GuardCodeSource&) {
+ ZeroizeSecret(credentials.password);
+ return {AuthError::kSignInRefused, std::nullopt};
+}
+
} // namespace playden::steam
diff --git a/src/steam/backend/auth_client.cpp b/src/steam/backend/auth_client.cpp
index ac88e64..4dcf653 100644
--- a/src/steam/backend/auth_client.cpp
+++ b/src/steam/backend/auth_client.cpp
@@ -1,5 +1,6 @@
#include "steam/backend/auth_client.h"
#include "steam/backend/auth_messages.h"
+#include "steam/backend/password_crypto.h"
#include "steam/backend/token_fingerprint.h"
#include <algorithm>
@@ -12,6 +13,11 @@
namespace playden::steam {
namespace {
constexpr std::uint64_t kLifetimeMs = 300000;
+// A password sign-in may wait for the player to fetch an email or open the Steam app, twice after a
+// wrong code: it gets longer than a QR code.
+constexpr std::uint64_t kCredentialLifetimeMs = 600000;
+// How often a sign-in that waits only for a typed code checks for one (it does not poll Steam).
+constexpr std::uint32_t kCodeCheckMs = 250;
constexpr std::size_t kBodyLimit = 65536;
constexpr std::uint32_t kRequestTimeoutMs = 10000;
@@ -91,10 +97,20 @@ bool ValidToken(const std::string& token, std::uint64_t id, std::uint64_t now) {
const auto claims = InspectTokenClaims(token);
return claims && claims->steam_id == id && claims->expires_at_unix_seconds > now;
}
-std::uint32_t Remaining(std::uint64_t start, const AuthClientHooks& hooks) {
+std::uint32_t Remaining(std::uint64_t start, const AuthClientHooks& hooks,
+ std::uint64_t lifetime = kLifetimeMs) {
const auto elapsed = hooks.monotonic_ms() - start;
- return elapsed >= kLifetimeMs ? 0 : static_cast<std::uint32_t>(kLifetimeMs - elapsed);
+ return elapsed >= lifetime ? 0 : static_cast<std::uint32_t>(lifetime - elapsed);
}
+std::uint32_t PollInterval(float interval) {
+ return static_cast<std::uint32_t>(std::min<double>(kLifetimeMs,
+ std::ceil(std::max<double>(interval, 1.0) * 1000.0)));
+}
+// Clears the password however the sign-in ends.
+struct PasswordWipe {
+ std::string& password;
+ ~PasswordWipe() { ZeroizeSecret(password); }
+};
}
AuthClient::AuthClient(std::string ca_bundle)
@@ -103,17 +119,23 @@ AuthClient::AuthClient(AuthClientHooks hooks) : hooks_(std::move(hooks)) {}
AuthError AuthClient::Post(const char* method, const std::vector<std::uint8_t>& message,
const std::atomic<bool>& cancel, std::uint32_t timeout_ms,
- bool restoring, std::vector<std::uint8_t>* body) {
+ bool restoring, std::vector<std::uint8_t>* body, bool get) {
body->clear();
if (cancel.load()) return AuthError::kCanceled;
if (!timeout_ms) return AuthError::kExpired;
if (message.size() > kBodyLimit) return AuthError::kProtocol;
HttpRequest req;
- req.method = HttpMethod::kPost;
+ req.method = get ? HttpMethod::kGet : HttpMethod::kPost;
req.url = std::string("https://api.steampowered.com/IAuthenticationService/") + method + "/v1/";
- req.headers = {{"Content-Type", "application/x-www-form-urlencoded"}, {"User-Agent", "Playden/1.0"}};
req.timeout_ms = std::min(timeout_ms, kRequestTimeoutMs); req.max_response_bytes = kBodyLimit;
- const auto form = FormBase64(message); req.body.assign(form.begin(), form.end());
+ const auto form = FormBase64(message);
+ if (get) {
+ req.headers = {{"User-Agent", "Playden/1.0"}};
+ req.url += "?" + form;
+ } else {
+ req.headers = {{"Content-Type", "application/x-www-form-urlencoded"}, {"User-Agent", "Playden/1.0"}};
+ req.body.assign(form.begin(), form.end());
+ }
HttpResponse response;
if (hooks_.perform) response = hooks_.perform(req, cancel);
else {
@@ -174,46 +196,192 @@ AuthResult AuthClient::AuthenticateQr(const std::atomic<bool>& cancel,
if (!auth::Decode(response,&session).ok() || !session.client_id || session.request_id.empty() ||
session.request_id.size() > 1024 || !ChallengeValid(session.challenge_url) ||
!std::isfinite(session.interval) || session.interval <= 0) return Failure(AuthError::kProtocol);
- const auto interval = static_cast<std::uint32_t>(std::min<double>(kLifetimeMs,
- std::ceil(std::max<double>(session.interval,1.0) * 1000.0)));
+ const auto interval = PollInterval(session.interval);
challenge(session.challenge_url);
while (!cancel.load()) {
const auto remaining = Remaining(started,hooks_);
if (!remaining) return Failure(AuthError::kExpired);
if (!hooks_.wait(std::min(interval, remaining),cancel) || cancel.load()) return Failure(AuthError::kCanceled);
if (!Remaining(started,hooks_)) return Failure(AuthError::kExpired);
- auth::PollAuthSessionStatusRequest poll;
- poll.client_id = session.client_id; poll.request_id = session.request_id;
- if (!auth::Encode(poll,&request).ok()) return Failure(AuthError::kProtocol);
- error = Post("PollAuthSessionStatus",request,cancel,Remaining(started,hooks_),false,&response);
+ auth::PollAuthSessionStatusResponse approval;
+ error = Poll(&session.client_id, session.request_id, cancel, Remaining(started,hooks_), &approval);
if (error != AuthError::kNone) return Failure(error);
if (!Remaining(started,hooks_)) return Failure(AuthError::kExpired);
- auth::PollAuthSessionStatusResponse approval;
- if (!auth::Decode(response,&approval).ok()) return Failure(AuthError::kProtocol);
- if (approval.new_client_id) {
- if (!*approval.new_client_id) return Failure(AuthError::kProtocol);
- session.client_id = *approval.new_client_id;
- }
if (approval.new_challenge_url) {
if (!ChallengeValid(*approval.new_challenge_url)) return Failure(AuthError::kProtocol);
challenge(*approval.new_challenge_url);
}
if (cancel.load()) return Failure(AuthError::kCanceled);
if (approval.refresh_token.empty()) continue;
- const auto claims = InspectTokenClaims(approval.refresh_token);
- const auto now = hooks_.unix_seconds();
- if (!claims || claims->expires_at_unix_seconds <= now || !AccountNameValid(approval.account_name))
- return Failure(AuthError::kProtocol);
- StoredSession stored{claims->steam_id, approval.account_name, std::move(approval.refresh_token),
- std::move(approval.access_token), std::nullopt};
- if (stored.access_token.empty()) {
- auto renewed = Renew(stored,cancel,Remaining(started,hooks_),false);
- if (cancel.load()) return Failure(AuthError::kCanceled);
- if (!Remaining(started,hooks_)) return Failure(AuthError::kExpired);
- return renewed;
+ return Approved(std::move(approval), started, kLifetimeMs, cancel);
+ }
+ return Failure(AuthError::kCanceled);
+}
+
+AuthError AuthClient::Poll(std::uint64_t* client_id, const std::vector<std::uint8_t>& request_id,
+ const std::atomic<bool>& cancel, std::uint32_t timeout_ms,
+ auth::PollAuthSessionStatusResponse* approval) {
+ auth::PollAuthSessionStatusRequest poll;
+ poll.client_id = *client_id; poll.request_id = request_id;
+ std::vector<std::uint8_t> request, response;
+ if (!auth::Encode(poll,&request).ok()) return AuthError::kProtocol;
+ const auto error = Post("PollAuthSessionStatus",request,cancel,timeout_ms,false,&response);
+ if (error != AuthError::kNone) return error;
+ if (!auth::Decode(response,approval).ok()) return AuthError::kProtocol;
+ if (approval->new_client_id) {
+ if (!*approval->new_client_id) return AuthError::kProtocol;
+ *client_id = *approval->new_client_id;
+ }
+ return AuthError::kNone;
+}
+
+AuthResult AuthClient::Approved(auth::PollAuthSessionStatusResponse approval, std::uint64_t started,
+ std::uint64_t lifetime_ms, const std::atomic<bool>& cancel) {
+ const auto claims = InspectTokenClaims(approval.refresh_token);
+ const auto now = hooks_.unix_seconds();
+ if (!claims || claims->expires_at_unix_seconds <= now || !AccountNameValid(approval.account_name))
+ return Failure(AuthError::kProtocol);
+ StoredSession stored{claims->steam_id, approval.account_name, std::move(approval.refresh_token),
+ std::move(approval.access_token), std::nullopt};
+ if (stored.access_token.empty()) {
+ auto renewed = Renew(stored,cancel,Remaining(started,hooks_,lifetime_ms),false);
+ if (cancel.load()) return Failure(AuthError::kCanceled);
+ if (!Remaining(started,hooks_,lifetime_ms)) return Failure(AuthError::kExpired);
+ return renewed;
+ }
+ if (!ValidToken(stored.access_token,stored.steam_id,now)) return Failure(AuthError::kProtocol);
+ return {AuthError::kNone,std::move(stored)};
+}
+
+AuthResult AuthClient::AuthenticateCredentials(Credentials& credentials, const std::atomic<bool>& cancel,
+ const GuardPromptCallback& prompt, const GuardCodeSource& code) {
+ PasswordWipe wipe{credentials.password};
+ if (cancel.load()) return Failure(AuthError::kCanceled);
+ if (!hooks_.monotonic_ms || !hooks_.unix_seconds || !hooks_.wait || !prompt || !code ||
+ !AccountNameValid(credentials.account_name) || credentials.password.empty())
+ return Failure(AuthError::kProtocol);
+ const auto started = hooks_.monotonic_ms();
+ auto remaining = [&] { return Remaining(started, hooks_, kCredentialLifetimeMs); };
+ // Steam's refusals of the password, the account or the device; the QR code may still work.
+ auto refused = [&](AuthError error) {
+ if (error != AuthError::kRejected) return error == AuthError::kExpired ? AuthError::kSignInTimedOut : error;
+ if (last_eresult_ == 5) return AuthError::kInvalidPassword;
+ if (last_eresult_ == 84) return AuthError::kRateLimited;
+ return AuthError::kSignInRefused;
+ };
+ auth::GetPasswordRsaPublicKeyRequest key_request;
+ key_request.account_name = credentials.account_name;
+ std::vector<std::uint8_t> request, response;
+ if (!auth::Encode(key_request, &request).ok()) return Failure(AuthError::kProtocol);
+ auto error = Post("GetPasswordRSAPublicKey", request, cancel, remaining(), false, &response, true);
+ if (error != AuthError::kNone) return Failure(refused(error));
+ auth::GetPasswordRsaPublicKeyResponse key;
+ if (!auth::Decode(response, &key).ok() || !key.timestamp) return Failure(AuthError::kProtocol);
+ auth::BeginAuthSessionViaCredentialsRequest begin;
+ begin.device_details.device_friendly_name = "Playden (PS5)";
+ begin.account_name = credentials.account_name;
+ begin.encryption_timestamp = key.timestamp;
+ auto encrypted = EncryptPassword(key.publickey_mod, key.publickey_exp, credentials.password);
+ ZeroizeSecret(credentials.password);
+ if (!encrypted) return Failure(AuthError::kProtocol);
+ begin.encrypted_password = std::move(*encrypted);
+ if (!auth::Encode(begin, &request).ok()) return Failure(AuthError::kProtocol);
+ error = Post("BeginAuthSessionViaCredentials", request, cancel, remaining(), false, &response);
+ if (error != AuthError::kNone) return Failure(refused(error));
+ if (!remaining()) return Failure(AuthError::kSignInTimedOut);
+ auth::BeginAuthSessionViaCredentialsResponse session;
+ if (!auth::Decode(response, &session).ok() || !session.client_id || !session.steam_id ||
+ session.request_id.empty() || session.request_id.size() > 1024 ||
+ !std::isfinite(session.interval) || session.interval <= 0) return Failure(AuthError::kProtocol);
+
+ // As the Steam client: approval in the app when offered (a typed code works meanwhile), else a code.
+ bool approval = false, none = session.allowed_confirmations.empty();
+ std::optional<GuardPromptKind> code_kind;
+ std::string email_domain;
+ for (const auto& confirmation : session.allowed_confirmations) {
+ switch (confirmation.confirmation_type) {
+ case auth::GuardType::kNone: none = true; break;
+ case auth::GuardType::kDeviceConfirmation: approval = true; break;
+ case auth::GuardType::kDeviceCode: code_kind = GuardPromptKind::kAuthenticatorCode; break;
+ case auth::GuardType::kEmailCode:
+ if (!code_kind) code_kind = GuardPromptKind::kEmailCode;
+ email_domain = confirmation.associated_message.substr(0, 253);
+ break;
+ case auth::GuardType::kEmailConfirmation:
+ approval = true;
+ if (email_domain.empty()) email_domain = confirmation.associated_message.substr(0, 253);
+ break;
+ default: break;
}
- if (!ValidToken(stored.access_token,stored.steam_id,now)) return Failure(AuthError::kProtocol);
- return {AuthError::kNone,std::move(stored)};
+ }
+ if (!none && !approval && !code_kind) return Failure(AuthError::kSignInRefused);
+ GuardPrompt shown;
+ if (!none) {
+ if (approval) {
+ shown.kind = GuardPromptKind::kApproval;
+ shown.code_allowed = code_kind.has_value();
+ if (code_kind) shown.code_kind = *code_kind;
+ } else {
+ shown.kind = *code_kind;
+ }
+ if (shown.kind == GuardPromptKind::kEmailCode || (shown.kind == GuardPromptKind::kApproval &&
+ (!shown.code_allowed || shown.code_kind == GuardPromptKind::kEmailCode)))
+ shown.email_domain = email_domain;
+ prompt(shown);
+ }
+ // A sign-in that waits only for a typed code polls Steam once the code is accepted.
+ bool polling = none || approval;
+ const auto interval = PollInterval(session.interval);
+ while (!cancel.load()) {
+ if (!remaining()) return Failure(AuthError::kSignInTimedOut);
+ if (code_kind) {
+ if (auto typed = code()) {
+ auth::UpdateAuthSessionWithSteamGuardCodeRequest update;
+ update.client_id = session.client_id;
+ update.steam_id = session.steam_id;
+ update.code = std::move(*typed);
+ update.code_type = *code_kind == GuardPromptKind::kEmailCode ? auth::GuardType::kEmailCode
+ : auth::GuardType::kDeviceCode;
+ ZeroizeSecret(*typed);
+ const bool usable = !update.code.empty() && update.code.size() <= 16;
+ std::vector<std::uint8_t> code_request;
+ if (usable && !auth::Encode(update, &code_request).ok()) return Failure(AuthError::kProtocol);
+ ZeroizeSecret(update.code);
+ error = usable ? Post("UpdateAuthSessionWithSteamGuardCode", code_request, cancel, remaining(), false, &response)
+ : AuthError::kRejected;
+ if (usable) std::fill(code_request.begin(), code_request.end(), std::uint8_t{0});
+ // DuplicateRequest (29): Steam already took this code.
+ if (error == AuthError::kNone || (error == AuthError::kRejected && last_eresult_ == 29)) {
+ polling = true;
+ } else if (error == AuthError::kRejected && (!usable || last_eresult_ == 65 || last_eresult_ == 88)) {
+ // A wrong code: the same sign-in asks again.
+ GuardPrompt again;
+ again.kind = *code_kind;
+ again.email_domain = *code_kind == GuardPromptKind::kEmailCode ? email_domain : std::string{};
+ again.code_rejected = true;
+ prompt(again);
+ continue;
+ } else {
+ return Failure(refused(error));
+ }
+ }
+ }
+ const auto left = remaining();
+ if (!left) return Failure(AuthError::kSignInTimedOut);
+ if (!hooks_.wait(std::min(polling ? interval : kCodeCheckMs, left), cancel) || cancel.load())
+ return Failure(AuthError::kCanceled);
+ if (!polling) continue;
+ if (!remaining()) return Failure(AuthError::kSignInTimedOut);
+ auth::PollAuthSessionStatusResponse approved;
+ error = Poll(&session.client_id, session.request_id, cancel, remaining(), &approved);
+ if (error != AuthError::kNone) return Failure(refused(error));
+ if (cancel.load()) return Failure(AuthError::kCanceled);
+ if (approved.refresh_token.empty()) continue;
+ auto result = Approved(std::move(approved), started, kCredentialLifetimeMs, cancel);
+ if (result.error == AuthError::kExpired) result.error = AuthError::kSignInTimedOut;
+ if (result.error == AuthError::kNone && result.session && result.session->steam_id != session.steam_id)
+ return Failure(AuthError::kProtocol);
+ return result;
}
return Failure(AuthError::kCanceled);
}
diff --git a/src/steam/backend/auth_client.h b/src/steam/backend/auth_client.h
index 97e3106..af1525d 100644
--- a/src/steam/backend/auth_client.h
+++ b/src/steam/backend/auth_client.h
@@ -1,6 +1,7 @@
#pragma once
#include "steam/auth_backend.h"
+#include "steam/backend/auth_messages.h"
#include "steam/backend/http_client.h"
#include <functional>
#include <memory>
@@ -44,10 +45,20 @@ class AuthClient final : public AuthBackend {
const ChallengeCallback& challenge) override;
AuthResult Restore(const StoredSession& session,
const std::atomic<bool>& cancel) override;
+ AuthResult AuthenticateCredentials(Credentials& credentials, const std::atomic<bool>& cancel,
+ const GuardPromptCallback& prompt, const GuardCodeSource& code) override;
private:
+ // get: the message goes in the query string (GetPasswordRSAPublicKey); otherwise it is the form body.
AuthError Post(const char* method, const std::vector<std::uint8_t>& message,
const std::atomic<bool>& cancel, std::uint32_t timeout_ms,
- bool restoring, std::vector<std::uint8_t>* body);
+ bool restoring, std::vector<std::uint8_t>* body, bool get = false);
+ // One PollAuthSessionStatus round. Updates client_id when Steam replaces it.
+ AuthError Poll(std::uint64_t* client_id, const std::vector<std::uint8_t>& request_id,
+ const std::atomic<bool>& cancel, std::uint32_t timeout_ms,
+ auth::PollAuthSessionStatusResponse* approval);
+ // Checks the approved tokens and renews a missing access token.
+ AuthResult Approved(auth::PollAuthSessionStatusResponse approval, std::uint64_t started,
+ std::uint64_t lifetime_ms, const std::atomic<bool>& cancel);
AuthResult Renew(const StoredSession& session, const std::atomic<bool>& cancel,
std::uint32_t timeout_ms, bool restoring);
AuthResult Restored(const char* path, const StoredSession& before, AuthResult result);
diff --git a/src/steam/backend/auth_messages.cpp b/src/steam/backend/auth_messages.cpp
index 97dba7f..295120d 100644
--- a/src/steam/backend/auth_messages.cpp
+++ b/src/steam/backend/auth_messages.cpp
@@ -121,6 +121,121 @@ Status Decode(const std::uint8_t* data, std::size_t size,
return {};
}
+Status Encode(const GetPasswordRsaPublicKeyRequest& message,
+ std::vector<std::uint8_t>* output) {
+ Writer writer;
+ writer.AddString(1, message.account_name);
+ return WriterStatus(writer, output);
+}
+
+Status Decode(const std::uint8_t* data, std::size_t size,
+ GetPasswordRsaPublicKeyResponse* message,
+ proto::DecodeLimits limits) {
+ if (message == nullptr) return {DecodeError::kInvalidArgument, 0};
+ GetPasswordRsaPublicKeyResponse decoded;
+ Reader reader(data, size, limits);
+ Field field;
+ while (reader.Next(&field)) {
+ if (field.number == 1 || field.number == 2) {
+ if (!HasWire(field, WireType::kLengthDelimited))
+ return WrongWire(field);
+ if (field.number == 1)
+ decoded.publickey_mod = field.AsString();
+ else
+ decoded.publickey_exp = field.AsString();
+ } else if (field.number == 3) {
+ if (!HasWire(field, WireType::kVarint)) return WrongWire(field);
+ decoded.timestamp = field.value;
+ }
+ }
+ if (!reader.ok()) return reader.status();
+ *message = std::move(decoded);
+ return {};
+}
+
+Status Encode(const BeginAuthSessionViaCredentialsRequest& message,
+ std::vector<std::uint8_t>* output) {
+ Writer device;
+ EncodeDeviceDetails(message.device_details, &device);
+ Writer writer;
+ writer.AddString(1, message.device_details.device_friendly_name);
+ writer.AddString(2, message.account_name);
+ writer.AddString(3, message.encrypted_password);
+ writer.AddVarint(4, message.encryption_timestamp);
+ writer.AddVarint(5, message.remember_login ? 1 : 0);
+ writer.AddVarint(6, static_cast<std::uint64_t>(message.device_details.platform_type));
+ writer.AddVarint(7, static_cast<std::uint64_t>(message.persistence));
+ writer.AddString(8, message.website_id);
+ writer.AddMessage(9, device);
+ return WriterStatus(writer, output);
+}
+
+Status Decode(const std::uint8_t* data, std::size_t size,
+ BeginAuthSessionViaCredentialsResponse* message,
+ proto::DecodeLimits limits) {
+ if (message == nullptr) return {DecodeError::kInvalidArgument, 0};
+ BeginAuthSessionViaCredentialsResponse decoded;
+ Reader reader(data, size, limits);
+ Field field;
+ while (reader.Next(&field)) {
+ switch (field.number) {
+ case 1:
+ case 5:
+ if (!HasWire(field, WireType::kVarint)) return WrongWire(field);
+ (field.number == 1 ? decoded.client_id : decoded.steam_id) = field.value;
+ break;
+ case 2:
+ if (!HasWire(field, WireType::kLengthDelimited))
+ return WrongWire(field);
+ decoded.request_id.assign(field.data, field.data + field.size);
+ break;
+ case 3: {
+ if (!HasWire(field, WireType::kFixed32)) return WrongWire(field);
+ const std::uint32_t bits = static_cast<std::uint32_t>(field.value);
+ std::memcpy(&decoded.interval, &bits, sizeof(bits));
+ break;
+ }
+ case 4: {
+ if (!HasWire(field, WireType::kLengthDelimited))
+ return WrongWire(field);
+ Reader child;
+ if (!reader.Submessage(field, &child)) return reader.status();
+ AllowedConfirmation confirmation;
+ const Status status = DecodeAllowedConfirmation(&child, &confirmation);
+ if (!status.ok()) return status;
+ decoded.allowed_confirmations.push_back(std::move(confirmation));
+ break;
+ }
+ case 6:
+ case 7:
+ case 8: {
+ if (!HasWire(field, WireType::kLengthDelimited))
+ return WrongWire(field);
+ auto& target = field.number == 6 ? decoded.weak_token
+ : field.number == 7 ? decoded.agreement_session_url
+ : decoded.extended_error_message;
+ target = field.AsString();
+ break;
+ }
+ default:
+ break;
+ }
+ }
+ if (!reader.ok()) return reader.status();
+ *message = std::move(decoded);
+ return {};
+}
+
+Status Encode(const UpdateAuthSessionWithSteamGuardCodeRequest& message,
+ std::vector<std::uint8_t>* output) {
+ Writer writer;
+ writer.AddVarint(1, message.client_id);
+ writer.AddFixed64(2, message.steam_id);
+ writer.AddString(3, message.code);
+ writer.AddVarint(4, static_cast<std::uint64_t>(message.code_type));
+ return WriterStatus(writer, output);
+}
+
Status Encode(const PollAuthSessionStatusRequest& message,
std::vector<std::uint8_t>* output) {
Writer writer;
diff --git a/src/steam/backend/auth_messages.h b/src/steam/backend/auth_messages.h
index a7dca00..dc56128 100644
--- a/src/steam/backend/auth_messages.h
+++ b/src/steam/backend/auth_messages.h
@@ -28,6 +28,11 @@ enum class GuardType : std::int32_t {
kLegacyMachineAuth = 7,
};
+enum class SessionPersistence : std::int32_t {
+ kEphemeral = 0,
+ kPersistent = 1,
+};
+
enum class TokenRenewalType : std::int32_t {
kNone = 0,
kAllow = 1,
@@ -58,6 +63,47 @@ struct BeginAuthSessionViaQrResponse {
std::int32_t version = 0;
};
+// Sent as a GET: the key encrypts the account's password for BeginAuthSessionViaCredentials.
+struct GetPasswordRsaPublicKeyRequest {
+ std::string account_name;
+};
+
+struct GetPasswordRsaPublicKeyResponse {
+ std::string publickey_mod; // hex
+ std::string publickey_exp; // hex
+ std::uint64_t timestamp = 0;
+};
+
+// The device's friendly name and platform are also sent at the top level, as the Steam client does.
+struct BeginAuthSessionViaCredentialsRequest {
+ DeviceDetails device_details;
+ std::string account_name;
+ std::string encrypted_password; // base64
+ std::uint64_t encryption_timestamp = 0;
+ bool remember_login = true;
+ SessionPersistence persistence = SessionPersistence::kPersistent;
+ std::string website_id = "Client";
+};
+
+struct BeginAuthSessionViaCredentialsResponse {
+ std::uint64_t client_id = 0;
+ std::vector<std::uint8_t> request_id;
+ float interval = 0;
+ std::vector<AllowedConfirmation> allowed_confirmations;
+ std::uint64_t steam_id = 0;
+ std::string weak_token;
+ std::string agreement_session_url;
+ std::string extended_error_message;
+};
+
+// Its response carries nothing Playden uses; success is the X-EResult header.
+struct UpdateAuthSessionWithSteamGuardCodeRequest {
+ std::uint64_t client_id = 0;
+ std::uint64_t steam_id = 0;
+ std::string code;
+ GuardType code_type = GuardType::kUnknown;
+};
+
struct PollAuthSessionStatusRequest {
std::uint64_t client_id = 0;
std::vector<std::uint8_t> request_id;
@@ -92,6 +138,21 @@ proto::Status Decode(const std::uint8_t* data, std::size_t size,
BeginAuthSessionViaQrResponse* message,
proto::DecodeLimits limits = {});
+proto::Status Encode(const GetPasswordRsaPublicKeyRequest& message,
+ std::vector<std::uint8_t>* output);
+proto::Status Decode(const std::uint8_t* data, std::size_t size,
+ GetPasswordRsaPublicKeyResponse* message,
+ proto::DecodeLimits limits = {});
+
+proto::Status Encode(const BeginAuthSessionViaCredentialsRequest& message,
+ std::vector<std::uint8_t>* output);
+proto::Status Decode(const std::uint8_t* data, std::size_t size,
+ BeginAuthSessionViaCredentialsResponse* message,
+ proto::DecodeLimits limits = {});
+
+proto::Status Encode(const UpdateAuthSessionWithSteamGuardCodeRequest& message,
+ std::vector<std::uint8_t>* output);
+
proto::Status Encode(const PollAuthSessionStatusRequest& message,
std::vector<std::uint8_t>* output);
proto::Status Decode(const std::uint8_t* data, std::size_t size,
diff --git a/src/steam/backend/password_crypto.cpp b/src/steam/backend/password_crypto.cpp
new file mode 100644
index 0000000..44e25f5
--- /dev/null
+++ b/src/steam/backend/password_crypto.cpp
@@ -0,0 +1,78 @@
+#include "steam/backend/password_crypto.h"
+
+#include <mbedtls/base64.h>
+#include <mbedtls/bignum.h>
+#include <mbedtls/ctr_drbg.h>
+#include <mbedtls/entropy.h>
+#include <mbedtls/rsa.h>
+
+#include <algorithm>
+#include <vector>
+
+namespace playden::steam {
+namespace {
+constexpr std::size_t kMaxModulusHex = 1024; // 4096 bits
+constexpr std::size_t kMaxExponentHex = 16;
+
+bool Hex(const std::string& value, std::size_t limit) {
+ return !value.empty() && value.size() <= limit &&
+ std::all_of(value.begin(), value.end(), [](char c) {
+ return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
+ });
+}
+
+// The contexts are freed on every path; the padding's random bytes come from the same entropy
+// source and DRBG the TLS stack uses.
+struct Contexts {
+ mbedtls_rsa_context rsa;
+ mbedtls_entropy_context entropy;
+ mbedtls_ctr_drbg_context drbg;
+ mbedtls_mpi n, e;
+ Contexts() {
+ mbedtls_rsa_init(&rsa);
+ mbedtls_entropy_init(&entropy);
+ mbedtls_ctr_drbg_init(&drbg);
+ mbedtls_mpi_init(&n);
+ mbedtls_mpi_init(&e);
+ }
+ ~Contexts() {
+ mbedtls_mpi_free(&e);
+ mbedtls_mpi_free(&n);
+ mbedtls_ctr_drbg_free(&drbg);
+ mbedtls_entropy_free(&entropy);
+ mbedtls_rsa_free(&rsa);
+ }
+ Contexts(const Contexts&) = delete;
+ Contexts& operator=(const Contexts&) = delete;
+};
+} // namespace
+
+std::optional<std::string> EncryptPassword(const std::string& modulus_hex, const std::string& exponent_hex,
+ const std::string& password) {
+ if (!Hex(modulus_hex, kMaxModulusHex) || !Hex(exponent_hex, kMaxExponentHex)) return std::nullopt;
+ Contexts c;
+ if (mbedtls_mpi_read_string(&c.n, 16, modulus_hex.c_str()) != 0 ||
+ mbedtls_mpi_read_string(&c.e, 16, exponent_hex.c_str()) != 0 ||
+ mbedtls_rsa_import(&c.rsa, &c.n, nullptr, nullptr, nullptr, &c.e) != 0 ||
+ mbedtls_rsa_complete(&c.rsa) != 0 || mbedtls_rsa_check_pubkey(&c.rsa) != 0)
+ return std::nullopt;
+ const std::size_t size = mbedtls_rsa_get_len(&c.rsa);
+ // PKCS#1 v1.5 needs 11 bytes of padding.
+ if (password.size() + 11 > size) return std::nullopt;
+ static const unsigned char kPersonal[] = "playden-password";
+ if (mbedtls_ctr_drbg_seed(&c.drbg, mbedtls_entropy_func, &c.entropy, kPersonal, sizeof(kPersonal) - 1) != 0)
+ return std::nullopt;
+ std::vector<unsigned char> encrypted(size);
+ if (mbedtls_rsa_pkcs1_encrypt(&c.rsa, mbedtls_ctr_drbg_random, &c.drbg, password.size(),
+ reinterpret_cast<const unsigned char*>(password.data()), encrypted.data()) != 0)
+ return std::nullopt;
+ std::size_t written = 0;
+ std::string encoded(4 * ((size + 2) / 3) + 1, '\0');
+ if (mbedtls_base64_encode(reinterpret_cast<unsigned char*>(encoded.data()), encoded.size(), &written,
+ encrypted.data(), encrypted.size()) != 0)
+ return std::nullopt;
+ encoded.resize(written);
+ return encoded;
+}
+
+} // namespace playden::steam
diff --git a/src/steam/backend/password_crypto.h b/src/steam/backend/password_crypto.h
new file mode 100644
index 0000000..4043c06
--- /dev/null
+++ b/src/steam/backend/password_crypto.h
@@ -0,0 +1,16 @@
+#pragma once
+
+#include "steam/secret.h"
+
+#include <optional>
+#include <string>
+
+namespace playden::steam {
+
+// Encrypts an account password with the RSA key Steam returns from GetPasswordRSAPublicKey (hex
+// modulus and exponent), PKCS#1 v1.5 as the Steam client does, and returns it base64-encoded.
+// Returns nothing when the key is malformed or encryption fails.
+std::optional<std::string> EncryptPassword(const std::string& modulus_hex, const std::string& exponent_hex,
+ const std::string& password);
+
+} // namespace playden::steam
diff --git a/src/steam/secret.h b/src/steam/secret.h
new file mode 100644
index 0000000..22deaa8
--- /dev/null
+++ b/src/steam/secret.h
@@ -0,0 +1,14 @@
+#pragma once
+
+#include <string>
+
+namespace playden::steam {
+
+// Overwrites a secret's bytes before clearing it; std::string::clear() leaves them in memory.
+inline void ZeroizeSecret(std::string& secret) {
+ volatile char* bytes = secret.data();
+ for (std::size_t i = 0; i < secret.size(); ++i) bytes[i] = 0;
+ secret.clear();
+}
+
+} // namespace playden::steam
diff --git a/src/steam/service.cpp b/src/steam/service.cpp
index 35f1645..91fcf79 100644
--- a/src/steam/service.cpp
+++ b/src/steam/service.cpp
@@ -1,4 +1,5 @@
#include "steam/service.h"
+#include "steam/secret.h"
#include <algorithm>
namespace playden::steam {
@@ -31,8 +32,10 @@ SteamService::~SteamService() {
worker_.join();
}
-RequestId SteamService::Submit(Operation operation) {
+RequestId SteamService::Submit(Operation operation, std::shared_ptr<Credentials> credentials) {
std::lock_guard<std::mutex> lock(mutex_);
+ if (guard_code_) ZeroizeSecret(*guard_code_);
+ guard_code_.reset();
if (cancel_) cancel_->store(true);
cancel_ = std::make_shared<std::atomic<bool>>(false);
active_ = true;
@@ -47,13 +50,27 @@ RequestId SteamService::Submit(Operation operation) {
pending_.erase(std::remove_if(pending_.begin(), pending_.end(),
[](const Job& job) { return job.operation != Operation::kClear; }), pending_.end());
}
- pending_.push_back({operation, request_, generation_, cancel_});
+ pending_.push_back({operation, request_, generation_, cancel_, std::move(credentials)});
wake_.notify_one();
return request_;
}
RequestId SteamService::BeginQrSignIn() { return Submit(Operation::kBegin); }
RequestId SteamService::RestoreSession() { return Submit(Operation::kRestore); }
+RequestId SteamService::BeginCredentialSignIn(std::string account_name, std::string password) {
+ std::shared_ptr<Credentials> credentials(new Credentials{std::move(account_name), std::move(password)},
+ [](Credentials* c) { ZeroizeSecret(c->password); delete c; });
+ ZeroizeSecret(password);
+ return Submit(Operation::kCredentials, std::move(credentials));
+}
+void SteamService::SubmitGuardCode(std::string code) {
+ std::lock_guard<std::mutex> lock(mutex_);
+ if (active_) {
+ if (guard_code_) ZeroizeSecret(*guard_code_);
+ guard_code_ = std::move(code);
+ }
+ ZeroizeSecret(code);
+}
void SteamService::SignOut() { Submit(Operation::kClear); }
void SteamService::Cancel(RequestId request) {
@@ -63,6 +80,8 @@ void SteamService::Cancel(RequestId request) {
cancel_->store(true);
++generation_;
events_.clear();
+ if (guard_code_) ZeroizeSecret(*guard_code_);
+ guard_code_.reset();
pending_.erase(std::remove_if(pending_.begin(), pending_.end(),
[](const Job& job) { return job.operation != Operation::kClear; }), pending_.end());
SteamEvent event;
@@ -114,6 +133,7 @@ void SteamService::Run() {
}
try { Execute(*job); }
catch (...) { Emit(*job, Failure(AuthError::kProtocol)); }
+ if (job->credentials) ZeroizeSecret(job->credentials->password);
}
}
@@ -159,6 +179,29 @@ void SteamService::Execute(const Job& job) {
restore_identity = loaded.value()->steam_id;
restore_account_name = loaded.value()->account_name;
result = backend_.Restore(*loaded.value(), *job.cancel);
+ } else if (job.operation == Operation::kCredentials) {
+ if (!job.credentials) { Emit(job, Failure(AuthError::kProtocol)); return; }
+ result = backend_.AuthenticateCredentials(*job.credentials, *job.cancel,
+ [this, &job](const GuardPrompt& prompt) {
+ SteamEvent event;
+ event.kind = prompt.code_rejected ? SteamEventKind::kCodeRejected
+ : prompt.kind == GuardPromptKind::kApproval ? SteamEventKind::kAwaitingApproval
+ : prompt.kind == GuardPromptKind::kEmailCode ? SteamEventKind::kNeedsEmailCode
+ : SteamEventKind::kNeedsAuthenticatorCode;
+ event.email_domain = prompt.email_domain.substr(0, 253);
+ event.code_allowed = prompt.kind != GuardPromptKind::kApproval || prompt.code_allowed;
+ const auto code_kind = prompt.kind == GuardPromptKind::kApproval ? prompt.code_kind : prompt.kind;
+ event.code_is_email = event.code_allowed && code_kind == GuardPromptKind::kEmailCode;
+ Emit(job, std::move(event));
+ },
+ [this, &job]() -> std::optional<std::string> {
+ std::lock_guard<std::mutex> lock(mutex_);
+ if (stopping_ || job.generation != generation_ || !guard_code_) return std::nullopt;
+ auto code = std::move(*guard_code_);
+ guard_code_.reset();
+ return code;
+ });
+ ZeroizeSecret(job.credentials->password);
} else {
result = backend_.AuthenticateQr(*job.cancel, [this, &job](const std::string& url) {
if (url.empty() || url.size() > 4096) return;
diff --git a/src/steam/service.h b/src/steam/service.h
index 3da1c4b..c447c2e 100644
--- a/src/steam/service.h
+++ b/src/steam/service.h
@@ -14,7 +14,10 @@ namespace playden::steam {
using RequestId = std::uint64_t;
enum class SteamEventKind {
kChallenge,
- kAwaitingApproval,
+ kAwaitingApproval, // QR: the code is shown; password: approve in the Steam app (code_allowed: or type a code)
+ kNeedsEmailCode,
+ kNeedsAuthenticatorCode,
+ kCodeRejected, // the typed code was wrong; the same sign-in waits for another (code_is_email says which)
kAuthenticated,
kOfflineSession,
kSignedOut,
@@ -29,6 +32,10 @@ struct SteamEvent {
std::string challenge_url;
std::uint64_t steam_id = 0;
std::string account_name;
+ // Password sign-in's Steam Guard prompts.
+ std::string email_domain;
+ bool code_allowed = false;
+ bool code_is_email = false;
};
// Commands enqueue work and invalidate older results without doing storage or
@@ -41,20 +48,26 @@ class SteamService {
SteamService(const SteamService&) = delete;
SteamService& operator=(const SteamService&) = delete;
RequestId BeginQrSignIn();
+ // The password is moved in and overwritten once the worker has encrypted it, or when the sign-in is
+ // replaced or canceled first.
+ RequestId BeginCredentialSignIn(std::string account_name, std::string password);
+ // A Steam Guard code for the current password sign-in; ignored when none is running.
+ void SubmitGuardCode(std::string code);
RequestId RestoreSession();
void Cancel(RequestId request);
void SignOut();
std::vector<SteamEvent> Pump(std::size_t max_events);
private:
- enum class Operation { kBegin, kRestore, kClear };
+ enum class Operation { kBegin, kRestore, kClear, kCredentials };
struct Job {
Operation operation;
RequestId request;
std::uint64_t generation;
std::shared_ptr<std::atomic<bool>> cancel;
+ std::shared_ptr<Credentials> credentials; // kCredentials; wiped when the last copy goes
};
- RequestId Submit(Operation operation);
+ RequestId Submit(Operation operation, std::shared_ptr<Credentials> credentials = nullptr);
bool Current(const Job& job) const;
void Emit(const Job& job, SteamEvent event);
void Run();
@@ -66,6 +79,7 @@ class SteamService {
std::deque<Job> pending_;
std::shared_ptr<std::atomic<bool>> cancel_;
std::deque<SteamEvent> events_;
+ std::optional<std::string> guard_code_; // for the current request only
RequestId request_ = 0;
std::uint64_t generation_ = 0;
bool stopping_ = false;
diff --git a/tests/auth_client_test.cpp b/tests/auth_client_test.cpp
index 0daf668..ab856a2 100644
--- a/tests/auth_client_test.cpp
+++ b/tests/auth_client_test.cpp
@@ -289,7 +289,219 @@ void Restoration() {
}
}
}
+// Password sign-in. The modulus is synthetic: any odd 2048-bit value encrypts.
+const std::string kModulus = "c" + std::string(510, '3') + "5";
+HttpResponse Key(std::uint64_t timestamp = 1700000000000000ULL) {
+ proto::Writer w; w.AddString(1, kModulus); w.AddString(2, "010001"); w.AddVarint(3, timestamp);
+ return Reply(w);
+}
+HttpResponse BeginCredentials(std::vector<std::pair<int, std::string>> confirmations, float interval = 0.1F) {
+ proto::Writer w; w.AddVarint(1, 123); w.AddString(2, "synthetic-request");
+ std::uint32_t bits; std::memcpy(&bits, &interval, sizeof(bits)); w.AddFixed32(3, bits);
+ for (const auto& [type, message] : confirmations) {
+ proto::Writer c; c.AddVarint(1, static_cast<std::uint64_t>(type)); if (!message.empty()) c.AddString(2, message);
+ w.AddMessage(4, c);
+ }
+ w.AddVarint(5, 76561198000000001ULL);
+ return Reply(w);
+}
+HttpResponse Empty(int result = 1) { proto::Writer w; return Reply(w, result); }
+// The protobuf bytes a request carried, from its query string (GET) or form body (POST).
+std::string Sent(const HttpRequest& request) {
+ std::string form = request.method == HttpMethod::kGet ? request.url.substr(request.url.find('?') + 1)
+ : std::string(request.body.begin(), request.body.end());
+ form = form.substr(std::strlen("input_protobuf_encoded="));
+ std::string b64;
+ for (std::size_t i = 0; i < form.size(); ++i) {
+ if (form[i] == '%') { const auto hex = form.substr(i + 1, 2); b64 += hex == "2B" ? '+' : hex == "2F" ? '/' : '='; i += 2; }
+ else b64 += form[i];
+ }
+ const std::string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+ std::string out; unsigned bits = 0, count = 0;
+ for (char c : b64) {
+ if (c == '=') break;
+ bits = (bits << 6) | static_cast<unsigned>(alphabet.find(c)); count += 6;
+ if (count >= 8) { count -= 8; out += static_cast<char>((bits >> count) & 0xff); }
+ }
+ return out;
+}
+struct Guard {
+ std::vector<GuardPrompt> prompts;
+ std::deque<std::optional<std::string>> codes;
+ GuardPromptCallback Prompt() { return [this](const GuardPrompt& p) { prompts.push_back(p); }; }
+ GuardCodeSource Code() {
+ return [this]() -> std::optional<std::string> {
+ if (codes.empty()) return std::nullopt;
+ auto c = codes.front(); codes.pop_front(); return c;
+ };
+ }
+};
+AuthResult SignIn(Fixture& f, Guard& g, std::string* password_after = nullptr) {
+ AuthClient c(f.Hooks());
+ playden::steam::Credentials credentials{"synthetic_account", "hunter2-synthetic"};
+ auto r = c.AuthenticateCredentials(credentials, f.cancel, g.Prompt(), g.Code());
+ if (password_after) *password_after = credentials.password;
+ return r;
+}
+constexpr int kDeviceConfirmation = 4, kEmailCode = 2, kDeviceCode = 3;
+void CredentialsWithoutGuard() {
+ Fixture f; Guard g; std::string left = "?";
+ f.replies = {Key(), BeginCredentials({}), Success()};
+ auto r = SignIn(f, g, &left);
+ assert(r.error == AuthError::kNone && r.session && r.session->steam_id == 76561198000000001ULL);
+ assert(left.empty() && g.prompts.empty() && f.requests.size() == 3);
+ const auto& key = f.requests[0];
+ assert(key.method == HttpMethod::kGet && key.body.empty());
+ assert(key.url.rfind("https://api.steampowered.com/IAuthenticationService/GetPasswordRSAPublicKey/v1/?input_protobuf_encoded=", 0) == 0);
+ assert(Sent(key).find("synthetic_account") != std::string::npos);
+ const auto& begin = f.requests[1];
+ assert(begin.method == HttpMethod::kPost &&
+ begin.url == "https://api.steampowered.com/IAuthenticationService/BeginAuthSessionViaCredentials/v1/");
+ const auto sent = Sent(begin);
+ assert(sent.find("synthetic_account") != std::string::npos && sent.find("Playden (PS5)") != std::string::npos);
+ // Only the encrypted password goes out.
+ for (const auto& request : f.requests) {
+ assert(Sent(request).find("hunter2-synthetic") == std::string::npos);
+ assert(request.url.find("hunter2") == std::string::npos);
+ }
+ assert(f.waits == std::vector<std::uint32_t>({1000}));
+}
+void CredentialsEmailCode() {
+ Fixture f; Guard g;
+ g.codes = {std::nullopt, std::string("WRONG"), std::nullopt, std::string("AB12C")};
+ f.replies = {Key(), BeginCredentials({{kEmailCode, "example.invalid"}}), Empty(65), Empty(), Success()};
+ auto r = SignIn(f, g);
+ assert(r.error == AuthError::kNone && r.session);
+ assert(g.prompts.size() == 2);
+ assert(g.prompts[0].kind == GuardPromptKind::kEmailCode && g.prompts[0].email_domain == "example.invalid" &&
+ !g.prompts[0].code_rejected);
+ assert(g.prompts[1].kind == GuardPromptKind::kEmailCode && g.prompts[1].code_rejected &&
+ g.prompts[1].email_domain == "example.invalid");
+ // No polling while it waits for a code: one check, then the wrong code, then a check, the right code and a poll.
+ assert(f.waits == std::vector<std::uint32_t>({250, 250, 1000}));
+ assert(f.requests.size() == 5);
+ assert(f.requests[2].url.find("UpdateAuthSessionWithSteamGuardCode") != std::string::npos);
+ const auto update = Sent(f.requests[3]);
+ assert(update.find("AB12C") != std::string::npos && update.back() == kEmailCode);
+}
+void CredentialsAuthenticatorCode() {
+ Fixture f; Guard g; g.codes = {std::string("XY34Z")};
+ f.replies = {Key(), BeginCredentials({{kDeviceCode, ""}}), Empty(), Success()};
+ auto r = SignIn(f, g);
+ assert(r.error == AuthError::kNone);
+ assert(g.prompts.size() == 1 && g.prompts[0].kind == GuardPromptKind::kAuthenticatorCode &&
+ g.prompts[0].email_domain.empty());
+ const auto update = Sent(f.requests[2]);
+ assert(update.find("XY34Z") != std::string::npos && update.back() == kDeviceCode);
+ // A code Steam already took (DuplicateRequest) is accepted as well.
+ Fixture d; Guard dg; dg.codes = {std::string("XY34Z")};
+ d.replies = {Key(), BeginCredentials({{kDeviceCode, ""}}), Empty(29), Success()};
+ assert(SignIn(d, dg).error == AuthError::kNone);
+}
+void CredentialsApproval() {
+ {
+ Fixture f; Guard g;
+ f.replies = {Key(), BeginCredentials({{kDeviceConfirmation, ""}, {kDeviceCode, ""}}), Empty(), Success()};
+ auto r = SignIn(f, g);
+ assert(r.error == AuthError::kNone);
+ assert(g.prompts.size() == 1 && g.prompts[0].kind == GuardPromptKind::kApproval && g.prompts[0].code_allowed &&
+ g.prompts[0].code_kind == GuardPromptKind::kAuthenticatorCode);
+ assert(f.waits == std::vector<std::uint32_t>({1000, 1000}) && f.requests.size() == 4);
+ }
+ {
+ // Approval offered, a code typed instead after one poll.
+ Fixture f; Guard g; g.codes = {std::nullopt, std::string("XY34Z")};
+ f.replies = {Key(), BeginCredentials({{kDeviceConfirmation, ""}, {kDeviceCode, ""}}), Empty(), Empty(), Success()};
+ auto r = SignIn(f, g);
+ assert(r.error == AuthError::kNone && f.requests.size() == 5);
+ assert(f.requests[3].url.find("UpdateAuthSessionWithSteamGuardCode") != std::string::npos);
+ }
+ {
+ // Approval only, without a code: email domain shown for an email confirmation.
+ Fixture f; Guard g; g.codes = {std::string("IGNORED")};
+ f.replies = {Key(), BeginCredentials({{5, "example.invalid"}}), Success()};
+ assert(SignIn(f, g).error == AuthError::kNone && f.requests.size() == 3);
+ assert(g.prompts.size() == 1 && g.prompts[0].kind == GuardPromptKind::kApproval && !g.prompts[0].code_allowed &&
+ g.prompts[0].email_domain == "example.invalid");
+ }
+}
+void CredentialsFailures() {
+ for (auto [result, expected] : {std::pair{5, AuthError::kInvalidPassword}, std::pair{84, AuthError::kRateLimited},
+ std::pair{63, AuthError::kSignInRefused}, std::pair{27, AuthError::kSignInTimedOut}}) {
+ Fixture f; Guard g; std::string left = "?";
+ f.replies = {Key(), Empty(result)};
+ assert(SignIn(f, g, &left).error == expected && left.empty() && g.prompts.empty());
+ Fixture k; Guard kg; k.replies = {Empty(result)};
+ assert(SignIn(k, kg, &left).error == expected && left.empty());
+ }
+ {
+ Fixture f; Guard g; std::string left = "?";
+ auto bad = Key(); bad.body = {0xff}; f.replies = {bad};
+ assert(SignIn(f, g, &left).error == AuthError::kProtocol && left.empty());
+ proto::Writer w; w.AddString(1, "zz"); w.AddString(2, "010001"); w.AddVarint(3, 1);
+ Fixture h; h.replies = {Reply(w)}; assert(SignIn(h, g, &left).error == AuthError::kProtocol && h.requests.size() == 1);
+ }
+ {
+ // A guard type Playden cannot answer (machine token) refuses the sign-in.
+ Fixture f; Guard g; f.replies = {Key(), BeginCredentials({{6, ""}})};
+ assert(SignIn(f, g).error == AuthError::kSignInRefused && g.prompts.empty());
+ }
+ {
+ // A wrong code that Steam refuses differently ends the sign-in.
+ Fixture f; Guard g; g.codes = {std::string("AB12C")};
+ f.replies = {Key(), BeginCredentials({{kEmailCode, "example.invalid"}}), Empty(84)};
+ assert(SignIn(f, g).error == AuthError::kRateLimited);
+ }
+ {
+ // Polls that Steam stops (session expired) time out.
+ Fixture f; Guard g; f.replies = {Key(), BeginCredentials({{kDeviceConfirmation, ""}}), Empty(9)};
+ assert(SignIn(f, g).error == AuthError::kSignInTimedOut);
+ }
+ {
+ Fixture f; Guard g; std::string left = "?";
+ AuthClient c(f.Hooks());
+ playden::steam::Credentials empty{"synthetic_account", ""};
+ assert(c.AuthenticateCredentials(empty, f.cancel, g.Prompt(), g.Code()).error == AuthError::kProtocol);
+ playden::steam::Credentials nameless{"", "secret"};
+ assert(c.AuthenticateCredentials(nameless, f.cancel, g.Prompt(), g.Code()).error == AuthError::kProtocol &&
+ nameless.password.empty() && f.requests.empty());
+ }
+}
+void CredentialsCancelAndDeadline() {
+ {
+ Fixture f; Guard g; std::string left = "?"; f.cancel = true;
+ assert(SignIn(f, g, &left).error == AuthError::kCanceled && f.requests.empty() && left.empty());
+ }
+ {
+ Fixture f; Guard g; f.cancel_on_response = true; f.replies = {Key()};
+ assert(SignIn(f, g).error == AuthError::kCanceled && f.requests.size() == 1);
+ }
+ for (int guard : {kEmailCode, kDeviceConfirmation}) {
+ // Waiting for a code, or polling for approval.
+ Fixture f; Guard g; f.cancel_on_wait = true; f.replies = {Key(), BeginCredentials({{guard, ""}})};
+ assert(SignIn(f, g).error == AuthError::kCanceled && f.requests.size() == 2 && g.prompts.size() == 1);
+ }
+ {
+ // A code never arrives: the sign-in times out after ten minutes without polling Steam.
+ Fixture f; Guard g; f.replies = {Key(), BeginCredentials({{kEmailCode, "example.invalid"}})};
+ assert(SignIn(f, g).error == AuthError::kSignInTimedOut && f.requests.size() == 2 && f.clock >= 600000);
+ }
+ {
+ // Approval never arrives.
+ Fixture f; Guard g; f.replies = {Key(), BeginCredentials({{kDeviceConfirmation, ""}})};
+ for (int i = 0; i < 700; ++i) f.replies.push_back(Empty());
+ assert(SignIn(f, g).error == AuthError::kSignInTimedOut && f.clock >= 600000 && f.requests.size() < 700);
+ }
+ {
+ // The approved account must be the one that signed in.
+ Fixture f; Guard g; f.replies = {Key(), BeginCredentials({}), Success(Token("76561198000000002"), Token("76561198000000002"))};
+ assert(SignIn(f, g).error == AuthError::kProtocol);
+ }
+}
+
int main() {
+ CredentialsWithoutGuard(); CredentialsEmailCode(); CredentialsAuthenticatorCode(); CredentialsApproval();
+ CredentialsFailures(); CredentialsCancelAndDeadline();
QrSuccessAndReplacement(); FailuresAndDeadline(); HeadersAndTokens(); DeadlineAndCancellationEdges(); Restoration(); AccountNames(); FailedReplacementKeepsSavedSession();
std::cout << "auth_client_test passed\n";
}
diff --git a/tests/auth_messages_test.cpp b/tests/auth_messages_test.cpp
index fb93ce7..9e5aef0 100644
--- a/tests/auth_messages_test.cpp
+++ b/tests/auth_messages_test.cpp
@@ -152,6 +152,50 @@ void TestOptionalSchemaFieldsKeepPresence() {
assert(!response.refresh_token.has_value());
}
+void TestCredentialMessages(const std::string& root) {
+ auth::GetPasswordRsaPublicKeyRequest key_request;
+ key_request.account_name = "synthetic_account";
+ ExpectGoldenEncode(root + "/rsa_key_request.pb", key_request);
+
+ auth::GetPasswordRsaPublicKeyResponse key;
+ assert(auth::Decode(ReadFile(root + "/rsa_key_response.pb"), &key).ok());
+ assert(key.publickey_mod == "c3a1f0");
+ assert(key.publickey_exp == "010001");
+ assert(key.timestamp == 1700000000000000ULL);
+
+ auth::BeginAuthSessionViaCredentialsRequest begin;
+ begin.device_details.device_friendly_name = "Playden Synthetic Device";
+ begin.device_details.platform_type = auth::PlatformType::kSteamClient;
+ begin.account_name = "synthetic_account";
+ begin.encrypted_password = "c3ludGhldGlj";
+ begin.encryption_timestamp = 1700000000000000ULL;
+ ExpectGoldenEncode(root + "/credentials_request.pb", begin);
+
+ auth::BeginAuthSessionViaCredentialsResponse session;
+ assert(auth::Decode(ReadFile(root + "/credentials_response.pb"), &session).ok());
+ assert(session.client_id == 0x0102030405060708ULL);
+ assert(session.request_id == std::vector<std::uint8_t>({0x10, 0x20, 0x30, 0x40, 0x50}));
+ assert(session.interval == 0.1f);
+ assert(session.allowed_confirmations.size() == 2);
+ assert(session.allowed_confirmations[0].confirmation_type == auth::GuardType::kDeviceConfirmation);
+ assert(session.allowed_confirmations[1].confirmation_type == auth::GuardType::kEmailCode);
+ assert(session.allowed_confirmations[1].associated_message == "example.invalid");
+ assert(session.steam_id == 76561197960287930ULL);
+ assert(session.weak_token == "synthetic.weak.token");
+ assert(session.extended_error_message == "synthetic extended error");
+
+ auth::UpdateAuthSessionWithSteamGuardCodeRequest code;
+ code.client_id = 0x0102030405060708ULL;
+ code.steam_id = 76561197960287930ULL;
+ code.code = "AB12C";
+ code.code_type = auth::GuardType::kEmailCode;
+ ExpectGoldenEncode(root + "/guard_code_request.pb", code);
+
+ // steamid is a varint in this response (fixed64 in the guard code request).
+ const std::vector<std::uint8_t> fixed_steam_id = {0x29, 1, 0, 0, 0, 0, 0, 0, 0};
+ assert(auth::Decode(fixed_steam_id, &session).error == proto::DecodeError::kWrongWireType);
+}
+
} // namespace
int main(int argc, char** argv) {
@@ -164,6 +208,7 @@ int main(int argc, char** argv) {
TestDecodeFailureDoesNotPublishPartialSecrets();
TestNestedDepthLimitIsEnforced(root);
TestOptionalSchemaFieldsKeepPresence();
+ TestCredentialMessages(root);
std::puts("auth_messages_test passed");
return 0;
}
diff --git a/tests/homebrew_account_test.cpp b/tests/homebrew_account_test.cpp
index ac832f7..ced8cc4 100644
--- a/tests/homebrew_account_test.cpp
+++ b/tests/homebrew_account_test.cpp
@@ -55,6 +55,37 @@ class Backend final : public AuthBackend {
return {error,error == AuthError::kNone ? std::optional<StoredSession>(Session()) : std::nullopt};
}
AuthResult Restore(const StoredSession& s,const std::atomic<bool>&) override { return {error,error == AuthError::kNone ? std::optional<StoredSession>(s) : std::nullopt}; }
+ // Password sign-in by account name: "wrong" is refused, "email-user" needs an email code ("WRONG" is
+ // rejected), "approve" waits for approval (or an app code); any other name signs in.
+ std::atomic<int> credential_calls{0};
+ std::atomic<bool> credential_canceled{false};
+ std::mutex seen_mutex;
+ std::string password_seen;
+ AuthResult AuthenticateCredentials(Credentials& c,const std::atomic<bool>& cancel,const GuardPromptCallback& prompt,
+ const GuardCodeSource& code) override {
+ ++credential_calls;
+ { std::lock_guard<std::mutex> lock(seen_mutex); password_seen=c.password; }
+ ZeroizeSecret(c.password);
+ if (c.account_name=="wrong") return {AuthError::kInvalidPassword,{}};
+ GuardPrompt shown;
+ if (c.account_name=="approve") { shown.kind=GuardPromptKind::kApproval; shown.code_allowed=true; }
+ else if (c.account_name=="email-user") { shown.kind=GuardPromptKind::kEmailCode; shown.email_domain="example.invalid"; }
+ else return {AuthError::kNone,Session()};
+ prompt(shown);
+ const auto deadline=std::chrono::steady_clock::now()+3s;
+ while (!cancel && !approve && std::chrono::steady_clock::now()<deadline) {
+ if (auto typed=code()) {
+ if (*typed=="WRONG") {
+ GuardPrompt again; again.kind=GuardPromptKind::kEmailCode; again.email_domain="example.invalid"; again.code_rejected=true;
+ prompt(again); continue;
+ }
+ return {AuthError::kNone,Session()};
+ }
+ std::this_thread::sleep_for(1ms);
+ }
+ if (cancel) { credential_canceled=true; return {AuthError::kCanceled,{}}; }
+ return {AuthError::kNone,Session()};
+ }
};
class LibraryBackendFixture final : public LibraryBackend {
public:
@@ -110,6 +141,110 @@ void OpenSettings(Simulation& model) {
}
void SignOut(Simulation& model) { OpenSettings(model); Choose(model,"signout-confirm"); Choose(model,"confirm-destructive"); }
void Connect(Simulation& model) { Choose(model,"connect"); }
+// Opens a sign-in field, types into it and commits it.
+void Type(Simulation& model,const std::string& action,const std::string& text) {
+ Choose(model,action); assert(model.state().editor.active);
+ assert(model.action("clear")); model.text(text); assert(model.action("done")); assert(!model.state().editor.active);
+}
+void PasswordSignIn(Simulation& model,const std::string& account,const std::string& password) {
+ Type(model,"signin-account",account); Type(model,"signin-password",password); Choose(model,"signin-submit");
+}
+void PasswordSignInWithGuardCode() {
+ Simulation model({}, {},ModelMode::Live); Repository repo; Backend backend;
+ Controller controller(model,backend,repo);
+ Wait(controller,[&]{return model.state().account.authentication==AuthState::SignedOut;});
+ // QR first, as before; the row below switches to the password form and stops the QR sign-in.
+ Connect(model); Wait(controller,[&]{return !model.state().account.challenge_url.empty();});
+ assert(model.state().sign_in.step==SignInStep::Qr);
+ Choose(model,"signin-password-mode"); controller.Tick();
+ assert(model.state().sign_in.step==SignInStep::Password && model.state().navigation.focus_key=="signin-account");
+ Wait(controller,[&]{return backend.calls==1;});
+ // Sign in stays disabled until both fields are filled.
+ Type(model,"signin-account","email-user");
+ const auto submit=std::find_if(model.view().rows.begin(),model.view().rows.end(),[](const ViewRow& r){return r.key=="signin-submit";});
+ assert(submit!=model.view().rows.end() && !submit->enabled);
+ Type(model,"signin-password","hunter2-fixture");
+ assert(model.snapshot().find("hunter2")==std::string::npos);
+ Choose(model,"signin-submit");
+ assert(model.state().sign_in.password.empty() && model.state().sign_in.step==SignInStep::Submitting);
+ Wait(controller,[&]{return model.state().sign_in.step==SignInStep::EmailCode;});
+ { std::lock_guard<std::mutex> lock(backend.seen_mutex); assert(backend.password_seen=="hunter2-fixture"); }
+ assert(model.state().sign_in.email_domain=="example.invalid" && model.state().navigation.focus_key=="guard-code");
+ assert(model.view().subtitle=="Enter the code sent to …@example.invalid.");
+ // Codes are five characters, uppercase, from the on-screen or a USB keyboard alike.
+ Type(model,"guard-code","wrong!x"); assert(model.state().sign_in.code=="WRONG");
+ Choose(model,"guard-submit");
+ Wait(controller,[&]{return model.state().sign_in.code_rejected;});
+ assert(model.state().sign_in.code.empty() && model.view().subtitle.rfind("That code was not right.",0)==0);
+ Type(model,"guard-code","ab12c"); Choose(model,"guard-submit");
+ Wait(controller,[&]{return model.state().account.authentication==AuthState::SignedIn;});
+ assert(model.state().sign_in_password && model.ExportPreferences().steam_sign_in_password);
+ assert(repo.Load().value() && backend.credential_calls==1);
+ // After a sign-out, Connect opens the password form without starting a QR sign-in.
+ SignOut(model);
+ Wait(controller,[&]{return model.state().account.authentication==AuthState::SignedOut;});
+ Connect(model); controller.Tick();
+ assert(model.state().navigation.route==Route::SignIn && model.state().sign_in.step==SignInStep::Password);
+ assert(model.state().sign_in.account_name=="email-user" && model.state().navigation.focus_key=="signin-password");
+ std::this_thread::sleep_for(20ms); controller.Tick();
+ assert(backend.calls==1 && model.state().account.authentication==AuthState::Waiting);
+ // A QR sign-in remembers QR again.
+ Choose(model,"signin-qr-mode"); backend.approve=true;
+ Wait(controller,[&]{return model.state().account.authentication==AuthState::SignedIn;});
+ assert(!model.state().sign_in_password && backend.calls==2);
+ controller.Shutdown();
+}
+void PasswordFailuresAndCancel() {
+ Simulation model({}, {},ModelMode::Live); Repository repo; Backend backend;
+ Controller controller(model,backend,repo);
+ Wait(controller,[&]{return model.state().account.authentication==AuthState::SignedOut;});
+ Connect(model); Choose(model,"signin-password-mode"); controller.Tick();
+ // A refused password returns to the form with the reason; the name stays and the password goes.
+ PasswordSignIn(model,"wrong","bad-password");
+ Wait(controller,[&]{return model.state().account.authentication==AuthState::Failed;});
+ assert(model.state().navigation.route==Route::SignIn && model.state().sign_in.step==SignInStep::Password);
+ assert(model.state().sign_in.account_name=="wrong" && model.state().sign_in.password.empty());
+ assert(model.view().subtitle.find("did not accept the account name or password")!=std::string::npos);
+ assert(model.state().navigation.focus_key=="signin-password" && !model.state().sign_in_password);
+ // Approval in the app, with a code allowed; Cancel stops the sign-in and wipes the form.
+ PasswordSignIn(model,"approve","pw");
+ Wait(controller,[&]{return model.state().sign_in.step==SignInStep::Approval;});
+ assert(model.state().sign_in.code_allowed && model.view().subtitle=="Approve the sign-in in the Steam Mobile app.");
+ Choose(model,"guard-use-code");
+ assert(model.state().sign_in.code_entry && model.state().navigation.focus_key=="guard-code");
+ // A wrong typed code keeps the approval: the screen says both still work.
+ Type(model,"guard-code","wrong"); Choose(model,"guard-submit");
+ Wait(controller,[&]{return model.state().sign_in.code_rejected;});
+ assert(model.state().sign_in.step==SignInStep::Approval && model.state().sign_in.code_entry);
+ assert(model.view().subtitle.find("also approve")!=std::string::npos);
+ // Tab switching does not leave the sign-in half done.
+ assert(model.action("r1") && model.state().navigation.route==Route::SignIn);
+ Choose(model,"guard-cancel"); controller.Tick();
+ Wait(controller,[&]{return backend.credential_canceled.load();});
+ Wait(controller,[&]{return model.state().account.authentication==AuthState::Cancelled;});
+ assert(model.state().navigation.route==Route::Startup && model.state().sign_in.password.empty());
+ // Approval arriving from the phone.
+ Connect(model); Choose(model,"signin-password-mode"); controller.Tick();
+ PasswordSignIn(model,"approve","pw");
+ Wait(controller,[&]{return model.state().sign_in.step==SignInStep::Approval;});
+ backend.approve=true;
+ Wait(controller,[&]{return model.state().account.authentication==AuthState::SignedIn;});
+ assert(model.state().sign_in_password);
+ // Signing in again opens the remembered form; a refused password keeps the form, Cancel keeps the account.
+ backend.approve=false;
+ OpenSettings(model); Choose(model,"account"); Choose(model,"account-reauth"); controller.Tick();
+ assert(model.state().sign_in.step==SignInStep::Password && model.state().account.id=="12345");
+ PasswordSignIn(model,"wrong","bad");
+ Wait(controller,[&]{return model.state().account.authentication==AuthState::Failed;});
+ assert(model.state().navigation.route==Route::SignIn && model.state().account.id=="12345");
+ Choose(model,"signin-qr-mode"); controller.Tick();
+ Wait(controller,[&]{return !model.state().account.challenge_url.empty();});
+ assert(model.state().account.id=="12345");
+ Choose(model,"qr-cancel"); controller.Tick();
+ Wait(controller,[&]{return model.state().account.authentication==AuthState::SignedIn;});
+ assert(repo.clears==0 && model.state().account.id=="12345");
+ controller.Shutdown();
+}
void ChallengeAndCancel() {
Simulation model({}, {},ModelMode::Live); Repository repo; Backend backend; backend.ignore_cancel=true;
Controller controller(model,backend,repo);
@@ -366,4 +501,4 @@ void SlowLicenseCheckShowsAfterAFewSeconds() {
}
std::filesystem::remove_all(root);
}
-int main() { SlowLicenseCheckShowsAfterAFewSeconds(); CanceledStorageRetryKeepsSavedSessionIntent(); RevokedSessionCleanupRetriesAfterStorageRecovery(); StorageFailureKeepsVisibleAccount(); StorageFailureRetriesSavedSession(); ChallengeAndCancel(); AuthenticationRestoreAndSignOut(); FailedClearDoesNotSwitch(); SignInAgainKeepsTheAccount(); ExitHonorsClearWithoutStartingNewQr(); StorageFailureAndRevocation(); ConnectedLibraryAndOfflineRestart(); ShutdownClearsLibraryBeforeSession(); RepeatedClearPreservesFirstIntent(); }
+int main() { PasswordSignInWithGuardCode(); PasswordFailuresAndCancel(); SlowLicenseCheckShowsAfterAFewSeconds(); CanceledStorageRetryKeepsSavedSessionIntent(); RevokedSessionCleanupRetriesAfterStorageRecovery(); StorageFailureKeepsVisibleAccount(); StorageFailureRetriesSavedSession(); ChallengeAndCancel(); AuthenticationRestoreAndSignOut(); FailedClearDoesNotSwitch(); SignInAgainKeepsTheAccount(); ExitHonorsClearWithoutStartingNewQr(); StorageFailureAndRevocation(); ConnectedLibraryAndOfflineRestart(); ShutdownClearsLibraryBeforeSession(); RepeatedClearPreservesFirstIntent(); }
diff --git a/tests/homebrew_simulation_test.cpp b/tests/homebrew_simulation_test.cpp
index f766948..5026bb5 100644
--- a/tests/homebrew_simulation_test.cpp
+++ b/tests/homebrew_simulation_test.cpp
@@ -945,6 +945,156 @@ void t52_recipe_values_in_game_settings(const std::filesystem::path& fixtures, c
check(simulation.known_problem(900003), "T52 a refused game shows Known problems");
}
+void type_into(playden::homebrew::Simulation& simulation, const std::string& key, const std::string& text) {
+ activate(simulation, key);
+ check(simulation.state().editor.active, "sign-in field opens the keyboard");
+ simulation.action("clear");
+ simulation.text(text);
+ simulation.action("done");
+}
+
+void t15_password_sign_in(const std::filesystem::path& fixtures, const std::filesystem::path& profile) {
+ using playden::homebrew::SignInStep;
+ playden::homebrew::Simulation simulation(fixtures, profile);
+ simulation.scenario("signed-out");
+ simulation.action("cross");
+ check(simulation.state().sign_in.step == SignInStep::Qr, "T15 the QR code is the default method");
+ check(find_row(simulation, "signin-password-mode") != nullptr, "T15 the QR screen offers the password form");
+ activate(simulation, "signin-password-mode");
+ check(simulation.state().sign_in.step == SignInStep::Password && find_row(simulation, "signin-account") &&
+ find_row(simulation, "signin-password") && find_row(simulation, "signin-qr-mode"),
+ "T15 the password form has its fields and the way back");
+ check(!find_row(simulation, "signin-submit")->enabled, "T15 Sign in waits for both fields");
+ type_into(simulation, "signin-account", "email");
+ check(!find_row(simulation, "signin-submit")->enabled, "T15 Sign in still waits for the password");
+
+ // The password shows as dots in the form, the keyboard and the snapshot; Show reveals it on the keyboard only.
+ activate(simulation, "signin-password");
+ check(simulation.state().editor.secret && !simulation.state().editor.revealed, "T15 the password field is secret");
+ simulation.text("p\xc3\xa4ss");
+ check(simulation.view().subtitle == "\u2022\u2022\u2022\u2022", "T15 the keyboard shows dots");
+ check(simulation.snapshot().find("p\xc3\xa4ss") == std::string::npos &&
+ simulation.snapshot().find("<redacted>") != std::string::npos,
+ "T15 the snapshot redacts the password");
+ for (int i = 0; i < 6; ++i) simulation.action("down");
+ for (int i = 0; i < 9; ++i) simulation.action("left");
+ for (int i = 0; i < 3; ++i) simulation.action("right");
+ simulation.action("cross");
+ check(simulation.state().editor.revealed && simulation.view().subtitle == "p\xc3\xa4ss", "T15 Show reveals the password");
+ simulation.action("cross");
+ check(!simulation.state().editor.revealed, "T15 Hide masks it again");
+ simulation.action("right"); simulation.action("right");
+ check(simulation.state().editor.focus_key == 5, "T15 a password's bottom row has six keys");
+ simulation.action("done");
+ check(find_row(simulation, "signin-password")->value == "\u2022\u2022\u2022\u2022", "T15 the form shows dots");
+ simulation.action("r1");
+ check(simulation.state().navigation.route == playden::homebrew::Route::SignIn &&
+ !simulation.state().sign_in.password.empty(),
+ "T15 R1 does not leave the password form");
+ simulation.action("route:home");
+ check(simulation.state().sign_in.password.empty(), "T15 leaving by route wipes the password");
+ simulation.scenario("signed-out");
+ simulation.action("cross");
+ activate(simulation, "signin-password-mode");
+ check(simulation.state().sign_in.account_name == "email", "T15 the account name stays");
+ type_into(simulation, "signin-password", "p\xc3\xa4ss");
+ check(simulation.snapshot().find("p\xc3\xa4ss") == std::string::npos, "T15 the form's password is not snapshotted");
+ activate(simulation, "signin-password");
+ check(!simulation.state().editor.revealed, "T15 reopening the field masks it");
+ simulation.action("circle");
+ check(find_row(simulation, "signin-submit")->enabled, "T15 Sign in is enabled with both fields");
+
+ // Email code: a wrong code asks again; the right one signs in and is remembered.
+ activate(simulation, "signin-submit");
+ check(simulation.state().sign_in.step == SignInStep::EmailCode && simulation.state().sign_in.password.empty(),
+ "T15 Steam asks for an email code and the password is gone");
+ check(simulation.view().subtitle == "Enter the code sent to …@example.invalid.", "T15 the email prompt names the domain");
+ type_into(simulation, "guard-code", "0 0-0000");
+ check(simulation.state().sign_in.code == "00000", "T15 codes keep five letters or digits");
+ activate(simulation, "guard-submit");
+ check(simulation.state().sign_in.code_rejected && simulation.view().subtitle.rfind("That code was not right.", 0) == 0,
+ "T15 a wrong code shows inline");
+ type_into(simulation, "guard-code", "ab12c");
+ activate(simulation, "guard-submit");
+ check(simulation.state().account.authentication == playden::homebrew::AuthState::Syncing &&
+ simulation.state().sign_in_password,
+ "T15 the right code signs in and remembers the password method");
+
+ // The next sign-in opens the form; the toggle goes back to QR.
+ simulation.scenario("signed-out");
+ simulation.action("focus:startup-connect"); simulation.action("cross");
+ check(simulation.state().sign_in.step == SignInStep::Password, "T15 the remembered method opens");
+ activate(simulation, "signin-qr-mode");
+ check(simulation.state().sign_in.step == SignInStep::Qr &&
+ simulation.state().account.authentication == playden::homebrew::AuthState::Waiting,
+ "T15 Use QR code instead shows the QR code");
+ activate(simulation, "signin-password-mode");
+
+ // Authenticator code and approval with a code allowed.
+ type_into(simulation, "signin-account", "mobile");
+ type_into(simulation, "signin-password", "pw");
+ activate(simulation, "signin-submit");
+ check(simulation.state().sign_in.step == SignInStep::AuthenticatorCode &&
+ simulation.view().subtitle == "Enter the code from the Steam Mobile app.",
+ "T15 Steam asks for the app's code");
+ activate(simulation, "guard-cancel");
+ check(simulation.state().navigation.route == playden::homebrew::Route::Startup, "T15 Cancel leaves the sign-in");
+ simulation.action("focus:startup-connect"); simulation.action("cross");
+ type_into(simulation, "signin-account", "approve");
+ type_into(simulation, "signin-password", "pw");
+ activate(simulation, "signin-submit");
+ check(simulation.state().sign_in.step == SignInStep::Approval && find_row(simulation, "guard-use-code") &&
+ simulation.view().subtitle == "Approve the sign-in in the Steam Mobile app.",
+ "T15 approval waits, with a code allowed");
+ activate(simulation, "guard-use-code");
+ check(find_row(simulation, "guard-code") && simulation.state().navigation.focus_key == "guard-code",
+ "T15 Type a code instead opens the code field");
+
+ // Cancel clears the password; a refused password returns to the form with the reason.
+ simulation.action("circle");
+ simulation.action("focus:startup-connect"); simulation.action("cross");
+ type_into(simulation, "signin-account", "wrong");
+ type_into(simulation, "signin-password", "secret");
+ simulation.action("circle");
+ check(simulation.state().sign_in.password.empty(), "T15 Cancel clears the password");
+ simulation.action("focus:startup-connect"); simulation.action("cross");
+ check(find_row(simulation, "signin-password")->value.empty() &&
+ simulation.state().sign_in.account_name == "wrong",
+ "T15 the form comes back with the name only");
+ type_into(simulation, "signin-password", "secret");
+ activate(simulation, "signin-submit");
+ check(simulation.state().sign_in.step == SignInStep::Password && simulation.state().sign_in.password.empty() &&
+ simulation.view().subtitle.find("did not accept") != std::string::npos,
+ "T15 a refused password shows why");
+}
+
+// The PS5's system keyboard: each opened field is offered once, and its accepted text commits like Done.
+void t16_system_keyboard_text(const std::filesystem::path& fixtures, const std::filesystem::path& profile) {
+ using playden::homebrew::SignInStep;
+ playden::homebrew::Simulation simulation(fixtures, profile);
+ simulation.scenario("signed-out");
+ simulation.action("cross");
+ activate(simulation, "signin-password-mode");
+ activate(simulation, "signin-account");
+ const auto first = simulation.state().editor.serial;
+ simulation.SubmitEditorText("email");
+ check(!simulation.state().editor.active && simulation.state().sign_in.account_name == "email" &&
+ simulation.state().navigation.focus_key == "signin-password",
+ "T16 accepted text commits the field");
+ activate(simulation, "signin-password");
+ check(simulation.state().editor.serial != first && simulation.state().editor.secret,
+ "T16 each field opens with a new serial and says it is secret");
+ simulation.SubmitEditorText("hunter2");
+ check(simulation.state().sign_in.password == "hunter2" && simulation.state().editor.value.empty(),
+ "T16 the password is taken and the editor keeps no copy");
+ activate(simulation, "signin-submit");
+ activate(simulation, "guard-code");
+ simulation.SubmitEditorText("ab 12c9");
+ check(simulation.state().sign_in.code == "AB12C", "T16 codes are normalized from the system keyboard too");
+ simulation.SubmitEditorText("ignored");
+ check(simulation.state().sign_in.code == "AB12C", "T16 text with no open field is ignored");
+}
+
int main(int argc, char** argv) {
check(argc == 2, "fixture directory argument is required");
const std::filesystem::path fixtures(argv[1]);
@@ -988,6 +1138,10 @@ int main(int argc, char** argv) {
clean();
t14_tab_bar_from_the_top_of_a_page(fixtures, profile);
clean();
+ t15_password_sign_in(fixtures, profile);
+ clean();
+ t16_system_keyboard_text(fixtures, profile);
+ clean();
public_contract_and_snapshot(fixtures, profile);
std::error_code error;
std::filesystem::remove(profile, error);
diff --git a/tests/homebrew_usb_keyboard_test.cpp b/tests/homebrew_usb_keyboard_test.cpp
index d114912..6be6050 100644
--- a/tests/homebrew_usb_keyboard_test.cpp
+++ b/tests/homebrew_usb_keyboard_test.cpp
@@ -78,6 +78,15 @@ int main() {
CHECK(Typed(input.Update(Keys({0x28}), true, now += 1000000)).empty());
CHECK(Typed(input.Update(Keys({}), true, now += 20000)).empty());
+ // Keys the system keyboard read: Enter held when it closes is not a new press, and a held
+ // letter does not keep repeating.
+ CHECK(Typed(input.Update(Keys({0x07}), true, now += 20000)) == "d");
+ input.Follow(Keys({0x07, 0x28}));
+ CHECK(Typed(input.Update(Keys({0x07, 0x28}), false, now += 1000000)).empty());
+ CHECK(Typed(input.Update(Keys({}), false, now += 20000)).empty());
+ CHECK(Typed(input.Update(Keys({0x28}), false, now += 20000)) == "<cross>");
+ CHECK(Typed(input.Update(Keys({}), false, now += 20000)).empty());
+
// Elsewhere the keys move around Playden, as in the desktop build.
CHECK(Typed(input.Update(Keys({0x51}), false, now += 20000)) == "<down>");
CHECK(Typed(input.Update(Keys({}), false, now += 20000)).empty());
diff --git a/tests/password_crypto_test.cpp b/tests/password_crypto_test.cpp
new file mode 100644
index 0000000..07c3706
--- /dev/null
+++ b/tests/password_crypto_test.cpp
@@ -0,0 +1,85 @@
+#include "steam/backend/password_crypto.h"
+
+#include <mbedtls/base64.h>
+#include <mbedtls/bignum.h>
+#include <mbedtls/ctr_drbg.h>
+#include <mbedtls/entropy.h>
+#include <mbedtls/rsa.h>
+
+#include <cstdio>
+#include <cstdlib>
+#include <string>
+#include <vector>
+
+using playden::steam::EncryptPassword;
+using playden::steam::ZeroizeSecret;
+
+namespace {
+void Check(bool condition, const char* message) {
+ if (!condition) { std::fprintf(stderr, "password_crypto_test: %s\n", message); std::exit(1); }
+}
+
+std::string HexOf(const mbedtls_mpi& value) {
+ char buffer[1100];
+ std::size_t written = 0;
+ Check(mbedtls_mpi_write_string(&value, 16, buffer, sizeof(buffer), &written) == 0, "hex export");
+ return std::string(buffer);
+}
+} // namespace
+
+int main() {
+ mbedtls_entropy_context entropy;
+ mbedtls_ctr_drbg_context drbg;
+ mbedtls_rsa_context rsa;
+ mbedtls_entropy_init(&entropy);
+ mbedtls_ctr_drbg_init(&drbg);
+ mbedtls_rsa_init(&rsa);
+ Check(mbedtls_ctr_drbg_seed(&drbg, mbedtls_entropy_func, &entropy, nullptr, 0) == 0, "seed");
+ Check(mbedtls_rsa_gen_key(&rsa, mbedtls_ctr_drbg_random, &drbg, 2048, 65537) == 0, "key generation");
+ mbedtls_mpi n, e;
+ mbedtls_mpi_init(&n);
+ mbedtls_mpi_init(&e);
+ Check(mbedtls_rsa_export(&rsa, &n, nullptr, nullptr, nullptr, &e) == 0, "export");
+ const auto modulus = HexOf(n), exponent = HexOf(e);
+
+ // Round trip: the private key recovers the password.
+ const std::string password = "correct horse battery staple ✓";
+ const auto encrypted = EncryptPassword(modulus, exponent, password);
+ Check(encrypted.has_value() && !encrypted->empty(), "encryption failed");
+ std::vector<unsigned char> raw(512);
+ std::size_t raw_size = 0;
+ Check(mbedtls_base64_decode(raw.data(), raw.size(), &raw_size,
+ reinterpret_cast<const unsigned char*>(encrypted->data()), encrypted->size()) == 0 &&
+ raw_size == 256, "not base64 of one RSA block");
+ unsigned char plain[256];
+ std::size_t plain_size = 0;
+ Check(mbedtls_rsa_pkcs1_decrypt(&rsa, mbedtls_ctr_drbg_random, &drbg, &plain_size, raw.data(), plain,
+ sizeof(plain)) == 0, "decryption failed");
+ Check(std::string(reinterpret_cast<char*>(plain), plain_size) == password, "round trip mismatch");
+ // Lowercase hex, as Steam sends it, works too.
+ std::string lower = modulus;
+ for (auto& c : lower) if (c >= 'A' && c <= 'F') c = static_cast<char>(c - 'A' + 'a');
+ Check(EncryptPassword(lower, "010001", password).has_value(), "lowercase hex refused");
+ // Padding is random: two encryptions differ.
+ Check(*EncryptPassword(modulus, exponent, password) != *encrypted, "padding not random");
+
+ // Bad keys fail cleanly.
+ Check(!EncryptPassword("", exponent, password), "empty modulus accepted");
+ Check(!EncryptPassword("zz" + modulus, exponent, password), "non-hex modulus accepted");
+ Check(!EncryptPassword("-" + modulus, exponent, password), "signed modulus accepted");
+ Check(!EncryptPassword(modulus, "", password), "empty exponent accepted");
+ Check(!EncryptPassword("0f", "03", password), "tiny modulus accepted");
+ Check(!EncryptPassword(modulus, exponent, std::string(300, 'x')), "oversized password accepted");
+
+ std::string secret = "hunter2";
+ ZeroizeSecret(secret);
+ Check(secret.empty(), "secret not cleared");
+
+ mbedtls_mpi_free(&e);
+ mbedtls_mpi_free(&n);
+ mbedtls_rsa_free(&rsa);
+ mbedtls_ctr_drbg_free(&drbg);
+ mbedtls_entropy_free(&entropy);
+ std::puts("password_crypto_test passed");
+ return 0;
+}
diff --git a/tests/preferences_test.cpp b/tests/preferences_test.cpp
index 967cf82..138c80a 100644
--- a/tests/preferences_test.cpp
+++ b/tests/preferences_test.cpp
@@ -176,6 +176,35 @@ void TitleStoreSuffixPersistsAndVersionOneStillLoads() {
"automatic Cloud saves off survives restart");
}
+void SignInMethodPersistsAndVersionThreeOpensQr() {
+ TemporaryDirectory directory;
+ playden::Storage storage(directory.path());
+ playden::PreferencesStore store(storage);
+ playden::Preferences preferences;
+ preferences.steam_sign_in_password = true;
+ preferences.cloud_saves_auto = true;
+ Check(store.Save(preferences).ok(), "sign-in method preference saves");
+ const auto saved = storage.Read("preferences.conf");
+ Check(saved.ok() && std::string(saved.value().begin(), saved.value().end()) ==
+ "version=4\nreduce_motion=0\ntitle_store_suffix=0\ncloud_saves_auto=1\nsteam_sign_in_password=1\n",
+ "version 4 format");
+ const auto loaded = store.Load();
+ Check(loaded.status == playden::PreferencesLoadStatus::kLoaded && loaded.preferences.steam_sign_in_password &&
+ loaded.preferences.cloud_saves_auto,
+ "password sign-in survives restart");
+ const std::string version_three = "version=3\nreduce_motion=1\ntitle_store_suffix=1\ncloud_saves_auto=1\n";
+ Check(storage.WriteAtomic("preferences.conf", playden::Bytes(version_three.begin(), version_three.end())).ok(),
+ "version 3 fixture is written");
+ const auto three = store.Load();
+ Check(three.status == playden::PreferencesLoadStatus::kLoaded && three.preferences.reduce_motion &&
+ three.preferences.title_store_suffix && three.preferences.cloud_saves_auto &&
+ !three.preferences.steam_sign_in_password,
+ "version 3 preferences load and sign in with the QR code");
+ const std::string bad = "version=4\nreduce_motion=0\ntitle_store_suffix=0\ncloud_saves_auto=0\nsteam_sign_in_password=2\n";
+ Check(storage.WriteAtomic("preferences.conf", playden::Bytes(bad.begin(), bad.end())).ok(), "bad fixture is written");
+ Check(store.Load().status == playden::PreferencesLoadStatus::kDefaultCorrupt, "bad sign-in value is corrupt");
+}
+
void CorruptPreferencesRestoreDefaultsWithVisibleDiagnostic() {
TemporaryDirectory directory;
playden::Storage storage(directory.path());
@@ -219,6 +248,7 @@ int main() {
PreferencesPersistAcrossStoreInstances();
CorruptPreferencesRestoreDefaultsWithVisibleDiagnostic();
TitleStoreSuffixPersistsAndVersionOneStillLoads();
+ SignInMethodPersistsAndVersionThreeOpensQr();
if (failures != 0) {
std::fprintf(stderr, "%d preference test assertion(s) failed\n", failures);
diff --git a/tests/steam_auth_test.cpp b/tests/steam_auth_test.cpp
index 2b4287a..010eeb5 100644
--- a/tests/steam_auth_test.cpp
+++ b/tests/steam_auth_test.cpp
@@ -58,6 +58,37 @@ class Backend : public AuthBackend {
++calls;if(restore_gate)restore_gate->ArriveAndWait();
return {result,result==AuthError::kNone?std::optional<StoredSession>(session):std::nullopt};
}
+ // Password sign-in: asks for an email code (approval with an app code when approval is set), rejects
+ // "WRONG" and signs in with any other code.
+ std::string password_seen, account_seen;
+ bool approval=false;
+ AuthResult AuthenticateCredentials(Credentials& credentials,const std::atomic<bool>& cancel,
+ const GuardPromptCallback& prompt,const GuardCodeSource& code) override {
+ ++calls;password_seen=credentials.password;account_seen=credentials.account_name;
+ ZeroizeSecret(credentials.password);
+ GuardPrompt shown;
+ shown.kind=approval?GuardPromptKind::kApproval:GuardPromptKind::kEmailCode;
+ shown.code_allowed=approval;shown.email_domain=approval?"":"example.invalid";
+ prompt(shown);
+ while(!cancel.load()){
+ if(auto typed=code()){
+ if(*typed=="WRONG"){GuardPrompt again;again.kind=GuardPromptKind::kEmailCode;again.email_domain="example.invalid";again.code_rejected=true;prompt(again);continue;}
+ if(result!=AuthError::kNone)return {result,std::nullopt};
+ return {AuthError::kNone,Session(7)};
+ }
+ std::this_thread::sleep_for(1ms);
+ }
+ return {AuthError::kCanceled,std::nullopt};
+ }
+};
+// Holds the first QR sign-in at a gate, so later commands queue behind it.
+class Recording : public Backend {
+ public:
+ Gate* gate=nullptr;
+ AuthResult AuthenticateQr(const std::atomic<bool>& cancel,const ChallengeCallback& challenge) override {
+ if(gate)gate->ArriveAndWait();
+ return Backend::AuthenticateQr(cancel,challenge);
+ }
};
SteamEvent WaitEvent(SteamService& service,SteamEventKind kind) {
auto deadline=std::chrono::steady_clock::now()+3s;
@@ -188,5 +219,59 @@ int main(){
service->BeginQrSignIn();gate.Wait();service->SignOut();gate.Release();service.reset();
Check(!store.Load().value(),"shutdown dropped signout barrier");
}
+ {
+ // Password sign-in: email code, a wrong code, then the right one; the session is saved as for QR.
+ Store store;Backend backend;SteamService service(backend,store);
+ std::string password="fixture-password";
+ auto id=service.BeginCredentialSignIn("fixture-account",password);
+ auto e=WaitEvent(service,SteamEventKind::kNeedsEmailCode);
+ Check(e.request_id==id&&e.email_domain=="example.invalid"&&e.code_allowed&&e.code_is_email,"email prompt");
+ Check(backend.password_seen=="fixture-password"&&backend.account_seen=="fixture-account","credentials not handed over");
+ service.SubmitGuardCode("WRONG");
+ e=WaitEvent(service,SteamEventKind::kCodeRejected);
+ Check(e.code_is_email&&e.email_domain=="example.invalid","rejected prompt");
+ service.SubmitGuardCode("AB12C");
+ e=WaitEvent(service,SteamEventKind::kAuthenticated);
+ Check(e.request_id==id&&e.steam_id==7&&store.saves==1,"password sign-in not saved");
+ }
+ {
+ // Approval with a typed code allowed.
+ Store store;Backend backend;backend.approval=true;SteamService service(backend,store);
+ service.BeginCredentialSignIn("fixture-account","fixture-password");
+ auto e=WaitEvent(service,SteamEventKind::kAwaitingApproval);
+ Check(e.code_allowed&&!e.code_is_email,"approval prompt");
+ service.SubmitGuardCode("XY34Z");WaitEvent(service,SteamEventKind::kAuthenticated);
+ }
+ {
+ // Codes go only to the running sign-in: one sent before it, or after a cancel, is dropped.
+ Store store;Backend backend;SteamService service(backend,store);
+ service.SubmitGuardCode("EARLY");
+ auto id=service.BeginCredentialSignIn("fixture-account","fixture-password");
+ WaitEvent(service,SteamEventKind::kNeedsEmailCode);
+ std::this_thread::sleep_for(20ms);
+ Check(service.Pump(64).empty(),"a stale code reached the sign-in");
+ service.Cancel(id);
+ Check(WaitEvent(service,SteamEventKind::kCanceled).request_id==id,"cancel lost");
+ service.SubmitGuardCode("LATE");
+ std::this_thread::sleep_for(20ms);
+ Check(service.Pump(64).empty()&&store.saves==0,"canceled password sign-in continued");
+ }
+ {
+ // A failed password sign-in reports the backend's error and leaves storage alone.
+ Store store;store.value=Session();Backend backend;backend.result=AuthError::kRateLimited;SteamService service(backend,store);
+ service.BeginCredentialSignIn("fixture-account","fixture-password");
+ WaitEvent(service,SteamEventKind::kNeedsEmailCode);service.SubmitGuardCode("AB12C");
+ Check(WaitEvent(service,SteamEventKind::kFailure).error==AuthError::kRateLimited,"rate limit lost");
+ Check(store.saves==0&&store.clears==0,"failed password sign-in changed storage");
+ }
+ {
+ // A queued password sign-in replaced before it runs never reaches the backend.
+ Store store;Recording backend;Gate gate;backend.gate=&gate;SteamService service(backend,store);
+ service.BeginQrSignIn();gate.Wait();
+ service.BeginCredentialSignIn("fixture-account","fixture-password");
+ service.BeginQrSignIn();gate.Release();
+ WaitEvent(service,SteamEventKind::kAuthenticated);
+ Check(backend.password_seen.empty(),"replaced password sign-in ran");
+ }
std::cout<<"steam_auth_test passed\n";
}