fix: audit P1-P3 — shell validation, accessibility, concurrency, haptics

This commit is contained in:
samosvalishe committed 2026-04-03 01:27:27 +03:00
1 parent d1237031b8
commit 9f1352ce3e
8 files changed
+340 -466

No files matched your search

@@ -65,6 +65,7 @@ class ProxyService : Service() {
}
private var wakeLock: PowerManager.WakeLock? = null
private var openAppIntent: PendingIntent? = null
// P1-1: AtomicReference вместо @Volatile — проверка null + вызов destroy() атомарны
private val process = AtomicReference<Process?>(null)
@@ -95,7 +96,7 @@ class ProxyService : Service() {
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (isRunning.value) return START_STICKY
val openIntent = packageManager.getLaunchIntentForPackage(packageName)?.let {
openAppIntent = packageManager.getLaunchIntentForPackage(packageName)?.let {
PendingIntent.getActivity(this, 0, it, PendingIntent.FLAG_IMMUTABLE)
}
val notification = NotificationCompat.Builder(this, "ProxyChannel")
@@ -103,7 +104,7 @@ class ProxyService : Service() {
.setContentText("Подключение...")
.setSmallIcon(android.R.drawable.ic_menu_preferences)
.setOngoing(true)
.setContentIntent(openIntent)
.setContentIntent(openAppIntent)
.build()
startForeground(1, notification)
@@ -113,8 +114,7 @@ class ProxyService : Service() {
val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "VkTurn::BgLock")
@Suppress("WakelockTimeout")
wakeLock?.acquire()
wakeLock?.acquire(TimeUnit.HOURS.toMillis(8))
registerNetworkCallback()
@@ -295,15 +295,12 @@ class ProxyService : Service() {
// ── Notification ─────────────────────────────────────────────────────────
private fun updateNotification(title: String, text: String) {
val openIntent = packageManager.getLaunchIntentForPackage(packageName)?.let {
PendingIntent.getActivity(this, 0, it, PendingIntent.FLAG_IMMUTABLE)
}
val notification = NotificationCompat.Builder(this, "ProxyChannel")
.setContentTitle(title)
.setContentText(text)
.setSmallIcon(android.R.drawable.ic_menu_preferences)
.setOngoing(true)
.setContentIntent(openIntent)
.setContentIntent(openAppIntent)
.build()
getSystemService(NotificationManager::class.java).notify(1, notification)
}
@@ -31,37 +31,54 @@ object HapticUtil {
fun perform(context: Context, pattern: Pattern) {
val vibrator = context.getSystemService(Vibrator::class.java) ?: return
val effect = when (pattern) {
Pattern.SELECTION -> VibrationEffect.createOneShot(11, 58)
Pattern.SELECTION -> VibrationEffect.createOneShot(20, 120)
Pattern.CLICK -> VibrationEffect.createOneShot(18, 100)
Pattern.CLICK -> VibrationEffect.createOneShot(25, 160)
Pattern.TOGGLE_ON -> VibrationEffect.createWaveform(
longArrayOf(0L, 24L, 60L, 15L),
intArrayOf(0, 138, 0, 72),
longArrayOf(0L, 35L, 50L, 20L),
intArrayOf(0, 200, 0, 110),
-1
)
Pattern.TOGGLE_OFF -> VibrationEffect.createWaveform(
longArrayOf(0L, 19L, 55L, 11L),
intArrayOf(0, 88, 0, 44),
longArrayOf(0L, 28L, 45L, 16L),
intArrayOf(0, 140, 0, 70),
-1
)
Pattern.SUCCESS -> VibrationEffect.createWaveform(
longArrayOf(0L, 16L, 48L, 11L, 48L, 8L),
intArrayOf(0, 88, 0, 58, 0, 36),
longArrayOf(0L, 22L, 40L, 16L, 40L, 12L),
intArrayOf(0, 140, 0, 100, 0, 65),
-1
)
Pattern.ERROR -> VibrationEffect.createWaveform(
longArrayOf(0L, 32L, 22L, 32L, 22L, 20L),
intArrayOf(0, 155, 0, 120, 0, 85),
longArrayOf(0L, 45L, 25L, 45L, 25L, 30L),
intArrayOf(0, 210, 0, 175, 0, 130),
-1
)
// Музыкальная вибрация
Pattern.LAUNCH -> VibrationEffect.createWaveform(
longArrayOf(0L, 36L, 88L, 22L),
intArrayOf(0, 112, 0, 58),
longArrayOf(
0L,
18L, 55L,
18L, 45L,
22L, 35L,
30L, 80L,
15L, 40L,
10L
),
intArrayOf(
0,
80, 0,
110, 0,
150, 0,
210, 0,
60, 0,
30
),
-1
)
}
@@ -336,15 +336,15 @@ private fun ProxyToggleButton(state: ProxyState, onClick: () -> Unit) {
when (state) {
is ProxyState.Starting -> CircularWavyProgressIndicator(color = contentColor)
is ProxyState.Running -> Icon(
painterResource(R.drawable.check_circle_24px), null,
painterResource(R.drawable.check_circle_24px), "Прокси активен — нажмите для остановки",
Modifier.size(52.dp), tint = contentColor
)
is ProxyState.Error -> Icon(
painterResource(R.drawable.error_24px), null,
painterResource(R.drawable.error_24px), "Ошибка — нажмите для повторного запуска",
Modifier.size(52.dp), tint = contentColor
)
else -> Icon(
painterResource(R.drawable.play_arrow_24px), null,
painterResource(R.drawable.play_arrow_24px), "Запустить прокси",
Modifier.size(52.dp), tint = contentColor
)
}
@@ -38,6 +38,7 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.freeturn.app.R
import com.freeturn.app.ui.HapticUtil
import com.freeturn.app.ui.theme.StatusGreen
import com.freeturn.app.ui.theme.StatusOrange
import com.freeturn.app.viewmodel.MainViewModel
@Composable
@@ -104,7 +105,7 @@ fun LogsScreen(viewModel: MainViewModel) {
.fillMaxSize()
.padding(padding)
) {
itemsIndexed(logs) { _, line ->
itemsIndexed(logs, key = { index, _ -> index }) { _, line ->
LogLine(line = line)
}
}
@@ -128,7 +129,7 @@ private fun LogLine(line: String) {
val textColor = when {
isError -> MaterialTheme.colorScheme.error
isWarning -> androidx.compose.ui.graphics.Color(0xFFE67E22)
isWarning -> StatusOrange
isSuccess -> StatusGreen
isHeader -> MaterialTheme.colorScheme.primary
else -> MaterialTheme.colorScheme.onSurfaceVariant
@@ -16,3 +16,4 @@ val OnBrandTealContainerDark = Color(0xFFB2EFE8)
val StatusGreen = Color(0xFF4CAF50)
val StatusGreenDark = Color(0xFF1B5E20)
val StatusRed = Color(0xFFE53935)
val StatusOrange = Color(0xFFE67E22)
@@ -89,9 +89,11 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
// P3-10: ArrayDeque — O(1) вместо O(n) list concatenation
private val sshLogBuffer = ArrayDeque<String>(500)
private fun appendSshLog(vararg lines: String) {
lines.forEach { sshLogBuffer.addLast(it) }
while (sshLogBuffer.size > 500) sshLogBuffer.removeFirst()
_sshLog.value = sshLogBuffer.toList()
synchronized(sshLogBuffer) {
lines.forEach { sshLogBuffer.addLast(it) }
while (sshLogBuffer.size > 500) sshLogBuffer.removeFirst()
_sshLog.value = sshLogBuffer.toList()
}
}
private fun logCommand(target: String, cmd: String) {
@@ -100,10 +102,9 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
appendSshLog(" ---")
}
// P2-2: единый форматтер времени вместо 5 копий SimpleDateFormat
private fun timestamp(): String =
java.text.SimpleDateFormat("HH:mm:ss", java.util.Locale.getDefault())
.format(java.util.Date())
// P2-2: единый форматтер времени (DateTimeFormatter — thread-safe, не требует Locale)
private val timeFormatter = java.time.format.DateTimeFormatter.ofPattern("HH:mm:ss")
private fun timestamp(): String = java.time.LocalTime.now().format(timeFormatter)
// P2-2: обобщённая SSH-операция — логирование + выполнение + вывод в SSH-лог
private suspend fun runSshCommand(cfg: SshConfig, label: String, cmd: String): String {
@@ -321,13 +322,21 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
}
}
private fun isValidHostPort(s: String): Boolean =
s.matches(Regex("""^[\w.\-]+:\d{1,5}$"""))
fun startServer() {
val cfg = activeSshConfig ?: sshConfig.value
if (cfg.ip.isEmpty()) return
_serverState.value = ServerState.Working("Запуск сервера...")
val l = proxyListen.value
val c = proxyConnect.value
if (!isValidHostPort(l) || !isValidHostPort(c)) {
_serverState.value = ServerState.Error("Неверный формат адреса (ожидается host:port)")
return
}
_serverState.value = ServerState.Working("Запуск сервера...")
val script = """
cd /opt/vk-turn &&
ARCH=${'$'}(uname -m);
@@ -374,8 +383,10 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
}
fun clearSshLog() {
sshLogBuffer.clear()
_sshLog.value = emptyList()
synchronized(sshLogBuffer) {
sshLogBuffer.clear()
_sshLog.value = emptyList()
}
}
// ── Local proxy ────────────────────────────────────────────────────────
@@ -491,8 +502,10 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
_serverState.value = ServerState.Unknown
_serverVersion.value = null
_serverLogs.value = null
_sshLog.value = emptyList()
sshLogBuffer.clear()
synchronized(sshLogBuffer) {
sshLogBuffer.clear()
_sshLog.value = emptyList()
}
_proxyState.value = ProxyState.Idle
_customKernelExists.value = false
ProxyService.clearLogs()
@@ -503,8 +516,4 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
context.startActivity(intent)
}
}
override fun onCleared() {
super.onCleared()
}
}