refactor(audio-rooms): NestsClient API matches nostrnests reality (phase 2/3)

The Phase-1 interop harness exposed a substantial mismatch between our
production HTTP client and what the nostrnests reference server actually
exposes. This commit refactors `:nestsClient` and the wiring above it so
the production code path can talk to a real moq-auth + moq-relay.

| Aspect    | Before                                    | After (matches nostrnests/moq-auth/src/index.ts) |
|-----------|-------------------------------------------|--------------------------------------------------|
| Method    | GET                                       | POST                                             |
| URL       | `<base>/<roomId>`                         | `<base>/auth`                                    |
| Body      | none                                      | `{"namespace":"nests/<kind>:<host>:<roomId>","publish":bool}` |
| Response  | `{endpoint, token, codec, sample_rate}`   | `{token}` only                                   |
| Endpoint  | from response                             | from event's `endpoint` tag (passed via `NestsRoomConfig.endpoint`) |
| NIP-98    | bound to GET URL                          | bound to POST URL + body hash                    |

Type changes:
- New `NestsRoomConfig` data class bundling (authBaseUrl, endpoint,
  hostPubkey, roomId, kind). Built by the caller (UI / VM) from the
  NIP-53 kind 30312 event before invoking connectNests*.
- `NestsRoomConfig.moqNamespace()` produces the exact format
  moq-auth's NAMESPACE_REGEX expects: `nests/<kind>:<hex64>:<roomId>`.
- `NestsRoomInfo` deleted; replaced with a tiny `NestsTokenResponse(token)`
  matching the real response shape.
- `NestsClient.resolveRoom(serviceBase, roomId, signer): NestsRoomInfo`
  → `NestsClient.mintToken(room, publish, signer): String`. The
  publish flag drives the JWT claims (`get` for listeners, `put`
  for speakers).

Wire path:
- `OkHttpNestsClient` now POSTs `<authBase>/auth` with a JSON body
  and a NIP-98 Authorization header bound to (POST, url, body-hash).
- `connectNestsListener` / `connectNestsSpeaker` take `room:
  NestsRoomConfig` instead of split (serviceBase, roomId), pass
  `publish=false` / `publish=true` respectively, and use the room's
  `endpoint` (not a server-returned one) for the WebTransport
  connect. The minted JWT is the bearer token.
- `NestsListenerState.Connected` / `NestsSpeakerState.Connected` /
  `Broadcasting` carry the `room: NestsRoomConfig` instead of the old
  `roomInfo: NestsRoomInfo`.
- MoQ TrackNamespace for the room is now a single segment whose
  bytes are `room.moqNamespace()` — the simplest mapping to the
  relay's JWT claim check (`root: "<namespace>"`); Phase-3 round-trip
  test will confirm and adjust if the relay expects a multi-segment
  tuple.

Wiring above:
- `AudioRoomViewModel` constructor: replaces `(serviceBase, roomId)`
  with `(room: NestsRoomConfig)`. Connector seam interfaces
  (NestsListenerConnector, NestsSpeakerConnector) follow the same
  shape.
- `AudioRoomViewModelFactory` (Android) takes `room: NestsRoomConfig`.
- `AudioRoomActivity` adds `EXTRA_AUTH_BASE_URL`, `EXTRA_ENDPOINT`,
  `EXTRA_HOST_PUBKEY`, `EXTRA_KIND` Intent extras (was just service
  + roomId) and reconstructs `NestsRoomConfig` in onCreate. Drops
  `EXTRA_SERVICE_BASE`.
- `AudioRoomJoinCard` reads `event.endpoint()` + `event.pubKey` +
  `event.kind` in addition to `event.service()`; rooms missing any
  of those are silently un-joinable (the event author didn't host
  on a nests-compatible relay).
- `AudioRoomActivityContent` takes `room: NestsRoomConfig` in place
  of (serviceBase, roomId) and threads it down.

Phase-1 ping test rewired to use the production `OkHttpNestsClient`
end-to-end against the real `/auth`, asserting we get back a
3-segment JWT.

Existing in-process tests updated for the new types: NestsConnectTest,
NestsSpeakerTest, AudioRoomViewModelTest. NestsRoomInfoTest renamed to
NestsRoomConfigTest with new cases for the namespace formatter and the
auth-URL helper. All 80 in-process tests still green.

