Add Kotlin and Rust Android agent with signed APK export

This commit is contained in:
tongtong committed 2026-11-13 13:03:58 +08:00
1 parent e366eb5bec
commit 5b3022e1f3
20 files changed
+3568 -2

No files matched your search

@@ -0,0 +1,12 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE"/>
<application android:label="ADS 手机设备端" android:theme="@android:style/Theme.Material.Light.NoActionBar" android:allowBackup="false" android:usesCleartextTraffic="false" android:supportsRtl="true">
<activity android:name=".MainActivity" android:exported="true"><intent-filter><action android:name="android.intent.action.MAIN"/><category android:name="android.intent.category.LAUNCHER"/></intent-filter></activity>
<service android:name=".AgentService" android:exported="false" android:stopWithTask="false" android:foregroundServiceType="specialUse"><property android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE" android:value="User-enabled remote ADB device relay for managed system devices"/></service>
<receiver android:name=".BootReceiver" android:exported="false"><intent-filter><action android:name="android.intent.action.BOOT_COMPLETED"/></intent-filter></receiver>
</application>
</manifest>
@@ -0,0 +1,23 @@
package com.ttstd.ads
import android.content.Context
import org.json.JSONObject
/** Agent credential comes from an ignored build-time file; never print it. */
object AgentConfig {
fun prefs(c: Context) = c.getSharedPreferences("agent", Context.MODE_PRIVATE)
fun save(c: Context, server: String, device: String, port: Int) {
require(device.matches(Regex("[A-Za-z0-9._-]{1,128}"))) { "Invalid device ID" }
require(port in 1..65535) { "Invalid adbd port" }
val uri = java.net.URI(server)
require(uri.scheme == "wss" && !uri.host.isNullOrEmpty() && uri.userInfo == null && uri.query == null && uri.fragment == null) { "Invalid WSS URL" }
check(prefs(c).edit().putString("server", server).putString("device", device).putInt("port", port)
.remove("token").remove("iv").commit()) { "Configuration write failed" }
}
fun json(c: Context): String {
val p = prefs(c)
return JSONObject().put("server", p.getString("server", "wss://ttstd.com/ads"))
.put("device", p.getString("device", "android-phone")).put("port", p.getInt("port", 5555))
.put("token", BuildConfig.AGENT_TOKEN).toString()
}
}
@@ -0,0 +1,19 @@
package com.ttstd.ads
import android.util.Log
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
object AgentLog {
private val lines = ArrayDeque<String>()
@Volatile var status = "未启动"
@Synchronized fun add(stage: String, text: String) {
// Call sites never supply config JSON, credentials, tickets, SDP, or ADB payloads.
val line = "${SimpleDateFormat("HH:mm:ss.SSS", Locale.ROOT).format(Date())} [$stage] ${text.take(1600)}"
Log.i("ADS-Agent", line)
lines.addLast(line)
while (lines.size > 300) lines.removeFirst()
}
@Synchronized fun text(): String = lines.joinToString("\n")
}
@@ -0,0 +1,75 @@
package com.ttstd.ads
import android.app.*
import android.content.*
import android.content.pm.ServiceInfo
import android.os.*
import org.json.JSONObject
class AgentService : Service() {
private lateinit var thread: HandlerThread
private lateinit var worker: Handler
private var started = false
private val poll = object : Runnable {
override fun run() {
if (!started) return
try {
val s = JSONObject(NativeBridge.snapshot())
AgentLog.status = when { !s.optBoolean("running") -> "原生核心已停止"; s.optBoolean("registered") -> "已注册 · 等待/处理远程连接"; else -> "连接中 · 自动重试" }
val logs = s.optJSONArray("logs")
if (logs != null) for (i in 0 until logs.length()) AgentLog.add("RUST", logs.getString(i).trim())
s.optString("error").takeIf { it.isNotEmpty() && it != "null" }?.let { AgentLog.status += " · $it" }
} catch (e: Exception) { AgentLog.add("POLL_FAILED", e.javaClass.simpleName) }
worker.postDelayed(this, 1000)
}
}
override fun onCreate() {
super.onCreate()
thread = HandlerThread("ads-agent-control").apply { start() }; worker = Handler(thread.looper)
AgentLog.add("SERVICE_CREATE", "Android API=${Build.VERSION.SDK_INT}; ABI=${Build.SUPPORTED_ABIS.joinToString()}; no permission requests")
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (!AgentConfig.prefs(this).getBoolean("enabled", false)) { stopSelf(); return START_NOT_STICKY }
try { foreground() } catch (e: Exception) {
AgentLog.add("FGS_DENIED", "${e.javaClass.simpleName}: ROM must allow foreground service startup")
stopSelf(); return START_NOT_STICKY
}
worker.post {
if (!started) {
try {
check(NativeBridge.loadError == null) { NativeBridge.loadError!! }
val error = NativeBridge.start(AgentConfig.json(this))
check(error.isEmpty()) { error }
started = true; AgentLog.add("NATIVE_STARTED", "网关已启动;registered 不等于 adbd 已授权;未自动开启 TCP ADB")
worker.post(poll)
} catch (e: Exception) {
AgentLog.status = "启动失败"
AgentLog.add("START_FAILED", if (e is IllegalStateException) e.message ?: "配置或核心错误" else "${e.javaClass.simpleName}: 配置不可用,请重新保存")
stopSelf()
}
}
}
return START_STICKY
}
private fun foreground() {
val manager = getSystemService(NotificationManager::class.java)
if (Build.VERSION.SDK_INT >= 26) manager.createNotificationChannel(NotificationChannel("agent", "ADS 远程调试", NotificationManager.IMPORTANCE_LOW))
val open = PendingIntent.getActivity(this, 0, Intent(this, MainActivity::class.java), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
val builder = if (Build.VERSION.SDK_INT >= 26) Notification.Builder(this, "agent") else Notification.Builder(this)
val notification = builder.setSmallIcon(android.R.drawable.stat_sys_upload).setContentTitle("ADS 远程调试服务")
.setContentText("手机正连接远程调试网关,点此查看或停止").setContentIntent(open).setOngoing(true).build()
if (Build.VERSION.SDK_INT >= 34) startForeground(1, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE) else startForeground(1, notification)
}
override fun onDestroy() {
worker.removeCallbacks(poll)
worker.post { if (started) { NativeBridge.stop(); started = false }; AgentLog.status = "已停止"; AgentLog.add("SERVICE_STOP", "数据会话与控制连接已释放"); thread.quitSafely() }
super.onDestroy()
}
override fun onBind(intent: Intent?) = null
companion object {
fun launch(c: Context) {
try { val i = Intent(c, AgentService::class.java); if (Build.VERSION.SDK_INT >= 26) c.startForegroundService(i) else c.startService(i) }
catch (e: Exception) { AgentLog.status = "系统拒绝启动"; AgentLog.add("LAUNCH_DENIED", "${e.javaClass.simpleName}: 检查系统预授权及后台启动策略") }
}
}
}
@@ -0,0 +1,11 @@
package com.ttstd.ads
import android.content.*
class BootReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action != Intent.ACTION_BOOT_COMPLETED) return
if (AgentConfig.prefs(context).getBoolean("enabled", false)) {
AgentLog.add("BOOT", "用户已启用远程调试,尝试恢复服务(解锁后启动)")
AgentService.launch(context)
}
}
}
@@ -0,0 +1,47 @@
package com.ttstd.ads
import android.app.Activity
import android.os.*
import android.content.Intent
import android.text.InputType
import android.widget.*
class MainActivity : Activity() {
private val handler = Handler(Looper.getMainLooper())
private lateinit var state: TextView
private lateinit var logs: TextView
private val refresh = object : Runnable {
override fun run() { state.text = AgentLog.status; logs.text = AgentLog.text(); handler.postDelayed(this, 1000) }
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val p = AgentConfig.prefs(this)
val box = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL; setPadding(24, 24, 24, 24) }
val scroll = ScrollView(this).apply { isFillViewport = true; addView(box) }; setContentView(scroll)
fun label(text: String) { box.addView(TextView(this).apply { this.text = text; textSize = 16f }) }
fun field(title: String, value: String, secret: Boolean = false): EditText {
label(title)
return EditText(this).apply { setSingleLine(true); setText(value); inputType = if (secret) InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD else InputType.TYPE_CLASS_TEXT; box.addView(this) }
}
label("ADS · 手机直接接入远程调试")
label("不需要 USB 线。ROM 必须预先允许本机 adbd 接入和后台运行。本应用不申请权限、不执行提权。")
val server = field("控制中心", p.getString("server", "wss://ttstd.com/ads")!!)
val device = field("设备 ID", p.getString("device", "android-phone")!!)
val port = field("本机 adbd 端口(仅连接 127.0.0.1)", p.getInt("port", 5555).toString())
port.inputType = InputType.TYPE_CLASS_NUMBER
label("Agent 令牌已内置,无需填写")
box.addView(Button(this).apply { text = "保存并启动(改配置前先停止)"; setOnClickListener {
try {
AgentConfig.save(this@MainActivity, server.text.toString().trim(), device.text.toString().trim(), port.text.toString().toInt())
p.edit().putBoolean("enabled", true).apply(); AgentService.launch(this@MainActivity)
} catch (e: Exception) { AgentLog.add("CONFIG_INVALID", if (e is IllegalArgumentException) "设备 ID / WSS / 令牌 / 端口格式错误" else "${e.javaClass.simpleName}: 无法保存配置") }
} })
box.addView(Button(this).apply { text = "停止并关闭开机恢复"; setOnClickListener {
p.edit().putBoolean("enabled", false).commit(); stopService(Intent(this@MainActivity, AgentService::class.java))
AgentLog.status = "停止中"; AgentLog.add("USER_STOP", "已关闭开机恢复")
} })
state = TextView(this).also { box.addView(it) }
logs = TextView(this).apply { typeface = android.graphics.Typeface.MONOSPACE; textSize = 12f; setTextIsSelectable(true); box.addView(this) }
}
override fun onStart() { super.onStart(); handler.post(refresh) }
override fun onStop() { handler.removeCallbacks(refresh); super.onStop() }
}
@@ -0,0 +1,9 @@
package com.ttstd.ads
/** JNI calls stay on the service worker; polling returns bounded, ticket-free native logs. */
object NativeBridge {
val loadError: String? = try { System.loadLibrary("ads_android"); null } catch (e: UnsatisfiedLinkError) { "JNI_LOAD_FAILED: ${e.javaClass.simpleName}; check APK ABI and native libraries" }
external fun start(config: String): String
external fun stop()
external fun snapshot(): String
}