Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 42 additions & 4 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,18 @@ on:
permissions:
contents: write

# A newer push to the same PR/branch cancels the older run; tag builds are never cancelled.
concurrency:
group: build-${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}

env:
IS_RELEASE: ${{ github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') }}

jobs:
build:
runs-on: ubuntu-latest
timeout-minutes: 40
steps:
- uses: actions/checkout@v4

Expand All @@ -31,6 +40,10 @@ jobs:
distribution: temurin
java-version: "17"

- uses: gradle/actions/setup-gradle@v4
with:
cache-read-only: ${{ github.event_name == 'pull_request' }}

- name: Setup Android SDK path
run: |
echo "ANDROID_HOME=${ANDROID_HOME:-$ANDROID_SDK_ROOT}" >> "$GITHUB_ENV"
Expand All @@ -55,6 +68,11 @@ jobs:
else
echo "present=false" >> "$GITHUB_OUTPUT"
echo "Secrets missing — debug signing fallback."
# Forks and contributors build debug-signed. Only the official repo must sign releases.
if [ "$IS_RELEASE" = "true" ] && [ "$GITHUB_REPOSITORY" = "wized2/Latch" ]; then
echo "::error::Release tag without signing secrets; refusing to publish a debug-signed APK."
exit 1
fi
fi

- name: Unit tests
Expand All @@ -72,31 +90,51 @@ jobs:
if [ "${{ steps.keystore.outputs.present }}" = "true" ]; then
export RELEASE_STORE_FILE="$GITHUB_WORKSPACE/release.jks"
fi
./gradlew assembleStableDebug assembleBetaDebug assembleStableRelease assembleBetaRelease --stacktrace
if [ "${{ github.event_name }}" = "pull_request" ]; then
./gradlew assembleStableRelease --stacktrace
else
./gradlew assembleStableDebug assembleBetaDebug assembleStableRelease assembleBetaRelease --stacktrace
fi
ls -la app/build/outputs/apk/stable/release/ app/build/outputs/apk/beta/release/ || true

- name: Verify APK signature
if: steps.keystore.outputs.present == 'true'
run: |
APKSIGNER=$(ls "$ANDROID_HOME"/build-tools/*/apksigner | sort -V | tail -1)
for f in app/build/outputs/apk/stable/release/*.apk; do
"$APKSIGNER" verify --verbose "$f"
done

- name: Upload test reports on failure
if: failure()
uses: actions/upload-artifact@v4
with:
name: test-reports
path: app/build/reports/tests
if-no-files-found: ignore

- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: Latch-release
path: app/build/outputs/apk/stable/release/*.apk

- name: Version
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
if: env.IS_RELEASE == 'true'
id: ver
run: |
VN=$(grep -E 'versionName\s*=' app/build.gradle.kts | head -1 | sed -E 's/.*"([^"]+)".*/\1/')
echo "name=$VN" >> "$GITHUB_OUTPUT"
echo "tag=v$VN" >> "$GITHUB_OUTPUT"

- name: Prepare assets
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
if: env.IS_RELEASE == 'true'
run: |
mkdir -p release-assets
cp app/build/outputs/apk/stable/release/*.apk release-assets/Latch-release.apk

- name: GitHub Release
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
if: env.IS_RELEASE == 'true'
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ steps.ver.outputs.tag }}
Expand Down
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,18 @@
## 0.8.0

### Security
- Package names are validated before `am force-stop`, so a rule can no longer inject shell commands
- The Plugin API switch in Settings is now honored by the receiver
- HTTP GET action accepts only http(s), logs host only, always closes the connection

### Reliability
- Shell and `su` calls have real timeouts (a hung process no longer blocks the rule thread)
- `su` availability is cached for 30 s

### Build
- CI: Gradle cache, timeout, concurrency, APK signature check; PRs build stable only
- Unit tests for package-name and URL validation

## 0.7.0

- Accessibility for APP_OPENED; UsageStats fallback; stronger sticky monitor notes
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ Optional **Shizuku** (preferred) or root `su` for shell / `svc` style actions. E

## Privacy

No `INTERNET` permission. No analytics. Rules stay on device unless you export them.
No analytics, no accounts, no telemetry. Rules stay on device unless you export them. The `INTERNET` permission is used only by the optional **HTTP GET** action, which accepts `http://` and `https://` URLs and logs the host only (never the query string).

## Plugin API

Expand All @@ -68,6 +68,8 @@ com.endroid.latch.api.FIRE_TRIGGER extra trigger=<string>
com.endroid.latch.api.RUN_RULE extra rule_id=<uuid>
```

Any installed app can send these broadcasts, so they can be switched off in Settings (**Plugin API**). When off, Latch ignores them. Turn it off if you have rules with shell actions and do not use plugins.

## Stable vs beta

| Channel | Branch | Application id |
Expand Down
16 changes: 10 additions & 6 deletions RELEASE_NOTES.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
# Latch 0.6.3
# Latch 0.8.0

## UI
- Home: search rules by name / trigger; enabled rules sort first
- Settings: seed colors as wrapping FilterChips (no overflow on small phones)
## Security
- Shell-injection fix for the force-stop action (package names are validated)
- Plugin API switch is now enforced
- HTTP GET action: http(s) only, host-only logging

## Reliability
- Shell / su timeouts that actually fire
- Cached su probe

## Docs
- README badges + website/download links
- Issue template + funding metadata
- README privacy section now matches the manifest (INTERNET is used only by HTTP GET)
8 changes: 8 additions & 0 deletions SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,11 @@ Security fixes target the latest release on `main`.

Email **acartoon766@gmail.com** or use GitHub private vulnerability reporting.
Do not open public issues for exploitable vulnerabilities.

## Threat model

- Latch runs entirely on the device. There are no accounts and no analytics.
- Shell actions (Shizuku or root) run only what the user typed into a rule. Package names used in force-stop are validated against a strict pattern.
- Other apps can send `FIRE_TRIGGER` / `RUN_RULE` broadcasts. The **Plugin API** switch in Settings makes Latch ignore them.
- The `INTERNET` permission exists only for the optional HTTP GET action (http/https, host-only logs).
- Release APKs are signed in CI; the signature is verified before publishing.
4 changes: 2 additions & 2 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ android {
applicationId = "com.endroid.latch"
minSdk = 26
targetSdk = 35
versionCode = 12
versionName = "0.7.0"
versionCode = 13
versionName = "0.8.0"
resourceConfigurations += listOf("en", "es", "de")
buildConfigField("String", "VERSION_NAME", "\"${defaultConfig.versionName}\"")
}
Expand Down
63 changes: 44 additions & 19 deletions app/src/main/java/com/endroid/latch/engine/Elevated.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ package com.endroid.latch.engine
import android.content.pm.PackageManager
import android.util.Log
import rikka.shizuku.Shizuku
import java.io.BufferedReader
import java.io.InputStreamReader
import java.lang.reflect.Method
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
Expand All @@ -13,13 +11,22 @@ object Elevated {
private const val TAG = "LatchElevated"
private val newProcessMethod = AtomicReference<Method?>()

fun hasSu(): Boolean = try {
val p = Runtime.getRuntime().exec(arrayOf("su", "-c", "echo ok"))
val out = BufferedReader(InputStreamReader(p.inputStream)).readLine()
p.waitFor(3, TimeUnit.SECONDS)
out?.contains("ok") == true
} catch (_: Exception) {
false
@Volatile private var suCache: Pair<Boolean, Long>? = null
private const val SU_CACHE_MS = 30_000L

/** su probe with a hard timeout (a su that waits for a prompt used to hang the caller). */
fun hasSu(): Boolean {
val now = System.currentTimeMillis()
suCache?.let { (ok, at) -> if (now - at < SU_CACHE_MS) return ok }
val ok = try {
val p = Runtime.getRuntime().exec(arrayOf("su", "-c", "echo ok"))
val r = drain(p, 3)
r.first == 0 && r.second.contains("ok")
} catch (_: Exception) {
false
}
suCache = ok to now
return ok
}

fun shizukuAvailable(): Boolean = try {
Expand Down Expand Up @@ -91,20 +98,35 @@ object Elevated {
}
}

/**
* Reads output on a helper thread so [timeoutSec] is real: the old version read the
* stream to EOF first, so a hung process blocked the caller forever.
*/
private fun drain(p: Process, timeoutSec: Long): Pair<Int, String> {
val out = StringBuilder()
try {
p.inputStream.bufferedReader().use { out.append(it.readText()) }
} catch (_: Exception) { }
val ok = try {
val out = StringBuffer()
val reader = Thread {
try {
p.inputStream.bufferedReader().use { r ->
val buf = CharArray(1024)
while (true) {
val n = r.read(buf)
if (n < 0) break
if (out.length < 4000) out.append(buf, 0, n)
}
}
} catch (_: Exception) { }
}.apply { isDaemon = true; start() }
val finished = try {
p.waitFor(timeoutSec, TimeUnit.SECONDS)
} catch (_: Exception) {
} catch (_: InterruptedException) {
false
}
if (!ok) {
p.destroy()
if (!finished) {
p.destroyForcibly()
reader.join(500)
return -1 to out.toString().take(4000)
}
reader.join(1000)
return p.exitValue() to out.toString().take(4000)
}

Expand Down Expand Up @@ -152,6 +174,9 @@ object Elevated {
fun setMobileData(enable: Boolean, preferShizuku: Boolean, allowSu: Boolean) =
runShell(if (enable) "svc data enable" else "svc data disable", preferShizuku, allowSu)

fun forceStop(packageName: String, preferShizuku: Boolean, allowSu: Boolean) =
runShell("am force-stop ${packageName.trim()}", preferShizuku, allowSu)
fun forceStop(packageName: String, preferShizuku: Boolean, allowSu: Boolean): Pair<Int, String> {
val pkg = packageName.trim()
if (!RuleLogic.isValidPackageName(pkg)) return -1 to "invalid package name"
return runShell("am force-stop $pkg", preferShizuku, allowSu)
}
}
16 changes: 11 additions & 5 deletions app/src/main/java/com/endroid/latch/engine/RuleEngine.kt
Original file line number Diff line number Diff line change
Expand Up @@ -471,20 +471,26 @@ object RuleEngine {
}
ActionType.HTTP_GET -> {
val url = action.param.trim().ifBlank { action.text.trim() }
if (url.startsWith("http")) {
if (RuleLogic.isHttpUrl(url)) {
val app = context.applicationContext
thread {
var c: java.net.HttpURLConnection? = null
try {
val c = java.net.URL(url).openConnection() as java.net.HttpURLConnection
c = java.net.URL(url).openConnection() as java.net.HttpURLConnection
c.connectTimeout = 8000
c.readTimeout = 8000
c.requestMethod = "GET"
val code = c.responseCode
SettingsStore(context).appendLog("HTTP $code $url")
c.disconnect()
// Host only: query strings often carry tokens.
SettingsStore(app).appendLog("HTTP $code ${RuleLogic.hostForLog(url)}")
} catch (e: Exception) {
SettingsStore(context).appendLog("HTTP ERR ${e.message}")
SettingsStore(app).appendLog("HTTP ERR ${RuleLogic.hostForLog(url)}: ${e.javaClass.simpleName}")
} finally {
c?.disconnect()
}
}
} else {
SettingsStore(context).appendLog("HTTP skipped: not an http(s) URL")
}
}
}
Expand Down
23 changes: 23 additions & 0 deletions app/src/main/java/com/endroid/latch/engine/RuleLogic.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,29 @@ package com.endroid.latch.engine
* Pure rule matching helpers — no Android deps so JVM unit tests can cover them.
*/
object RuleLogic {
private val PACKAGE_NAME = Regex("^[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z0-9_]+)+$")

/**
* True only for a well-formed Android package name. Anything else must never be
* placed on a shell command line (force-stop builds "am force-stop <pkg>").
*/
fun isValidPackageName(name: String?): Boolean =
name != null && name.length <= 255 && PACKAGE_NAME.matches(name)

/** Only plain http(s) URLs may be requested by the HTTP GET action. */
fun isHttpUrl(url: String): Boolean {
val u = url.trim()
return (u.startsWith("http://", ignoreCase = true) || u.startsWith("https://", ignoreCase = true)) &&
u.length > 8 && u.none { it.isWhitespace() }
}

/** Host only (no path/query) so secrets in a URL never reach the on-device log. */
fun hostForLog(url: String): String = try {
java.net.URI(url.trim()).host ?: "?"
} catch (_: Exception) {
"?"
}

fun batteryBelow(percent: Int, threshold: Int): Boolean = percent <= threshold
fun batteryAbove(percent: Int, threshold: Int): Boolean = percent >= threshold

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,8 @@ class PluginReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent?) {
if (intent == null) return
val app = context.applicationContext
// The Settings switch "Plugin API" used to only gate outgoing broadcasts.
if (!com.endroid.latch.data.SettingsStore(app).pluginApiEnabled) return
when (intent.action) {
ACTION_FIRE_TRIGGER -> {
val custom = intent.getStringExtra(EXTRA_TRIGGER)
Expand All @@ -183,10 +185,6 @@ class PluginReceiver : BroadcastReceiver() {
RuleEngine.run(app, it)
}
}
else -> {
// Treat any matching action string as custom broadcast trigger param
intent.action?.let { RuleEngine.onCustomBroadcast(app, it) }
}
}
}

Expand Down
28 changes: 28 additions & 0 deletions app/src/test/java/com/endroid/latch/RuleLogicTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -108,4 +108,32 @@ class RuleLogicTest {
assertFalse(RuleLogic.cooldownOk(1, 1000L, 1999L))
assertTrue(RuleLogic.cooldownOk(1, 1000L, 2000L))
}

@Test fun packageNameAcceptsRealNames() {
assertTrue(RuleLogic.isValidPackageName("com.android.chrome"))
assertTrue(RuleLogic.isValidPackageName("org.example.app_2"))
}

@Test fun packageNameRejectsShellMetacharacters() {
val bad = listOf(
null, "", "chrome", "com.a;reboot", "com.a && id", "com.a|id", "com.a\nid",
"\$(id).app", "com.a`id`", "com.a b", "com.a>x", "-f.com.a", ".com.a", "com.a.",
"com..a", "1com.a", "a".repeat(300) + ".b",
)
for (b in bad) assertFalse("accepted: $b", RuleLogic.isValidPackageName(b))
}

@Test fun httpUrlOnlyHttpAndHttps() {
assertTrue(RuleLogic.isHttpUrl("https://example.com/hook?x=1"))
assertTrue(RuleLogic.isHttpUrl("http://192.168.1.5/on"))
assertFalse(RuleLogic.isHttpUrl("httpfoo://x"))
assertFalse(RuleLogic.isHttpUrl("file:///etc/passwd"))
assertFalse(RuleLogic.isHttpUrl("https://a b"))
assertFalse(RuleLogic.isHttpUrl("https://"))
}

@Test fun hostForLogDropsPathAndQuery() {
assertEquals("example.com", RuleLogic.hostForLog("https://example.com/hook?token=SECRET"))
assertEquals("?", RuleLogic.hostForLog("not a url"))
}
}
Loading