Files
frid/crates/music-dht/src/jam.rs
T
sanapachandClaude Opus 5.5 085bff6191 Harden podcast sync registers, versions and snapshots
- Order subscription and share registers by a per-podcast Lamport
  generation before hlc_ms (next_podcast_generation), so clock skew
  cannot undo an observed unsubscribe or share decision.
- share=false is register state, not a compactable tombstone.
- Add podcast_feed_aliases_added so refreshes can sync aliases without
  touching the registers; SubscriptionRecord::feed_urls keeps the current
  feed URL resolvable beyond the alias bound.
- Carry progress_generation on queue items for handoff.
- Distinguish self-reported and relayed peer versions, and gate
  PairRequest by an optional inviter version in InviteWire.
- Give each podcast snapshot section its own byte budget, drop channel
  descriptions from snapshots and allow a caller-provided budget.
- Reject one-slash http(s) typos in FeedUrl::from_user_input.
- Pin that malformed ids and feed URLs reject the whole message.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 16:10:33 +02:00

352 lines
12 KiB
Rust

//! Ephemeral shared playback control between independent Furumi peers.
//!
//! Jam is separate from personal-device sync. Possession of a [`JamInvite`]
//! capability authorizes playback control for one host process, but never
//! grants likes, playlists, history, or trusted-device membership.
//!
//! Podcast episodes are private. Hosts send [`redact_jam_snapshot`] to
//! participants, reject participant commands for which
//! [`crate::device_sync::jam_command_allowed`] is false, and map placeholders
//! back with [`crate::device_sync::restore_jam_private_items`] before applying
//! a participant's state.
use serde::{Deserialize, Serialize};
use tokio::io::{AsyncRead, AsyncReadExt};
use crate::device_sync::{PlaybackCommand, PlaybackSnapshot};
use crate::error::{MusicDhtError, Result};
/// Dedicated stream protocol for Jam control version 1.
pub const JAM_ALPN_V1: &[u8] = b"furumi/jam/1";
/// Current Jam stream protocol.
pub const JAM_ALPN: &[u8] = JAM_ALPN_V1;
/// Current Jam wire version.
pub const JAM_PROTOCOL_VERSION: u16 = 1;
/// Maximum accepted JSON message.
pub const MAX_JAM_LINE: usize = 8 * 1024 * 1024;
/// Recommended timeout for a host with no participant polls.
pub const DEFAULT_JAM_IDLE_TTL_MS: i64 = 30 * 60 * 1_000;
/// Maximum commands accepted in one participant poll.
pub const MAX_JAM_COMMANDS_PER_POLL: usize = 128;
/// Long-lived host capability encoded as `frid://j/<base64url-json>`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct JamInvite {
/// Invite schema version.
pub v: u16,
/// Host transport ticket.
#[serde(rename = "t")]
pub ticket: String,
/// Runtime Jam session id.
#[serde(rename = "j")]
pub jam_id: String,
/// Runtime capability secret.
#[serde(rename = "s")]
pub secret: String,
/// Host player/device id.
#[serde(rename = "d")]
pub host_device_id: String,
/// Host display name.
#[serde(rename = "n")]
pub host_name: String,
}
impl JamInvite {
/// Encodes this invite as an opaque `frid://j/...` capability.
pub fn to_uri(&self) -> Result<String> {
validate_invite(self)?;
let bytes = serde_json::to_vec(self).map_err(protocol_err)?;
Ok(format!("frid://j/{}", base64url_encode(&bytes)))
}
/// Parses and validates an opaque Jam capability.
pub fn from_uri(uri: &str) -> Result<Self> {
let encoded = uri
.trim()
.strip_prefix("frid://j/")
.ok_or_else(|| MusicDhtError::Protocol("expected frid://j invite".to_string()))?;
let bytes = base64url_decode(encoded)?;
let invite: Self = serde_json::from_slice(&bytes).map_err(protocol_err)?;
validate_invite(&invite)?;
Ok(invite)
}
}
/// Display identity scoped to one runtime Jam.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct JamParticipant {
/// Participant runtime id.
pub participant_id: String,
/// User-visible name.
pub name: String,
/// Last successful host exchange in Unix milliseconds.
pub last_seen_ms: i64,
}
/// Deduplicated playback command submitted by a participant.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct JamCommand {
/// Unique command id generated by the participant.
pub command_id: String,
/// Participant runtime id.
pub participant_id: String,
/// Command payload shared with personal-device and web control.
pub command: PlaybackCommand,
/// Client timestamp for diagnostics.
pub sent_at_ms: i64,
}
/// Top-level JSON-lines Jam message.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum JamWireMessage {
/// Participant poll: submits commands and requests host state.
Poll {
/// Protocol version.
version: u16,
/// Jam id from the capability.
jam_id: String,
/// Capability secret.
secret: String,
/// Participant display identity.
participant: JamParticipant,
/// Commands not yet acknowledged by the host.
#[serde(default)]
commands: Vec<JamCommand>,
},
/// Host response to a poll.
Snapshot {
/// Whether the capability was accepted.
accepted: bool,
/// Optional refusal reason.
#[serde(default)]
error: Option<String>,
/// IDs of commands accepted by this host runtime.
#[serde(default)]
acknowledged_command_ids: Vec<String>,
/// Current host playback state.
#[serde(default)]
playback: Option<PlaybackSnapshot>,
/// Currently visible participants.
#[serde(default)]
participants: Vec<JamParticipant>,
/// Host response time in Unix milliseconds.
host_time_ms: i64,
},
/// Explicit best-effort participant departure.
Leave {
/// Protocol version.
version: u16,
/// Jam id from the capability.
jam_id: String,
/// Capability secret.
secret: String,
/// Participant runtime id.
participant_id: String,
},
}
/// Returns a playback snapshot safe to send to Jam participants.
///
/// Podcast episodes become opaque placeholders (see
/// [`crate::device_sync::redact_for_jam`]) and the personal coordination
/// envelope is removed, since it belongs to the trusted-device scope.
pub fn redact_jam_snapshot(mut snapshot: PlaybackSnapshot) -> PlaybackSnapshot {
snapshot.state = crate::device_sync::redact_for_jam(snapshot.state);
snapshot.coordination = None;
snapshot
}
/// Reads a bounded Jam message from an async reader.
pub async fn read_message_from<R: AsyncRead + Unpin>(reader: &mut R) -> Result<JamWireMessage> {
let mut line = Vec::new();
let mut byte = [0_u8; 1];
loop {
let read = reader.read(&mut byte).await.map_err(network_err)?;
if read == 0 || byte[0] == b'\n' {
break;
}
line.push(byte[0]);
if line.len() > MAX_JAM_LINE {
return Err(MusicDhtError::Protocol(
"Jam protocol line is too large".to_string(),
));
}
}
if line.is_empty() {
return Err(MusicDhtError::Protocol(
"Jam protocol message is empty".to_string(),
));
}
serde_json::from_slice(&line).map_err(protocol_err)
}
fn validate_invite(invite: &JamInvite) -> Result<()> {
if invite.v != JAM_PROTOCOL_VERSION {
return Err(MusicDhtError::Protocol(format!(
"unsupported Jam invite version {}",
invite.v
)));
}
if invite.ticket.trim().is_empty()
|| invite.jam_id.trim().is_empty()
|| invite.secret.len() < 16
|| invite.host_device_id.trim().is_empty()
|| invite.host_name.trim().is_empty()
{
return Err(MusicDhtError::Protocol("incomplete Jam invite".to_string()));
}
Ok(())
}
fn base64url_encode(bytes: &[u8]) -> String {
const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
let mut out = String::new();
let mut i = 0;
while i < bytes.len() {
let b0 = bytes[i];
let b1 = bytes.get(i + 1).copied().unwrap_or(0);
let b2 = bytes.get(i + 2).copied().unwrap_or(0);
out.push(TABLE[(b0 >> 2) as usize] as char);
out.push(TABLE[(((b0 & 3) << 4) | (b1 >> 4)) as usize] as char);
if i + 1 < bytes.len() {
out.push(TABLE[(((b1 & 15) << 2) | (b2 >> 6)) as usize] as char);
}
if i + 2 < bytes.len() {
out.push(TABLE[(b2 & 63) as usize] as char);
}
i += 3;
}
out
}
fn base64url_decode(value: &str) -> Result<Vec<u8>> {
fn decode(byte: u8) -> Option<u8> {
match byte {
b'A'..=b'Z' => Some(byte - b'A'),
b'a'..=b'z' => Some(byte - b'a' + 26),
b'0'..=b'9' => Some(byte - b'0' + 52),
b'-' => Some(62),
b'_' => Some(63),
_ => None,
}
}
let bytes = value.as_bytes();
if bytes.len() % 4 == 1 {
return Err(invalid_base64());
}
let mut out = Vec::with_capacity(bytes.len() * 3 / 4);
let mut i = 0;
while i < bytes.len() {
let a = decode(bytes[i]).ok_or_else(invalid_base64)?;
let b = decode(*bytes.get(i + 1).ok_or_else(invalid_base64)?).ok_or_else(invalid_base64)?;
let c = bytes.get(i + 2).and_then(|byte| decode(*byte));
let d = bytes.get(i + 3).and_then(|byte| decode(*byte));
out.push((a << 2) | (b >> 4));
if let Some(c) = c {
out.push((b << 4) | (c >> 2));
if let Some(d) = d {
out.push((c << 6) | d);
}
}
i += 4;
}
Ok(out)
}
fn invalid_base64() -> MusicDhtError {
MusicDhtError::Protocol("invalid base64url Jam invite".to_string())
}
fn protocol_err(err: impl std::fmt::Display) -> MusicDhtError {
MusicDhtError::Protocol(err.to_string())
}
fn network_err(err: impl std::fmt::Display) -> MusicDhtError {
MusicDhtError::Network(err.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
fn invite() -> JamInvite {
JamInvite {
v: JAM_PROTOCOL_VERSION,
ticket: "endpoint-ticket".to_string(),
jam_id: "jam_123".to_string(),
secret: "0123456789abcdef0123456789abcdef".to_string(),
host_device_id: "dev_host".to_string(),
host_name: "Living room".to_string(),
}
}
#[test]
fn jam_invite_round_trips() {
let invite = invite();
let uri = invite.to_uri().unwrap();
assert!(uri.starts_with("frid://j/"));
assert_eq!(JamInvite::from_uri(&uri).unwrap(), invite);
}
#[test]
fn personal_device_invites_are_not_jam_capabilities() {
assert!(JamInvite::from_uri("frid://i/abcd").is_err());
}
#[test]
fn jam_snapshots_hide_podcast_episodes() {
use crate::device_sync::{PlaybackRepeat, PlaybackStateWire, PlaybackTrack};
use crate::podcast::{EpisodeId, FeedUrl, PodcastEpisodeRef, PodcastId};
let feed = FeedUrl::parse("https://private.test/feed").unwrap();
let podcast_id = PodcastId::from_feed_url(&feed);
let episode = PodcastEpisodeRef {
episode_id: EpisodeId::from_guid(&podcast_id, "e").unwrap(),
podcast_id,
feed_url: feed,
podcast_title: "Hidden show".to_string(),
episode_title: "Hidden episode".to_string(),
audio_url: "https://private.test/e.mp3".to_string(),
mime: None,
duration_ms: None,
published_at_ms: None,
season: None,
episode_number: None,
image_url: None,
progress_generation: Some(7),
};
let snapshot = PlaybackSnapshot {
device_id: "host".to_string(),
device_name: "Host".to_string(),
active: true,
updated_at_ms: 1,
state: PlaybackStateWire {
queue: vec![PlaybackTrack::podcast_episode(episode)],
queue_pos: 0,
playing: true,
paused: false,
idle_since_ms: None,
position_secs: 1.0,
volume: 50,
shuffle: false,
repeat: PlaybackRepeat::Off,
playback_rate: None,
},
coordination: None,
};
let redacted = redact_jam_snapshot(snapshot);
let json = serde_json::to_string(&redacted).unwrap();
assert!(!json.contains("Hidden"));
assert!(!json.contains("private.test"));
assert!(redacted.state.queue[0].is_private_placeholder());
}
#[test]
fn weak_capability_is_rejected() {
let mut invite = invite();
invite.secret = "short".to_string();
assert!(invite.to_uri().is_err());
}
}