mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-20 21:35:59 +00:00
Xbox: fix sign-in on phones with a slow StrongBox Keystore (#1521)
On some phones (tester: Honor BKQ-N49, Android 17) Xbox sign-in stopped with "the Xbox helper stopped with exit code 1" before Microsoft's page opened. The backend asks the app to read and save credentials over a socket and waits 10 s for each reply. The app sealed credentials with a StrongBox-backed Keystore key, and each StrongBox operation took 7-15 s on that phone, so the backend gave up. The app still finished those saves afterwards, leaving a record without a username that every later attempt had to read back slowly. - Seal new store credentials with a TEE Keystore key (v2 envelopes); v1 envelopes still open with the old key and move to v2 on their next write. - A sign-in discards an Xbox record without a username (an unfinished sign-in) before starting the backend. - The backend waits 30 s for the app's credential reply. - The backend names the failing step instead of only credential-io (socket connect/exchange, session lock, missing socket name/port/key), and falls back to a keyed 127.0.0.1 port when the abstract socket is refused. - The app's credential listener logs and retries accept errors, serves each connection on its own thread, and logs slow requests with per-stage times. Refs #1337, #1300 Co-authored-by: KeegantheVeganat0r <58369898+KeegantheVeganat0r@users.noreply.github.com>
This commit is contained in:
1 parent
82d8eb3b79
commit
5ca1f610ab
11 files changed
+541
-41
No files matched your search
@@ -1,6 +1,5 @@
|
||||
package com.droiddeck.launcher.stores
|
||||
|
||||
import android.os.Build
|
||||
import android.security.keystore.KeyGenParameterSpec
|
||||
import android.security.keystore.KeyProperties
|
||||
import android.util.Base64
|
||||
@@ -13,6 +12,8 @@ import javax.crypto.spec.GCMParameterSpec
|
||||
|
||||
object CredentialCipher {
|
||||
const val VERSION = 1
|
||||
/** Sealed with the hardware-keystore (TEE) key; [VERSION] envelopes keep opening with the older, possibly StrongBox, key. */
|
||||
const val VERSION_TEE = 2
|
||||
const val ALG = "AES/GCM"
|
||||
private const val TRANSFORMATION = "AES/GCM/NoPadding"
|
||||
private const val TAG_BITS = 128
|
||||
@@ -21,6 +22,11 @@ object CredentialCipher {
|
||||
fun key(): SecretKey
|
||||
|
||||
fun existing(): SecretKey = key()
|
||||
|
||||
/** Key for [VERSION] envelopes written before [VERSION_TEE]. */
|
||||
fun legacy(): SecretKey = existing()
|
||||
|
||||
val version: Int get() = VERSION
|
||||
}
|
||||
|
||||
class KeyMissing : java.security.GeneralSecurityException("no key")
|
||||
@@ -29,33 +35,33 @@ object CredentialCipher {
|
||||
e is android.security.keystore.KeyPermanentlyInvalidatedException ||
|
||||
e is KeyMissing || e is org.json.JSONException || e is IllegalArgumentException
|
||||
|
||||
// StrongBox took over 10 s per Xbox credential write on a tester's phone, past the backend's
|
||||
// 10 s reply timeout, so new writes use a TEE key. The old alias stays readable.
|
||||
object Keystore : KeyProvider {
|
||||
private const val ALIAS = "droiddeck-store-credentials"
|
||||
private const val LEGACY_ALIAS = "droiddeck-store-credentials"
|
||||
private const val ALIAS = "droiddeck-store-credentials-tee"
|
||||
private const val PROVIDER = "AndroidKeyStore"
|
||||
|
||||
@Synchronized
|
||||
override fun existing(): SecretKey {
|
||||
val ks = KeyStore.getInstance(PROVIDER).apply { load(null) }
|
||||
return ks.getKey(ALIAS, null) as? SecretKey ?: throw KeyMissing()
|
||||
}
|
||||
override val version: Int get() = VERSION_TEE
|
||||
|
||||
@Synchronized
|
||||
override fun key(): SecretKey {
|
||||
val ks = KeyStore.getInstance(PROVIDER).apply { load(null) }
|
||||
(ks.getKey(ALIAS, null) as? SecretKey)?.let { return it }
|
||||
if (Build.VERSION.SDK_INT >= 28) {
|
||||
try { return generate(strongBox = true) } catch (e: Exception) { }
|
||||
}
|
||||
return generate(strongBox = false)
|
||||
}
|
||||
override fun existing(): SecretKey = stored(ALIAS) ?: throw KeyMissing()
|
||||
|
||||
private fun generate(strongBox: Boolean): SecretKey {
|
||||
@Synchronized
|
||||
override fun legacy(): SecretKey = stored(LEGACY_ALIAS) ?: throw KeyMissing()
|
||||
|
||||
@Synchronized
|
||||
override fun key(): SecretKey = stored(ALIAS) ?: generate()
|
||||
|
||||
private fun stored(alias: String): SecretKey? =
|
||||
KeyStore.getInstance(PROVIDER).apply { load(null) }.getKey(alias, null) as? SecretKey
|
||||
|
||||
private fun generate(): SecretKey {
|
||||
val spec = KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
|
||||
.setKeySize(256)
|
||||
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
|
||||
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
|
||||
.setUserAuthenticationRequired(false)
|
||||
.apply { if (strongBox && Build.VERSION.SDK_INT >= 28) setIsStrongBoxBacked(true) }
|
||||
.build()
|
||||
return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, PROVIDER).run { init(spec); generateKey() }
|
||||
}
|
||||
@@ -64,15 +70,16 @@ object CredentialCipher {
|
||||
fun seal(plain: String, keys: KeyProvider): JSONObject {
|
||||
val cipher = Cipher.getInstance(TRANSFORMATION).apply { init(Cipher.ENCRYPT_MODE, keys.key()) }
|
||||
val ct = cipher.doFinal(plain.toByteArray(Charsets.UTF_8))
|
||||
return JSONObject().put("v", VERSION).put("alg", ALG)
|
||||
return JSONObject().put("v", keys.version).put("alg", ALG)
|
||||
.put("iv", b64(cipher.iv)).put("ct", b64(ct))
|
||||
}
|
||||
|
||||
fun open(envelope: JSONObject, keys: KeyProvider): String {
|
||||
require(envelope.optInt("v", -1) == VERSION && envelope.optString("alg") == ALG) { "unknown envelope" }
|
||||
val version = envelope.optInt("v", -1)
|
||||
require((version == VERSION || version == VERSION_TEE) && envelope.optString("alg") == ALG) { "unknown envelope" }
|
||||
val iv = Base64.decode(envelope.getString("iv"), Base64.NO_WRAP)
|
||||
val ct = Base64.decode(envelope.getString("ct"), Base64.NO_WRAP)
|
||||
val cipher = Cipher.getInstance(TRANSFORMATION).apply { init(Cipher.DECRYPT_MODE, keys.existing(), GCMParameterSpec(TAG_BITS, iv)) }
|
||||
val cipher = Cipher.getInstance(TRANSFORMATION).apply { init(Cipher.DECRYPT_MODE, if (version == VERSION) keys.legacy() else keys.existing(), GCMParameterSpec(TAG_BITS, iv)) }
|
||||
return String(cipher.doFinal(ct), Charsets.UTF_8)
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,11 @@ internal class XboxCredentials(private val app: Context, expectedGeneration: Str
|
||||
val name = "droiddeck-xbox-${UUID.randomUUID()}"
|
||||
private val generation = lifecycle(app, expectedGeneration) { it }
|
||||
private val server = LocalServerSocket(name)
|
||||
// Some devices refuse the abstract socket from inside PRoot; the backend then falls back to this keyed loopback port.
|
||||
private val loopback = java.net.ServerSocket(0, 8, java.net.InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1)))
|
||||
val port: Int get() = loopback.localPort
|
||||
val key: String = ByteArray(32).also { java.security.SecureRandom().nextBytes(it) }.joinToString("") { "%02x".format(it) }
|
||||
@Volatile private var loopbackUsed = false
|
||||
@Volatile private var closed = false
|
||||
private val bound = java.util.concurrent.CountDownLatch(1)
|
||||
private var backend: Process? = null
|
||||
@@ -79,33 +84,122 @@ internal class XboxCredentials(private val app: Context, expectedGeneration: Str
|
||||
} }
|
||||
}
|
||||
|
||||
init {
|
||||
/** Each connection gets its own thread; an accept error is logged and retried instead of silently ending the loop. */
|
||||
private fun <S> listen(route: String, accept: () -> S, serve: (S) -> Unit) = Thread({
|
||||
var failures = 0
|
||||
while (!closed) {
|
||||
val socket = try { accept() } catch (e: Exception) {
|
||||
if (closed) break
|
||||
failures++
|
||||
note("Credential $route accept failed: ${e.javaClass.simpleName}")
|
||||
if (failures >= 20) { note("Credential $route listener stopped after repeated accept failures"); break }
|
||||
Thread.sleep(100)
|
||||
continue
|
||||
}
|
||||
failures = 0
|
||||
Thread({ serve(socket) }, "xbox-credentials-$route-request").start()
|
||||
}
|
||||
}, "xbox-credentials-$route").start()
|
||||
|
||||
/** Logs requests that take 2 s or more, and the stage a request is still in after 8 s (the backend waits 30 s). */
|
||||
private fun tracked(route: String, block: (step: (String) -> Unit) -> JSONObject): JSONObject {
|
||||
val started = android.os.SystemClock.elapsedRealtime()
|
||||
val stage = java.util.concurrent.atomic.AtomicReference("auth")
|
||||
val done = java.util.concurrent.CountDownLatch(1)
|
||||
val stages = java.util.Collections.synchronizedList(mutableListOf<String>())
|
||||
var mark = started
|
||||
val step = { next: String ->
|
||||
val now = android.os.SystemClock.elapsedRealtime()
|
||||
stages += "${stage.getAndSet(next)} ${now - mark} ms"
|
||||
mark = now
|
||||
}
|
||||
Thread({
|
||||
while (!closed) {
|
||||
val socket = runCatching { server.accept() }.getOrNull() ?: break
|
||||
socket.use {
|
||||
it.soTimeout = 10_000
|
||||
val reply = runCatching {
|
||||
if (!done.await(8, java.util.concurrent.TimeUnit.SECONDS)) note("Credential $route request still in ${stage.get()} after 8 s")
|
||||
}, "xbox-credentials-watch").apply { isDaemon = true; start() }
|
||||
try {
|
||||
return block(step)
|
||||
} finally {
|
||||
done.countDown()
|
||||
step("done")
|
||||
val total = android.os.SystemClock.elapsedRealtime() - started
|
||||
if (total >= 2000) note("Credential $route request took $total ms (${stages.joinToString(", ")})")
|
||||
}
|
||||
}
|
||||
|
||||
init {
|
||||
listen("socket", { server.accept() }) { socket ->
|
||||
socket.use {
|
||||
it.soTimeout = 10_000
|
||||
val reply = tracked("socket") { step ->
|
||||
runCatching {
|
||||
val peer = it.peerCredentials
|
||||
check(peer.uid == android.os.Process.myUid() && authorized(peer.pid))
|
||||
step("read")
|
||||
val request = JSONObject(readLine(it.inputStream.buffered(), 2_097_152))
|
||||
step("lock")
|
||||
storage(app) {
|
||||
step("answer")
|
||||
check(!closed && epoch(app) == generation && authorized(peer.pid))
|
||||
answer(request)
|
||||
answer(request, step)
|
||||
}
|
||||
}.getOrElse {
|
||||
note("Credential request rejected: ${it.javaClass.simpleName}")
|
||||
JSONObject().put("ok", false)
|
||||
}
|
||||
runCatching { it.outputStream.write((reply.toString() + "\n").toByteArray()) }
|
||||
}
|
||||
runCatching { it.outputStream.write((reply.toString() + "\n").toByteArray()) }
|
||||
.onFailure { failure -> note("Credential reply not delivered: ${failure.javaClass.simpleName}") }
|
||||
}
|
||||
}, "xbox-credentials").start()
|
||||
}
|
||||
listen("loopback", { loopback.accept() }) { socket ->
|
||||
socket.use {
|
||||
it.soTimeout = 10_000
|
||||
val reply = tracked("loopback") { step ->
|
||||
runCatching {
|
||||
val input = it.getInputStream().buffered()
|
||||
check(it.inetAddress.isLoopbackAddress)
|
||||
if (!java.security.MessageDigest.isEqual(readLine(input, 128).toByteArray(), key.toByteArray())) {
|
||||
rejected("loopback-key"); error("loopback key")
|
||||
}
|
||||
if (!loopbackOwner(it.port)) { rejected("loopback-owner"); error("loopback owner") }
|
||||
check(bound.await(5, java.util.concurrent.TimeUnit.SECONDS) && backend?.isAlive == true)
|
||||
if (!loopbackUsed) { loopbackUsed = true; note("Backend reached the app over the loopback fallback") }
|
||||
step("read")
|
||||
val request = JSONObject(readLine(input, 2_097_152))
|
||||
step("lock")
|
||||
storage(app) {
|
||||
step("answer")
|
||||
check(!closed && epoch(app) == generation)
|
||||
answer(request, step)
|
||||
}
|
||||
}.getOrElse { failure ->
|
||||
note("Credential request rejected: ${failure.javaClass.simpleName}")
|
||||
JSONObject().put("ok", false)
|
||||
}
|
||||
}
|
||||
runCatching { it.getOutputStream().write((reply.toString() + "\n").toByteArray()) }
|
||||
.onFailure { failure -> note("Credential reply not delivered: ${failure.javaClass.simpleName}") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun answer(request: JSONObject): JSONObject {
|
||||
/** The connecting socket must belong to this app's user; an unreadable table (newer Android) leaves the key as the check. */
|
||||
private fun loopbackOwner(peerPort: Int): Boolean {
|
||||
val uid = android.os.Process.myUid()
|
||||
val rows = listOf("/proc/net/tcp", "/proc/net/tcp6").mapNotNull { runCatching { java.io.File(it).readLines().drop(1) }.getOrNull() }.flatten()
|
||||
val owners = rows.mapNotNull { row ->
|
||||
val fields = row.trim().split(Regex("\\s+"))
|
||||
val local = fields.getOrNull(1)?.substringAfterLast(':')?.toIntOrNull(16)
|
||||
val remote = fields.getOrNull(2)?.substringAfterLast(':')?.toIntOrNull(16)
|
||||
if (local == peerPort && remote == loopback.localPort) fields.getOrNull(7)?.toIntOrNull() else null
|
||||
}
|
||||
return owners.isEmpty() || owners.all { it == uid }
|
||||
}
|
||||
|
||||
private fun answer(request: JSONObject, step: (String) -> Unit = {}): JSONObject {
|
||||
val key = request.getString("key")
|
||||
require(key.isNotEmpty() && key.length <= 512)
|
||||
step("record-read")
|
||||
val record = StoreAccounts.read(app, Store.XBOX)
|
||||
check(!StoreAccounts.isUnavailable(Store.XBOX))
|
||||
val json = record ?: JSONObject()
|
||||
@@ -118,15 +212,16 @@ internal class XboxCredentials(private val app: Context, expectedGeneration: Str
|
||||
require(bytes.length() <= 262_144)
|
||||
for (i in 0 until bytes.length()) require(bytes.getInt(i) in 0..255)
|
||||
slots.put(key, bytes)
|
||||
step("record-save")
|
||||
StoreAccounts.write(app, Store.XBOX, json)
|
||||
}
|
||||
"remove" -> { slots.remove(key); StoreAccounts.write(app, Store.XBOX, json) }
|
||||
"remove" -> { slots.remove(key); step("record-save"); StoreAccounts.write(app, Store.XBOX, json) }
|
||||
else -> error("Invalid credential operation")
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
override fun close() { closed = true; bound.countDown(); runCatching { server.close() } }
|
||||
override fun close() { closed = true; bound.countDown(); runCatching { server.close() }; runCatching { loopback.close() } }
|
||||
|
||||
companion object {
|
||||
val lock = Any()
|
||||
|
||||
@@ -31,6 +31,7 @@ class XboxLoginActivity : ComponentActivity() {
|
||||
@Volatile private var session = 0L
|
||||
@Volatile private var closed = false
|
||||
@Volatile private var step = "starting"
|
||||
private val codes = java.util.concurrent.CopyOnWriteArrayList<String>()
|
||||
|
||||
@SuppressLint("SetJavaScriptEnabled")
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
@@ -53,6 +54,14 @@ class XboxLoginActivity : ComponentActivity() {
|
||||
Thread({
|
||||
if (closed) return@Thread
|
||||
try {
|
||||
// A record without a username is left from a sign-in that never finished; starting clean
|
||||
// also avoids reading it back with an older, slow Keystore key.
|
||||
progress("preparing the sign-in", "Preparing Microsoft sign-in…")
|
||||
val leftover = StoreAccounts.read(applicationContext, Store.XBOX)
|
||||
if (leftover != null && leftover.optString("username").isBlank()) {
|
||||
XboxCredentials.invalidate(applicationContext)
|
||||
logStep("discarded credentials from an unfinished sign-in")
|
||||
}
|
||||
val accountGeneration = XboxCredentials.lifecycle(applicationContext) { it }
|
||||
progress("downloading the Xbox components", "Downloading Xbox components…")
|
||||
check(AddonPack.XBOX.await(applicationContext, { !closed }) { state ->
|
||||
@@ -64,7 +73,10 @@ class XboxLoginActivity : ComponentActivity() {
|
||||
child = process
|
||||
if (closed) return@use
|
||||
// StoresState.logLine writes no file in this process, so the reason would miss the shared log.
|
||||
Xodus.diagnostics(process) { logStep(it) }
|
||||
Xodus.diagnostics(process) { line ->
|
||||
logStep(line)
|
||||
line.removePrefix("NEXUS_CREDENTIAL_ERROR_V1 ").takeIf { it != line && it !in codes && codes.size < 6 }?.let(codes::add)
|
||||
}
|
||||
progress("waiting for the Xbox helper", "Waiting for the Xbox helper…")
|
||||
val timer = Thread({
|
||||
runCatching { if (!process.process.waitFor(10, TimeUnit.MINUTES)) process.process.destroy() }
|
||||
@@ -140,7 +152,8 @@ class XboxLoginActivity : ComponentActivity() {
|
||||
logStep("failed while $failed: $reason")
|
||||
runOnUiThread {
|
||||
disposeView()
|
||||
status.text = "Microsoft sign-in did not complete.\nFailed while $failed: $reason\nClose this window and try again."
|
||||
val details = if (codes.isEmpty()) "" else "\nDetails: ${codes.joinToString(", ")}"
|
||||
status.text = "Microsoft sign-in did not complete.\nFailed while $failed: $reason$details\nClose this window and try again."
|
||||
}
|
||||
}
|
||||
}, "xbox-login").start()
|
||||
|
||||
@@ -101,6 +101,8 @@ internal object Xodus {
|
||||
val command = LinuxRuntime.commandWithBinds(app, root, binds, guestCommand)
|
||||
val builder = ProcessBuilder(command).directory(LinuxRuntime.rootDir(app))
|
||||
if (launchDirectory != null) builder.environment()["TMPDIR"] = launchDirectory.path
|
||||
builder.environment()["DROIDDECK_XBOX_CREDENTIAL_PORT"] = credentials.port.toString()
|
||||
builder.environment()["DROIDDECK_XBOX_CREDENTIAL_KEY"] = credentials.key
|
||||
builder.environment().apply {
|
||||
remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH")
|
||||
put("PROOT_LOADER", LinuxRuntime.prootLoader(app).path)
|
||||
|
||||
@@ -201,4 +201,20 @@ class StoreAccountsCipherTest {
|
||||
assertFalse(StoreAccounts.isUnavailable(Store.AMAZON))
|
||||
assertFalse(file(Store.AMAZON).exists())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun teeEnvelopesUseTheCurrentKeyAndOlderOnesTheLegacyKey() {
|
||||
val legacy = SecretKeySpec(ByteArray(32) { 7 }, "AES")
|
||||
val keys = object : CredentialCipher.KeyProvider {
|
||||
override fun key(): SecretKey = key
|
||||
override fun legacy(): SecretKey = legacy
|
||||
override val version: Int get() = CredentialCipher.VERSION_TEE
|
||||
}
|
||||
val old = CredentialCipher.seal("old", CredentialCipher.KeyProvider { legacy })
|
||||
assertEquals(CredentialCipher.VERSION, old.getInt("v"))
|
||||
assertEquals("old", CredentialCipher.open(old, keys))
|
||||
val new = CredentialCipher.seal("new", keys)
|
||||
assertEquals(CredentialCipher.VERSION_TEE, new.getInt("v"))
|
||||
assertEquals("new", CredentialCipher.open(new, keys))
|
||||
}
|
||||
}
|
||||
@@ -144,7 +144,8 @@ def wine(argv, source_env=None):
|
||||
if len(command) < 3 or command[1] != 'waitforexitandrun' or len(argv) != 1:
|
||||
raise ValueError('Invalid Xbox Proton invocation')
|
||||
env = dict(source_env)
|
||||
env.pop('DROIDDECK_XBOX_CREDENTIAL_SOCKET', None)
|
||||
for name in ('DROIDDECK_XBOX_CREDENTIAL_SOCKET', 'DROIDDECK_XBOX_CREDENTIAL_PORT', 'DROIDDECK_XBOX_CREDENTIAL_KEY'):
|
||||
env.pop(name, None)
|
||||
env.pop('DROIDDECK_XBOX_COMMAND_FILE', None)
|
||||
prefix = Path(source_env['STEAM_COMPAT_DATA_PATH']) / 'pfx'
|
||||
prefix.parent.mkdir(parents=True, exist_ok=True)
|
||||
@@ -207,7 +208,8 @@ def launch(command, env):
|
||||
owned_env = dict(env, DROIDDECK_XBOX_ACTIVE='1', DROIDDECK_XBOX_COMMAND_FILE=str(context),
|
||||
XODUS_SOCKET=reply['socket'], XODUS_BRIDGE_PORT=str(port), XODUS_BRIDGE_KEY=key,
|
||||
XODUS_LOG='off', RUST_LOG='off', XODUS_SAVE_SYNC='auto' if sidecar.get('cloud', True) else 'off')
|
||||
owned_env.pop('DROIDDECK_XBOX_CREDENTIAL_SOCKET', None)
|
||||
for name in ('DROIDDECK_XBOX_CREDENTIAL_SOCKET', 'DROIDDECK_XBOX_CREDENTIAL_PORT', 'DROIDDECK_XBOX_CREDENTIAL_KEY'):
|
||||
owned_env.pop(name, None)
|
||||
if reply.get('playfab'):
|
||||
owned_env['XODUS_XSTS_PLAYFAB'] = reply['playfab']
|
||||
content = folder / '.xbox-content'
|
||||
|
||||
@@ -56,11 +56,13 @@ class XboxLaunchTest(unittest.TestCase):
|
||||
patch.dict(xbox['launch'].__globals__, wine=unittest.mock.Mock(return_value=7)):
|
||||
launch = xbox['launch']
|
||||
self.assertEqual(launch(['/proton', 'waitforexitandrun', '/encrypted/Game.exe'],
|
||||
{'BL_LAUNCH_DIR': '/launch', 'DROIDDECK_XBOX_CREDENTIAL_SOCKET': 'stale'}), 7)
|
||||
{'BL_LAUNCH_DIR': '/launch', 'DROIDDECK_XBOX_CREDENTIAL_SOCKET': 'stale',
|
||||
'DROIDDECK_XBOX_CREDENTIAL_PORT': '4100', 'DROIDDECK_XBOX_CREDENTIAL_KEY': 'stale-key'}), 7)
|
||||
wine = launch.__globals__['wine']
|
||||
self.assertEqual(wine.call_args.args[0], ['/private/Game.exe'])
|
||||
env = wine.call_args.args[1]
|
||||
self.assertNotIn('DROIDDECK_XBOX_CREDENTIAL_SOCKET', env)
|
||||
for name in ('DROIDDECK_XBOX_CREDENTIAL_SOCKET', 'DROIDDECK_XBOX_CREDENTIAL_PORT', 'DROIDDECK_XBOX_CREDENTIAL_KEY'):
|
||||
self.assertNotIn(name, env)
|
||||
self.assertEqual(env['XODUS_XSTS_PLAYFAB'], 'game-token')
|
||||
close.assert_called_once()
|
||||
self.assertEqual(store['ask'].call_args.args[1], {'op': 'xbox-released', 'lease': 'lease-1'})
|
||||
@@ -117,7 +119,8 @@ class XboxLaunchTest(unittest.TestCase):
|
||||
command = root / 'command.json'
|
||||
command.write_text(json.dumps(['/selected/proton', 'waitforexitandrun', '/encrypted/Game.exe', '--custom', 'two words']))
|
||||
env = {'STEAM_COMPAT_DATA_PATH': str(prefix.parent), 'DROIDDECK_XBOX_COMMAND_FILE': str(command),
|
||||
'DROIDDECK_XBOX_CREDENTIAL_SOCKET': 'private-account-channel', 'XODUS_BRIDGE_KEY': 'runtime-key'}
|
||||
'DROIDDECK_XBOX_CREDENTIAL_SOCKET': 'private-account-channel', 'DROIDDECK_XBOX_CREDENTIAL_PORT': '4100',
|
||||
'DROIDDECK_XBOX_CREDENTIAL_KEY': 'private-key', 'XODUS_BRIDGE_KEY': 'runtime-key'}
|
||||
with patch.dict(os.environ, env), patch.dict(xbox['wine'].__globals__, RUNTIME=runtime.parent), patch('subprocess.run') as initialize, patch('subprocess.call', return_value=7) as call:
|
||||
initialize.return_value.returncode = 0
|
||||
self.assertEqual(xbox['wine'](['/private-view/Game.exe']), 7)
|
||||
@@ -128,7 +131,8 @@ class XboxLaunchTest(unittest.TestCase):
|
||||
initialize.assert_called_once()
|
||||
for child in (initialize, call):
|
||||
child_env = child.call_args.kwargs['env']
|
||||
self.assertNotIn('DROIDDECK_XBOX_CREDENTIAL_SOCKET', child_env)
|
||||
for name in ('DROIDDECK_XBOX_CREDENTIAL_SOCKET', 'DROIDDECK_XBOX_CREDENTIAL_PORT', 'DROIDDECK_XBOX_CREDENTIAL_KEY'):
|
||||
self.assertNotIn(name, child_env)
|
||||
self.assertNotIn('DROIDDECK_XBOX_COMMAND_FILE', child_env)
|
||||
self.assertEqual(child_env['XODUS_BRIDGE_KEY'], 'runtime-key')
|
||||
|
||||
|
||||
@@ -30,6 +30,16 @@ patched backend source archive and the checksum-verified runtime source archive
|
||||
in the build cache and publishes both in CI's `xbox-corresponding-source`
|
||||
artifact; distribute corresponding sources with published binaries.
|
||||
|
||||
`droiddeck-credential-fallback.patch` names the reason when the backend cannot reach the
|
||||
app's credential socket (`NEXUS_CREDENTIAL_ERROR_V1 socket-refused`, `-denied`, ...) and then
|
||||
uses a keyed loopback port the app also listens on; some devices refuse the abstract socket
|
||||
from inside PRoot. The key is passed in the backend's environment only.
|
||||
|
||||
`droiddeck-credential-diagnostics.patch` names the step behind a `credential-io` failure: the
|
||||
session lock (`lock-dir-owner`, `lock-file-mode`, `lock-flock-<reason>`, ...), a socket or loopback
|
||||
exchange that broke after connecting (`socket-exchange-<reason>`), a malformed host reply, or a
|
||||
missing socket name, port or key. Errno values without a name are spelled with letters, a = 0 ... j = 9.
|
||||
|
||||
`droiddeck-credentials.patch` replaces Linux Secret Service with a bounded,
|
||||
Android abstract socket restricted to the backend process started by the host. The Android host encrypts every persistent
|
||||
write using its existing Keystore cipher, verifies backend read-backs, and
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
diff --git a/crates/xodus/src/tokens/backend/keychain.rs b/crates/xodus/src/tokens/backend/keychain.rs
|
||||
index 19480da..dc8f136 100644
|
||||
--- a/crates/xodus/src/tokens/backend/keychain.rs
|
||||
+++ b/crates/xodus/src/tokens/backend/keychain.rs
|
||||
@@ -13,29 +13,24 @@ pub struct KeychainBackend;
|
||||
// keyed loopback port the app also listens on is used for the rest of the process.
|
||||
static LOOPBACK: AtomicBool = AtomicBool::new(false);
|
||||
static REPORTED: AtomicBool = AtomicBool::new(false);
|
||||
+// The app seals credentials with the Android Keystore, which took over 10 s on some phones.
|
||||
+const REPLY_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
-/// Letters and dashes only: the app passes `NEXUS_CREDENTIAL_ERROR_V1 [a-z-]{1,48}` lines to its log.
|
||||
-fn reason(error: &std::io::Error) -> &'static str {
|
||||
- match error.raw_os_error() {
|
||||
- Some(111) => "refused",
|
||||
- Some(13) => "denied",
|
||||
- Some(1) => "not-permitted",
|
||||
- Some(2) => "missing",
|
||||
- Some(110) => "timed-out",
|
||||
- Some(38) => "unsupported",
|
||||
- Some(97) => "family-unsupported",
|
||||
- Some(22) => "invalid",
|
||||
- Some(104) => "reset",
|
||||
- Some(32) => "broken-pipe",
|
||||
- _ => match error.kind() {
|
||||
- std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock => "timed-out",
|
||||
- std::io::ErrorKind::UnexpectedEof => "closed",
|
||||
- _ => "other",
|
||||
- },
|
||||
- }
|
||||
+use crate::tokens::store::io_reason as reason;
|
||||
+
|
||||
+fn exchange<S: Read + Write>(stream: S, prefix: Option<&str>, value: &Value) -> Result<Value, TokenStoreError> {
|
||||
+ let route = if prefix.is_some() { "loopback" } else { "socket" };
|
||||
+ transfer(stream, prefix, value).inspect_err(|error| {
|
||||
+ // Kind Other is the host's own refusal, already reported.
|
||||
+ if let TokenStoreError::Io(error) = error
|
||||
+ && error.kind() != std::io::ErrorKind::Other
|
||||
+ {
|
||||
+ eprintln!("NEXUS_CREDENTIAL_ERROR_V1 {route}-exchange-{}", reason(error));
|
||||
+ }
|
||||
+ })
|
||||
}
|
||||
|
||||
-fn exchange<S: Read + Write>(mut stream: S, prefix: Option<&str>, value: &Value) -> Result<Value, TokenStoreError> {
|
||||
+fn transfer<S: Read + Write>(mut stream: S, prefix: Option<&str>, value: &Value) -> Result<Value, TokenStoreError> {
|
||||
if let Some(key) = prefix {
|
||||
stream.write_all(key.as_bytes())?;
|
||||
stream.write_all(b"\n")?;
|
||||
@@ -45,6 +40,7 @@ fn exchange<S: Read + Write>(mut stream: S, prefix: Option<&str>, value: &Value)
|
||||
let mut bytes = Vec::new();
|
||||
std::io::BufReader::new(stream).take(2_097_153).read_until(b'\n', &mut bytes)?;
|
||||
if bytes.len() > 2_097_152 || bytes.last() != Some(&b'\n') {
|
||||
+ eprintln!("NEXUS_CREDENTIAL_ERROR_V1 host-response-invalid");
|
||||
return Err(std::io::Error::other("Invalid Android credential response").into());
|
||||
}
|
||||
let response: Value = serde_json::from_slice(&bytes)?;
|
||||
@@ -56,28 +52,36 @@ fn exchange<S: Read + Write>(mut stream: S, prefix: Option<&str>, value: &Value)
|
||||
}
|
||||
|
||||
fn loopback(value: &Value) -> Result<Value, TokenStoreError> {
|
||||
- let port: u16 = std::env::var("DROIDDECK_XBOX_CREDENTIAL_PORT").ok().and_then(|v| v.parse().ok())
|
||||
- .ok_or_else(|| std::io::Error::other("Android credential port is unavailable"))?;
|
||||
- let key = std::env::var("DROIDDECK_XBOX_CREDENTIAL_KEY")
|
||||
- .map_err(|_| std::io::Error::other("Android credential key is unavailable"))?;
|
||||
+ let port: u16 = std::env::var("DROIDDECK_XBOX_CREDENTIAL_PORT").ok().and_then(|v| v.parse().ok()).ok_or_else(|| {
|
||||
+ eprintln!("NEXUS_CREDENTIAL_ERROR_V1 loopback-port-missing");
|
||||
+ std::io::Error::other("Android credential port is unavailable")
|
||||
+ })?;
|
||||
+ let key = std::env::var("DROIDDECK_XBOX_CREDENTIAL_KEY").map_err(|_| {
|
||||
+ eprintln!("NEXUS_CREDENTIAL_ERROR_V1 loopback-key-missing");
|
||||
+ std::io::Error::other("Android credential key is unavailable")
|
||||
+ })?;
|
||||
let address = SocketAddrV4::new(Ipv4Addr::LOCALHOST, port).into();
|
||||
let stream = TcpStream::connect_timeout(&address, Duration::from_secs(5)).inspect_err(|error| {
|
||||
eprintln!("NEXUS_CREDENTIAL_ERROR_V1 loopback-{}", reason(error));
|
||||
})?;
|
||||
- stream.set_read_timeout(Some(Duration::from_secs(10)))?;
|
||||
- stream.set_write_timeout(Some(Duration::from_secs(10)))?;
|
||||
+ stream.set_read_timeout(Some(REPLY_TIMEOUT))?;
|
||||
+ stream.set_write_timeout(Some(REPLY_TIMEOUT))?;
|
||||
exchange(stream, Some(&key), value)
|
||||
}
|
||||
|
||||
fn request(value: Value) -> Result<Value, TokenStoreError> {
|
||||
if LOOPBACK.load(Ordering::Relaxed) { return loopback(&value); }
|
||||
- let name = std::env::var("DROIDDECK_XBOX_CREDENTIAL_SOCKET")
|
||||
- .map_err(|_| std::io::Error::other("Android credential host is unavailable"))?;
|
||||
- let address = SocketAddr::from_abstract_name(name)?;
|
||||
+ let name = std::env::var("DROIDDECK_XBOX_CREDENTIAL_SOCKET").map_err(|_| {
|
||||
+ eprintln!("NEXUS_CREDENTIAL_ERROR_V1 socket-name-missing");
|
||||
+ std::io::Error::other("Android credential host is unavailable")
|
||||
+ })?;
|
||||
+ let address = SocketAddr::from_abstract_name(name).inspect_err(|_| {
|
||||
+ eprintln!("NEXUS_CREDENTIAL_ERROR_V1 socket-name-invalid");
|
||||
+ })?;
|
||||
match UnixStream::connect_addr(&address) {
|
||||
Ok(stream) => {
|
||||
- stream.set_read_timeout(Some(Duration::from_secs(10)))?;
|
||||
- stream.set_write_timeout(Some(Duration::from_secs(10)))?;
|
||||
+ stream.set_read_timeout(Some(REPLY_TIMEOUT))?;
|
||||
+ stream.set_write_timeout(Some(REPLY_TIMEOUT))?;
|
||||
exchange(stream, None, &value)
|
||||
}
|
||||
Err(error) => {
|
||||
diff --git a/crates/xodus/src/tokens/session.rs b/crates/xodus/src/tokens/session.rs
|
||||
index 38c4b2b..254c14f 100644
|
||||
--- a/crates/xodus/src/tokens/session.rs
|
||||
+++ b/crates/xodus/src/tokens/session.rs
|
||||
@@ -44,14 +44,30 @@ async fn renewal_lock_at(
|
||||
wait: WaitDuration,
|
||||
) -> std::io::Result<std::fs::File> {
|
||||
use std::os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt};
|
||||
+ fn report(stage: &'static str) -> impl Fn(&std::io::Error) {
|
||||
+ move |error| eprintln!("NEXUS_CREDENTIAL_ERROR_V1 lock-{stage}-{}", super::store::io_reason(error))
|
||||
+ }
|
||||
+ fn unsafe_lock(stage: &str, check: &str) -> std::io::Error {
|
||||
+ eprintln!("NEXUS_CREDENTIAL_ERROR_V1 lock-{stage}-{check}");
|
||||
+ std::io::Error::other(if stage == "dir" { "Unsafe session lock directory" } else { "Unsafe session lock" })
|
||||
+ }
|
||||
match std::fs::DirBuilder::new().mode(0o700).create(&root) {
|
||||
Ok(()) => {}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
|
||||
- Err(error) => return Err(error),
|
||||
+ Err(error) => {
|
||||
+ report("dir-create")(&error);
|
||||
+ return Err(error);
|
||||
+ }
|
||||
+ }
|
||||
+ let dir = std::fs::symlink_metadata(&root).inspect_err(report("dir-stat"))?;
|
||||
+ if !dir.is_dir() {
|
||||
+ return Err(unsafe_lock("dir", "type"));
|
||||
+ }
|
||||
+ if dir.uid() != uid {
|
||||
+ return Err(unsafe_lock("dir", "owner"));
|
||||
}
|
||||
- let dir = std::fs::symlink_metadata(&root)?;
|
||||
- if !dir.is_dir() || dir.uid() != uid || dir.mode() & 0o077 != 0 {
|
||||
- return Err(std::io::Error::other("Unsafe session lock directory"));
|
||||
+ if dir.mode() & 0o077 != 0 {
|
||||
+ return Err(unsafe_lock("dir", "mode"));
|
||||
}
|
||||
let file = std::fs::OpenOptions::new()
|
||||
.read(true)
|
||||
@@ -60,10 +76,20 @@ async fn renewal_lock_at(
|
||||
.truncate(false)
|
||||
.mode(0o600)
|
||||
.custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
|
||||
- .open(root.join("device.lock"))?;
|
||||
- let meta = file.metadata()?;
|
||||
- if !meta.is_file() || meta.uid() != uid || meta.nlink() != 1 || meta.mode() & 0o077 != 0 {
|
||||
- return Err(std::io::Error::other("Unsafe session lock"));
|
||||
+ .open(root.join("device.lock"))
|
||||
+ .inspect_err(report("file-open"))?;
|
||||
+ let meta = file.metadata().inspect_err(report("file-stat"))?;
|
||||
+ if !meta.is_file() {
|
||||
+ return Err(unsafe_lock("file", "type"));
|
||||
+ }
|
||||
+ if meta.uid() != uid {
|
||||
+ return Err(unsafe_lock("file", "owner"));
|
||||
+ }
|
||||
+ if meta.nlink() != 1 {
|
||||
+ return Err(unsafe_lock("file", "links"));
|
||||
+ }
|
||||
+ if meta.mode() & 0o077 != 0 {
|
||||
+ return Err(unsafe_lock("file", "mode"));
|
||||
}
|
||||
let deadline = tokio::time::Instant::now() + wait;
|
||||
loop {
|
||||
@@ -75,7 +101,10 @@ async fn renewal_lock_at(
|
||||
{
|
||||
tokio::time::sleep(WaitDuration::from_millis(100)).await
|
||||
}
|
||||
- Err(error) => return Err(error),
|
||||
+ Err(error) => {
|
||||
+ report("flock")(&error);
|
||||
+ return Err(error);
|
||||
+ }
|
||||
}
|
||||
}
|
||||
}
|
||||
diff --git a/crates/xodus/src/tokens/store.rs b/crates/xodus/src/tokens/store.rs
|
||||
index 78b73d0..15cbff0 100644
|
||||
--- a/crates/xodus/src/tokens/store.rs
|
||||
+++ b/crates/xodus/src/tokens/store.rs
|
||||
@@ -50,3 +50,51 @@ impl TokenStoreError {
|
||||
eprintln!("{self}");
|
||||
}
|
||||
}
|
||||
+
|
||||
+/// Letters and dashes only: DroidDeck passes `NEXUS_CREDENTIAL_ERROR_V1 [a-z-]{1,48}` lines to its
|
||||
+/// log. Unlisted errno values are spelled with letters, a = 0 ... j = 9 (`os-dh` = errno 37).
|
||||
+pub(crate) fn io_reason(error: &std::io::Error) -> String {
|
||||
+ let known = match error.raw_os_error() {
|
||||
+ Some(111) => "refused",
|
||||
+ Some(13) => "denied",
|
||||
+ Some(1) => "not-permitted",
|
||||
+ Some(2) => "missing",
|
||||
+ Some(110) => "timed-out",
|
||||
+ Some(38) => "unsupported",
|
||||
+ Some(97) => "family-unsupported",
|
||||
+ Some(22) => "invalid",
|
||||
+ Some(104) => "reset",
|
||||
+ Some(32) => "broken-pipe",
|
||||
+ Some(4) => "interrupted",
|
||||
+ Some(11) => "would-block",
|
||||
+ Some(17) => "exists",
|
||||
+ Some(20) => "not-directory",
|
||||
+ Some(21) => "is-directory",
|
||||
+ Some(28) => "no-space",
|
||||
+ Some(30) => "read-only",
|
||||
+ Some(37) => "no-locks",
|
||||
+ Some(40) => "symlink-loop",
|
||||
+ Some(95) => "not-supported",
|
||||
+ Some(code) => {
|
||||
+ let letters: String = code.unsigned_abs().to_string().bytes().map(|b| (b - b'0' + b'a') as char).collect();
|
||||
+ return format!("os-{letters}");
|
||||
+ }
|
||||
+ None => match error.kind() {
|
||||
+ std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock => "timed-out",
|
||||
+ std::io::ErrorKind::UnexpectedEof => "closed",
|
||||
+ _ => "other",
|
||||
+ },
|
||||
+ };
|
||||
+ known.to_string()
|
||||
+}
|
||||
+
|
||||
+#[cfg(test)]
|
||||
+mod io_reason_tests {
|
||||
+ #[test]
|
||||
+ fn io_reason_is_letters_and_dashes() {
|
||||
+ for (code, expected) in [(37, "no-locks"), (13, "denied"), (99, "os-jj"), (125, "os-bcf")] {
|
||||
+ assert_eq!(super::io_reason(&std::io::Error::from_raw_os_error(code)), expected);
|
||||
+ }
|
||||
+ assert_eq!(super::io_reason(&std::io::Error::other("x")), "other");
|
||||
+ }
|
||||
+}
|
||||
@@ -0,0 +1,113 @@
|
||||
diff --git a/crates/xodus/src/tokens/backend/keychain.rs b/crates/xodus/src/tokens/backend/keychain.rs
|
||||
index 1903638..19480da 100644
|
||||
--- a/crates/xodus/src/tokens/backend/keychain.rs
|
||||
+++ b/crates/xodus/src/tokens/backend/keychain.rs
|
||||
@@ -1,20 +1,46 @@
|
||||
use crate::tokens::store::{TokenBackend, TokenStoreError};
|
||||
use serde_json::{Value, json};
|
||||
use std::io::{BufRead, Read, Write};
|
||||
+use std::net::{Ipv4Addr, SocketAddrV4, TcpStream};
|
||||
use std::os::linux::net::SocketAddrExt;
|
||||
use std::os::unix::net::{SocketAddr, UnixStream};
|
||||
+use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
pub struct KeychainBackend;
|
||||
|
||||
-fn request(value: Value) -> Result<Value, TokenStoreError> {
|
||||
- let name = std::env::var("DROIDDECK_XBOX_CREDENTIAL_SOCKET")
|
||||
- .map_err(|_| std::io::Error::other("Android credential host is unavailable"))?;
|
||||
- let address = SocketAddr::from_abstract_name(name)?;
|
||||
- let mut stream = UnixStream::connect_addr(&address)?;
|
||||
- stream.set_read_timeout(Some(Duration::from_secs(10)))?;
|
||||
- stream.set_write_timeout(Some(Duration::from_secs(10)))?;
|
||||
- serde_json::to_writer(&mut stream, &value)?;
|
||||
+// Some Android devices refuse the abstract socket from inside PRoot; after one failure the
|
||||
+// keyed loopback port the app also listens on is used for the rest of the process.
|
||||
+static LOOPBACK: AtomicBool = AtomicBool::new(false);
|
||||
+static REPORTED: AtomicBool = AtomicBool::new(false);
|
||||
+
|
||||
+/// Letters and dashes only: the app passes `NEXUS_CREDENTIAL_ERROR_V1 [a-z-]{1,48}` lines to its log.
|
||||
+fn reason(error: &std::io::Error) -> &'static str {
|
||||
+ match error.raw_os_error() {
|
||||
+ Some(111) => "refused",
|
||||
+ Some(13) => "denied",
|
||||
+ Some(1) => "not-permitted",
|
||||
+ Some(2) => "missing",
|
||||
+ Some(110) => "timed-out",
|
||||
+ Some(38) => "unsupported",
|
||||
+ Some(97) => "family-unsupported",
|
||||
+ Some(22) => "invalid",
|
||||
+ Some(104) => "reset",
|
||||
+ Some(32) => "broken-pipe",
|
||||
+ _ => match error.kind() {
|
||||
+ std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock => "timed-out",
|
||||
+ std::io::ErrorKind::UnexpectedEof => "closed",
|
||||
+ _ => "other",
|
||||
+ },
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+fn exchange<S: Read + Write>(mut stream: S, prefix: Option<&str>, value: &Value) -> Result<Value, TokenStoreError> {
|
||||
+ if let Some(key) = prefix {
|
||||
+ stream.write_all(key.as_bytes())?;
|
||||
+ stream.write_all(b"\n")?;
|
||||
+ }
|
||||
+ serde_json::to_writer(&mut stream, value)?;
|
||||
stream.write_all(b"\n")?;
|
||||
let mut bytes = Vec::new();
|
||||
std::io::BufReader::new(stream).take(2_097_153).read_until(b'\n', &mut bytes)?;
|
||||
@@ -22,10 +48,52 @@ fn request(value: Value) -> Result<Value, TokenStoreError> {
|
||||
return Err(std::io::Error::other("Invalid Android credential response").into());
|
||||
}
|
||||
let response: Value = serde_json::from_slice(&bytes)?;
|
||||
- if response["ok"] != true { return Err(std::io::Error::other("Android credential storage unavailable").into()); }
|
||||
+ if response["ok"] != true {
|
||||
+ eprintln!("NEXUS_CREDENTIAL_ERROR_V1 host-refused");
|
||||
+ return Err(std::io::Error::other("Android credential storage unavailable").into());
|
||||
+ }
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
+fn loopback(value: &Value) -> Result<Value, TokenStoreError> {
|
||||
+ let port: u16 = std::env::var("DROIDDECK_XBOX_CREDENTIAL_PORT").ok().and_then(|v| v.parse().ok())
|
||||
+ .ok_or_else(|| std::io::Error::other("Android credential port is unavailable"))?;
|
||||
+ let key = std::env::var("DROIDDECK_XBOX_CREDENTIAL_KEY")
|
||||
+ .map_err(|_| std::io::Error::other("Android credential key is unavailable"))?;
|
||||
+ let address = SocketAddrV4::new(Ipv4Addr::LOCALHOST, port).into();
|
||||
+ let stream = TcpStream::connect_timeout(&address, Duration::from_secs(5)).inspect_err(|error| {
|
||||
+ eprintln!("NEXUS_CREDENTIAL_ERROR_V1 loopback-{}", reason(error));
|
||||
+ })?;
|
||||
+ stream.set_read_timeout(Some(Duration::from_secs(10)))?;
|
||||
+ stream.set_write_timeout(Some(Duration::from_secs(10)))?;
|
||||
+ exchange(stream, Some(&key), value)
|
||||
+}
|
||||
+
|
||||
+fn request(value: Value) -> Result<Value, TokenStoreError> {
|
||||
+ if LOOPBACK.load(Ordering::Relaxed) { return loopback(&value); }
|
||||
+ let name = std::env::var("DROIDDECK_XBOX_CREDENTIAL_SOCKET")
|
||||
+ .map_err(|_| std::io::Error::other("Android credential host is unavailable"))?;
|
||||
+ let address = SocketAddr::from_abstract_name(name)?;
|
||||
+ match UnixStream::connect_addr(&address) {
|
||||
+ Ok(stream) => {
|
||||
+ stream.set_read_timeout(Some(Duration::from_secs(10)))?;
|
||||
+ stream.set_write_timeout(Some(Duration::from_secs(10)))?;
|
||||
+ exchange(stream, None, &value)
|
||||
+ }
|
||||
+ Err(error) => {
|
||||
+ if !REPORTED.swap(true, Ordering::Relaxed) {
|
||||
+ eprintln!("NEXUS_CREDENTIAL_ERROR_V1 socket-{}", reason(&error));
|
||||
+ }
|
||||
+ let result = loopback(&value);
|
||||
+ if result.is_ok() {
|
||||
+ LOOPBACK.store(true, Ordering::Relaxed);
|
||||
+ eprintln!("NEXUS_CREDENTIAL_ERROR_V1 loopback-in-use");
|
||||
+ }
|
||||
+ result
|
||||
+ }
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
impl TokenBackend for KeychainBackend {
|
||||
fn get(&self, key: &str) -> Result<Option<Vec<u8>>, TokenStoreError> {
|
||||
let response = request(json!({"op":"get", "key":key}))?;
|
||||
@@ -9,7 +9,8 @@ import sys
|
||||
recipe = Path(__file__).resolve().parent
|
||||
cache = Path(sys.argv[1]).resolve()
|
||||
lock = json.loads((recipe / 'backend.lock.json').read_text())
|
||||
local_patches = ['droiddeck-credentials.patch', 'droiddeck-launch-view.patch', 'droiddeck-library-subscriptions.patch']
|
||||
local_patches = ['droiddeck-credentials.patch', 'droiddeck-launch-view.patch', 'droiddeck-library-subscriptions.patch',
|
||||
'droiddeck-credential-fallback.patch', 'droiddeck-credential-diagnostics.patch']
|
||||
identity = hashlib.sha256((recipe / 'backend.lock.json').read_bytes() + b''.join((recipe / name).read_bytes() for name in local_patches)).hexdigest()
|
||||
source = cache / ('source-' + identity[:16])
|
||||
if not (source / '.prepared').is_file():
|
||||
|
||||
Reference in new issue
Block a user