feat(beta): External Beta — passwords, channel join, mute, bookmarks, encrypted identity
The v0.3 client could only ever connect to a hardcoded default
channel with no password and offered no controls mid-call.
External Beta closes those gaps and tightens identity-at-rest.
User-facing additions
---------------------
* **Server password** on the connect form. Plumbed through
`BridgeError`-aware `connect(host, nickname, password)`. Empty
string means "no password" — no behaviour change for open
servers.
* **Channel join**: tapping a row (or its login icon) in the
channel tree issues a `client_move`. Names containing "🔒" or
"password" prompt for a channel password first.
* **Self-mute** for both microphone (`client_input_muted`) and
speaker (`client_output_muted`) via FilterChips. Output mute
also flips the audio engine's local output-muted flag so
playback silences immediately, before the server acknowledges.
* **Master output gain** slider (0–200%). Plumbed through an
`AtomicU32` (f32 bits) on the engine that the cpal output
callback multiplies into every sample.
* **Bookmarks**: SQLite-backed list with Save / Connect / Delete
actions. Bookmarks persist across app restarts; tapping one
pre-fills the form and dials immediately.
Hardening
---------
* **Encrypted identity at rest** (RISK-PoC-002 closure for the
file-only threat model). ChaCha20-Poly1305 envelope: nonce +
ciphertext written atomically with mode 0600; 32-byte DEK in a
separate `identity.dek` file. Legacy plaintext identity files
are auto-detected, read, and upgraded on the next save. Full OS-
keyring integration is still v0.4 work — documented in the
store's doc comment.
* **Mobile voice-comm routing**: on Android, `AudioEngine::start`
uses JNI to set `AudioManager.setMode(MODE_IN_COMMUNICATION)`
when `cfg.mobile_voice_preset` is true (default). This engages
the device-side AEC/NS pipeline on most Pixel/Moto/Samsung
hardware even though cpal still opens the AAudio default input
preset. Full `setInputPreset(VOICE_COMMUNICATION)` switch is
still RISK-AUDIO-MOBILE-001 (needs cpal upstream or an Oboe
fork).
* **Log noise**: bridge default `EnvFilter` now silences
`tsproto::resend=error` and `tsproto::packet_codec=error` so
the redacted diagnostic export is human-readable. Still
overridable via `RUST_LOG=...`.
Engineering
-----------
* **`chanora_storage`** gains `BookmarkRepository` (rusqlite
bundled) with `add` / `update` / `delete` / `list`. The
identity store now layers on `chacha20poly1305` + `rand` +
`zeroize` for the envelope.
* **`chanora_protocol`** exposes `move_to_channel` and
`set_muted` on `ProtocolClient`, dispatched through the
existing `connection_task` request channel onto tsclientlib's
generated `client.client_move(...)` and
`state.client_update().set_input_muted/set_output_muted(...)`
paths.
* **`chanora_core::ChanoraSession`** wires the bookmark store
next to the identity store inside `init_storage`, and adds
`list_bookmarks` / `add_bookmark` / `update_bookmark` /
`delete_bookmark` / `move_to_channel` / `set_self_muted` /
`set_output_gain`.
* **`chanora_audio::AudioEngine`** carries `output_gain` and
`output_muted` atomics; the output callback consults both. The
Android branch of `start()` engages MODE_IN_COMMUNICATION via
a small JNI helper that reuses the `ndk_context` global set by
the bridge's `android_init` hook.
* **`chanora_bridge::api`** adds `set_input_muted`,
`set_output_muted`, `set_output_gain`, `move_to_channel`,
`list_bookmarks`, `add_bookmark`, `update_bookmark`,
`delete_bookmark`, and the `BridgeBookmark` DTO. FRB v2.12
codegen regenerated.
Tests + CI
----------
* `chanora_storage` test count rises from 3 to 8 — bookmark CRUD
round-trip, missing-row → `NotFound`, encrypted round-trip
(verifies ciphertext is not the plaintext on disk), and the
legacy plaintext upgrade path.
* New `.github/workflows/ci.yml`: `cargo check --workspace`,
`cargo test --workspace --no-fail-fast`, `cargo clippy`
(advisory), `flutter analyze`, and `flutter test` excluding
the live-server `e2e` tag.
Live-verified on Moto G Stylus 5G against cn.teamspeak.app:
saved a bookmark, reconnected via it, joined a non-default
channel via tap, toggled both mutes, slid the volume, and the
redacted diagnostic export confirmed `AudioManager mode set to
MODE_IN_COMMUNICATION`, `client_move sent`, and `client_update
sent` lines.
This commit is contained in:
@@ -26,3 +26,10 @@ audiopus = "0.3.0-rc.0"
|
||||
tsclientlib = { git = "https://github.com/ReSpeak/tsclientlib.git", rev = "04aa2491", default-features = false, features = ["default-tls", "audio"] }
|
||||
|
||||
tokio = { version = "1", features = ["sync", "rt", "macros", "time"] }
|
||||
|
||||
[target.'cfg(target_os = "android")'.dependencies]
|
||||
# JNI bindings to flip Android's AudioManager into MODE_IN_COMMUNICATION
|
||||
# when the voice-comm preset is requested. ndk_context is initialised
|
||||
# by the bridge crate's android_init shim.
|
||||
jni = { version = "0.21", default-features = false }
|
||||
ndk-context = "0.1"
|
||||
|
||||
@@ -80,6 +80,15 @@ pub struct AudioEngine {
|
||||
ptt: Arc<AtomicBool>,
|
||||
frames_sent: Arc<AtomicU32>,
|
||||
frames_received: Arc<AtomicU32>,
|
||||
/// Master output gain as f32 bits in an AtomicU32. Default 1.0.
|
||||
/// Adjusted via [`Self::set_output_gain`] from the bridge.
|
||||
output_gain: Arc<AtomicU32>,
|
||||
/// Master output mute. When true the output callback fills the
|
||||
/// device buffer with silence regardless of incoming voice
|
||||
/// frames. Used for self-output-mute on the local device,
|
||||
/// independent of the server-side mute the protocol layer
|
||||
/// broadcasts.
|
||||
output_muted: Arc<AtomicBool>,
|
||||
|
||||
// Streams must be dropped to stop audio. Both are `!Send` because
|
||||
// cpal's Stream isn't Send on some backends; we keep them in an
|
||||
@@ -141,17 +150,24 @@ impl AudioEngine {
|
||||
#[cfg(target_os = "android")]
|
||||
{
|
||||
if cfg.mobile_voice_preset {
|
||||
info!(
|
||||
target: "chanora_audio",
|
||||
"android: mobile_voice_preset requested (RISK-AUDIO-MOBILE-001 — flag plumbed, switch pending cpal upstream)"
|
||||
);
|
||||
match android_engage_voice_communication() {
|
||||
Ok(()) => info!(
|
||||
target: "chanora_audio",
|
||||
"android: AudioManager mode set to MODE_IN_COMMUNICATION"
|
||||
),
|
||||
Err(e) => warn!(
|
||||
target: "chanora_audio",
|
||||
error = %e,
|
||||
"android: failed to set MODE_IN_COMMUNICATION; falling back to default routing"
|
||||
),
|
||||
}
|
||||
}
|
||||
if cfg.effects.aec || cfg.effects.noise_suppression {
|
||||
info!(
|
||||
target: "chanora_audio",
|
||||
aec = cfg.effects.aec,
|
||||
ns = cfg.effects.noise_suppression,
|
||||
"android: effects requested; awaiting OS-source switch to engage hardware AEC/NS"
|
||||
"android: effects requested; engagement depends on device AEC/NS support under MODE_IN_COMMUNICATION"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -168,6 +184,8 @@ impl AudioEngine {
|
||||
let ptt = Arc::new(AtomicBool::new(cfg.ptt_initial));
|
||||
let frames_sent = Arc::new(AtomicU32::new(0));
|
||||
let frames_received = Arc::new(AtomicU32::new(0));
|
||||
let output_gain = Arc::new(AtomicU32::new(1.0_f32.to_bits()));
|
||||
let output_muted = Arc::new(AtomicBool::new(false));
|
||||
|
||||
// ---------- Capture ----------
|
||||
// Capture is best-effort. If the platform default input
|
||||
@@ -218,16 +236,22 @@ impl AudioEngine {
|
||||
&out_dev,
|
||||
&out_stream_cfg,
|
||||
audio_handler.clone(),
|
||||
output_gain.clone(),
|
||||
output_muted.clone(),
|
||||
)?,
|
||||
SampleFormat::I16 => build_output_stream::<i16>(
|
||||
&out_dev,
|
||||
&out_stream_cfg,
|
||||
audio_handler.clone(),
|
||||
output_gain.clone(),
|
||||
output_muted.clone(),
|
||||
)?,
|
||||
SampleFormat::U16 => build_output_stream::<u16>(
|
||||
&out_dev,
|
||||
&out_stream_cfg,
|
||||
audio_handler.clone(),
|
||||
output_gain.clone(),
|
||||
output_muted.clone(),
|
||||
)?,
|
||||
other => {
|
||||
return Err(AudioError::StreamConfig(format!(
|
||||
@@ -272,6 +296,8 @@ impl AudioEngine {
|
||||
ptt,
|
||||
frames_sent,
|
||||
frames_received,
|
||||
output_gain,
|
||||
output_muted,
|
||||
_input_stream: Mutex::new(input_stream),
|
||||
_output_stream: Mutex::new(Some(output_stream)),
|
||||
shutdown_tx: Some(shutdown_tx),
|
||||
@@ -316,6 +342,31 @@ impl AudioEngine {
|
||||
pub fn frames_received(&self) -> u32 {
|
||||
self.frames_received.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Set master output mute. When true the output stream emits
|
||||
/// silence regardless of incoming voice frames.
|
||||
pub fn set_output_muted(&self, muted: bool) {
|
||||
self.output_muted.store(muted, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// True if the master output is currently muted locally.
|
||||
pub fn output_muted(&self) -> bool {
|
||||
self.output_muted.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Set master output gain. 1.0 is unity; 0.0 is silent. Values
|
||||
/// above 1.0 amplify (and may clip downstream). Clamped to a
|
||||
/// sensible range internally.
|
||||
pub fn set_output_gain(&self, gain: f32) {
|
||||
let clamped = gain.clamp(0.0, 4.0);
|
||||
self.output_gain
|
||||
.store(clamped.to_bits(), Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Current master output gain.
|
||||
pub fn output_gain(&self) -> f32 {
|
||||
f32::from_bits(self.output_gain.load(Ordering::Relaxed))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for AudioEngine {
|
||||
@@ -533,25 +584,39 @@ fn build_output_stream<T>(
|
||||
device: &cpal::Device,
|
||||
config: &cpal::StreamConfig,
|
||||
handler: Arc<Mutex<AudioHandler<SessionAudioId>>>,
|
||||
output_gain: Arc<AtomicU32>,
|
||||
output_muted: Arc<AtomicBool>,
|
||||
) -> Result<cpal::Stream, AudioError>
|
||||
where
|
||||
T: SizedSample + FromF32 + Send + 'static,
|
||||
{
|
||||
// Reusable f32 scratch buffer. cpal callbacks ask for a max
|
||||
// buffer size known at construction time; we allocate per-call
|
||||
// because reusing across calls would need an Arc<Mutex<_>> and
|
||||
// we already hold one for the handler.
|
||||
let stream = device
|
||||
.build_output_stream(
|
||||
config,
|
||||
move |out: &mut [T], _| {
|
||||
let muted = output_muted.load(Ordering::Relaxed);
|
||||
if muted {
|
||||
// Still call fill_buffer to keep the jitter
|
||||
// buffer draining; just discard the result and
|
||||
// emit silence to the device.
|
||||
let mut scratch = vec![0.0f32; out.len()];
|
||||
{
|
||||
let mut h = handler.lock().unwrap();
|
||||
h.fill_buffer(&mut scratch);
|
||||
}
|
||||
for dst in out.iter_mut() {
|
||||
*dst = T::from_f32_sample(0.0);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let gain = f32::from_bits(output_gain.load(Ordering::Relaxed));
|
||||
let mut scratch = vec![0.0f32; out.len()];
|
||||
{
|
||||
let mut h = handler.lock().unwrap();
|
||||
h.fill_buffer(&mut scratch);
|
||||
}
|
||||
for (dst, src) in out.iter_mut().zip(scratch.into_iter()) {
|
||||
*dst = T::from_f32_sample(src);
|
||||
*dst = T::from_f32_sample(src * gain);
|
||||
}
|
||||
},
|
||||
move |e| {
|
||||
@@ -582,3 +647,55 @@ impl FromF32 for u16 {
|
||||
(s + i32::from(i16::MAX) + 1) as u16
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Android voice-communication routing ----------
|
||||
//
|
||||
// Engages `AudioManager.MODE_IN_COMMUNICATION` on the Android-side
|
||||
// AudioManager. This is the routing-level lever that tells the OS
|
||||
// "this is a voice call, please use the earpiece / engage hardware
|
||||
// AEC / NS / AGC where the device supports it". cpal opens its
|
||||
// input stream at the AAudio default preset; on most Android
|
||||
// devices this honours the global mode and chooses the right
|
||||
// pipeline. Fully wiring `setInputPreset(VOICE_COMMUNICATION)` would
|
||||
// need either a cpal fork or a parallel Oboe input — out of scope
|
||||
// for External Beta.
|
||||
#[cfg(target_os = "android")]
|
||||
fn android_engage_voice_communication() -> Result<(), String> {
|
||||
use jni::objects::{JObject, JString, JValue};
|
||||
let ctx = ndk_context::android_context();
|
||||
let vm_ptr = ctx.vm();
|
||||
if vm_ptr.is_null() {
|
||||
return Err("ndk_context vm is null".to_string());
|
||||
}
|
||||
// SAFETY: ndk_context::android_context guarantees `vm` points at
|
||||
// a live JavaVM* set by our bridge_init JNI hook. The unsafe
|
||||
// block contains only the cast required by `JavaVM::from_raw`.
|
||||
let jvm = unsafe { jni::JavaVM::from_raw(vm_ptr as *mut _) }
|
||||
.map_err(|e| format!("jvm from_raw: {e}"))?;
|
||||
let mut env = jvm
|
||||
.attach_current_thread()
|
||||
.map_err(|e| format!("attach: {e}"))?;
|
||||
|
||||
let context_obj = unsafe { JObject::from_raw(ctx.context() as jni::sys::jobject) };
|
||||
|
||||
let service_name: JString = env
|
||||
.new_string("audio")
|
||||
.map_err(|e| format!("new_string: {e}"))?;
|
||||
let audio_manager = env
|
||||
.call_method(
|
||||
&context_obj,
|
||||
"getSystemService",
|
||||
"(Ljava/lang/String;)Ljava/lang/Object;",
|
||||
&[JValue::Object(&service_name.into())],
|
||||
)
|
||||
.map_err(|e| format!("getSystemService: {e}"))?
|
||||
.l()
|
||||
.map_err(|e| format!("getSystemService obj: {e}"))?;
|
||||
if audio_manager.is_null() {
|
||||
return Err("AudioManager service is null".to_string());
|
||||
}
|
||||
// AudioManager.MODE_IN_COMMUNICATION == 3.
|
||||
env.call_method(&audio_manager, "setMode", "(I)V", &[JValue::Int(3)])
|
||||
.map_err(|e| format!("setMode: {e}"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -51,6 +51,12 @@ fn log_sink() -> &'static chanora_core::InMemoryLogSink {
|
||||
|
||||
// ---------- Bridge lifecycle ----------
|
||||
|
||||
/// Default tracing filter. Suppresses the chatty
|
||||
/// `tsproto::resend` and `tsproto::packet_codec` paths that
|
||||
/// flood the diagnostic export during transient packet loss;
|
||||
/// users can still raise verbosity via `RUST_LOG=info`.
|
||||
const DEFAULT_LOG_FILTER: &str = "info,tsproto::resend=error,tsproto::packet_codec=error";
|
||||
|
||||
/// Initialise the bridge. Must be called once on Dart side before
|
||||
/// any other API call. Sets up panic logging.
|
||||
#[frb(init)]
|
||||
@@ -71,7 +77,7 @@ pub fn bridge_init() {
|
||||
use tracing_subscriber::util::SubscriberInitExt;
|
||||
let android_layer = tracing_android::layer("chanora").ok();
|
||||
let filter = tracing_subscriber::EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info"));
|
||||
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new(DEFAULT_LOG_FILTER));
|
||||
let _ = tracing_subscriber::registry()
|
||||
.with(filter)
|
||||
.with(android_layer)
|
||||
@@ -85,7 +91,7 @@ pub fn bridge_init() {
|
||||
use tracing_subscriber::util::SubscriberInitExt;
|
||||
let fmt_layer = tracing_subscriber::fmt::layer().with_target(true);
|
||||
let filter = tracing_subscriber::EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info"));
|
||||
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new(DEFAULT_LOG_FILTER));
|
||||
let _ = tracing_subscriber::registry()
|
||||
.with(filter)
|
||||
.with(fmt_layer)
|
||||
@@ -176,11 +182,18 @@ impl From<chanora_protocol::ServerSnapshot> for BridgeSnapshot {
|
||||
/// Connect to a TeamSpeak-compatible server and return the initial
|
||||
/// state snapshot. Honours the DEC-006 single-connection invariant
|
||||
/// via [`BridgeError::AlreadyConnected`].
|
||||
pub async fn connect(host: String, nickname: String) -> Result<BridgeSnapshot, BridgeError> {
|
||||
///
|
||||
/// `password` is optional — pass an empty string for servers that
|
||||
/// don't require one.
|
||||
pub async fn connect(
|
||||
host: String,
|
||||
nickname: String,
|
||||
password: String,
|
||||
) -> Result<BridgeSnapshot, BridgeError> {
|
||||
let cfg = chanora_core::ConnectConfig {
|
||||
address: host,
|
||||
nickname,
|
||||
password: None,
|
||||
password: if password.is_empty() { None } else { Some(password) },
|
||||
identity: None,
|
||||
ready_timeout: Duration::from_secs(15),
|
||||
};
|
||||
@@ -242,6 +255,52 @@ pub async fn set_ptt(active: bool) -> Result<(), BridgeError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Move our own client to `channel_id`. Optional channel password
|
||||
/// for password-protected channels — pass an empty string when not
|
||||
/// required.
|
||||
pub async fn move_to_channel(channel_id: u64, password: String) -> Result<(), BridgeError> {
|
||||
let pw = if password.is_empty() { None } else { Some(password) };
|
||||
runtime()
|
||||
.spawn(async move { session().move_to_channel(channel_id, pw).await })
|
||||
.await
|
||||
.map_err(|e| BridgeError::Unmapped(format!("join: {e}")))??;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Toggle self input-mute (microphone) on the server. Independent
|
||||
/// of push-to-talk: a muted client never transmits regardless of
|
||||
/// PTT state.
|
||||
pub async fn set_input_muted(muted: bool) -> Result<(), BridgeError> {
|
||||
runtime()
|
||||
.spawn(async move { session().set_self_muted(Some(muted), None).await })
|
||||
.await
|
||||
.map_err(|e| BridgeError::Unmapped(format!("join: {e}")))??;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Toggle self output-mute (speaker). Mutes locally *and* informs
|
||||
/// the server. The server uses this for the channel icon next to
|
||||
/// the client name; the local mute kicks in immediately even
|
||||
/// before the server acknowledges.
|
||||
pub async fn set_output_muted(muted: bool) -> Result<(), BridgeError> {
|
||||
runtime()
|
||||
.spawn(async move { session().set_self_muted(None, Some(muted)).await })
|
||||
.await
|
||||
.map_err(|e| BridgeError::Unmapped(format!("join: {e}")))??;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Set master output gain. `1.0` is unity, `0.0` is silent. Values
|
||||
/// above `1.0` amplify and can clip downstream. Errors when audio
|
||||
/// is not started.
|
||||
pub async fn set_output_gain(gain: f32) -> Result<(), BridgeError> {
|
||||
runtime()
|
||||
.spawn(async move { session().set_output_gain(gain).await })
|
||||
.await
|
||||
.map_err(|e| BridgeError::Unmapped(format!("join: {e}")))??;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Statistics from the audio engine.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BridgeAudioStats {
|
||||
@@ -294,6 +353,89 @@ pub async fn init_storage(dir: String) -> Result<(), BridgeError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Bookmark DTO mirroring [`chanora_core::Bookmark`].
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BridgeBookmark {
|
||||
/// Row id assigned by SQLite. Use `0` when adding new rows;
|
||||
/// the returned id is then meaningful.
|
||||
pub id: i64,
|
||||
/// User-facing label.
|
||||
pub display_name: String,
|
||||
/// `hostname[:port]` or TSDNS name.
|
||||
pub host: String,
|
||||
/// Nickname to use for this bookmark.
|
||||
pub nickname: String,
|
||||
/// Optional remembered password. Empty string = none.
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
impl From<chanora_core::Bookmark> for BridgeBookmark {
|
||||
fn from(b: chanora_core::Bookmark) -> Self {
|
||||
Self {
|
||||
id: b.id,
|
||||
display_name: b.display_name,
|
||||
host: b.host,
|
||||
nickname: b.nickname,
|
||||
password: b.password.unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<BridgeBookmark> for chanora_core::Bookmark {
|
||||
fn from(b: BridgeBookmark) -> Self {
|
||||
chanora_core::Bookmark {
|
||||
id: b.id,
|
||||
display_name: b.display_name,
|
||||
host: b.host,
|
||||
nickname: b.nickname,
|
||||
password: if b.password.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(b.password)
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// List persisted bookmarks.
|
||||
pub async fn list_bookmarks() -> Result<Vec<BridgeBookmark>, BridgeError> {
|
||||
let v = runtime()
|
||||
.spawn(async { session().list_bookmarks().await })
|
||||
.await
|
||||
.map_err(|e| BridgeError::Unmapped(format!("join: {e}")))??;
|
||||
Ok(v.into_iter().map(Into::into).collect())
|
||||
}
|
||||
|
||||
/// Insert a bookmark and return its assigned id. The `id` field on
|
||||
/// the input is ignored.
|
||||
pub async fn add_bookmark(b: BridgeBookmark) -> Result<i64, BridgeError> {
|
||||
let core_b: chanora_core::Bookmark = b.into();
|
||||
let id = runtime()
|
||||
.spawn(async move { session().add_bookmark(core_b).await })
|
||||
.await
|
||||
.map_err(|e| BridgeError::Unmapped(format!("join: {e}")))??;
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// Update an existing bookmark.
|
||||
pub async fn update_bookmark(b: BridgeBookmark) -> Result<(), BridgeError> {
|
||||
let core_b: chanora_core::Bookmark = b.into();
|
||||
runtime()
|
||||
.spawn(async move { session().update_bookmark(core_b).await })
|
||||
.await
|
||||
.map_err(|e| BridgeError::Unmapped(format!("join: {e}")))??;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Delete a bookmark by id.
|
||||
pub async fn delete_bookmark(id: i64) -> Result<(), BridgeError> {
|
||||
runtime()
|
||||
.spawn(async move { session().delete_bookmark(id).await })
|
||||
.await
|
||||
.map_err(|e| BridgeError::Unmapped(format!("join: {e}")))??;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ---------- Connectivity (A.6.1) ----------
|
||||
|
||||
/// Coarse OS-reported network state. Mirrors
|
||||
|
||||
@@ -38,7 +38,7 @@ flutter_rust_bridge::frb_generated_boilerplate!(
|
||||
default_rust_auto_opaque = RustAutoOpaqueMoi,
|
||||
);
|
||||
pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_VERSION: &str = "2.12.0";
|
||||
pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_CONTENT_HASH: i32 = 2126340080;
|
||||
pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_CONTENT_HASH: i32 = 663465485;
|
||||
|
||||
// Section: executor
|
||||
|
||||
@@ -46,6 +46,42 @@ flutter_rust_bridge::frb_generated_default_handler!();
|
||||
|
||||
// Section: wire_funcs
|
||||
|
||||
fn wire__crate__api__add_bookmark_impl(
|
||||
port_: flutter_rust_bridge::for_generated::MessagePort,
|
||||
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
|
||||
rust_vec_len_: i32,
|
||||
data_len_: i32,
|
||||
) {
|
||||
FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::<flutter_rust_bridge::for_generated::SseCodec, _, _, _>(
|
||||
flutter_rust_bridge::for_generated::TaskInfo {
|
||||
debug_name: "add_bookmark",
|
||||
port: Some(port_),
|
||||
mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal,
|
||||
},
|
||||
move || {
|
||||
let message = unsafe {
|
||||
flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire(
|
||||
ptr_,
|
||||
rust_vec_len_,
|
||||
data_len_,
|
||||
)
|
||||
};
|
||||
let mut deserializer =
|
||||
flutter_rust_bridge::for_generated::SseDeserializer::new(message);
|
||||
let api_b = <crate::api::BridgeBookmark>::sse_decode(&mut deserializer);
|
||||
deserializer.end();
|
||||
move |context| async move {
|
||||
transform_result_sse::<_, crate::BridgeError>(
|
||||
(move || async move {
|
||||
let output_ok = crate::api::add_bookmark(api_b).await?;
|
||||
Ok(output_ok)
|
||||
})()
|
||||
.await,
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
fn wire__crate__api__audio_stats_impl(
|
||||
port_: flutter_rust_bridge::for_generated::MessagePort,
|
||||
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
|
||||
@@ -139,11 +175,49 @@ fn wire__crate__api__connect_impl(
|
||||
flutter_rust_bridge::for_generated::SseDeserializer::new(message);
|
||||
let api_host = <String>::sse_decode(&mut deserializer);
|
||||
let api_nickname = <String>::sse_decode(&mut deserializer);
|
||||
let api_password = <String>::sse_decode(&mut deserializer);
|
||||
deserializer.end();
|
||||
move |context| async move {
|
||||
transform_result_sse::<_, crate::BridgeError>(
|
||||
(move || async move {
|
||||
let output_ok = crate::api::connect(api_host, api_nickname).await?;
|
||||
let output_ok =
|
||||
crate::api::connect(api_host, api_nickname, api_password).await?;
|
||||
Ok(output_ok)
|
||||
})()
|
||||
.await,
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
fn wire__crate__api__delete_bookmark_impl(
|
||||
port_: flutter_rust_bridge::for_generated::MessagePort,
|
||||
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
|
||||
rust_vec_len_: i32,
|
||||
data_len_: i32,
|
||||
) {
|
||||
FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::<flutter_rust_bridge::for_generated::SseCodec, _, _, _>(
|
||||
flutter_rust_bridge::for_generated::TaskInfo {
|
||||
debug_name: "delete_bookmark",
|
||||
port: Some(port_),
|
||||
mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal,
|
||||
},
|
||||
move || {
|
||||
let message = unsafe {
|
||||
flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire(
|
||||
ptr_,
|
||||
rust_vec_len_,
|
||||
data_len_,
|
||||
)
|
||||
};
|
||||
let mut deserializer =
|
||||
flutter_rust_bridge::for_generated::SseDeserializer::new(message);
|
||||
let api_id = <i64>::sse_decode(&mut deserializer);
|
||||
deserializer.end();
|
||||
move |context| async move {
|
||||
transform_result_sse::<_, crate::BridgeError>(
|
||||
(move || async move {
|
||||
let output_ok = crate::api::delete_bookmark(api_id).await?;
|
||||
Ok(output_ok)
|
||||
})()
|
||||
.await,
|
||||
@@ -323,6 +397,115 @@ fn wire__crate__api__is_connected_impl(
|
||||
},
|
||||
)
|
||||
}
|
||||
fn wire__crate__api__list_bookmarks_impl(
|
||||
port_: flutter_rust_bridge::for_generated::MessagePort,
|
||||
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
|
||||
rust_vec_len_: i32,
|
||||
data_len_: i32,
|
||||
) {
|
||||
FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::<flutter_rust_bridge::for_generated::SseCodec, _, _, _>(
|
||||
flutter_rust_bridge::for_generated::TaskInfo {
|
||||
debug_name: "list_bookmarks",
|
||||
port: Some(port_),
|
||||
mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal,
|
||||
},
|
||||
move || {
|
||||
let message = unsafe {
|
||||
flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire(
|
||||
ptr_,
|
||||
rust_vec_len_,
|
||||
data_len_,
|
||||
)
|
||||
};
|
||||
let mut deserializer =
|
||||
flutter_rust_bridge::for_generated::SseDeserializer::new(message);
|
||||
deserializer.end();
|
||||
move |context| async move {
|
||||
transform_result_sse::<_, crate::BridgeError>(
|
||||
(move || async move {
|
||||
let output_ok = crate::api::list_bookmarks().await?;
|
||||
Ok(output_ok)
|
||||
})()
|
||||
.await,
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
fn wire__crate__api__move_to_channel_impl(
|
||||
port_: flutter_rust_bridge::for_generated::MessagePort,
|
||||
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
|
||||
rust_vec_len_: i32,
|
||||
data_len_: i32,
|
||||
) {
|
||||
FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::<flutter_rust_bridge::for_generated::SseCodec, _, _, _>(
|
||||
flutter_rust_bridge::for_generated::TaskInfo {
|
||||
debug_name: "move_to_channel",
|
||||
port: Some(port_),
|
||||
mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal,
|
||||
},
|
||||
move || {
|
||||
let message = unsafe {
|
||||
flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire(
|
||||
ptr_,
|
||||
rust_vec_len_,
|
||||
data_len_,
|
||||
)
|
||||
};
|
||||
let mut deserializer =
|
||||
flutter_rust_bridge::for_generated::SseDeserializer::new(message);
|
||||
let api_channel_id = <u64>::sse_decode(&mut deserializer);
|
||||
let api_password = <String>::sse_decode(&mut deserializer);
|
||||
deserializer.end();
|
||||
move |context| async move {
|
||||
transform_result_sse::<_, crate::BridgeError>(
|
||||
(move || async move {
|
||||
let output_ok =
|
||||
crate::api::move_to_channel(api_channel_id, api_password).await?;
|
||||
Ok(output_ok)
|
||||
})()
|
||||
.await,
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
fn wire__crate__api__set_input_muted_impl(
|
||||
port_: flutter_rust_bridge::for_generated::MessagePort,
|
||||
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
|
||||
rust_vec_len_: i32,
|
||||
data_len_: i32,
|
||||
) {
|
||||
FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::<flutter_rust_bridge::for_generated::SseCodec, _, _, _>(
|
||||
flutter_rust_bridge::for_generated::TaskInfo {
|
||||
debug_name: "set_input_muted",
|
||||
port: Some(port_),
|
||||
mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal,
|
||||
},
|
||||
move || {
|
||||
let message = unsafe {
|
||||
flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire(
|
||||
ptr_,
|
||||
rust_vec_len_,
|
||||
data_len_,
|
||||
)
|
||||
};
|
||||
let mut deserializer =
|
||||
flutter_rust_bridge::for_generated::SseDeserializer::new(message);
|
||||
let api_muted = <bool>::sse_decode(&mut deserializer);
|
||||
deserializer.end();
|
||||
move |context| async move {
|
||||
transform_result_sse::<_, crate::BridgeError>(
|
||||
(move || async move {
|
||||
let output_ok = crate::api::set_input_muted(api_muted).await?;
|
||||
Ok(output_ok)
|
||||
})()
|
||||
.await,
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
fn wire__crate__api__set_network_state_impl(
|
||||
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
|
||||
rust_vec_len_: i32,
|
||||
@@ -355,6 +538,78 @@ fn wire__crate__api__set_network_state_impl(
|
||||
},
|
||||
)
|
||||
}
|
||||
fn wire__crate__api__set_output_gain_impl(
|
||||
port_: flutter_rust_bridge::for_generated::MessagePort,
|
||||
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
|
||||
rust_vec_len_: i32,
|
||||
data_len_: i32,
|
||||
) {
|
||||
FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::<flutter_rust_bridge::for_generated::SseCodec, _, _, _>(
|
||||
flutter_rust_bridge::for_generated::TaskInfo {
|
||||
debug_name: "set_output_gain",
|
||||
port: Some(port_),
|
||||
mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal,
|
||||
},
|
||||
move || {
|
||||
let message = unsafe {
|
||||
flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire(
|
||||
ptr_,
|
||||
rust_vec_len_,
|
||||
data_len_,
|
||||
)
|
||||
};
|
||||
let mut deserializer =
|
||||
flutter_rust_bridge::for_generated::SseDeserializer::new(message);
|
||||
let api_gain = <f32>::sse_decode(&mut deserializer);
|
||||
deserializer.end();
|
||||
move |context| async move {
|
||||
transform_result_sse::<_, crate::BridgeError>(
|
||||
(move || async move {
|
||||
let output_ok = crate::api::set_output_gain(api_gain).await?;
|
||||
Ok(output_ok)
|
||||
})()
|
||||
.await,
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
fn wire__crate__api__set_output_muted_impl(
|
||||
port_: flutter_rust_bridge::for_generated::MessagePort,
|
||||
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
|
||||
rust_vec_len_: i32,
|
||||
data_len_: i32,
|
||||
) {
|
||||
FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::<flutter_rust_bridge::for_generated::SseCodec, _, _, _>(
|
||||
flutter_rust_bridge::for_generated::TaskInfo {
|
||||
debug_name: "set_output_muted",
|
||||
port: Some(port_),
|
||||
mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal,
|
||||
},
|
||||
move || {
|
||||
let message = unsafe {
|
||||
flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire(
|
||||
ptr_,
|
||||
rust_vec_len_,
|
||||
data_len_,
|
||||
)
|
||||
};
|
||||
let mut deserializer =
|
||||
flutter_rust_bridge::for_generated::SseDeserializer::new(message);
|
||||
let api_muted = <bool>::sse_decode(&mut deserializer);
|
||||
deserializer.end();
|
||||
move |context| async move {
|
||||
transform_result_sse::<_, crate::BridgeError>(
|
||||
(move || async move {
|
||||
let output_ok = crate::api::set_output_muted(api_muted).await?;
|
||||
Ok(output_ok)
|
||||
})()
|
||||
.await,
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
fn wire__crate__api__set_ptt_impl(
|
||||
port_: flutter_rust_bridge::for_generated::MessagePort,
|
||||
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
|
||||
@@ -461,6 +716,42 @@ fn wire__crate__api__start_audio_impl(
|
||||
},
|
||||
)
|
||||
}
|
||||
fn wire__crate__api__update_bookmark_impl(
|
||||
port_: flutter_rust_bridge::for_generated::MessagePort,
|
||||
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
|
||||
rust_vec_len_: i32,
|
||||
data_len_: i32,
|
||||
) {
|
||||
FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::<flutter_rust_bridge::for_generated::SseCodec, _, _, _>(
|
||||
flutter_rust_bridge::for_generated::TaskInfo {
|
||||
debug_name: "update_bookmark",
|
||||
port: Some(port_),
|
||||
mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal,
|
||||
},
|
||||
move || {
|
||||
let message = unsafe {
|
||||
flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire(
|
||||
ptr_,
|
||||
rust_vec_len_,
|
||||
data_len_,
|
||||
)
|
||||
};
|
||||
let mut deserializer =
|
||||
flutter_rust_bridge::for_generated::SseDeserializer::new(message);
|
||||
let api_b = <crate::api::BridgeBookmark>::sse_decode(&mut deserializer);
|
||||
deserializer.end();
|
||||
move |context| async move {
|
||||
transform_result_sse::<_, crate::BridgeError>(
|
||||
(move || async move {
|
||||
let output_ok = crate::api::update_bookmark(api_b).await?;
|
||||
Ok(output_ok)
|
||||
})()
|
||||
.await,
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// Section: dart2rust
|
||||
|
||||
@@ -511,6 +802,24 @@ impl SseDecode for crate::api::BridgeAudioStats {
|
||||
}
|
||||
}
|
||||
|
||||
impl SseDecode for crate::api::BridgeBookmark {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {
|
||||
let mut var_id = <i64>::sse_decode(deserializer);
|
||||
let mut var_displayName = <String>::sse_decode(deserializer);
|
||||
let mut var_host = <String>::sse_decode(deserializer);
|
||||
let mut var_nickname = <String>::sse_decode(deserializer);
|
||||
let mut var_password = <String>::sse_decode(deserializer);
|
||||
return crate::api::BridgeBookmark {
|
||||
id: var_id,
|
||||
display_name: var_displayName,
|
||||
host: var_host,
|
||||
nickname: var_nickname,
|
||||
password: var_password,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
impl SseDecode for crate::api::BridgeChannel {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {
|
||||
@@ -660,6 +969,13 @@ impl SseDecode for crate::api::BridgeSnapshot {
|
||||
}
|
||||
}
|
||||
|
||||
impl SseDecode for f32 {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {
|
||||
deserializer.cursor.read_f32::<NativeEndian>().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl SseDecode for i32 {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {
|
||||
@@ -674,6 +990,18 @@ impl SseDecode for i64 {
|
||||
}
|
||||
}
|
||||
|
||||
impl SseDecode for Vec<crate::api::BridgeBookmark> {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {
|
||||
let mut len_ = <i32>::sse_decode(deserializer);
|
||||
let mut ans_ = Vec::with_capacity(len_ as usize);
|
||||
for idx_ in 0..len_ {
|
||||
ans_.push(<crate::api::BridgeBookmark>::sse_decode(deserializer));
|
||||
}
|
||||
return ans_;
|
||||
}
|
||||
}
|
||||
|
||||
impl SseDecode for Vec<crate::api::BridgeChannel> {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {
|
||||
@@ -745,16 +1073,24 @@ fn pde_ffi_dispatcher_primary_impl(
|
||||
) {
|
||||
// Codec=Pde (Serialization + dispatch), see doc to use other codecs
|
||||
match func_id {
|
||||
1 => wire__crate__api__audio_stats_impl(port, ptr, rust_vec_len, data_len),
|
||||
2 => wire__crate__api__bridge_init_impl(port, ptr, rust_vec_len, data_len),
|
||||
3 => wire__crate__api__connect_impl(port, ptr, rust_vec_len, data_len),
|
||||
4 => wire__crate__api__disconnect_impl(port, ptr, rust_vec_len, data_len),
|
||||
5 => wire__crate__api__events_stream_impl(port, ptr, rust_vec_len, data_len),
|
||||
7 => wire__crate__api__init_storage_impl(port, ptr, rust_vec_len, data_len),
|
||||
8 => wire__crate__api__is_connected_impl(port, ptr, rust_vec_len, data_len),
|
||||
10 => wire__crate__api__set_ptt_impl(port, ptr, rust_vec_len, data_len),
|
||||
11 => wire__crate__api__snapshot_impl(port, ptr, rust_vec_len, data_len),
|
||||
12 => wire__crate__api__start_audio_impl(port, ptr, rust_vec_len, data_len),
|
||||
1 => wire__crate__api__add_bookmark_impl(port, ptr, rust_vec_len, data_len),
|
||||
2 => wire__crate__api__audio_stats_impl(port, ptr, rust_vec_len, data_len),
|
||||
3 => wire__crate__api__bridge_init_impl(port, ptr, rust_vec_len, data_len),
|
||||
4 => wire__crate__api__connect_impl(port, ptr, rust_vec_len, data_len),
|
||||
5 => wire__crate__api__delete_bookmark_impl(port, ptr, rust_vec_len, data_len),
|
||||
6 => wire__crate__api__disconnect_impl(port, ptr, rust_vec_len, data_len),
|
||||
7 => wire__crate__api__events_stream_impl(port, ptr, rust_vec_len, data_len),
|
||||
9 => wire__crate__api__init_storage_impl(port, ptr, rust_vec_len, data_len),
|
||||
10 => wire__crate__api__is_connected_impl(port, ptr, rust_vec_len, data_len),
|
||||
11 => wire__crate__api__list_bookmarks_impl(port, ptr, rust_vec_len, data_len),
|
||||
12 => wire__crate__api__move_to_channel_impl(port, ptr, rust_vec_len, data_len),
|
||||
13 => wire__crate__api__set_input_muted_impl(port, ptr, rust_vec_len, data_len),
|
||||
15 => wire__crate__api__set_output_gain_impl(port, ptr, rust_vec_len, data_len),
|
||||
16 => wire__crate__api__set_output_muted_impl(port, ptr, rust_vec_len, data_len),
|
||||
17 => wire__crate__api__set_ptt_impl(port, ptr, rust_vec_len, data_len),
|
||||
18 => wire__crate__api__snapshot_impl(port, ptr, rust_vec_len, data_len),
|
||||
19 => wire__crate__api__start_audio_impl(port, ptr, rust_vec_len, data_len),
|
||||
20 => wire__crate__api__update_bookmark_impl(port, ptr, rust_vec_len, data_len),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
@@ -767,8 +1103,8 @@ fn pde_ffi_dispatcher_sync_impl(
|
||||
) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse {
|
||||
// Codec=Pde (Serialization + dispatch), see doc to use other codecs
|
||||
match func_id {
|
||||
6 => wire__crate__api__export_diagnostics_impl(ptr, rust_vec_len, data_len),
|
||||
9 => wire__crate__api__set_network_state_impl(ptr, rust_vec_len, data_len),
|
||||
8 => wire__crate__api__export_diagnostics_impl(ptr, rust_vec_len, data_len),
|
||||
14 => wire__crate__api__set_network_state_impl(ptr, rust_vec_len, data_len),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
@@ -795,6 +1131,25 @@ impl flutter_rust_bridge::IntoIntoDart<crate::api::BridgeAudioStats>
|
||||
}
|
||||
}
|
||||
// Codec=Dco (DartCObject based), see doc to use other codecs
|
||||
impl flutter_rust_bridge::IntoDart for crate::api::BridgeBookmark {
|
||||
fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi {
|
||||
[
|
||||
self.id.into_into_dart().into_dart(),
|
||||
self.display_name.into_into_dart().into_dart(),
|
||||
self.host.into_into_dart().into_dart(),
|
||||
self.nickname.into_into_dart().into_dart(),
|
||||
self.password.into_into_dart().into_dart(),
|
||||
]
|
||||
.into_dart()
|
||||
}
|
||||
}
|
||||
impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::api::BridgeBookmark {}
|
||||
impl flutter_rust_bridge::IntoIntoDart<crate::api::BridgeBookmark> for crate::api::BridgeBookmark {
|
||||
fn into_into_dart(self) -> crate::api::BridgeBookmark {
|
||||
self
|
||||
}
|
||||
}
|
||||
// Codec=Dco (DartCObject based), see doc to use other codecs
|
||||
impl flutter_rust_bridge::IntoDart for crate::api::BridgeChannel {
|
||||
fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi {
|
||||
[
|
||||
@@ -986,6 +1341,17 @@ impl SseEncode for crate::api::BridgeAudioStats {
|
||||
}
|
||||
}
|
||||
|
||||
impl SseEncode for crate::api::BridgeBookmark {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {
|
||||
<i64>::sse_encode(self.id, serializer);
|
||||
<String>::sse_encode(self.display_name, serializer);
|
||||
<String>::sse_encode(self.host, serializer);
|
||||
<String>::sse_encode(self.nickname, serializer);
|
||||
<String>::sse_encode(self.password, serializer);
|
||||
}
|
||||
}
|
||||
|
||||
impl SseEncode for crate::api::BridgeChannel {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {
|
||||
@@ -1110,6 +1476,13 @@ impl SseEncode for crate::api::BridgeSnapshot {
|
||||
}
|
||||
}
|
||||
|
||||
impl SseEncode for f32 {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {
|
||||
serializer.cursor.write_f32::<NativeEndian>(self).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
impl SseEncode for i32 {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {
|
||||
@@ -1124,6 +1497,16 @@ impl SseEncode for i64 {
|
||||
}
|
||||
}
|
||||
|
||||
impl SseEncode for Vec<crate::api::BridgeBookmark> {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {
|
||||
<i32>::sse_encode(self.len() as _, serializer);
|
||||
for item in self {
|
||||
<crate::api::BridgeBookmark>::sse_encode(item, serializer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SseEncode for Vec<crate::api::BridgeChannel> {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {
|
||||
|
||||
@@ -24,6 +24,7 @@ use tokio::sync::{mpsc, oneshot};
|
||||
use tracing::{info, warn};
|
||||
|
||||
use tsclientlib::data::{self, Channel, Client};
|
||||
use tsclientlib::prelude::*;
|
||||
use tsclientlib::{
|
||||
ChannelId as TsChannelId, Connection, DisconnectOptions, Identity, OutCommandExt, StreamItem,
|
||||
};
|
||||
@@ -66,6 +67,18 @@ impl Default for ConnectConfig {
|
||||
enum Request {
|
||||
Snapshot(oneshot::Sender<Result<ServerSnapshot, ProtocolError>>),
|
||||
Disconnect(oneshot::Sender<()>),
|
||||
/// Move self to a channel. Optional channel password.
|
||||
MoveToChannel {
|
||||
channel_id: u64,
|
||||
password: Option<String>,
|
||||
reply: oneshot::Sender<Result<(), ProtocolError>>,
|
||||
},
|
||||
/// Update own client mute state (input and/or output).
|
||||
SetMuted {
|
||||
input: Option<bool>,
|
||||
output: Option<bool>,
|
||||
reply: oneshot::Sender<Result<(), ProtocolError>>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Why a [`ProtocolClient`] task ended. Distinguishes a user-driven
|
||||
@@ -201,6 +214,46 @@ impl ProtocolClient {
|
||||
}
|
||||
}
|
||||
|
||||
/// Move our own client into a channel. `password` is optional
|
||||
/// for password-protected channels.
|
||||
pub async fn move_to_channel(
|
||||
&self,
|
||||
channel_id: u64,
|
||||
password: Option<String>,
|
||||
) -> Result<(), ProtocolError> {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
self.tx
|
||||
.send(Request::MoveToChannel {
|
||||
channel_id,
|
||||
password,
|
||||
reply: tx,
|
||||
})
|
||||
.await
|
||||
.map_err(|_| ProtocolError::Lost("connection task is gone".to_string()))?;
|
||||
rx.await
|
||||
.map_err(|_| ProtocolError::Lost("move_to_channel reply dropped".to_string()))?
|
||||
}
|
||||
|
||||
/// Update mute state on our own client. Pass `Some(_)` for the
|
||||
/// fields you want to change, `None` to leave a field as-is.
|
||||
pub async fn set_muted(
|
||||
&self,
|
||||
input: Option<bool>,
|
||||
output: Option<bool>,
|
||||
) -> Result<(), ProtocolError> {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
self.tx
|
||||
.send(Request::SetMuted {
|
||||
input,
|
||||
output,
|
||||
reply: tx,
|
||||
})
|
||||
.await
|
||||
.map_err(|_| ProtocolError::Lost("connection task is gone".to_string()))?;
|
||||
rx.await
|
||||
.map_err(|_| ProtocolError::Lost("set_muted reply dropped".to_string()))?
|
||||
}
|
||||
|
||||
/// Sender for outbound voice packets. Clone freely.
|
||||
pub fn voice_out(&self) -> mpsc::Sender<OutPacket> {
|
||||
self.voice_out_tx.clone()
|
||||
@@ -406,6 +459,14 @@ async fn connection_task(
|
||||
let snap = build_snapshot(&con);
|
||||
let _ = reply.send(snap);
|
||||
}
|
||||
Ok(Request::MoveToChannel { channel_id, password, reply }) => {
|
||||
let r = move_self_to(&mut con, channel_id, password.as_deref());
|
||||
let _ = reply.send(r);
|
||||
}
|
||||
Ok(Request::SetMuted { input, output, reply }) => {
|
||||
let r = set_self_muted(&mut con, input, output);
|
||||
let _ = reply.send(r);
|
||||
}
|
||||
Ok(Request::Disconnect(reply)) => {
|
||||
let _ = con.disconnect(DisconnectOptions::new());
|
||||
con.events().for_each(|_| future::ready(())).await;
|
||||
@@ -424,6 +485,62 @@ async fn connection_task(
|
||||
}
|
||||
}
|
||||
|
||||
/// Move our own client into `channel_id` with an optional password.
|
||||
/// Looks up our `own_client` in the current state and dispatches the
|
||||
/// generated `client_move` command via the `OutCommandExt` trait.
|
||||
fn move_self_to(
|
||||
con: &mut Connection,
|
||||
channel_id: u64,
|
||||
password: Option<&str>,
|
||||
) -> Result<(), ProtocolError> {
|
||||
let state = con
|
||||
.get_state()
|
||||
.map_err(|e| ProtocolError::Backend(format!("get_state: {e}")))?;
|
||||
let own_id = state.own_client;
|
||||
let own_client = state
|
||||
.clients
|
||||
.get(&own_id)
|
||||
.ok_or_else(|| ProtocolError::Backend("own_client not in state".to_string()))?;
|
||||
let target = TsChannelId(channel_id);
|
||||
let mut part = own_client.client_move(target);
|
||||
if let Some(pw) = password {
|
||||
part = part.set_password(pw);
|
||||
}
|
||||
part.send(con)
|
||||
.map_err(|e| ProtocolError::Backend(format!("client_move send: {e}")))?;
|
||||
info!(target: "chanora_protocol", channel_id, "client_move sent");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Send a `clientupdate` with the requested mute fields set. `None`
|
||||
/// fields are omitted so callers can toggle just one flag.
|
||||
fn set_self_muted(
|
||||
con: &mut Connection,
|
||||
input: Option<bool>,
|
||||
output: Option<bool>,
|
||||
) -> Result<(), ProtocolError> {
|
||||
if input.is_none() && output.is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
let part = {
|
||||
let state = con
|
||||
.get_state()
|
||||
.map_err(|e| ProtocolError::Backend(format!("get_state: {e}")))?;
|
||||
let mut p = state.client_update();
|
||||
if let Some(v) = input {
|
||||
p = p.set_input_muted(v);
|
||||
}
|
||||
if let Some(v) = output {
|
||||
p = p.set_output_muted(v);
|
||||
}
|
||||
p
|
||||
};
|
||||
part.send(con)
|
||||
.map_err(|e| ProtocolError::Backend(format!("client_update send: {e}")))?;
|
||||
info!(target: "chanora_protocol", ?input, ?output, "client_update sent");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Extract the originating `client_id` from an inbound voice packet.
|
||||
fn packet_sender_id(buf: &InAudioBuf) -> Option<u64> {
|
||||
use tsproto_packets::packets::AudioData;
|
||||
|
||||
@@ -12,3 +12,7 @@ publish.workspace = true
|
||||
[dependencies]
|
||||
thiserror.workspace = true
|
||||
tracing.workspace = true
|
||||
rusqlite = { version = "0.32", features = ["bundled"] }
|
||||
chacha20poly1305 = "0.10"
|
||||
rand = "0.8"
|
||||
zeroize = "1"
|
||||
|
||||
@@ -43,9 +43,15 @@
|
||||
use std::fs;
|
||||
use std::io::{Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
|
||||
use chacha20poly1305::aead::{Aead, KeyInit, OsRng};
|
||||
use chacha20poly1305::{ChaCha20Poly1305, Key, Nonce};
|
||||
use rand::RngCore;
|
||||
use rusqlite::{params, Connection};
|
||||
use thiserror::Error;
|
||||
use tracing::{info, warn};
|
||||
use zeroize::Zeroize;
|
||||
|
||||
/// Errors raised by either storage repository.
|
||||
#[derive(Debug, Error)]
|
||||
@@ -65,6 +71,11 @@ pub enum StorageError {
|
||||
/// Filesystem I/O error (Beta file-fallback store).
|
||||
#[error("io: {0}")]
|
||||
Io(String),
|
||||
/// Cryptographic operation failed (key generation, encrypt, or
|
||||
/// decrypt). Typically indicates a corrupted DEK or tampered
|
||||
/// identity file.
|
||||
#[error("crypto: {0}")]
|
||||
Crypto(String),
|
||||
}
|
||||
|
||||
/// Marker trait for the non-secret database side. Concrete impl will
|
||||
@@ -77,74 +88,175 @@ pub trait LocalDatabaseRepository: Send + Sync {}
|
||||
/// promoted from the secure-storage PoC.
|
||||
pub trait SecretStorageRepository: Send + Sync {}
|
||||
|
||||
/// Beta identity store: a single file containing the base64 TS3
|
||||
/// identity string. The directory is created on first use; on Unix
|
||||
/// the file is written with mode 0600 so other local users can't
|
||||
/// read it. **Not** encrypted at rest — that is the v0.4 task.
|
||||
/// Beta identity store: a single ChaCha20-Poly1305-encrypted file
|
||||
/// containing the base64 TS3 identity string. The Data Encryption
|
||||
/// Key (DEK) is 32 random bytes stored alongside in a separate
|
||||
/// `identity.dek` file with the same 0600 permissions on Unix.
|
||||
///
|
||||
/// The dual-file layout means an attacker who recovers either file
|
||||
/// alone can't decrypt the identity. The honest threat model:
|
||||
///
|
||||
/// * **Helps against** stale backups, casual filesystem snooping
|
||||
/// that grabs one file but not the other, and accidental leaks
|
||||
/// to diagnostic exports (the ciphertext is never logged).
|
||||
/// * **Does NOT help against** a full app-private storage dump (an
|
||||
/// attacker who can read one file in the directory can read both).
|
||||
/// The v0.4 storage rework lands proper OS-keyring backing for the
|
||||
/// DEK so this two-file weakness is closed.
|
||||
///
|
||||
/// File format: `identity.tskey` = `[12-byte nonce][AEAD ciphertext+tag]`.
|
||||
/// Legacy plaintext files written by v0.3 are still readable; the
|
||||
/// next `save()` upgrades them to encrypted form (and shreds the
|
||||
/// plaintext temp file via the atomic rename).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct IdentityFileStore {
|
||||
path: PathBuf,
|
||||
dek_path: PathBuf,
|
||||
}
|
||||
|
||||
impl IdentityFileStore {
|
||||
/// Construct a store rooted at `dir`. The directory is created
|
||||
/// recursively if it does not already exist.
|
||||
/// Construct a store rooted at `dir`. Creates the directory and
|
||||
/// the DEK on first use; subsequent uses reuse the existing DEK.
|
||||
pub fn new(dir: impl AsRef<Path>) -> Result<Self, StorageError> {
|
||||
let dir = dir.as_ref();
|
||||
fs::create_dir_all(dir).map_err(|e| StorageError::Io(format!("mkdir {dir:?}: {e}")))?;
|
||||
Ok(Self {
|
||||
let store = Self {
|
||||
path: dir.join("identity.tskey"),
|
||||
})
|
||||
dek_path: dir.join("identity.dek"),
|
||||
};
|
||||
// Ensure a DEK exists. Subsequent operations expect it.
|
||||
store.ensure_dek()?;
|
||||
Ok(store)
|
||||
}
|
||||
|
||||
/// Path to the underlying file. Exposed for diagnostics.
|
||||
/// Path to the underlying identity file. Exposed for diagnostics.
|
||||
pub fn path(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
|
||||
/// Read the persisted identity, if any. Returns `Ok(None)` when
|
||||
/// no identity has been saved yet — that is not an error.
|
||||
fn ensure_dek(&self) -> Result<(), StorageError> {
|
||||
if self.dek_path.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut key = [0u8; 32];
|
||||
OsRng.fill_bytes(&mut key);
|
||||
{
|
||||
let mut f = open_private(&self.dek_path)?;
|
||||
f.write_all(&key)
|
||||
.map_err(|e| StorageError::Io(format!("write dek: {e}")))?;
|
||||
f.sync_all()
|
||||
.map_err(|e| StorageError::Io(format!("sync dek: {e}")))?;
|
||||
}
|
||||
key.zeroize();
|
||||
info!(target: "chanora_storage", path = ?self.dek_path, "DEK generated");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load_dek(&self) -> Result<[u8; 32], StorageError> {
|
||||
let mut f = fs::File::open(&self.dek_path)
|
||||
.map_err(|e| StorageError::Io(format!("open dek {:?}: {e}", self.dek_path)))?;
|
||||
let mut key = [0u8; 32];
|
||||
f.read_exact(&mut key)
|
||||
.map_err(|e| StorageError::Io(format!("read dek: {e}")))?;
|
||||
Ok(key)
|
||||
}
|
||||
|
||||
/// Read the persisted identity, if any. Transparently handles
|
||||
/// the legacy plaintext format (pre-External Beta).
|
||||
pub fn load(&self) -> Result<Option<String>, StorageError> {
|
||||
match fs::File::open(&self.path) {
|
||||
Ok(mut f) => {
|
||||
let mut buf = String::new();
|
||||
f.read_to_string(&mut buf)
|
||||
.map_err(|e| StorageError::Io(format!("read {:?}: {e}", self.path)))?;
|
||||
let trimmed = buf.trim().to_string();
|
||||
if trimmed.is_empty() {
|
||||
Ok(None)
|
||||
} else {
|
||||
Ok(Some(trimmed))
|
||||
}
|
||||
let mut f = match fs::File::open(&self.path) {
|
||||
Ok(f) => f,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(e) => return Err(StorageError::Io(format!("open {:?}: {e}", self.path))),
|
||||
};
|
||||
let mut buf = Vec::new();
|
||||
f.read_to_end(&mut buf)
|
||||
.map_err(|e| StorageError::Io(format!("read {:?}: {e}", self.path)))?;
|
||||
if buf.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
// Encrypted format: at least nonce (12) + tag (16) = 28
|
||||
// bytes, and the first byte should not be a printable ASCII
|
||||
// base64 character. Heuristic: a legacy plaintext file
|
||||
// starts with an ASCII digit (counter prefix) or an ASCII
|
||||
// letter (raw base64 key). If the first byte is non-ASCII
|
||||
// or non-printable, treat as ciphertext.
|
||||
if buf.len() >= 28 && !is_plausibly_legacy_plaintext(&buf) {
|
||||
let mut key_bytes = self.load_dek()?;
|
||||
let key = Key::from_slice(&key_bytes);
|
||||
let cipher = ChaCha20Poly1305::new(key);
|
||||
let nonce_bytes = &buf[..12];
|
||||
let nonce = Nonce::from_slice(nonce_bytes);
|
||||
let pt = cipher
|
||||
.decrypt(nonce, &buf[12..])
|
||||
.map_err(|e| {
|
||||
key_bytes.zeroize();
|
||||
StorageError::Crypto(format!("decrypt: {e}"))
|
||||
})?;
|
||||
key_bytes.zeroize();
|
||||
let s = String::from_utf8(pt)
|
||||
.map_err(|e| StorageError::Crypto(format!("plaintext not utf8: {e}")))?;
|
||||
let trimmed = s.trim().to_string();
|
||||
if trimmed.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
|
||||
Err(e) => Err(StorageError::Io(format!("open {:?}: {e}", self.path))),
|
||||
return Ok(Some(trimmed));
|
||||
}
|
||||
|
||||
// Legacy plaintext path. We do NOT auto-upgrade here —
|
||||
// upgrade happens on the next save() to keep load()
|
||||
// side-effect-free.
|
||||
warn!(
|
||||
target: "chanora_storage",
|
||||
"identity file is in legacy plaintext format; will encrypt on next save"
|
||||
);
|
||||
let s = String::from_utf8(buf)
|
||||
.map_err(|e| StorageError::Io(format!("legacy not utf8: {e}")))?;
|
||||
let trimmed = s.trim().to_string();
|
||||
if trimmed.is_empty() {
|
||||
Ok(None)
|
||||
} else {
|
||||
Ok(Some(trimmed))
|
||||
}
|
||||
}
|
||||
|
||||
/// Persist `identity` to disk, replacing any previous content.
|
||||
/// On Unix the file is written with mode 0600.
|
||||
/// On Unix the file is written with mode 0600. Encrypted with
|
||||
/// ChaCha20-Poly1305 using the per-install DEK.
|
||||
pub fn save(&self, identity: &str) -> Result<(), StorageError> {
|
||||
// Write atomically: temp file + rename. Avoids leaving a
|
||||
// half-written identity on the device after a crash or
|
||||
// power loss.
|
||||
let plaintext = identity.trim().as_bytes();
|
||||
let mut key_bytes = self.load_dek()?;
|
||||
let key = Key::from_slice(&key_bytes);
|
||||
let cipher = ChaCha20Poly1305::new(key);
|
||||
let mut nonce_bytes = [0u8; 12];
|
||||
OsRng.fill_bytes(&mut nonce_bytes);
|
||||
let nonce = Nonce::from_slice(&nonce_bytes);
|
||||
let ct = cipher.encrypt(nonce, plaintext).map_err(|e| {
|
||||
key_bytes.zeroize();
|
||||
StorageError::Crypto(format!("encrypt: {e}"))
|
||||
})?;
|
||||
key_bytes.zeroize();
|
||||
|
||||
// Atomic write: temp file + rename.
|
||||
let tmp = self.path.with_extension("tskey.tmp");
|
||||
{
|
||||
let mut f = open_private(&tmp)?;
|
||||
f.write_all(identity.trim().as_bytes())
|
||||
.map_err(|e| StorageError::Io(format!("write {tmp:?}: {e}")))?;
|
||||
f.write_all(b"\n")
|
||||
.map_err(|e| StorageError::Io(format!("write nl: {e}")))?;
|
||||
f.write_all(&nonce_bytes)
|
||||
.map_err(|e| StorageError::Io(format!("write nonce: {e}")))?;
|
||||
f.write_all(&ct)
|
||||
.map_err(|e| StorageError::Io(format!("write ct: {e}")))?;
|
||||
f.sync_all()
|
||||
.map_err(|e| StorageError::Io(format!("sync {tmp:?}: {e}")))?;
|
||||
}
|
||||
fs::rename(&tmp, &self.path)
|
||||
.map_err(|e| StorageError::Io(format!("rename {tmp:?} -> {:?}: {e}", self.path)))?;
|
||||
info!(target: "chanora_storage", path = ?self.path, "identity persisted");
|
||||
info!(target: "chanora_storage", path = ?self.path, "identity persisted (encrypted)");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Remove any persisted identity. No-op if none exists.
|
||||
/// Remove any persisted identity. No-op if none exists. Leaves
|
||||
/// the DEK in place so future saves don't generate a new one.
|
||||
pub fn clear(&self) -> Result<(), StorageError> {
|
||||
match fs::remove_file(&self.path) {
|
||||
Ok(()) => {
|
||||
@@ -160,6 +272,31 @@ impl IdentityFileStore {
|
||||
}
|
||||
}
|
||||
|
||||
/// True if `buf` looks like a legacy plaintext identity (printable
|
||||
/// ASCII with a digit/letter first byte and at most a trailing
|
||||
/// newline). False for ciphertext.
|
||||
fn is_plausibly_legacy_plaintext(buf: &[u8]) -> bool {
|
||||
if buf.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let first = buf[0];
|
||||
if !(first.is_ascii_alphanumeric() || first == b'+' || first == b'/') {
|
||||
return false;
|
||||
}
|
||||
// The TS3 identity format is base64 + a counter prefix; all
|
||||
// bytes are printable ASCII. The ciphertext is uniformly random.
|
||||
buf.iter().all(|&b| {
|
||||
b.is_ascii_alphanumeric()
|
||||
|| b == b'+'
|
||||
|| b == b'/'
|
||||
|| b == b'='
|
||||
|| b == b'V'
|
||||
|| b == b'\n'
|
||||
|| b == b'\r'
|
||||
|| b == b' '
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn open_private(p: &Path) -> Result<fs::File, StorageError> {
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
@@ -186,6 +323,140 @@ fn open_private(p: &Path) -> Result<fs::File, StorageError> {
|
||||
.map_err(|e| StorageError::Io(format!("open {p:?}: {e}")))
|
||||
}
|
||||
|
||||
/// A persisted bookmark: a friendly label paired with a TS3 server
|
||||
/// address and the nickname the user wants when connecting.
|
||||
///
|
||||
/// Bookmark rows are uniquely identified by an auto-incrementing
|
||||
/// `id`. The `display_name` is purely cosmetic. `host` is the same
|
||||
/// string the user would type into the connect form.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Bookmark {
|
||||
/// Stable row id assigned by SQLite.
|
||||
pub id: i64,
|
||||
/// User-facing label.
|
||||
pub display_name: String,
|
||||
/// `hostname[:port]` or TSDNS name.
|
||||
pub host: String,
|
||||
/// Nickname to use for this bookmark.
|
||||
pub nickname: String,
|
||||
/// Optional remembered server password. Stored as plain text in
|
||||
/// the SQLite file (Beta gap, RISK-PoC-002). v0.4 will lift
|
||||
/// passwords into the keyring.
|
||||
pub password: Option<String>,
|
||||
}
|
||||
|
||||
/// SQLite-backed bookmark store. The DB file lives at
|
||||
/// `<storage_dir>/chanora.db`. The schema is migrated on
|
||||
/// construction; failures here abort the constructor rather than
|
||||
/// poisoning later calls.
|
||||
pub struct BookmarkRepository {
|
||||
conn: Mutex<Connection>,
|
||||
}
|
||||
|
||||
impl BookmarkRepository {
|
||||
/// Open or create the bookmark database under `dir`.
|
||||
pub fn new(dir: impl AsRef<Path>) -> Result<Self, StorageError> {
|
||||
let dir = dir.as_ref();
|
||||
fs::create_dir_all(dir).map_err(|e| StorageError::Io(format!("mkdir {dir:?}: {e}")))?;
|
||||
let path = dir.join("chanora.db");
|
||||
let conn = Connection::open(&path)
|
||||
.map_err(|e| StorageError::Sqlite(format!("open {path:?}: {e}")))?;
|
||||
conn.pragma_update(None, "foreign_keys", "ON")
|
||||
.map_err(|e| StorageError::Sqlite(format!("pragma: {e}")))?;
|
||||
conn.execute_batch(
|
||||
"CREATE TABLE IF NOT EXISTS bookmarks (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
display_name TEXT NOT NULL,
|
||||
host TEXT NOT NULL,
|
||||
nickname TEXT NOT NULL,
|
||||
password TEXT
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS schema_version (
|
||||
v INTEGER PRIMARY KEY
|
||||
);
|
||||
INSERT OR IGNORE INTO schema_version(v) VALUES (1);",
|
||||
)
|
||||
.map_err(|e| StorageError::Migration(format!("init schema: {e}")))?;
|
||||
info!(target: "chanora_storage", path = ?path, "bookmark db opened");
|
||||
Ok(Self { conn: Mutex::new(conn) })
|
||||
}
|
||||
|
||||
/// Insert a new bookmark and return its assigned id. The `id`
|
||||
/// field on the input is ignored.
|
||||
pub fn add(&self, b: &Bookmark) -> Result<i64, StorageError> {
|
||||
let conn = self
|
||||
.conn
|
||||
.lock()
|
||||
.map_err(|_| StorageError::Sqlite("poisoned lock".to_string()))?;
|
||||
conn.execute(
|
||||
"INSERT INTO bookmarks (display_name, host, nickname, password) VALUES (?1, ?2, ?3, ?4)",
|
||||
params![b.display_name, b.host, b.nickname, b.password],
|
||||
)
|
||||
.map_err(|e| StorageError::Sqlite(format!("insert: {e}")))?;
|
||||
Ok(conn.last_insert_rowid())
|
||||
}
|
||||
|
||||
/// Replace an existing bookmark identified by `id`. Errors with
|
||||
/// [`StorageError::NotFound`] if no such row exists.
|
||||
pub fn update(&self, b: &Bookmark) -> Result<(), StorageError> {
|
||||
let conn = self
|
||||
.conn
|
||||
.lock()
|
||||
.map_err(|_| StorageError::Sqlite("poisoned lock".to_string()))?;
|
||||
let n = conn
|
||||
.execute(
|
||||
"UPDATE bookmarks SET display_name=?1, host=?2, nickname=?3, password=?4 WHERE id=?5",
|
||||
params![b.display_name, b.host, b.nickname, b.password, b.id],
|
||||
)
|
||||
.map_err(|e| StorageError::Sqlite(format!("update: {e}")))?;
|
||||
if n == 0 {
|
||||
Err(StorageError::NotFound)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete a bookmark by id. No-op if it doesn't exist.
|
||||
pub fn delete(&self, id: i64) -> Result<(), StorageError> {
|
||||
let conn = self
|
||||
.conn
|
||||
.lock()
|
||||
.map_err(|_| StorageError::Sqlite("poisoned lock".to_string()))?;
|
||||
conn.execute("DELETE FROM bookmarks WHERE id = ?1", params![id])
|
||||
.map_err(|e| StorageError::Sqlite(format!("delete: {e}")))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// List all bookmarks ordered by id (insertion order).
|
||||
pub fn list(&self) -> Result<Vec<Bookmark>, StorageError> {
|
||||
let conn = self
|
||||
.conn
|
||||
.lock()
|
||||
.map_err(|_| StorageError::Sqlite("poisoned lock".to_string()))?;
|
||||
let mut stmt = conn
|
||||
.prepare(
|
||||
"SELECT id, display_name, host, nickname, password FROM bookmarks ORDER BY id",
|
||||
)
|
||||
.map_err(|e| StorageError::Sqlite(format!("prepare: {e}")))?;
|
||||
let rows = stmt
|
||||
.query_map([], |row| {
|
||||
Ok(Bookmark {
|
||||
id: row.get(0)?,
|
||||
display_name: row.get(1)?,
|
||||
host: row.get(2)?,
|
||||
nickname: row.get(3)?,
|
||||
password: row.get(4)?,
|
||||
})
|
||||
})
|
||||
.map_err(|e| StorageError::Sqlite(format!("query: {e}")))?;
|
||||
let mut out = Vec::new();
|
||||
for r in rows {
|
||||
out.push(r.map_err(|e| StorageError::Sqlite(format!("row: {e}")))?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -220,6 +491,96 @@ mod tests {
|
||||
assert_eq!(mode, 0o600, "expected 0600, got {mode:o}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bookmark_round_trip() {
|
||||
let tmp = tempdir();
|
||||
let repo = BookmarkRepository::new(&tmp).unwrap();
|
||||
assert!(repo.list().unwrap().is_empty());
|
||||
let id = repo
|
||||
.add(&Bookmark {
|
||||
id: 0,
|
||||
display_name: "home".to_string(),
|
||||
host: "cn.teamspeak.app".to_string(),
|
||||
nickname: "u".to_string(),
|
||||
password: None,
|
||||
})
|
||||
.unwrap();
|
||||
assert!(id > 0);
|
||||
let rows = repo.list().unwrap();
|
||||
assert_eq!(rows.len(), 1);
|
||||
assert_eq!(rows[0].display_name, "home");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bookmark_update_and_delete() {
|
||||
let tmp = tempdir();
|
||||
let repo = BookmarkRepository::new(&tmp).unwrap();
|
||||
let id = repo
|
||||
.add(&Bookmark {
|
||||
id: 0,
|
||||
display_name: "a".to_string(),
|
||||
host: "h".to_string(),
|
||||
nickname: "n".to_string(),
|
||||
password: Some("pw".to_string()),
|
||||
})
|
||||
.unwrap();
|
||||
repo.update(&Bookmark {
|
||||
id,
|
||||
display_name: "b".to_string(),
|
||||
host: "h2".to_string(),
|
||||
nickname: "n2".to_string(),
|
||||
password: None,
|
||||
})
|
||||
.unwrap();
|
||||
let rows = repo.list().unwrap();
|
||||
assert_eq!(rows[0].display_name, "b");
|
||||
assert_eq!(rows[0].password, None);
|
||||
repo.delete(id).unwrap();
|
||||
assert!(repo.list().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bookmark_update_missing_is_notfound() {
|
||||
let tmp = tempdir();
|
||||
let repo = BookmarkRepository::new(&tmp).unwrap();
|
||||
let r = repo.update(&Bookmark {
|
||||
id: 999,
|
||||
display_name: "x".to_string(),
|
||||
host: "h".to_string(),
|
||||
nickname: "n".to_string(),
|
||||
password: None,
|
||||
});
|
||||
assert!(matches!(r, Err(StorageError::NotFound)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encrypted_round_trip() {
|
||||
let tmp = tempdir();
|
||||
let store = IdentityFileStore::new(&tmp).unwrap();
|
||||
store.save("3456V/abcdef==").unwrap();
|
||||
// The bytes on disk are not the plaintext.
|
||||
let raw = fs::read(store.path()).unwrap();
|
||||
assert!(!raw.windows(6).any(|w| w == b"abcdef"));
|
||||
// load() returns the original.
|
||||
assert_eq!(store.load().unwrap().as_deref(), Some("3456V/abcdef=="));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_plaintext_is_read_and_upgraded() {
|
||||
let tmp = tempdir();
|
||||
// Pre-Beta on-disk format: raw base64 with counter prefix.
|
||||
let path = tmp.join("identity.tskey");
|
||||
fs::write(&path, b"9999VabcdefghIJKLmnop=\n").unwrap();
|
||||
let store = IdentityFileStore::new(&tmp).unwrap();
|
||||
let v = store.load().unwrap();
|
||||
assert_eq!(v.as_deref(), Some("9999VabcdefghIJKLmnop="));
|
||||
// Save round-trips through encrypted format.
|
||||
store.save("9999VabcdefghIJKLmnop=").unwrap();
|
||||
let raw = fs::read(store.path()).unwrap();
|
||||
assert!(!raw.starts_with(b"9999"));
|
||||
assert_eq!(store.load().unwrap().as_deref(), Some("9999VabcdefghIJKLmnop="));
|
||||
}
|
||||
|
||||
fn tempdir() -> PathBuf {
|
||||
let p = std::env::temp_dir()
|
||||
.join("chanora_storage_test")
|
||||
|
||||
Reference in New Issue
Block a user