diff --git a/app/src/main/java/com/droiddeck/launcher/session/SteamWebLogin.kt b/app/src/main/java/com/droiddeck/launcher/session/SteamWebLogin.kt new file mode 100644 index 000000000..f9075857f --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/SteamWebLogin.kt @@ -0,0 +1,81 @@ +package com.droiddeck.launcher.session + +import android.database.sqlite.SQLiteDatabase +import java.io.File +import javax.crypto.Cipher +import javax.crypto.SecretKeyFactory +import javax.crypto.spec.IvParameterSpec +import javax.crypto.spec.PBEKeySpec +import javax.crypto.spec.SecretKeySpec + +/** A cookie for one https host, in the form CookieManager.setCookie takes. */ +data class WebCookie(val host: String, val header: String) + +/** + * The web sign-in the Steam client in the session already has, so the bottom-screen chat opens signed in. + * Steam's built-in browser keeps it in its Chromium cookie store under config/htmlcache. With no keyring + * (SteamOS and DroidDeck) Chromium encrypts values as "v10": AES-128-CBC, key PBKDF2-SHA1("peanuts", + * "saltysalt", 1 round), IV of 16 spaces. Values are never logged. + */ +object SteamWebLogin { + val HOSTS = listOf("steamcommunity.com", "steam-chat.com") + private const val COOKIES = "config/htmlcache/Default/Cookies" + private const val V10 = "v10" + // From cookie store version 24 Chromium puts the SHA-256 of the host before each value. + private const val HOST_HASH_VERSION = 24 + private const val HOST_HASH_BYTES = 32 + + private val key: SecretKeySpec by lazy { + val spec = PBEKeySpec("peanuts".toCharArray(), "saltysalt".toByteArray(), 1, 128) + SecretKeySpec(SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").generateSecret(spec).encoded, "AES") + } + + internal fun decrypt(encrypted: ByteArray, hostHashed: Boolean): String? = runCatching { + if (encrypted.size <= V10.length || String(encrypted, 0, V10.length, Charsets.US_ASCII) != V10) return null + val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding") + cipher.init(Cipher.DECRYPT_MODE, key, IvParameterSpec(ByteArray(16) { ' '.code.toByte() })) + val plain = cipher.doFinal(encrypted, V10.length, encrypted.size - V10.length) + val value = if (hostHashed && plain.size >= HOST_HASH_BYTES) plain.copyOfRange(HOST_HASH_BYTES, plain.size) else plain + String(value, Charsets.UTF_8) + }.getOrNull() + + /** Steam's own pages send the sign-in with its "||" separator percent-encoded. */ + internal fun header(name: String, value: String, httpOnly: Boolean): String { + val v = if (name == "steamLoginSecure") value.replace("||", "%7C%7C") else value + return "$name=$v; Path=/; Secure" + if (httpOnly) "; HttpOnly" else "" + } + + /** Empty when the client has no web sign-in, for example before the first login. */ + fun read(runtimeRoot: File, client: String?, scratch: File): List { + val homes = client?.let { listOf(if (it == "x86_64") SteamDownloadMonitor.STEAM_HOMES[1] else SteamDownloadMonitor.STEAM_HOMES[0]) } + ?: SteamDownloadMonitor.STEAM_HOMES + val store = homes.map { File(runtimeRoot, "$it/$COOKIES") }.filter { it.isFile }.maxByOrNull { it.lastModified() } + ?: return emptyList() + // A copy, journal included: Steam keeps the store open and may be in the middle of a write. + scratch.deleteRecursively() + if (!scratch.mkdirs()) return emptyList() + return try { + val copy = File(scratch, "Cookies") + store.copyTo(copy, overwrite = true) + File(store.path + "-journal").takeIf { it.length() > 0L }?.copyTo(File(scratch, "Cookies-journal"), overwrite = true) + SQLiteDatabase.openDatabase(copy.path, null, SQLiteDatabase.OPEN_READWRITE).use { db -> + val version = db.rawQuery("SELECT value FROM meta WHERE key = 'version'", null).use { if (it.moveToFirst()) it.getString(0).toIntOrNull() else null } ?: 0 + val marks = HOSTS.joinToString { "?" } + db.rawQuery("SELECT host_key, name, value, encrypted_value, is_httponly FROM cookies WHERE host_key IN ($marks)", HOSTS.toTypedArray()).use { c -> + val out = ArrayList() + while (c.moveToNext()) { + val name = c.getString(1) + val value = c.getString(2).takeUnless { it.isNullOrEmpty() } + ?: decrypt(c.getBlob(3) ?: continue, version >= HOST_HASH_VERSION) ?: continue + out += WebCookie(c.getString(0), header(name, value, c.getInt(4) != 0)) + } + out + } + } + } catch (_: Exception) { + emptyList() + } finally { + scratch.deleteRecursively() + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/BottomChatPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/BottomChatPage.kt index cd74f18bc..6bfc9423f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/BottomChatPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/BottomChatPage.kt @@ -19,6 +19,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf @@ -36,9 +37,16 @@ import androidx.compose.ui.viewinterop.AndroidView import com.droiddeck.launcher.R import com.droiddeck.launcher.session.SessionService import com.droiddeck.launcher.session.SessionState +import com.droiddeck.launcher.session.SteamWebLogin +import com.droiddeck.launcher.runtime.LinuxRuntime +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.suspendCancellableCoroutine +import kotlinx.coroutines.withContext +import java.io.File +import kotlin.coroutines.resume private const val STEAM_CHAT = "https://steamcommunity.com/chat" -private val STEAM_HOSTS = listOf("steamcommunity.com", "steampowered.com", "steamstatic.com", "steamcontent.com") +private val STEAM_HOSTS = listOf("steamcommunity.com", "steam-chat.com", "steampowered.com", "steamstatic.com", "steamcontent.com") /** Steam chat stays on Steam's own sites; anything else is not opened on the bottom screen. */ internal fun steamChatAllows(host: String?): Boolean = @@ -55,6 +63,21 @@ fun BottomChatPage() { val context = LocalContext.current val colors = MaterialTheme.colorScheme var chatOpen by remember { mutableStateOf(false) } + // null while the Steam client's sign-in is being copied, then whether there was one. + var fromSteam by remember { mutableStateOf(null) } + LaunchedEffect(chatOpen) { + if (!chatOpen) { + fromSteam = null + return@LaunchedEffect + } + val cookies = withContext(Dispatchers.IO) { + SteamWebLogin.read(LinuxRuntime.rootDir(context), SessionState.steamClientArch, File(context.cacheDir, "steam-web-login")) + } + val manager = CookieManager.getInstance() + for (c in cookies) suspendCancellableCoroutine { cont -> manager.setCookie("https://${c.host}", c.header) { cont.resume(Unit) } } + manager.flush() + fromSteam = cookies.any { it.header.startsWith("steamLoginSecure=") } + } Column(Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(8.dp)) { VoiceRow(context) if (!chatOpen) { @@ -64,8 +87,10 @@ fun BottomChatPage() { BottomPillButton(stringResource(R.string.bottom_chat_open), "bottom-chat-open") { chatOpen = true } } } else { - Box(Modifier.weight(1f).fillMaxWidth().clip(RoundedCornerShape(14.dp))) { SteamChatView() } - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { + Box(Modifier.weight(1f).fillMaxWidth().clip(RoundedCornerShape(14.dp))) { if (fromSteam != null) SteamChatView() } + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Text(if (fromSteam == false) stringResource(R.string.bottom_chat_not_signed_in) else "", fontSize = 12.sp, + color = colors.onSurfaceVariant, maxLines = 2, modifier = Modifier.weight(1f).padding(end = 8.dp)) BottomPillButton(stringResource(R.string.bottom_chat_close), "bottom-chat-close") { chatOpen = false } } } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 93030b637..bd981e2f3 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1897,7 +1897,8 @@ Could not take a screenshot. No screenshots yet. Chat & voice - Read and answer Steam chat here while the game keeps running on the main screen. Sign in to Steam once; DroidDeck keeps you signed in. + Read and answer Steam chat here while the game keeps running on the main screen. It uses the account Steam is signed in with. + Steam has no web sign-in to share yet, so sign in here once. Open Steam Chat Close chat Mic on diff --git a/app/src/test/java/com/droiddeck/launcher/session/SteamWebLoginTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SteamWebLoginTest.kt new file mode 100644 index 000000000..01988bf84 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/SteamWebLoginTest.kt @@ -0,0 +1,31 @@ +package com.droiddeck.launcher.session + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class SteamWebLoginTest { + private fun hex(s: String) = ByteArray(s.length / 2) { s.substring(it * 2, it * 2 + 2).toInt(16).toByte() } + + // Made with: openssl enc -aes-128-cbc -K -iv <16 spaces>, prefixed "v10". + @Test fun chromiumV10ValuesDecrypt() { + val encrypted = hex("7631300b9cf0a6eee9cf1aaac601b85ca37cf9fe9e67078564f0e05835ae2aa3d9b0ab") + assertEquals("0123456789abcdef01234567", SteamWebLogin.decrypt(encrypted, hostHashed = false)) + } + + @Test fun newerStoresDropTheHostHash() { + val encrypted = hex("7631304d4114329f1e692e807b8b044d67460f5e14d92ffb48b9f83be318ebd0d84c727674aea32f351b8a33c8aa42553dfeb5") + assertEquals("hello", SteamWebLogin.decrypt(encrypted, hostHashed = true)) + } + + @Test fun otherFormatsAreSkipped() { + assertNull(SteamWebLogin.decrypt("v11garbage".toByteArray(), hostHashed = false)) + assertNull(SteamWebLogin.decrypt(ByteArray(2), hostHashed = false)) + } + + @Test fun theSignInIsSentTheWaySteamPagesSendIt() { + assertEquals("steamLoginSecure=76561190000000000%7C%7Ca.b.c; Path=/; Secure; HttpOnly", + SteamWebLogin.header("steamLoginSecure", "76561190000000000||a.b.c", httpOnly = true)) + assertEquals("sessionid=0123; Path=/; Secure", SteamWebLogin.header("sessionid", "0123", httpOnly = false)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/BottomChatPageTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/BottomChatPageTest.kt index 9d7309182..17f2e1f8f 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/BottomChatPageTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/BottomChatPageTest.kt @@ -9,6 +9,7 @@ class BottomChatPageTest { @Test fun steamSitesOpenOthersDoNot() { assertTrue(steamChatAllows("steamcommunity.com")) assertTrue(steamChatAllows("login.steampowered.com")) + assertTrue(steamChatAllows("steam-chat.com")) assertTrue(steamChatAllows("community.cloudflare.steamstatic.com")) assertFalse(steamChatAllows("steamcommunity.com.example.net")) assertFalse(steamChatAllows("evilsteamcommunity.com"))