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
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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
Expand All @@ -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/<version> (Android <sdk>)`. */
@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
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.stacknoise.haac.core.network.http

import okhttp3.Interceptor
import okhttp3.Response

/** Sets `User-Agent: HAAC/<version> (Android <sdk>)`, 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())
}
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
)
}
}
Original file line number Diff line number Diff line change
@@ -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"])
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<AuthException> { session.accessToken() }
assertEquals(ErrorCode.AUTH_SESSION_EXPIRED, assertThrows<AuthException> { 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)
}
}
5 changes: 4 additions & 1 deletion docs/code-index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<version> (Android <sdk>)`. |
| `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. |
Expand Down Expand Up @@ -1001,6 +1002,8 @@ Lists every class and function of the app with signature, file and a one-line KD
| `Json.decodeOrUnexpected` | `fun <T> Json.decodeOrUnexpected(deserializer: DeserializationStrategy<T>, 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 <T> Json.decodeOrUnexpected(deserializer: DeserializationStrategy<T>, 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 <T> 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/<version> (Android <sdk>)`, 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

Expand Down
1 change: 1 addition & 0 deletions docs/concept.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<version> (Android <sdk>)` 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

Expand Down
2 changes: 1 addition & 1 deletion docs/development.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Loading