Phase 3 (next) will add the full round-trip interop test that runs
production `connectNestsListener` + `connectNestsSpeaker` through the
real moq-relay — that's where MoQ wire-format assumptions (draft
revision, OBJECT_DATAGRAM layout, namespace tuple shape) get verified
or get followup audit findings.
This commit is contained in:
Claude
2026-04-26 14:42:26 +00:00
parent 3283d302fa
commit beec8204e5
17 changed files with 353 additions and 318 deletions
@@ -41,17 +41,19 @@ import kotlin.test.assertTrue
import kotlin.test.fail
class NestsConnectTest {
private val room =
NestsRoomConfig(
authBaseUrl = "https://relay.example.com/api/v1/nests",
endpoint = "https://relay.example.com/moq",
hostPubkey = "0".repeat(64),
roomId = "abc",
)
@Test
fun connect_walks_resolveRoom_then_transport_then_moq_handshake() =
fun connect_walks_mintToken_then_transport_then_moq_handshake() =
runTest {
val (clientSide, serverSide) = FakeWebTransport.pair()
val httpClient =
FakeNestsClient(
NestsRoomInfo(
endpoint = "https://relay.example.com/moq",
token = "tok-abc",
),
)
val httpClient = FakeNestsClient(token = "tok-abc")
val transport = ConstantWebTransportFactory(clientSide)
// Server-side raw peer answers SETUP.
@@ -67,31 +69,29 @@ class NestsConnectTest {
httpClient = httpClient,
transport = transport,
scope = this,
serviceBase = "https://relay.example.com/api/v1/nests",
roomId = "abc",
room = room,
signer = NostrSignerInternal(KeyPair()),
)
server.await()
val connected = assertIs<NestsListenerState.Connected>(listener.state.value)
assertEquals("https://relay.example.com/moq", connected.roomInfo.endpoint)
assertEquals(room, connected.room)
assertEquals(MoqVersion.DRAFT_17, connected.negotiatedMoqVersion)
assertEquals("relay.example.com", transport.lastConnectedAuthority)
assertEquals("/moq", transport.lastConnectedPath)
assertEquals("tok-abc", transport.lastBearer)
assertEquals(false, httpClient.lastPublishFlag, "listener mints with publish=false")
listener.close()
assertIs<NestsListenerState.Closed>(listener.state.value)
}
@Test
fun resolveRoom_failure_short_circuits_to_Failed() =
fun mintToken_failure_short_circuits_to_Failed() =
runTest {
val httpClient =
ThrowingNestsClient(
NestsException("server returned 500", status = 500),
)
val httpClient = ThrowingNestsClient(NestsException("server returned 500", status = 500))
val transport = NeverConnectFactory()
val listener =
@@ -99,13 +99,12 @@ class NestsConnectTest {
httpClient = httpClient,
transport = transport,
scope = this,
serviceBase = "https://relay.example.com/api/v1/nests",
roomId = "abc",
room = room,
signer = NostrSignerInternal(KeyPair()),
)
val failed = assertIs<NestsListenerState.Failed>(listener.state.value)
assertTrue("Room resolution failed" in failed.reason)
assertTrue("Auth failed" in failed.reason)
assertTrue("500" in failed.reason || (failed.cause as? NestsException)?.status == 500)
assertEquals(0, transport.connectCallCount, "transport must not be reached")
}
@@ -113,8 +112,7 @@ class NestsConnectTest {
@Test
fun transport_handshake_failure_short_circuits_to_Failed() =
runTest {
val httpClient =
FakeNestsClient(NestsRoomInfo(endpoint = "https://relay.example.com/moq"))
val httpClient = FakeNestsClient(token = "tok")
val transport =
ThrowingTransportFactory(
WebTransportException(
@@ -128,8 +126,7 @@ class NestsConnectTest {
httpClient = httpClient,
transport = transport,
scope = this,
serviceBase = "https://relay.example.com/api/v1/nests",
roomId = "abc",
room = room,
signer = NostrSignerInternal(KeyPair()),
)
@@ -140,16 +137,13 @@ class NestsConnectTest {
@Test
fun malformed_endpoint_url_short_circuits_to_Failed() =
runTest {
val httpClient =
FakeNestsClient(NestsRoomInfo(endpoint = "not-a-url"))
val badRoom = room.copy(endpoint = "not-a-url")
val listener =
connectNestsListener(
httpClient = httpClient,
httpClient = FakeNestsClient(token = "tok"),
transport = NeverConnectFactory(),
scope = this,
serviceBase = "https://relay.example.com/api/v1/nests",
roomId = "abc",
room = badRoom,
signer = NostrSignerInternal(KeyPair()),
)
@@ -180,23 +174,29 @@ class NestsConnectTest {
// ---------------------------------------------------------- fakes
private class FakeNestsClient(
private val info: NestsRoomInfo,
private val token: String,
) : NestsClient {
override suspend fun resolveRoom(
serviceBase: String,
roomId: String,
var lastPublishFlag: Boolean? = null
private set
override suspend fun mintToken(
room: NestsRoomConfig,
publish: Boolean,
signer: NostrSigner,
): NestsRoomInfo = info
): String {
lastPublishFlag = publish
return token
}
}
private class ThrowingNestsClient(
private val toThrow: NestsException,
) : NestsClient {
override suspend fun resolveRoom(
serviceBase: String,
roomId: String,
override suspend fun mintToken(
room: NestsRoomConfig,
publish: Boolean,
signer: NostrSigner,
): NestsRoomInfo = throw toThrow
): String = throw toThrow
}
private class ConstantWebTransportFactory(
@@ -0,0 +1,76 @@
/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.nestsclient
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
class NestsRoomConfigTest {
@Test
fun moq_namespace_uses_kind_host_pubkey_room_id_format() {
val cfg =
NestsRoomConfig(
authBaseUrl = "https://nostrnests.com/api/v1/nests",
endpoint = "https://relay.nostrnests.com:4443/anon",
hostPubkey = "0".repeat(64),
roomId = "room-abc",
)
// Matches moq-auth's NAMESPACE_REGEX: nests/<kind>:<hex64>:<room>
assertEquals(
"nests/30312:${"0".repeat(64)}:room-abc",
cfg.moqNamespace(),
)
}
@Test
fun parses_token_response_from_moq_auth() {
val r = NestsTokenResponse.parse("""{"token":"abc.def.ghi"}""")
assertEquals("abc.def.ghi", r.token)
}
@Test
fun ignores_unknown_response_fields() {
val r = NestsTokenResponse.parse("""{"token":"t","exp":1234567,"future_knob":"x"}""")
assertEquals("t", r.token)
}
@Test
fun rejects_missing_token_field() {
assertFailsWith<Exception> { NestsTokenResponse.parse("""{"endpoint":"x"}""") }
}
@Test
fun builds_auth_url_from_service_base() {
assertEquals(
"https://nostrnests.com/api/v1/nests/auth",
nestsAuthUrl("https://nostrnests.com/api/v1/nests"),
)
}
@Test
fun trims_trailing_slash_from_service_base() {
assertEquals(
"https://nostrnests.com/api/v1/nests/auth",
nestsAuthUrl("https://nostrnests.com/api/v1/nests/"),
)
}
}
@@ -1,90 +0,0 @@
/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.nestsclient
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertNull
class NestsRoomInfoTest {
@Test
fun parses_full_payload() {
val info =
NestsRoomInfo.parse(
"""{"endpoint":"https://relay.example.com/moq","token":"abc.def","codec":"opus","sample_rate":48000,"transport":"webtransport"}""",
)
assertEquals("https://relay.example.com/moq", info.endpoint)
assertEquals("abc.def", info.token)
assertEquals("opus", info.codec)
assertEquals(48000, info.sampleRate)
assertEquals("webtransport", info.transport)
}
@Test
fun tolerates_minimal_payload() {
val info = NestsRoomInfo.parse("""{"endpoint":"https://r.example.com/moq"}""")
assertEquals("https://r.example.com/moq", info.endpoint)
assertNull(info.token)
assertNull(info.codec)
assertNull(info.sampleRate)
}
@Test
fun ignores_unknown_fields() {
val info =
NestsRoomInfo.parse(
"""{"endpoint":"https://r.example.com/moq","token":"t","future_knob":"future_value"}""",
)
assertEquals("t", info.token)
}
@Test
fun rejects_missing_endpoint() {
assertFailsWith<Exception> {
NestsRoomInfo.parse("""{"token":"t"}""")
}
}
@Test
fun builds_room_info_url_from_service_and_room_id() {
assertEquals(
"https://nostrnests.com/api/v1/nests/abc-123",
nestsRoomInfoUrl("https://nostrnests.com/api/v1/nests", "abc-123"),
)
}
@Test
fun trims_trailing_slash_from_service_base() {
assertEquals(
"https://nostrnests.com/api/v1/nests/xyz",
nestsRoomInfoUrl("https://nostrnests.com/api/v1/nests/", "xyz"),
)
}
@Test
fun trims_whitespace_from_room_id() {
assertEquals(
"https://a.example.com/api/v1/nests/room",
nestsRoomInfoUrl("https://a.example.com/api/v1/nests", " room "),
)
}
}
@@ -63,7 +63,7 @@ class NestsSpeakerTest {
val state =
MutableStateFlow<NestsSpeakerState>(
NestsSpeakerState.Connected(
roomInfo = NestsRoomInfo(endpoint = "https://relay.example/moq"),
room = TEST_ROOM,
negotiatedMoqVersion = speakerSession.selectedVersion!!,
),
)
@@ -118,7 +118,7 @@ class NestsSpeakerTest {
val state =
MutableStateFlow<NestsSpeakerState>(
NestsSpeakerState.Connected(
roomInfo = NestsRoomInfo(endpoint = "https://relay.example/moq"),
room = TEST_ROOM,
negotiatedMoqVersion = speakerSession.selectedVersion!!,
),
)
@@ -167,4 +167,14 @@ class NestsSpeakerTest {
override fun release() {}
}
companion object {
private val TEST_ROOM =
NestsRoomConfig(
authBaseUrl = "https://relay.example/api/v1/nests",
endpoint = "https://relay.example/moq",
hostPubkey = "0".repeat(64),
roomId = "test-room",
)
}
}