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:
@@ -35,21 +35,25 @@ import com.vitorpamplona.quartz.nip01Core.signers.NostrSigner
|
||||
*/
|
||||
interface NestsClient {
|
||||
/**
|
||||
* Fetch [NestsRoomInfo] for a specific room.
|
||||
* Mint a JWT scoped to one MoQ namespace. Posts a NIP-98-signed
|
||||
* request to `<authBase>/auth` per the nostrnests reference server
|
||||
* (`moq-auth/src/index.ts`); the returned token is the bearer the
|
||||
* MoQ relay validates against the auth sidecar's JWKS endpoint.
|
||||
*
|
||||
* @param serviceBase value of the NIP-53 kind 30312 `service` tag
|
||||
* (e.g. `https://nostrnests.com/api/v1/nests`)
|
||||
* @param roomId the event's `d` tag
|
||||
* @param signer signs the NIP-98 auth event that the server uses to verify
|
||||
* the caller owns the pubkey it claims
|
||||
* @throws NestsException on transport errors, non-2xx responses, or malformed
|
||||
* JSON
|
||||
* @param room per-room config carrying authBase, host pubkey, room id.
|
||||
* @param publish `true` if the caller wants publish rights for their
|
||||
* own pubkey under this namespace; `false` for listen-only.
|
||||
* @param signer signs the NIP-98 auth event. The server verifies the
|
||||
* event binds to this exact (url, method, body-hash) tuple, so
|
||||
* the JWT cannot be replayed against a different request.
|
||||
* @throws NestsException on transport errors, non-2xx responses, or
|
||||
* malformed JSON.
|
||||
*/
|
||||
suspend fun resolveRoom(
|
||||
serviceBase: String,
|
||||
roomId: String,
|
||||
suspend fun mintToken(
|
||||
room: NestsRoomConfig,
|
||||
publish: Boolean,
|
||||
signer: NostrSigner,
|
||||
): NestsRoomInfo
|
||||
): String
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -36,10 +36,11 @@ import kotlinx.coroutines.flow.MutableStateFlow
|
||||
* Walk the full join-as-listener handshake against a nests-compatible audio
|
||||
* server:
|
||||
*
|
||||
* 1. Resolve the room — POST/GET `<serviceBase>/<roomId>` with NIP-98 auth,
|
||||
* returning [NestsRoomInfo] (the MoQ endpoint + bearer token).
|
||||
* 1. Mint a JWT — POST `<authBase>/auth` with NIP-98 + namespace body
|
||||
* (see [NestsClient.mintToken]).
|
||||
* 2. Open a [com.vitorpamplona.nestsclient.transport.WebTransportSession]
|
||||
* against the endpoint via [transport].
|
||||
* against the [room.endpoint] via [transport], passing the JWT as the
|
||||
* bearer token.
|
||||
* 3. Run the MoQ SETUP handshake.
|
||||
*
|
||||
* The returned [NestsListener] is in state [NestsListenerState.Connected];
|
||||
@@ -47,7 +48,9 @@ import kotlinx.coroutines.flow.MutableStateFlow
|
||||
* [NestsListenerState.Failed] with the underlying cause attached and the
|
||||
* transport torn down.
|
||||
*
|
||||
* @param signer NIP-98 signer for the resolveRoom HTTP call.
|
||||
* @param room per-room config built from the NIP-53 kind 30312 event by
|
||||
* the caller (UI / VM).
|
||||
* @param signer NIP-98 signer for the mintToken HTTP call.
|
||||
* @param scope where the [MoqSession] pumps live (typically the caller's
|
||||
* ViewModel scope so they cancel when the screen leaves).
|
||||
* @param supportedMoqVersions in preference order; defaults to draft-17.
|
||||
@@ -56,8 +59,7 @@ suspend fun connectNestsListener(
|
||||
httpClient: NestsClient,
|
||||
transport: WebTransportFactory,
|
||||
scope: CoroutineScope,
|
||||
serviceBase: String,
|
||||
roomId: String,
|
||||
room: NestsRoomConfig,
|
||||
signer: NostrSigner,
|
||||
supportedMoqVersions: List<Long> = listOf(MoqVersion.DRAFT_17),
|
||||
): NestsListener {
|
||||
@@ -66,11 +68,11 @@ suspend fun connectNestsListener(
|
||||
NestsListenerState.Connecting(NestsListenerState.Connecting.ConnectStep.ResolvingRoom),
|
||||
)
|
||||
|
||||
val roomInfo =
|
||||
val token =
|
||||
try {
|
||||
httpClient.resolveRoom(serviceBase = serviceBase, roomId = roomId, signer = signer)
|
||||
httpClient.mintToken(room = room, publish = false, signer = signer)
|
||||
} catch (t: NestsException) {
|
||||
state.value = NestsListenerState.Failed("Room resolution failed: ${t.message}", t)
|
||||
state.value = NestsListenerState.Failed("Auth failed: ${t.message}", t)
|
||||
return failedListener(state)
|
||||
}
|
||||
|
||||
@@ -78,11 +80,11 @@ suspend fun connectNestsListener(
|
||||
|
||||
val (authority, path) =
|
||||
try {
|
||||
parseEndpoint(roomInfo.endpoint)
|
||||
parseEndpoint(room.endpoint)
|
||||
} catch (t: Throwable) {
|
||||
state.value =
|
||||
NestsListenerState.Failed(
|
||||
"Malformed MoQ endpoint URL '${roomInfo.endpoint}': ${t.message}",
|
||||
"Malformed MoQ endpoint URL '${room.endpoint}': ${t.message}",
|
||||
t,
|
||||
)
|
||||
return failedListener(state)
|
||||
@@ -90,7 +92,7 @@ suspend fun connectNestsListener(
|
||||
|
||||
val webTransport =
|
||||
try {
|
||||
transport.connect(authority = authority, path = path, bearerToken = roomInfo.token)
|
||||
transport.connect(authority = authority, path = path, bearerToken = token)
|
||||
} catch (t: WebTransportException) {
|
||||
state.value =
|
||||
NestsListenerState.Failed(
|
||||
@@ -118,10 +120,15 @@ suspend fun connectNestsListener(
|
||||
return failedListener(state)
|
||||
}
|
||||
|
||||
state.value = NestsListenerState.Connected(roomInfo, negotiatedVersion)
|
||||
state.value = NestsListenerState.Connected(room, negotiatedVersion)
|
||||
return DefaultNestsListener(
|
||||
session = moq,
|
||||
roomNamespace = TrackNamespace.of("nests", roomId),
|
||||
// moq-auth's JWT claim is `root: "<moqNamespace>"` — the simplest
|
||||
// wire-level mapping is a 1-segment TrackNamespace whose only
|
||||
// element is that exact string. Phase-3 interop test will
|
||||
// confirm; if the real relay expects a multi-segment tuple
|
||||
// (e.g. split on `/` or `:`), adjust here.
|
||||
roomNamespace = TrackNamespace.of(room.moqNamespace()),
|
||||
mutableState = state,
|
||||
)
|
||||
}
|
||||
@@ -160,8 +167,7 @@ suspend fun connectNestsSpeaker(
|
||||
httpClient: NestsClient,
|
||||
transport: WebTransportFactory,
|
||||
scope: CoroutineScope,
|
||||
serviceBase: String,
|
||||
roomId: String,
|
||||
room: NestsRoomConfig,
|
||||
signer: NostrSigner,
|
||||
speakerPubkeyHex: String,
|
||||
captureFactory: () -> AudioCapture,
|
||||
@@ -173,11 +179,11 @@ suspend fun connectNestsSpeaker(
|
||||
NestsSpeakerState.Connecting(NestsSpeakerState.Connecting.ConnectStep.ResolvingRoom),
|
||||
)
|
||||
|
||||
val roomInfo =
|
||||
val token =
|
||||
try {
|
||||
httpClient.resolveRoom(serviceBase = serviceBase, roomId = roomId, signer = signer)
|
||||
httpClient.mintToken(room = room, publish = true, signer = signer)
|
||||
} catch (t: NestsException) {
|
||||
state.value = NestsSpeakerState.Failed("Room resolution failed: ${t.message}", t)
|
||||
state.value = NestsSpeakerState.Failed("Auth failed: ${t.message}", t)
|
||||
return failedSpeaker(state)
|
||||
}
|
||||
|
||||
@@ -185,11 +191,11 @@ suspend fun connectNestsSpeaker(
|
||||
|
||||
val (authority, path) =
|
||||
try {
|
||||
parseEndpoint(roomInfo.endpoint)
|
||||
parseEndpoint(room.endpoint)
|
||||
} catch (t: Throwable) {
|
||||
state.value =
|
||||
NestsSpeakerState.Failed(
|
||||
"Malformed MoQ endpoint URL '${roomInfo.endpoint}': ${t.message}",
|
||||
"Malformed MoQ endpoint URL '${room.endpoint}': ${t.message}",
|
||||
t,
|
||||
)
|
||||
return failedSpeaker(state)
|
||||
@@ -197,7 +203,7 @@ suspend fun connectNestsSpeaker(
|
||||
|
||||
val webTransport =
|
||||
try {
|
||||
transport.connect(authority = authority, path = path, bearerToken = roomInfo.token)
|
||||
transport.connect(authority = authority, path = path, bearerToken = token)
|
||||
} catch (t: WebTransportException) {
|
||||
state.value =
|
||||
NestsSpeakerState.Failed(
|
||||
@@ -225,10 +231,11 @@ suspend fun connectNestsSpeaker(
|
||||
return failedSpeaker(state)
|
||||
}
|
||||
|
||||
state.value = NestsSpeakerState.Connected(roomInfo, negotiatedVersion)
|
||||
state.value = NestsSpeakerState.Connected(room, negotiatedVersion)
|
||||
return DefaultNestsSpeaker(
|
||||
session = moq,
|
||||
roomNamespace = TrackNamespace.of("nests", roomId),
|
||||
// Same single-segment shape as the listener path; see comment there.
|
||||
roomNamespace = TrackNamespace.of(room.moqNamespace()),
|
||||
speakerTrackName = speakerPubkeyHex.encodeToByteArray(),
|
||||
captureFactory = captureFactory,
|
||||
encoderFactory = encoderFactory,
|
||||
|
||||
@@ -82,9 +82,9 @@ sealed class NestsListenerState {
|
||||
}
|
||||
}
|
||||
|
||||
/** Connection is live. [roomInfo] reflects the resolved server metadata. */
|
||||
/** Connection is live. [room] reflects the (auth, endpoint, room) we connected to. */
|
||||
data class Connected(
|
||||
val roomInfo: NestsRoomInfo,
|
||||
val room: NestsRoomConfig,
|
||||
val negotiatedMoqVersion: Long,
|
||||
) : NestsListenerState()
|
||||
|
||||
|
||||
@@ -20,30 +20,51 @@
|
||||
*/
|
||||
package com.vitorpamplona.nestsclient
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
|
||||
/**
|
||||
* Information returned by a nests audio-room backend when a client
|
||||
* authenticates against `<service>/api/v1/nests/<roomId>`.
|
||||
* Per-room configuration that orchestration needs to connect. Built from
|
||||
* the NIP-53 kind 30312 [MeetingSpaceEvent] by the caller (UI / VM)
|
||||
* before invoking `connectNestsListener` / `connectNestsSpeaker`:
|
||||
*
|
||||
* Field names mirror the nests reference server payload:
|
||||
* ```
|
||||
* { "endpoint": "...", "token": "...", "codec": "opus", "sample_rate": 48000 }
|
||||
* ```
|
||||
* All fields except [endpoint] are optional so the client can negotiate with
|
||||
* alternate nests implementations that omit codec/token metadata.
|
||||
* - [authBaseUrl] — the event's `service` tag (e.g. `https://nostrnests.com/api/v1/nests`).
|
||||
* Note: the real moq-auth API is rooted at this base; the client posts
|
||||
* to `<authBaseUrl>/auth` to mint a JWT.
|
||||
* - [endpoint] — the event's `endpoint` tag (e.g. `https://relay.nostrnests.com:4443/anon`).
|
||||
* The MoQ relay's WebTransport URL.
|
||||
* - [hostPubkey] — the event author's pubkey. Goes into the
|
||||
* [NestsAuth.MOQ_NAMESPACE_PREFIX] to scope the JWT to this room.
|
||||
* - [roomId] — the event's `d` tag.
|
||||
* - [kind] — the NIP-53 event kind (30312 for meeting spaces).
|
||||
*/
|
||||
data class NestsRoomConfig(
|
||||
val authBaseUrl: String,
|
||||
val endpoint: String,
|
||||
val hostPubkey: String,
|
||||
val roomId: String,
|
||||
val kind: Int = MEETING_SPACE_KIND,
|
||||
) {
|
||||
/**
|
||||
* MoQ namespace string for this room, in the format moq-auth expects:
|
||||
* `nests/<kind>:<host_pubkey_hex>:<roomId>`.
|
||||
*/
|
||||
fun moqNamespace(): String = "nests/$kind:$hostPubkey:$roomId"
|
||||
|
||||
companion object {
|
||||
const val MEETING_SPACE_KIND: Int = 30312
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Response shape from `POST <authBase>/auth`. The reference server
|
||||
* (`nostrnests/nests/moq-auth/src/index.ts`) returns `{"token":"<jwt>"}`
|
||||
* — that JWT is then passed as the WebTransport bearer token to the
|
||||
* MoQ relay.
|
||||
*/
|
||||
@Serializable
|
||||
data class NestsRoomInfo(
|
||||
val endpoint: String,
|
||||
val token: String? = null,
|
||||
val codec: String? = null,
|
||||
@SerialName("sample_rate") val sampleRate: Int? = null,
|
||||
val transport: String? = null,
|
||||
val extra: Map<String, JsonElement> = emptyMap(),
|
||||
data class NestsTokenResponse(
|
||||
val token: String,
|
||||
) {
|
||||
companion object {
|
||||
private val json =
|
||||
@@ -52,23 +73,15 @@ data class NestsRoomInfo(
|
||||
explicitNulls = false
|
||||
}
|
||||
|
||||
fun parse(body: String): NestsRoomInfo = json.decodeFromString(serializer(), body)
|
||||
fun parse(body: String): NestsTokenResponse = json.decodeFromString(serializer(), body)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the URL a client should call to resolve [NestsRoomInfo] for a specific
|
||||
* room. [serviceBase] comes from the `service` tag of the NIP-53 kind 30312
|
||||
* event; [roomId] is the event's `d` tag.
|
||||
* Build the auth URL for a given service base. Trims trailing slashes
|
||||
* and appends `/auth`.
|
||||
*
|
||||
* Example: `https://nostrnests.com/api/v1/nests` + `abc-123` →
|
||||
* `https://nostrnests.com/api/v1/nests/abc-123`.
|
||||
* Example: `https://nostrnests.com/api/v1/nests` →
|
||||
* `https://nostrnests.com/api/v1/nests/auth`.
|
||||
*/
|
||||
fun nestsRoomInfoUrl(
|
||||
serviceBase: String,
|
||||
roomId: String,
|
||||
): String {
|
||||
val trimmed = serviceBase.trimEnd('/')
|
||||
val encoded = roomId.trim()
|
||||
return "$trimmed/$encoded"
|
||||
}
|
||||
fun nestsAuthUrl(authBase: String): String = authBase.trimEnd('/') + "/auth"
|
||||
|
||||
@@ -95,13 +95,13 @@ sealed class NestsSpeakerState {
|
||||
|
||||
/** Connection live; ready for [NestsSpeaker.startBroadcasting]. */
|
||||
data class Connected(
|
||||
val roomInfo: NestsRoomInfo,
|
||||
val room: NestsRoomConfig,
|
||||
val negotiatedMoqVersion: Long,
|
||||
) : NestsSpeakerState()
|
||||
|
||||
/** Currently announcing + emitting OBJECT_DATAGRAMs for our track. */
|
||||
data class Broadcasting(
|
||||
val roomInfo: NestsRoomInfo,
|
||||
val room: NestsRoomConfig,
|
||||
val negotiatedMoqVersion: Long,
|
||||
val isMuted: Boolean,
|
||||
) : NestsSpeakerState()
|
||||
@@ -161,7 +161,7 @@ class DefaultNestsSpeaker internal constructor(
|
||||
broadcaster.start()
|
||||
mutableState.value =
|
||||
NestsSpeakerState.Broadcasting(
|
||||
roomInfo = current.roomInfo,
|
||||
room = current.room,
|
||||
negotiatedMoqVersion = current.negotiatedMoqVersion,
|
||||
isMuted = false,
|
||||
)
|
||||
@@ -187,7 +187,7 @@ class DefaultNestsSpeaker internal constructor(
|
||||
val current = mutableState.value
|
||||
if (current is NestsSpeakerState.Broadcasting) {
|
||||
mutableState.value =
|
||||
NestsSpeakerState.Connected(current.roomInfo, current.negotiatedMoqVersion)
|
||||
NestsSpeakerState.Connected(current.room, current.negotiatedMoqVersion)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user