From 3f2d696d0f688d2b05c2186e41c9ffda92aefca0 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 17:38:26 +0000 Subject: [PATCH 1/3] feat(network): send a HAAC user agent and test the token refresh HA's log showed /auth/token failures as okhttp/5.5.0. Requests now carry HAAC/ (Android ), so HAAC can be told apart from other apps. Tests: fixed client_id on refresh, no request after a revoked token, one refresh for parallel access token calls. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01GJNKFeeESsuXpfVuyktb3h --- .../haac/core/network/di/NetworkModule.kt | 18 +++++++++++- .../core/network/http/UserAgentInterceptor.kt | 13 +++++++++ .../haac/core/network/auth/TokenClientTest.kt | 10 +++++++ .../network/http/UserAgentInterceptorTest.kt | 28 +++++++++++++++++++ .../network/session/InstanceSessionTest.kt | 18 ++++++++++++ docs/code-index.md | 5 +++- 6 files changed, 90 insertions(+), 2 deletions(-) create mode 100644 core/network/src/main/kotlin/com/stacknoise/haac/core/network/http/UserAgentInterceptor.kt create mode 100644 core/network/src/test/kotlin/com/stacknoise/haac/core/network/http/UserAgentInterceptorTest.kt diff --git a/core/network/src/main/kotlin/com/stacknoise/haac/core/network/di/NetworkModule.kt b/core/network/src/main/kotlin/com/stacknoise/haac/core/network/di/NetworkModule.kt index b0ae383b..236d358c 100644 --- a/core/network/src/main/kotlin/com/stacknoise/haac/core/network/di/NetworkModule.kt +++ b/core/network/src/main/kotlin/com/stacknoise/haac/core/network/di/NetworkModule.kt @@ -1,6 +1,8 @@ package com.stacknoise.haac.core.network.di import android.content.Context +import android.content.pm.PackageManager +import android.os.Build import android.net.nsd.NsdManager import com.stacknoise.haac.core.common.dispatch.MainDispatcher import dagger.Module @@ -14,6 +16,7 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.SupervisorJob import kotlinx.serialization.json.Json +import com.stacknoise.haac.core.network.http.UserAgentInterceptor import com.stacknoise.haac.core.network.tls.PinRegistry import com.stacknoise.haac.core.network.tls.pinnedBy import okhttp3.OkHttpClient @@ -27,13 +30,26 @@ object NetworkModule { /** The one client of the app; trusts by pin or by system certificates (concept 4.3). */ @Provides @Singleton - fun provideOkHttpClient(pins: PinRegistry): OkHttpClient = OkHttpClient.Builder() + fun provideOkHttpClient(pins: PinRegistry, userAgent: UserAgentInterceptor): OkHttpClient = OkHttpClient.Builder() .pinnedBy(pins) + .addInterceptor(userAgent) .connectTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) .readTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) .followRedirects(false) .build() + /** Names the app in HA's log: `HAAC/ (Android )`. */ + @Provides + @Singleton + fun provideUserAgentInterceptor(@ApplicationContext context: Context): UserAgentInterceptor { + val version = try { + context.packageManager.getPackageInfo(context.packageName, 0).versionName + } catch (_: PackageManager.NameNotFoundException) { + null + } + return UserAgentInterceptor(version ?: "unknown", Build.VERSION.SDK_INT) + } + /** JSON that tolerates new fields from future HA versions. */ @Provides @Singleton diff --git a/core/network/src/main/kotlin/com/stacknoise/haac/core/network/http/UserAgentInterceptor.kt b/core/network/src/main/kotlin/com/stacknoise/haac/core/network/http/UserAgentInterceptor.kt new file mode 100644 index 00000000..8a91370c --- /dev/null +++ b/core/network/src/main/kotlin/com/stacknoise/haac/core/network/http/UserAgentInterceptor.kt @@ -0,0 +1,13 @@ +package com.stacknoise.haac.core.network.http + +import okhttp3.Interceptor +import okhttp3.Response + +/** Sets `User-Agent: HAAC/ (Android )`, so HA's log shows which client sent a request. */ +class UserAgentInterceptor(appVersion: String, sdkInt: Int) : Interceptor { + private val value = "HAAC/$appVersion (Android $sdkInt)" + + /** Replaces the OkHttp default user agent of every request. */ + override fun intercept(chain: Interceptor.Chain): Response = + chain.proceed(chain.request().newBuilder().header("User-Agent", value).build()) +} diff --git a/core/network/src/test/kotlin/com/stacknoise/haac/core/network/auth/TokenClientTest.kt b/core/network/src/test/kotlin/com/stacknoise/haac/core/network/auth/TokenClientTest.kt index ba97fd4f..b45f2db1 100644 --- a/core/network/src/test/kotlin/com/stacknoise/haac/core/network/auth/TokenClientTest.kt +++ b/core/network/src/test/kotlin/com/stacknoise/haac/core/network/auth/TokenClientTest.kt @@ -75,4 +75,14 @@ class TokenClientTest { assertEquals("/auth/revoke", request.url.encodedPath) assertEquals("token=ref", request.body!!.utf8()) } + + @Test + fun `refresh sends the fixed client_id whatever the base URL`() = runTest { + respond(200, """{"access_token":"acc2","token_type":"Bearer","expires_in":1800}""") + tokens.refresh(server.url("/ha/"), "ref") + assertEquals( + "grant_type=refresh_token&refresh_token=ref&client_id=https%3A%2F%2Fstacknoise.com%2Fhaac%2F", + server.takeRequest().body!!.utf8(), + ) + } } diff --git a/core/network/src/test/kotlin/com/stacknoise/haac/core/network/http/UserAgentInterceptorTest.kt b/core/network/src/test/kotlin/com/stacknoise/haac/core/network/http/UserAgentInterceptorTest.kt new file mode 100644 index 00000000..150c28d5 --- /dev/null +++ b/core/network/src/test/kotlin/com/stacknoise/haac/core/network/http/UserAgentInterceptorTest.kt @@ -0,0 +1,28 @@ +package com.stacknoise.haac.core.network.http + +import com.stacknoise.haac.core.error.DefaultErrorFactory +import com.stacknoise.haac.core.network.auth.TokenClient +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.json.Json +import mockwebserver3.MockResponse +import mockwebserver3.MockWebServer +import okhttp3.OkHttpClient +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test + +class UserAgentInterceptorTest { + @Test + fun `token refresh carries the HAAC user agent`() = runTest { + MockWebServer().use { server -> + server.start() + server.enqueue( + MockResponse.Builder().code(200) + .body("""{"access_token":"acc","token_type":"Bearer","expires_in":1800}""").build(), + ) + val client = OkHttpClient.Builder().addInterceptor(UserAgentInterceptor("0.8.1", 36)).build() + val tokens = TokenClient(HaHttpClient(client, DefaultErrorFactory()), Json { ignoreUnknownKeys = true }) + tokens.refresh(server.url("/"), "ref") + assertEquals("HAAC/0.8.1 (Android 36)", server.takeRequest().headers["User-Agent"]) + } + } +} diff --git a/core/network/src/test/kotlin/com/stacknoise/haac/core/network/session/InstanceSessionTest.kt b/core/network/src/test/kotlin/com/stacknoise/haac/core/network/session/InstanceSessionTest.kt index 964bd07c..f249091a 100644 --- a/core/network/src/test/kotlin/com/stacknoise/haac/core/network/session/InstanceSessionTest.kt +++ b/core/network/src/test/kotlin/com/stacknoise/haac/core/network/session/InstanceSessionTest.kt @@ -9,6 +9,8 @@ import com.stacknoise.haac.core.network.auth.TokenClient import com.stacknoise.haac.core.network.http.HaHttpClient import com.stacknoise.haac.core.security.token.TokenProtection import com.stacknoise.haac.core.security.token.TokenStore +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll import kotlinx.coroutines.test.runTest import kotlinx.serialization.json.Json import mockwebserver3.MockResponse @@ -109,4 +111,20 @@ class InstanceSessionTest { assertFalse("s1" in stored) assertEquals(0, server.requestCount) } + + @Test + fun `after a revoked token no further request goes to HA`() = runTest { + server.enqueue(MockResponse.Builder().code(400).body("""{"error":"invalid_grant"}""").build()) + assertThrows { session.accessToken() } + assertEquals(ErrorCode.AUTH_SESSION_EXPIRED, assertThrows { session.accessToken() }.code) + assertEquals(1, server.requestCount) + } + + @Test + fun `parallel calls with an expired access token refresh only once`() = runTest { + accessToken("a1") + val results = (1..5).map { async { session.accessToken() } }.awaitAll() + assertEquals(List(5) { "a1" }, results) + assertEquals(1, server.requestCount) + } } diff --git a/docs/code-index.md b/docs/code-index.md index ee5abfc6..c8bd1820 100644 --- a/docs/code-index.md +++ b/docs/code-index.md @@ -914,7 +914,8 @@ Lists every class and function of the app with signature, file and a one-line KD | `NetworkBindings.bindBackoff` | `abstract fun bindBackoff(backoff: ExponentialBackoff): Backoff` | `core/network/src/main/kotlin/com/stacknoise/haac/core/network/di/NetworkBindings.kt` | Reconnect back-off (concept 11.4). | | `NetworkBindings.bindLiveConnection` | `abstract fun bindLiveConnection(supervisor: ConnectionSupervisor): LiveConnection` | `core/network/src/main/kotlin/com/stacknoise/haac/core/network/di/NetworkBindings.kt` | The live connection for service calls (concept 8.1). | | `NetworkModule` | `object NetworkModule` | `core/network/src/main/kotlin/com/stacknoise/haac/core/network/di/NetworkModule.kt` | Shared HTTP client and JSON settings; no logging interceptor, so auth requests are never logged (concept 5.1). | -| `NetworkModule.provideOkHttpClient` | `fun provideOkHttpClient(pins: PinRegistry): OkHttpClient` | `core/network/src/main/kotlin/com/stacknoise/haac/core/network/di/NetworkModule.kt` | The one client of the app; trusts by pin or by system certificates (concept 4.3). | +| `NetworkModule.provideOkHttpClient` | `fun provideOkHttpClient(pins: PinRegistry, userAgent: UserAgentInterceptor): OkHttpClient` | `core/network/src/main/kotlin/com/stacknoise/haac/core/network/di/NetworkModule.kt` | The one client of the app; trusts by pin or by system certificates (concept 4.3). | +| `NetworkModule.provideUserAgentInterceptor` | `fun provideUserAgentInterceptor(@ApplicationContext context: Context): UserAgentInterceptor` | `core/network/src/main/kotlin/com/stacknoise/haac/core/network/di/NetworkModule.kt` | Names the app in HA's log: `HAAC/ (Android )`. | | `NetworkModule.provideJson` | `fun provideJson(): Json` | `core/network/src/main/kotlin/com/stacknoise/haac/core/network/di/NetworkModule.kt` | JSON that tolerates new fields from future HA versions. | | `NetworkModule.provideNsdManager` | `fun provideNsdManager(@ApplicationContext context: Context): NsdManager` | `core/network/src/main/kotlin/com/stacknoise/haac/core/network/di/NetworkModule.kt` | The system NsdManager for LAN discovery (concept 4.2, 4.5). | | `NetworkModule.provideConnectionScope` | `fun provideConnectionScope(@MainDispatcher main: CoroutineDispatcher): CoroutineScope` | `core/network/src/main/kotlin/com/stacknoise/haac/core/network/di/NetworkModule.kt` | Scope of [com.stacknoise.haac.core.network.connection.ConnectionSupervisor]; lives as long as the app. | @@ -1001,6 +1002,8 @@ Lists every class and function of the app with signature, file and a one-line KD | `Json.decodeOrUnexpected` | `fun Json.decodeOrUnexpected(deserializer: DeserializationStrategy, body: String): T` | `core/network/src/main/kotlin/com/stacknoise/haac/core/network/http/JsonFields.kt` | Decodes an answer of a server already known to be HA; malformed JSON is HAAC-APP-000. | | `Json.decodeOrUnexpected` | `fun Json.decodeOrUnexpected(deserializer: DeserializationStrategy, element: JsonElement): T` | `core/network/src/main/kotlin/com/stacknoise/haac/core/network/http/JsonFields.kt` | Decodes a WebSocket `result` of a server known to be HA; an unexpected shape is HAAC-APP-000. | | `unexpectedOnError` | `private inline fun unexpectedOnError(decode: () -> T): T` | `core/network/src/main/kotlin/com/stacknoise/haac/core/network/http/JsonFields.kt` | Runs [decode]; `SerializationException` is an `IllegalArgumentException`, so one catch covers both. | +| `UserAgentInterceptor` | `class UserAgentInterceptor(appVersion: String, sdkInt: Int) : Interceptor` | `core/network/src/main/kotlin/com/stacknoise/haac/core/network/http/UserAgentInterceptor.kt` | Sets `User-Agent: HAAC/ (Android )`, so HA's log shows which client sent a request. | +| `UserAgentInterceptor.intercept` | `override fun intercept(chain: Interceptor.Chain): Response` | `core/network/src/main/kotlin/com/stacknoise/haac/core/network/http/UserAgentInterceptor.kt` | Replaces the OkHttp default user agent of every request. | ## com.stacknoise.haac.core.network.server From af2ad99ba417e4ff51e1af3895a882fe236198c1 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 17:41:36 +0000 Subject: [PATCH 2/3] docs(concept): describe the HAAC user agent in 5.1 Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01GJNKFeeESsuXpfVuyktb3h --- docs/concept.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/concept.md b/docs/concept.md index df7c3cdd..bb168082 100644 --- a/docs/concept.md +++ b/docs/concept.md @@ -258,6 +258,7 @@ sequenceDiagram - If the user has several MFA modules, HA first asks for one (`select_mfa_module`); the app picks the first module offered and then asks only for its code. - The password lives only in a `CharArray` for the duration of the request and is overwritten afterwards; it is never logged, persisted, put in a `String` constant or sent anywhere except to the configured HA server over TLS. - HTTP logging is disabled for all `/auth/*` requests, also in debug builds. +- **User agent**: every request of the app (REST and WebSocket) carries `User-Agent: HAAC/ (Android )` instead of the OkHttp default, so HA's log (e.g. `homeassistant.components.http.ban` for a rejected `/auth/token` request) shows that HAAC sent it. The header holds no token and no instance data. ### 5.2 Token handling From 22f0d23672020451630d751d3bda668ed8cf4df3 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 18:06:43 +0000 Subject: [PATCH 3/3] docs: make docs/concept.md the only version of the concept The online Claude Doc no longer exists. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01GJNKFeeESsuXpfVuyktb3h --- CLAUDE.md | 2 +- docs/development.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index d2efe500..6e6f1ece 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -5,7 +5,7 @@ Native Android client for Home Assistant (HA). This repository contains the Andr ## Source of truth - `docs/concept.md` is the full technical concept. Read the chapter that matches the task before writing code; do not work from this file alone. -- After changing `docs/concept.md`, apply the same change to the online Claude Doc of the concept (https://claude.ai/artifact/3dxVZDWcZqvvJHdPj5hnvz) in the same task, and copy the file to `stacknoise/haac-bridge` after the merge (`docs/development.md`, *The concept document*). +- `docs/concept.md` is the only version of the concept (there is no online copy). After changing it, copy the file to `stacknoise/haac-bridge` after the merge (`docs/development.md`, *The concept document*). - `docs/mockups/png/M-0x-*.png` shows one screen each; `docs/mockups/haac-mockups-1c.html` is the interactive design source (open it in a browser). Chapter 15 of the concept describes every screen in text and lists the design tokens. - Precedence: concept chapters 1–14 define behaviour and data; mockups define layout, style and wording. If they disagree, follow the concept; `docs/concept.md` 15.5 lists the decisions that override the mockups. - Items in concept 14.5 ("Open points") are undecided. Do not pick an answer silently: ask, or implement behind a clearly marked TODO. diff --git a/docs/development.md b/docs/development.md index 8ed616d7..69469af7 100644 --- a/docs/development.md +++ b/docs/development.md @@ -226,7 +226,7 @@ NET_UNREACHABLE( ### The concept document -`docs/concept.md` here is the **leading copy** of the specification; `stacknoise/haac-bridge` holds an identical copy. A change goes first into this repository; after it is merged, the copy is taken over into the bridge repository in its own pull request (same blob). The online document, the Claude Doc [HA Android Client (HAAC) – Technical Concept](https://claude.ai/artifact/3dxVZDWcZqvvJHdPj5hnvz), is kept in step automatically: whoever changes `docs/concept.md` (a coding agent with access to Claude Docs) applies the same change to the Claude Doc in the same task, section by section, and says so in the pull request. Text, tables and code blocks must match; images are uploaded there separately. A coding agent without access to Claude Docs says in the pull request that the doc still needs the update. Read the matching chapter before changing behaviour; items in concept 14.5 ("Open points") are undecided: ask, or implement behind a clearly marked TODO. +`docs/concept.md` here is the **leading copy** of the specification; `stacknoise/haac-bridge` holds an identical copy. A change goes first into this repository; after it is merged, the copy is taken over into the bridge repository in its own pull request (same blob). There is no other copy: the former online Claude Doc no longer exists. Read the matching chapter before changing behaviour; items in concept 14.5 ("Open points") are undecided: ask, or implement behind a clearly marked TODO. ## 10. Versions and releases