Files
aiturk-mobil/app/build.gradle.kts
T
M57andhy4ri 26b104b2bb [feature] issue #634: HTTPS + reverse-proxy server endpoint support (#638)
* [feature] issue #634: HTTPS + reverse-proxy server endpoint support

- Add ServerEndpoint model (scheme-aware base URL, resolve/webSocketUrl/relativeRequestPath, cleartext policy)
- AuthManager: baseUrl is canonical; setHost/setPort derive from endpoint; endpointForBuild() for scheme-aware URLs
- ApiClient/CookieManager/HermesWsClient: route through ServerEndpoint (no hardcoded http://)
- Data migration: ServerUrlMigration converts legacy host/port to baseUrl
- UI: Connect/AuthLogin/Settings now use a single Server URL field with transport warning
- Build: ALLOW_CLEARTEXT buildConfigField + manifest placeholder for dev
- Tests: ServerEndpointTest + ServerUrlMigrationTest; adapt existing suite to baseUrl API

Co-Authored-By: M57 <Hy4ri@users.noreply.github.com>

* fix(authlogin): basic-auth derives token automatically, no manual entry

connectBasicAuth() built a fresh OkHttpClient for the password-login call and
a different one for the ws-ticket call, so the Set-Cookie from
/auth/password-login (the session token lives in the cookie, not the JSON body)
never reached /api/auth/ws-ticket. That 401'd the ticket request, returned null,
and the UI fell back to asking the user to paste a token.

Both calls now use the shared OkHttpProvider.probe client (same CookieManager
jar), so the session cookie flows through and the WS ticket mints automatically —
matching the dashboard contract (routes.py: password-login sets Set-Cookie,
ws-ticket requires it).

Add AuthLoginBasicAuthFlowTest proving the cookie propagates on the shared
client (and that ws-ticket 401s without it).

Fixes the basic-auth token prompt reported against issue #634.

* chore: remove TASK-634-TESTS.md (stray task-tracking doc, not part of feature)

* ci: broaden .gitguardian.yml test-file ignores (unit + instrumented + variant dirs)

* feat(authlogin): smart auth-mode detection from /api/status + drop pairing-string login

- Replace 302-sniff probe with authoritative GET /api/status read
  (auth_required + auth_providers) to derive DashboardAuthMode.
- Add OAUTH mode (stubbed, 'coming soon' UI, TODO tracks issue #639).
- Render login UI by detected mode: token (loopback), username+password
  (basic/gated), or OAuth notice.
- Remove legacy pairing-string box + onPairingString/applyLegacyPairing.
- Extract internal deriveAuthMode() + add 5 unit tests.

Closes nothing; OAuth tracked in #639.

* fix(chat): don't block WS connect on empty token in gated (ticket) mode

connectWebSocket() gated on getToken() != null, correct for loopback
(token) mode but wrong for gated (ticket) mode: the ticket is minted
fresh by HermesWsClient.refreshWsTicketIfNeeded() from the persisted
session cookie, so getToken() is expected empty at connect time. The
early return left the WS unopened -> DISCONNECTED -> chat showed
'reconnect' immediately after basic-auth login.

Only require a non-blank token in non-gated mode.

Fixes #640.

* test: remove onPairingString test cases for deleted pairing-login path

The pairing-string login (onPairingString/applyLegacyPairing) was removed
from ConnectViewModel, so the 5 tests that exercised it (3 in
ConnectViewModelTest, 2 in E2eIntegrationTest) no longer compile. Remove
them. Also drop the now-orphaned connect_pairing_string from values-ko.

Fixes the Unit & Integration Tests CI failure on PR #638.

---------

Co-authored-by: hy4ri <hy4ri@users.noreply.github.com>
2026-07-20 17:26:10 +03:00

289 lines
11 KiB
Kotlin

import org.gradle.api.tasks.testing.Test
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.compose.compiler)
alias(libs.plugins.kotlin.serialization)
alias(libs.plugins.room)
alias(libs.plugins.ksp)
}
android {
namespace = "com.m57.hermescontrol"
lint {
disable += "MissingTranslation"
}
compileSdk = 36
defaultConfig {
applicationId = "com.m57.hermescontrol"
minSdk = 26
targetSdk = 36
// Version overrides passed from CI via -PversionName / -PversionCode
// Falls back to defaults for local development.
versionCode = (project.findProperty("versionCode") as? String)?.toIntOrNull() ?: 1
versionName = (project.findProperty("versionName") as? String) ?: "1.0-dev"
// Embed git commit SHA for the About card in Settings
val gitSha =
providers.exec {
commandLine("git", "rev-parse", "--short", "HEAD")
}.standardOutput.asText.get().trim()
buildConfigField("String", "GIT_SHA", "\"$gitSha\"")
}
signingConfigs {
create("release") {
val isReleaseBuild =
gradle.startParameter.taskNames.any { name ->
name.contains("Release", ignoreCase = true) || name == "build"
}
if (isReleaseBuild) {
val storePath = System.getenv("KEYSTORE_PATH")
val storePass = System.getenv("KEYSTORE_PASSWORD")
val alias = System.getenv("KEY_ALIAS")
val keyPass = System.getenv("KEY_PASSWORD")
if (storePath != null && storePass != null && alias != null && keyPass != null) {
storeFile = file(storePath)
storePassword = storePass
keyAlias = alias
keyPassword = keyPass
} else {
// Env vars missing — signing deferred to release workflow.
// Don't hard-require(): that would break compileReleaseKotlin
// in CI where keystore secrets aren't set.
logger.warn("Release signing config missing env vars — signing deferred to release workflow")
storeFile = file("dummy.keystore")
storePassword = "dummy"
keyAlias = "dummy"
keyPassword = "dummy"
}
} else {
// Dummy values for evaluation configuration during non-release builds
storeFile = file("dummy.keystore")
storePassword = "dummy"
keyAlias = "dummy"
keyPassword = "dummy"
}
}
}
buildTypes {
debug {
buildConfigField("boolean", "ALLOW_CLEARTEXT", "true")
manifestPlaceholders["usesCleartextTraffic"] = "true"
}
release {
isMinifyEnabled = true
isShrinkResources = true
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
signingConfig = signingConfigs["release"]
buildConfigField("boolean", "ALLOW_CLEARTEXT", "true")
manifestPlaceholders["usesCleartextTraffic"] = "true"
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_21
targetCompatibility = JavaVersion.VERSION_21
}
buildFeatures {
compose = true
aidl = false
buildConfig = true
shaders = false
}
dependenciesInfo {
includeInApk = false
}
packaging {
resources {
pickFirsts += "META-INF/AL2.0"
pickFirsts += "META-INF/LGPL2.1"
pickFirsts += "META-INF/LICENSE"
pickFirsts += "META-INF/LICENSE.md"
pickFirsts += "META-INF/LICENSE-notice.md"
pickFirsts += "META-INF/NOTICE"
pickFirsts += "META-INF/NOTICE.md"
}
}
}
// Overwrite version-control-info with empty content for reproducible builds
// F-Droid CI uses detached HEAD (branches: []) while GitHub CI uses main
// (branches: ["main"]) — this field in the generated textproto causes a
// byte-level APK difference. Emptying the file makes both CI environments
// produce identical artifacts.
tasks.matching { it.name.endsWith("VersionControlInfo") }.configureEach {
doLast {
outputs.files.filter { it.exists() }.forEach { it.writeText("") }
}
}
kotlin {
jvmToolchain(21)
}
room {
schemaDirectory("$projectDir/schemas")
}
dependencies {
val composeBom = platform(libs.androidx.compose.bom)
implementation(composeBom)
androidTestImplementation(composeBom)
// Core Android dependencies
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.lifecycle.runtime.ktx)
implementation(libs.androidx.activity.compose)
// Arch Components
implementation(libs.androidx.lifecycle.runtime.compose)
implementation(libs.androidx.lifecycle.viewmodel.compose)
// Compose
implementation(libs.androidx.compose.ui)
implementation(libs.androidx.compose.ui.tooling.preview)
implementation(libs.androidx.compose.material3)
implementation(libs.androidx.compose.material.icons.extended)
// Tooling
debugImplementation(libs.androidx.compose.ui.tooling)
debugImplementation(libs.leakcanary.android)
// Instrumented tests
androidTestImplementation(libs.androidx.compose.ui.test.junit4)
debugImplementation(libs.androidx.compose.ui.test.manifest)
// Networking
implementation(libs.okhttp)
implementation(libs.okhttp.logging)
implementation(libs.retrofit)
implementation(libs.retrofit.converter.kotlinx.serialization)
implementation(libs.kotlinx.serialization.json)
// Image loading
implementation(libs.coil.compose)
// Encrypted storage
implementation(libs.androidx.security.crypto)
implementation(libs.androidx.datastore)
implementation("androidx.startup:startup-runtime:1.1.1")
// Local database (Room) — message persistence
implementation(libs.androidx.room.runtime)
implementation(libs.androidx.room.ktx)
implementation(libs.sqlcipher)
ksp(libs.androidx.room.compiler)
// Local tests: jUnit, coroutines, Android runner
testImplementation(libs.junit)
testImplementation(libs.junit.jupiter.api)
testRuntimeOnly(libs.junit.jupiter.engine)
testRuntimeOnly(libs.junit.vintage.engine)
testRuntimeOnly(libs.junit.platform.launcher)
testImplementation(libs.okhttp.mockwebserver)
testImplementation(libs.kotlinx.coroutines.test)
testImplementation(libs.mockk)
testImplementation(libs.turbine)
// Instrumented tests: jUnit rules and runners
androidTestImplementation(libs.androidx.test.core)
androidTestImplementation(libs.androidx.test.ext.junit)
androidTestImplementation(libs.androidx.test.runner)
androidTestImplementation(libs.androidx.test.espresso.core)
androidTestImplementation(libs.mockk.android)
// Navigation
implementation(libs.androidx.navigation3.ui)
implementation(libs.androidx.navigation3.runtime)
implementation(libs.androidx.lifecycle.viewmodel.navigation3)
}
tasks.register<Exec>("ktlintCheck") {
group = "verification"
description = "Runs ktlint check."
workingDir = rootProject.projectDir
commandLine("sh", "-c", "ktlint \"app/src/**/*.kt\"")
}
tasks.register<Exec>("ktlintFormat") {
group = "formatting"
description = "Runs ktlint format."
workingDir = rootProject.projectDir
commandLine("sh", "-c", "ktlint -F \"app/src/**/*.kt\"")
}
// ── Hardcoded Color Guard (issue #622) ────────────────────────────────────
//
// Fails the build if a hardcoded Color literal (Color(0x...) or named
// Color.White/Black/Red/Green/Gray/etc.) is introduced outside the theme
// module, *Preview.kt files, and _test sources. Pairing/Auth screens are
// exempt via the per-path overlay list below.
//
// Acceptable replacements (see docs/color-hardcoded-audit.md):
// - MaterialTheme.colorScheme.<token>
// - LocalHermesStatusColors.current.<semantic>
// - Color.Transparent / Color.Unspecified (intentional)
// Resolve paths at configuration time (config-cache compatible).
val colorGuardSrcDir = layout.projectDirectory
.dir("src/main/java/com/m57/hermescontrol")
val colorGuardExemptions = listOf(
"/theme/",
"PairingScreen.kt",
"AuthLoginScreen.kt",
"Preview.kt",
)
val colorGuardHexPattern = Regex("""Color\(\s*0x[0-9A-Fa-f]{6,8}\s*\)""")
val colorGuardNamedPattern = Regex("""Color\.(White|Black|Red|Green|Gray|LightGray|DarkGray|Yellow|Blue|Cyan|Magenta)\b""")
tasks.register("checkColorLiterals") {
group = "verification"
description = "Fails if hardcoded Color(...) literals appear outside theme/, *Preview.kt, and _test."
val srcDir = colorGuardSrcDir
val exemptions = colorGuardExemptions
val hexPattern = colorGuardHexPattern
val namedPattern = colorGuardNamedPattern
doLast {
val offenders = mutableListOf<Pair<String, Int>>()
srcDir.asFile.walkTopDown().filter { it.isFile && it.extension == "kt" }.forEach { file ->
if (exemptions.any { file.absolutePath.contains(it) }) return@forEach
file.useLines { lines ->
lines.forEachIndexed { idx, raw ->
val line = raw.trim()
if (line.startsWith("import ")) return@forEachIndexed
if (line.startsWith("//") || line.startsWith("*")) return@forEachIndexed
if (hexPattern.containsMatchIn(line) || namedPattern.containsMatchIn(line)) {
offenders.add(file.absolutePath to (idx + 1))
}
}
}
}
if (offenders.isNotEmpty()) {
val report = offenders.joinToString("\n") { (path, line) ->
" - $path:$line"
}
throw GradleException(
"Hardcoded Color literals found outside theme/ + *Preview.kt + _test:\n$report\n\n" +
"Replace with MaterialTheme.colorScheme.<token>, " +
"LocalHermesStatusColors.current.<semantic>, or " +
"Color.Transparent / Color.Unspecified (intentional).\n" +
"See docs/color-hardcoded-audit.md.",
)
}
logger.lifecycle("checkColorLiterals: no hardcoded Color literals found. ✅")
}
}
tasks.named("check") {
dependsOn("checkColorLiterals")
}
tasks.withType<Test> {
useJUnitPlatform()
}