feat(rockstar): broaden launcher protocol compatibility (#2547)

This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-11-13 06:17:12 -05:00
1 parent f33181e430
commit 83de0e7f8c
20 files changed
+1368 -90

No files matched your search

@@ -418,7 +418,7 @@ object AddedGames {
private fun scanGame(context: Context, folder: File, out: MutableList<Game>, single: AddedExes.Entry? = null, reuse: Boolean = false) {
run {
val sidecar = StoreGameSidecar.read(folder)?.let { com.droiddeck.launcher.stores.StoreLaunch.adopt(folder, it) }
if (sidecar?.store == Store.ROCKSTAR && (!com.droiddeck.launcher.stores.rockstar.RockstarLaunch.supports(sidecar.id) || sidecar.launcher != com.droiddeck.launcher.stores.StoreLaunch.LAUNCHER)) return
if (sidecar?.store == Store.ROCKSTAR && sidecar.launcher != com.droiddeck.launcher.stores.StoreLaunch.LAUNCHER) return
sidecar?.takeIf { it.id.isNotEmpty() }?.let { SessionPrefs.followStoreGame(context, "${it.store.id}:${it.id}", folder.path) { old -> !File(old).exists() } }
val ranking = rank(folder, reuse)
val candidates = ranking.exes
@@ -21,10 +21,6 @@ object StoreLaunch {
val needs = sidecar.args.isNotEmpty() || sidecar.env.isNotEmpty() || sidecar.store == Store.EPIC || sidecar.store == Store.EA || sidecar.store == Store.UBISOFT || sidecar.store == Store.ROCKSTAR
val file = File(folder, LAUNCHER)
if (sidecar.store == Store.ROCKSTAR && java.nio.file.Files.isSymbolicLink(file.toPath())) return sidecar.copy(launcher = null)
if (sidecar.store == Store.ROCKSTAR && !com.droiddeck.launcher.stores.rockstar.RockstarLaunch.supports(sidecar.id)) {
file.delete()
return sidecar.copy(launcher = null)
}
if (!needs) { file.delete(); return sidecar.copy(launcher = null) }
file.writeText(launcherText(sidecar))
return sidecar.copy(launcher = LAUNCHER)
@@ -36,11 +32,11 @@ object StoreLaunch {
?: exe.substringBeforeLast('\\', "")
val lines = ArrayList<String>()
lines += "@echo off"
lines += "setlocal"
lines += if (sidecar.store == Store.ROCKSTAR) "setlocal DisableDelayedExpansion" else "setlocal"
if (sidecar.store != Store.ROCKSTAR) lines += "rem Written by DroidDeck for ${sidecar.store.label}: ${sidecar.title}. Steam's shortcut runs this file."
lines += "cd /d \"%~dp0$dir\""
for ((k, v) in sidecar.env) if (ENV_NAME.matches(k)) lines += "set \"$k=${v.replace("\"", "")}\""
val args = sidecar.args.joinToString(" ") { quoteArg(it) }
val args = sidecar.args.joinToString(" ") { if (sidecar.store == Store.ROCKSTAR) batchArg(it) else quoteArg(it) }
val run = "\"%~dp0$exe\"" + (if (args.isNotEmpty()) " $args" else "")
if (sidecar.store == Store.EPIC) {
lines += "if exist \"%~dp0$EPIC_ARGS\" goto client"
@@ -60,8 +56,11 @@ object StoreLaunch {
lines += "if exist \"%~dp0$EPIC_CODE\" del \"%~dp0$EPIC_CODE\""
lines += "set \"$CLIENT_VAR=\" & \"%~dp0$exe\" %$CLIENT_VAR%"
} else if (sidecar.store == Store.ROCKSTAR) {
lines += "if not exist \"C:\\Program Files\\Rockstar Games\\Launcher\\launch.json\" goto direct"
lines += "\"C:\\Program Files\\Rockstar Games\\Launcher\\Launcher.exe\""
lines += "exit /b %errorlevel%"
lines += ":direct"
lines += run
} else if (sidecar.store == Store.UBISOFT) {
lines += "if not exist \"%~dp0$UBISOFT_LAUNCH\" goto direct"
lines += "if not exist \"$UBISOFT_SERVICE\" goto direct"
@@ -85,6 +84,22 @@ object StoreLaunch {
private val ENV_NAME = Regex("[A-Za-z_][A-Za-z0-9_]*")
private fun batchArg(arg: String): String {
val quoted = StringBuilder("\"")
var slashes = 0
for (c in arg.filter { it >= ' ' && it != '\u007f' }) {
if (c == '\\') { slashes++; continue }
quoted.append("\\".repeat(if (c == '"') slashes * 2 + 1 else slashes)).append(c)
slashes = 0
}
quoted.append("\\".repeat(slashes * 2)).append('"')
return quoted.toString().map { c -> when (c) {
'%' -> "%%"
in "^&|<>()\"" -> "^$c"
else -> c.toString()
} }.joinToString("")
}
fun quoteArg(arg: String): String {
val clean = arg.filter { it >= ' ' && it != '\u007f' }
return if (' ' in clean && !clean.contains('"')) "\"$clean\"" else clean
@@ -103,11 +118,12 @@ object StoreLaunch {
fun adopt(folder: File, sidecar: StoreGameSidecar): StoreGameSidecar {
if (sidecar.store !in listOf(Store.UBISOFT, Store.ROCKSTAR) || !sidecar.isInstalled) return sidecar
if (sidecar.store == Store.ROCKSTAR && !com.droiddeck.launcher.stores.rockstar.RockstarLaunch.supports(sidecar.id)) return sidecar
if (sidecar.store == Store.ROCKSTAR && java.nio.file.Files.isSymbolicLink(File(folder, LAUNCHER).toPath())) return sidecar.copy(launcher = null)
val wrongExe = !sidecar.exeFile(folder).isFile || sidecar.exe.contains("installer", ignoreCase = true) || sidecar.exe.contains("autorun", ignoreCase = true)
if (sidecar.store == Store.UBISOFT && sidecar.launcher == LAUNCHER && !wrongExe) return sidecar
val exe = if (wrongExe) StoreExe.pick(folder, null, sidecar.title).ifEmpty { sidecar.exe } else sidecar.exe
val metadataExe = if (sidecar.store == Store.ROCKSTAR) com.droiddeck.launcher.stores.rockstar.RockstarMetadata.find(folder)?.exe
?.takeIf { File(folder, it).isFile && File(folder, it).canonicalPath.startsWith(folder.canonicalPath + File.separator) } else null
val exe = metadataExe ?: if (wrongExe) StoreExe.pick(folder, null, sidecar.title).ifEmpty { sidecar.exe } else sidecar.exe
if (exe == sidecar.exe && sidecar.launcher == LAUNCHER &&
runCatching { File(folder, LAUNCHER).readText() }.getOrNull() == launcherText(sidecar)) return sidecar
return runCatching { writeLauncher(folder, sidecar.copy(exe = exe)).also { it.write(folder) } }.getOrDefault(sidecar)
@@ -29,7 +29,7 @@ object RockstarAuth {
private const val TICKET_MARGIN_MS = 15 * 60 * 1000L
private val lock = Any()
class Ticket(val ticket: String, val sessionKey: String, val sessionTicket: String, val rockstarId: String, val nickname: String, val expiresAt: Long)
class Ticket(val ticket: String, val sessionKey: String, val sessionTicket: String, val rockstarId: String, val nickname: String, val expiresAt: Long, val email: String = "", val sdkTicket: String = "")
internal fun fingerprint(context: Context): JSONObject {
val p = context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
@@ -159,7 +159,7 @@ object RockstarAuth {
private fun stored(o: JSONObject): Ticket? {
val t = o.optString("ticket").takeIf { it.isNotEmpty() } ?: return null
return Ticket(t, o.optString("session_key"), o.optString("session_ticket"), o.optString("rockstar_id"), o.optString("display_name"), o.optLong("ticket_expires_at"))
return Ticket(t, o.optString("session_key"), o.optString("session_ticket"), o.optString("rockstar_id"), o.optString("display_name"), o.optLong("ticket_expires_at"), o.optString("email"), o.optString("sdk_ticket").takeIf { o.optInt("sdk_ticket_version") == 1 }.orEmpty())
}
private fun mint(context: Context): Ticket {
@@ -176,7 +176,7 @@ object RockstarAuth {
}
val t = parseTicket(root) ?: throw IllegalStateException("no ticket in the answer")
o.put("ticket", t.ticket).put("session_key", t.sessionKey).put("session_ticket", t.sessionTicket)
.put("rockstar_id", t.rockstarId).put("ticket_expires_at", t.expiresAt)
.put("rockstar_id", t.rockstarId).put("ticket_expires_at", t.expiresAt).put("email", t.email).put("sdk_ticket", t.sdkTicket).put("sdk_ticket_version", 1)
if (t.nickname.isNotEmpty()) o.put("display_name", t.nickname)
StoreAccounts.write(app, Store.ROCKSTAR, o)
return t
@@ -191,8 +191,49 @@ object RockstarAuth {
(account?.let { RockstarRos.text(it, "RockstarId") } ?: RockstarRos.text(root, "RockstarId")).orEmpty(),
account?.let { RockstarRos.text(it, "Nickname") }.orEmpty(),
now + secs * 1000L,
account?.let { RockstarRos.text(it, "Email") }.orEmpty(),
sdkTicket(root),
)
}
internal fun sdkTicket(root: org.w3c.dom.Element): String {
val document = javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument()
val response = document.createElement("Response").also { document.appendChild(it) }
val fields = setOf("Status", "Ticket", "SessionKey", "SessionTicket", "SecsUntilExpiration", "PlayerAccountId", "PlayerAccountRuid",
"Region", "Privileges", "Privs", "Services", "SslServices", "Hosts", "DisabledSecurityFlags", "SessionId", "CloudKey", "PublicIp", "PosixTime", "IsSubAccount")
val blocked = setOf("scauthtoken", "accesstoken", "refreshtoken", "rememberedmachinetoken", "loginguid", "password")
fun copy(source: org.w3c.dom.Element): org.w3c.dom.Element {
val target = document.createElement(source.tagName)
for (i in 0 until source.attributes.length) {
val attribute = source.attributes.item(i)
if (attribute.nodeName.lowercase() !in blocked) target.setAttribute(attribute.nodeName, attribute.nodeValue)
}
var child = source.firstChild
while (child != null) {
if (child is org.w3c.dom.Element) {
if (child.tagName.lowercase() !in blocked) target.appendChild(copy(child))
} else if (child.nodeType == org.w3c.dom.Node.TEXT_NODE || child.nodeType == org.w3c.dom.Node.CDATA_SECTION_NODE) {
target.appendChild(document.createTextNode(child.nodeValue))
}
child = child.nextSibling
}
return target
}
for (field in fields) RockstarRos.first(root, field)?.let { response.appendChild(copy(it)) }
RockstarRos.first(root, "RockstarAccount")?.let { account ->
val target = document.createElement("RockstarAccount")
for (field in setOf("RockstarId", "Nickname", "Email", "Age", "CountryCode", "LanguageCode", "AvatarUrl", "ZipCode", "Ruid")) {
RockstarRos.first(account, field)?.let { target.appendChild(copy(it)) }
}
response.appendChild(target)
}
val output = java.io.StringWriter()
javax.xml.transform.TransformerFactory.newInstance().newTransformer().apply {
setOutputProperty(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes")
transform(javax.xml.transform.dom.DOMSource(document), javax.xml.transform.stream.StreamResult(output))
}
return output.toString()
}
fun signOut(context: Context) = synchronized(lock) { StoreAccounts.clear(context.applicationContext, Store.ROCKSTAR) }
}
@@ -147,6 +147,9 @@ object RockstarLibrary {
internal fun owned(account: RockstarAccountApps): List<RockstarTitle> =
account.packages.filter { !it.featured }.flatMap { RockstarTitles.forName(it.title) }.distinct()
internal fun owns(account: RockstarAccountApps, rosId: Int, id: String): Boolean =
owned(account).any { it.rosTitleId == rosId } || account.packages.any { !it.featured && it.title == id }
internal fun games(account: RockstarAccountApps): List<CatalogItem> = owned(account).mapNotNull { t ->
RockstarApps.deliverer(account.apps, t)?.let { RockstarTitles.item(t, owned = true, extra = mapOf("app" to it.name, "appId" to it.id)) }
}.sortedBy { it.title.lowercase() }
@@ -10,9 +10,9 @@ import java.security.MessageDigest
import java.util.Base64
object RockstarLaunch {
internal val pipes = mapOf("gta3" to "GTA3_Pipe", "gtavc" to "GTA-VC_Pipe", "gtasa" to "GTA_SA_Pipe")
internal val pipes = mapOf("gta3" to "GTA3_Pipe", "gtavc" to "GTA-VC_Pipe", "gtasa" to "GTA_SA_Pipe", "gta4" to "GTAIV_Pipe", "lanoire" to "LANOIRE_Pipe")
fun supports(id: String?) = id != null && id in pipes
fun usesClassicLauncher(id: String) = id in pipes
fun applyDefaults(app: Context, id: String, appId: Long) {
val scope = (appId and 0xffffffffL).toString()
@@ -23,16 +23,22 @@ object RockstarLaunch {
}
fun prepare(app: Context, id: String): JSONObject {
val pipe = pipes[id] ?: return failure("unsupported-title")
val title = RockstarTitles.byId(id) ?: return failure("unknown-title")
val folder = StoreInstallRoot.gameFolders(app).firstOrNull { folder ->
StoreGameSidecar.read(folder)?.let { it.store == Store.ROCKSTAR && it.id == id && it.isInstalled } == true
} ?: return failure("not-installed")
val installed = StoreGameSidecar.read(folder) ?: return failure("not-installed")
val exe = installed.exeFile(folder).canonicalFile
if (!exe.path.startsWith(folder.canonicalPath + java.io.File.separator) || !exe.isFile ||
!java.io.File(folder, "MTLX.dll").isFile) return failure("missing-game-files")
if (!exe.path.startsWith(folder.canonicalPath + java.io.File.separator) || !exe.isFile) return failure("missing-game-files")
val metadata = RockstarMetadata.find(folder)
val pipe = pipes[id]
val sdk = (pipe == null && metadata != null) || id in setOf("gta4", "lanoire") || listOf(folder, exe.parentFile).any { dir ->
dir.listFiles().orEmpty().any { it.isFile && it.name.lowercase() in setOf("socialclub.dll", "socialclub64.dll") }
}
if (pipe == null && !sdk) return failure("no-launcher-protocol")
if (pipe != null && !listOf(folder, exe.parentFile).any { java.io.File(it, "MTLX.dll").isFile }) return failure("missing-game-files")
val rosId = metadata?.rosId ?: RockstarTitles.byId(id)?.rosTitleId ?: return failure("missing-title-metadata")
var ticket = RockstarAuth.ticket(app) ?: RockstarAuth.ticket(app, fresh = true) ?: return failure("signed-out")
if (sdk && ticket.sdkTicket.isEmpty()) ticket = RockstarAuth.ticket(app, fresh = true) ?: return failure("signed-out")
val account = try {
RockstarApps.fetch(ticket.ticket) {}
} catch (e: RockstarRos.RosException) {
@@ -40,16 +46,23 @@ object RockstarLaunch {
ticket = RockstarAuth.ticket(app, fresh = true) ?: return failure("signed-out")
RockstarApps.fetch(ticket.ticket) {}
}
if (RockstarLibrary.owned(account).none { it.id == id } || RockstarApps.deliverer(account.apps, title) == null) return failure("not-owned")
val tokenRoot = RockstarRos.result("app.asmx/GetTitleAccessToken2", listOf("ticket" to ticket.ticket, "titleId" to title.rosTitleId.toString(), "platformId" to "8"))
if (metadata != null && account.apps.none { it.titleId.toIntOrNull() == rosId && (it.name == metadata.id || it.name.startsWith(metadata.id + "_")) }) return failure("title-metadata-mismatch")
val tokenRoot = RockstarRos.result("app.asmx/GetTitleAccessToken2", listOf("ticket" to ticket.ticket, "titleId" to rosId.toString(), "platformId" to "8"))
val token = RockstarRos.text(tokenRoot, "Result")?.takeIf { it.isNotEmpty() } ?: return failure("no-title-token")
val result = JSONObject().put("ok", true).put("expiresAt", System.currentTimeMillis() + 90_000)
if (sdk) {
val session = JSONObject().put("accountId", ticket.rockstarId).put("identity", ticket.email.ifEmpty { ticket.nickname }).put("ticket", ticket.sdkTicket)
if (RockstarLibrary.owns(account, rosId, metadata?.id ?: id)) session.put("titleId", metadata?.id ?: id)
result.put("session", session)
}
if (pipe == null) return result
val hash = MessageDigest.getInstance("SHA-256").digest(RockstarAuth.fingerprint(app).toString().toByteArray()).copyOf(16)
val launch = RockstarRos.result("app.asmx/GetTitleLaunchData", listOf("ticket" to ticket.ticket, "titleAccessToken" to token,
"machineHash" to Base64.getEncoder().encodeToString(hash)))
val encoded = RockstarRos.text(launch, "Data") ?: return failure("no-launch-data")
val iv = RockstarRos.text(launch, "EndpointIV") ?: return failure("no-launch-iv")
val material = RockstarLaunchCipher.decode(encoded, iv)
return JSONObject().put("ok", true).put("pipe", pipe).put("material", material).put("expiresAt", System.currentTimeMillis() + 90_000)
return result.put("pipe", pipe).put("material", material)
}
private fun failure(reason: String) = JSONObject().put("ok", false).put("reason", reason)
@@ -0,0 +1,53 @@
package com.droiddeck.launcher.stores.rockstar
import org.json.JSONObject
import java.io.File
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.charset.CodingErrorAction
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
internal object RockstarMetadata {
data class Title(val id: String, val rosId: Int, val exe: String)
fun find(folder: File): Title? {
val root = folder.canonicalFile
var level = listOf(root)
repeat(4) {
val entries = level.map { it.listFiles().orEmpty() }
val metadata = entries.flatMap { files -> files.filter { it.name.equals("title.rgl", true) } }
for (file in metadata.filter { it.isFile && !java.nio.file.Files.isSymbolicLink(it.toPath()) && it.canonicalPath.startsWith(root.path + File.separator) }) {
if (file.length() in 112..1_048_576) runCatching { decode(file.readBytes()) }.getOrNull()?.let {
return it.copy(exe = File(file.parentFile, it.exe).relativeTo(root).invariantSeparatorsPath)
}
}
level = entries.flatMap { files -> files.asSequence().filter {
it.isDirectory && !java.nio.file.Files.isSymbolicLink(it.toPath()) && it.canonicalPath.startsWith(root.path + File.separator)
}.take(256).toList() }.take(256)
}
return null
}
fun decode(bytes: ByteArray): Title? = runCatching {
require(bytes.size in 112..1_048_576 && bytes.copyOfRange(0, 4).contentEquals(byteArrayOf(82, 71, 76, 77)))
val header = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)
require(header.getInt(4) == 1 && header.getInt(8) == bytes.size - 80 && (bytes.size - 80) % 16 == 0)
val cipher = Cipher.getInstance("AES/CBC/NoPadding")
cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(ByteArray(32), "AES"), IvParameterSpec(bytes.copyOfRange(80, 96)))
val clear = cipher.doFinal(bytes, 96, bytes.size - 96)
val pad = clear.last().toInt() and 255
val size = if (pad in 1..16 && clear.takeLast(pad).all { (it.toInt() and 255) == pad }) clear.size - pad
else clear.indexOfLast { it != 0.toByte() } + 1
val text = Charsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT).decode(ByteBuffer.wrap(clear, 0, size)).toString().removePrefix("\uFEFF")
val json = JSONObject(text)
val id = json.getString("titleId")
val rosId = json.get("rosTitleId").toString().takeIf { Regex("[1-9][0-9]{0,4}").matches(it) }?.toInt() ?: return null
val exe = json.getString("principalFileName").replace('\\', '/')
require(Regex("[a-z][a-z0-9_]{0,63}").matches(id) && rosId in 1..65535)
require(exe.isNotEmpty() && !exe.startsWith('/') && ':' !in exe && '\u0000' !in exe && exe.split('/').none { it == ".." })
Title(id, rosId, exe)
}.getOrNull()
}
@@ -400,7 +400,6 @@ internal fun GameActions(
val failed = rawDownload?.takeIf { it.state == DownloadState.FAILED }
val cloud = game?.library == Library.XBOX_CLOUD && installed == null
val downloadBytes = catalogSize(item)
val launchSupported = store != Store.ROCKSTAR || com.droiddeck.launcher.stores.rockstar.RockstarLaunch.supports(id)
Actions {
when {
s.shortcutPicker && game != null -> {
@@ -412,8 +411,8 @@ internal fun GameActions(
val xboxBusy = store == Store.XBOX && id != null && XboxContent.busy(id)
val preparing = (game?.launchKey ?: storeKey)?.let { it in s.preparingGames } == true
PrimaryButton(
stringResource(if (!launchSupported) R.string.stores_rockstar_launch_unavailable else if (preparing) R.string.store_starting else R.string.stores_play),
enabled = launchSupported && !s.busy && !preparing && gone == null && download == null && !xboxBusy && (store != Store.GOG || installed?.sidecar?.isInstalled != false),
stringResource(if (preparing) R.string.store_starting else R.string.stores_play),
enabled = !s.busy && !preparing && gone == null && download == null && !xboxBusy && (store != Store.GOG || installed?.sidecar?.isInstalled != false),
main = true, icon = Icons.Filled.PlayArrow, modifier = leadOn,
) {
if (game != null) a.onSteamGame(game) else if (store != null && id != null) launchStoreGame(store, id, s, a)
@@ -221,7 +221,7 @@ private fun FinishedRow(d: DownloadEntry, s: FrontEndState, a: FrontEndActions,
val ctx = LocalContext.current
ArtStrip(d.cover, d.name) {
StripLabel(d.name, d.store.id, stringResource(if (d.state == DownloadState.INSTALLED) R.string.stores_installed_chip else R.string.stores_dl_cancelled), Color.White.copy(alpha = 0.72f))
if (d.state == DownloadState.INSTALLED && (d.store != Store.ROCKSTAR || com.droiddeck.launcher.stores.rockstar.RockstarLaunch.supports(d.id))) Box(Modifier.bloomIn(bloom, GATHER_HOLD_MS + 150)) {
if (d.state == DownloadState.INSTALLED) Box(Modifier.bloomIn(bloom, GATHER_HOLD_MS + 150)) {
RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_play), primary = true) { if (d.key == EpicClient.DOWNLOAD_KEY) a.onEpicLauncher() else if (d.key == com.droiddeck.launcher.stores.battlenet.BattleNetClient.DOWNLOAD_KEY) a.onBattleNet() else launchStoreGame(d.store, d.id, s, a) }
}
}
@@ -374,7 +374,7 @@ private fun DownloadCard(d: DownloadEntry, s: FrontEndState, a: FrontEndActions)
RoundAction(Icons.Filled.Refresh, stringResource(R.string.stores_dl_resume), primary = true) { DownloadQueue.retry(ctx, d.key) }
CancelAction { DownloadQueue.clear(ctx, d.key) }
}
DownloadState.INSTALLED -> if (d.store != Store.ROCKSTAR || com.droiddeck.launcher.stores.rockstar.RockstarLaunch.supports(d.id)) Box(Modifier.bloomIn(true, 420)) {
DownloadState.INSTALLED -> Box(Modifier.bloomIn(true, 420)) {
RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_play), primary = true) { if (d.key == EpicClient.DOWNLOAD_KEY) a.onEpicLauncher() else if (d.key == com.droiddeck.launcher.stores.battlenet.BattleNetClient.DOWNLOAD_KEY) a.onBattleNet() else launchStoreGame(d.store, d.id, s, a) }
}
DownloadState.CANCELLED -> {}
-1
View File
@@ -3999,6 +3999,5 @@
<string name="theme_white_red">Scarlet Snow</string>
<string name="theme_white_red_detail">White surfaces with red accents.</string>
<string name="stores_rockstar_launch_unavailable">Launch unavailable</string>
<string name="agent_browser_unavailable">No web browser is available to open this link.</string>
</resources>
@@ -0,0 +1,78 @@
package com.droiddeck.launcher.stores.rockstar
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import java.nio.ByteBuffer
import java.nio.ByteOrder
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33], application = android.app.Application::class)
class RockstarMetadataTest {
@Test fun findsRootMetadataAfterManyOtherFiles() {
val root = java.nio.file.Files.createTempDirectory("rockstar-many-files").toFile()
try {
repeat(300) { java.io.File(root, "asset-$it.dat").writeText("asset") }
java.io.File(root, "title.rgl").writeBytes(container("""{"titleId":"game","rosTitleId":123,"principalFileName":"Game.exe"}"""))
assertEquals("game", RockstarMetadata.find(root)?.id)
java.io.File(root, "title.rgl").delete()
java.io.File(root, "Title.RGL").writeBytes(container("""{"titleId":"game","rosTitleId":123,"principalFileName":"Game.exe"}"""))
assertEquals("game", RockstarMetadata.find(root)?.id)
} finally {
root.deleteRecursively()
}
}
private fun container(json: String): ByteArray {
val iv = ByteArray(16) { it.toByte() }
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(ByteArray(32), "AES"), IvParameterSpec(iv))
val payload = iv + cipher.doFinal(json.toByteArray())
val header = ByteBuffer.allocate(80).order(ByteOrder.LITTLE_ENDIAN)
header.put(byteArrayOf(82, 71, 76, 77)).putInt(1).putInt(payload.size)
return header.array() + payload
}
@Test fun decodesInstalledTitleWithoutAnAppIdAllowlist() {
val title = RockstarMetadata.decode(container("""{"titleId":"new_title","rosTitleId":123,"principalFileName":"Game/Binaries/Win64/Game.exe"}"""))!!
assertEquals("new_title", title.id)
assertEquals(123, title.rosId)
assertEquals("Game/Binaries/Win64/Game.exe", title.exe)
}
@Test fun rejectsBrokenContainersAndEscapingExecutables() {
val valid = container("""{"titleId":"game","rosTitleId":123,"principalFileName":"Game.exe"}""")
assertNull(RockstarMetadata.decode(valid.copyOf(90)))
assertNull(RockstarMetadata.decode(valid.copyOf().also { it[4] = 2 }))
assertNull(RockstarMetadata.decode(valid + byteArrayOf(0)))
assertNull(RockstarMetadata.decode(container("""{"titleId":"game","rosTitleId":1.5,"principalFileName":"Game.exe"}""")))
for (exe in listOf("../outside.exe", "C:/outside.exe", "/outside.exe")) {
assertNull(RockstarMetadata.decode(container("""{"titleId":"game","rosTitleId":123,"principalFileName":"$exe"}""")))
}
}
@Test fun doesNotFollowMetadataSymlinksOutsideTheGame() {
val root = java.nio.file.Files.createTempDirectory("rockstar-metadata").toFile()
val outside = java.io.File.createTempFile("rockstar-external", ".rgl")
try {
outside.writeBytes(container("""{"titleId":"game","rosTitleId":123,"principalFileName":"Game.exe"}"""))
val link = java.io.File(root, "title.rgl").toPath()
try { java.nio.file.Files.createSymbolicLink(link, outside.toPath()) }
catch (e: java.nio.file.FileSystemException) { org.junit.Assume.assumeNoException(e) }
assertNull(RockstarMetadata.find(root))
java.nio.file.Files.delete(link)
java.io.File(root, "nested").mkdir()
outside.copyTo(java.io.File(root, "nested/title.rgl"))
assertEquals("game", RockstarMetadata.find(root)?.id)
assertEquals("nested/Game.exe", RockstarMetadata.find(root)?.exe)
} finally {
root.deleteRecursively()
outside.delete()
}
}
}
@@ -12,6 +12,54 @@ import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33], application = android.app.Application::class)
class RockstarTest {
@Test fun sdkTicketExportsOnlyTheShortLivedServerResponse() {
val root = RockstarRos.parse("""<Response><Status>1</Status><Result><Ticket>opaque-game-ticket</Ticket><PlayerAccountId>456</PlayerAccountId><SessionKey>session-key</SessionKey><SessionTicket>session-ticket</SessionTicket><Services Count="1"><Service Name="game"><Hosts Count="1"><Host>example.invalid</Host></Hosts></Service><ScAuthToken>service-refresh-secret</ScAuthToken></Services><ScAuthToken>refresh-secret</ScAuthToken><RockstarAccount><RockstarId>123</RockstarId><Nickname>Player</Nickname><Email>player@example.invalid</Email><ScAuthToken>nested-refresh-secret</ScAuthToken></RockstarAccount></Result></Response>""")
val sdk = RockstarRos.parse(RockstarAuth.sdkTicket(root))
assertEquals("opaque-game-ticket", RockstarRos.text(sdk, "Ticket"))
assertEquals("session-key", RockstarRos.text(sdk, "SessionKey"))
assertEquals("123", RockstarRos.text(sdk, "RockstarId"))
assertEquals("456", RockstarRos.text(sdk, "PlayerAccountId"))
assertEquals("1", RockstarRos.first(sdk, "Services")?.getAttribute("Count"))
assertEquals("example.invalid", RockstarRos.text(sdk, "Host"))
assertNull(RockstarRos.first(sdk, "ScAuthToken"))
assertFalse(RockstarAuth.sdkTicket(root).contains("refresh-secret"))
}
@Test fun sdkTitleStateRequiresAnOwnedPackageInsteadOfCatalogVisibility() {
val visible = RockstarApp("1", "future_title", "123", emptyList())
val featured = RockstarAccountApps(listOf(visible), listOf(RockstarPackage("future_title", true)))
assertFalse(RockstarLibrary.owns(featured, 123, "future_title"))
val owned = RockstarAccountApps(listOf(visible), listOf(RockstarPackage("future_title", false)))
assertTrue(RockstarLibrary.owns(owned, 123, "future_title"))
assertFalse(RockstarLibrary.owns(owned, 124, "other_title"))
}
@Test fun directLaunchPreservesArgumentsThroughTheWindowsBatchInterpreter() {
org.junit.Assume.assumeTrue(java.io.File.separatorChar == '\\')
val root = java.nio.file.Files.createTempDirectory("rockstar-batch").toFile()
try {
java.io.File(System.getenv("SystemRoot"), "System32/cscript.exe").copyTo(java.io.File(root, "Game.exe"))
java.io.File(root, "probe.vbs").writeText("""
Set output = CreateObject("Scripting.FileSystemObject").CreateTextFile("args.txt", True)
For Each arg In WScript.Arguments
output.WriteLine(arg)
Next
output.Close
""".trimIndent())
val args = listOf("", "&literal", "one argument", "%PATH%", "!PATH!", "^&|<>()")
val game = com.droiddeck.launcher.stores.StoreGameSidecar(com.droiddeck.launcher.stores.Store.ROCKSTAR,
"future_title", "Game", "Game.exe", args = listOf("//nologo", "probe.vbs") + args)
com.droiddeck.launcher.stores.StoreLaunch.writeLauncher(root, game)
val process = ProcessBuilder("cmd.exe", "/d", "/c", java.io.File(root, com.droiddeck.launcher.stores.StoreLaunch.LAUNCHER).path)
.directory(root).redirectErrorStream(true).start()
assertTrue(process.waitFor(10, java.util.concurrent.TimeUnit.SECONDS))
assertEquals(process.inputStream.bufferedReader().readText(), 0, process.exitValue())
assertEquals(args, java.io.File(root, "args.txt").readLines())
} finally {
root.deleteRecursively()
}
}
@Test fun launcherAdoptionDoesNotFollowSymbolicLinks() {
val folder = java.nio.file.Files.createTempDirectory("rockstar-launch-link").toFile()
val outside = java.io.File.createTempFile("rockstar-keep", ".txt").apply { writeText("keep") }
@@ -51,7 +99,7 @@ class RockstarTest {
}
}
@Test fun unsupportedGamesKeepTheirFilesWithoutRegisteringALauncher() {
@Test fun otherRockstarGamesRegisterAndLaunchTheirInstalledExecutable() {
val app = org.robolectric.RuntimeEnvironment.getApplication()
com.droiddeck.launcher.session.SessionPrefs.setGameStorage(app, com.droiddeck.launcher.session.SessionPrefs.GAME_STORAGE_OFF, "")
val folder = java.io.File(com.droiddeck.launcher.stores.StoreInstallRoot.storeDir(com.droiddeck.launcher.stores.StoreInstallRoot.installRoot(app), com.droiddeck.launcher.stores.Store.ROCKSTAR), "RDR2").apply { mkdirs() }
@@ -62,11 +110,27 @@ class RockstarTest {
script.writeText("old launcher")
val finished = com.droiddeck.launcher.stores.StoreLaunch.writeLauncher(folder, game)
finished.write(folder)
assertFalse(RockstarLaunch.supports(game.id))
assertNull(finished.launcher)
assertFalse(script.exists())
assertFalse(RockstarLaunch.usesClassicLauncher(game.id))
assertEquals(com.droiddeck.launcher.stores.StoreLaunch.LAUNCHER, finished.launcher)
assertTrue(script.readText().contains("\"%~dp0RDR2.exe\""))
assertTrue(script.readText().contains("if not exist \"C:\\Program Files\\Rockstar Games\\Launcher\\launch.json\" goto direct"))
assertTrue(java.io.File(folder, game.exe).isFile)
assertNull(com.droiddeck.launcher.frontend.AddedGames.single(app, folder.path))
} finally {
folder.deleteRecursively()
}
}
@Test fun otherRockstarGamesCanRegisterShortcuts() {
org.junit.Assume.assumeTrue(java.io.File.separatorChar == '/')
val app = org.robolectric.RuntimeEnvironment.getApplication()
com.droiddeck.launcher.session.SessionPrefs.setGameStorage(app, com.droiddeck.launcher.session.SessionPrefs.GAME_STORAGE_OFF, "")
val folder = java.io.File(com.droiddeck.launcher.stores.StoreInstallRoot.storeDir(com.droiddeck.launcher.stores.StoreInstallRoot.installRoot(app), com.droiddeck.launcher.stores.Store.ROCKSTAR), "RDR2").apply { mkdirs() }
try {
java.io.File(folder, "RDR2.exe").writeText("installed game")
com.droiddeck.launcher.stores.StoreGameSidecar(com.droiddeck.launcher.stores.Store.ROCKSTAR, "rdr2", "RDR2", "RDR2.exe").write(folder)
val game = com.droiddeck.launcher.frontend.AddedGames.single(app, folder.path)
assertTrue(game != null)
assertTrue(game!!.guestExe.endsWith("/" + com.droiddeck.launcher.stores.StoreLaunch.LAUNCHER))
} finally {
folder.deleteRecursively()
}
@@ -110,7 +174,8 @@ class RockstarTest {
}
@Test fun classicTitlesUseTheirObservedPipeNames() {
assertEquals(mapOf("gta3" to "GTA3_Pipe", "gtavc" to "GTA-VC_Pipe", "gtasa" to "GTA_SA_Pipe"), RockstarLaunch.pipes)
assertEquals(mapOf("gta3" to "GTA3_Pipe", "gtavc" to "GTA-VC_Pipe", "gtasa" to "GTA_SA_Pipe", "gta4" to "GTAIV_Pipe", "lanoire" to "LANOIRE_Pipe"), RockstarLaunch.pipes)
for (id in RockstarLaunch.pipes.keys) assertTrue(RockstarLaunch.usesClassicLauncher(id))
}
@Test fun signingOutClearsOwnedShelfCards() {
@@ -162,14 +227,15 @@ class RockstarTest {
}
@Test
fun classicGamesStartTheirParentLauncherWithoutEmbeddingCredentials() {
fun rockstarLaunchScriptsContainNoCredentials() {
val sidecar = com.droiddeck.launcher.stores.StoreGameSidecar(
com.droiddeck.launcher.stores.Store.ROCKSTAR, "gtavc", "Vice City", "gta-vc.exe",
)
val text = com.droiddeck.launcher.stores.StoreLaunch.launcherText(sidecar)
assertTrue(text.contains("\"C:\\Program Files\\Rockstar Games\\Launcher\\Launcher.exe\""))
assertTrue(text.contains("exit /b %errorlevel%"))
assertFalse(text.contains("gta-vc.exe"))
assertTrue(text.contains("goto direct"))
assertTrue(text.contains("\"%~dp0gta-vc.exe\""))
assertFalse(text.contains("ticket", true))
assertFalse(text.contains("rem ", true))
}