Unpair every device from one button, over a collection DELETE per plane #213
+97
-1
@@ -10,7 +10,7 @@
|
||||
"name": "MIT OR Apache-2.0",
|
||||
"identifier": "MIT OR Apache-2.0"
|
||||
},
|
||||
"version": "0.27.0"
|
||||
"version": "0.28.0"
|
||||
},
|
||||
"paths": {
|
||||
"/api/v1/clients": {
|
||||
@@ -45,6 +45,36 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"delete": {
|
||||
"tags": [
|
||||
"clients"
|
||||
],
|
||||
"summary": "Unpair every client",
|
||||
"description": "The collection form of [`unpair_client`]: empties the pairing store in ONE persisted write,\ncarrying the same revocation guarantees across the whole set. A LIVE GameStream session is\nended (its owning certificate is necessarily one of those just removed), and the ENet control\nport (UDP 47999) closes, because no pairing is left to hold it open.\n\nIdempotent, and so a 200 rather than the single unpair's 204/404 pair: \"unpair everything\" is\nsatisfied by an already-empty store, and the operator still wants to know whether that meant\nthree devices or none.",
|
||||
"operationId": "unpairAllClients",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Every client unpaired (possibly none)",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/UnpairAllResult"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Missing or invalid bearer token",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ApiError"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/clients/{fingerprint}": {
|
||||
@@ -1767,6 +1797,56 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"delete": {
|
||||
"tags": [
|
||||
"native"
|
||||
],
|
||||
"summary": "Unpair every native client",
|
||||
"description": "The collection form of [`unpair_native_client`]: empties the punktfunk/1 trust store in ONE\npersisted write (not a loop of them — a failure partway would leave a half-emptied store), and\nends every live native session the removed clients own.\n\nIdempotent, hence a 200 rather than the single unpair's 204/404: an already-empty store\nsatisfies the request, and the count still tells the operator what it meant.",
|
||||
"operationId": "unpairAllNativeClients",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Every native client unpaired (possibly none)",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/UnpairAllResult"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Missing or invalid bearer token",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ApiError"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Could not persist the trust store",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ApiError"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"503": {
|
||||
"description": "Native host not enabled",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ApiError"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/native/clients/{fingerprint}": {
|
||||
@@ -7687,6 +7767,22 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"UnpairAllResult": {
|
||||
"type": "object",
|
||||
"description": "What a bulk unpair removed. Shared by the two collection DELETEs (`/clients` and\n`/native/clients`) so the console sees one schema across both pairing planes.\n\nA count rather than 204: \"unpair everything\" is idempotent, so an empty store is a success, and\nthe operator still wants to be told whether that meant three devices or none.",
|
||||
"required": [
|
||||
"unpaired"
|
||||
],
|
||||
"properties": {
|
||||
"unpaired": {
|
||||
"type": "integer",
|
||||
"format": "int32",
|
||||
"description": "Clients removed from the trust store — 0 when nothing was paired.",
|
||||
"example": 3,
|
||||
"minimum": 0
|
||||
}
|
||||
}
|
||||
},
|
||||
"UpdateJobInfo": {
|
||||
"type": "object",
|
||||
"description": "A running apply job (or a spawned installer that hasn't resolved yet).",
|
||||
|
||||
@@ -214,7 +214,12 @@ fn api_router_parts() -> (Router<Arc<MgmtState>>, utoipa::openapi::OpenApi) {
|
||||
))
|
||||
.routes(routes!(host::get_status))
|
||||
.routes(routes!(host::get_local_summary))
|
||||
.routes(routes!(clients::list_paired_clients))
|
||||
// GET and DELETE share the `/clients` path, so they must be ONE `routes!` — utoipa-axum
|
||||
// merges the methods of a single call into one route; two calls collide on the path.
|
||||
.routes(routes!(
|
||||
clients::list_paired_clients,
|
||||
clients::unpair_all_clients
|
||||
))
|
||||
.routes(routes!(clients::unpair_client));
|
||||
// The GameStream PIN flow exists only when the compat planes do (WP19) — a native-only
|
||||
// build's API (and its OpenAPI document) simply has no such endpoints.
|
||||
@@ -226,7 +231,11 @@ fn api_router_parts() -> (Router<Arc<MgmtState>>, utoipa::openapi::OpenApi) {
|
||||
.routes(routes!(native::get_native_pairing))
|
||||
.routes(routes!(native::arm_native_pairing))
|
||||
.routes(routes!(native::disarm_native_pairing))
|
||||
.routes(routes!(native::list_native_clients))
|
||||
// Same-path pair as `/clients` above — one `routes!` for both methods.
|
||||
.routes(routes!(
|
||||
native::list_native_clients,
|
||||
native::unpair_all_native_clients
|
||||
))
|
||||
.routes(routes!(native::unpair_native_client))
|
||||
.routes(routes!(native::list_pending_devices))
|
||||
.routes(routes!(native::approve_pending_device))
|
||||
|
||||
@@ -153,6 +153,62 @@ pub(crate) async fn unpair_client(
|
||||
}
|
||||
}
|
||||
|
||||
/// Unpair every client
|
||||
///
|
||||
/// The collection form of [`unpair_client`]: empties the pairing store in ONE persisted write,
|
||||
/// carrying the same revocation guarantees across the whole set. A LIVE GameStream session is
|
||||
/// ended (its owning certificate is necessarily one of those just removed), and the ENet control
|
||||
/// port (UDP 47999) closes, because no pairing is left to hold it open.
|
||||
///
|
||||
/// Idempotent, and so a 200 rather than the single unpair's 204/404 pair: "unpair everything" is
|
||||
/// satisfied by an already-empty store, and the operator still wants to know whether that meant
|
||||
/// three devices or none.
|
||||
#[utoipa::path(
|
||||
delete,
|
||||
path = "/clients",
|
||||
tag = "clients",
|
||||
operation_id = "unpairAllClients",
|
||||
responses(
|
||||
(status = OK, description = "Every client unpaired (possibly none)", body = UnpairAllResult),
|
||||
(status = UNAUTHORIZED, description = "Missing or invalid bearer token", body = ApiError),
|
||||
)
|
||||
)]
|
||||
pub(crate) async fn unpair_all_clients(State(st): State<Arc<MgmtState>>) -> Response {
|
||||
let mut paired = st.app.paired.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if paired.is_empty() {
|
||||
// Nothing to persist, no port to sync — an empty store is already the requested state.
|
||||
return Json(UnpairAllResult { unpaired: 0 }).into_response();
|
||||
}
|
||||
let removed: Vec<[u8; 32]> = paired
|
||||
.iter()
|
||||
.map(|der| Sha256::digest(der).into())
|
||||
.collect();
|
||||
paired.clear();
|
||||
// Persist under the lock, as the single unpair does: a pairing resurrected by a restart would
|
||||
// silently re-open the control port.
|
||||
crate::gamestream::save_paired(&paired);
|
||||
drop(paired);
|
||||
// A mid-stream client must not keep streaming once its pairing is gone. Clearing the launch
|
||||
// makes the ENet control thread send the standard TERMINATION+disconnect. (An owner-less
|
||||
// launch — the cert was unreadable at /launch — cannot be attributed, and is left to the port
|
||||
// teardown below, which here always fires: no pairing remains.)
|
||||
let live_owner = st
|
||||
.app
|
||||
.launch
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.and_then(|l| l.owner_fp);
|
||||
if live_owner.is_some_and(|fp| removed.contains(&fp)) {
|
||||
st.app.quit_session("client unpaired");
|
||||
}
|
||||
if let Err(e) = crate::gamestream::sync_control(&st.app) {
|
||||
tracing::warn!(error = %format!("{e:#}"), "control port sync after unpair-all failed");
|
||||
}
|
||||
let unpaired = removed.len() as u32;
|
||||
tracing::info!(unpaired, "management API: all clients unpaired");
|
||||
Json(UnpairAllResult { unpaired }).into_response()
|
||||
}
|
||||
|
||||
/// Pairing-flow status
|
||||
///
|
||||
/// Poll this to know when to prompt the user for the PIN Moonlight displays.
|
||||
|
||||
@@ -256,6 +256,52 @@ pub(crate) async fn unpair_native_client(
|
||||
}
|
||||
}
|
||||
|
||||
/// Unpair every native client
|
||||
///
|
||||
/// The collection form of [`unpair_native_client`]: empties the punktfunk/1 trust store in ONE
|
||||
/// persisted write (not a loop of them — a failure partway would leave a half-emptied store), and
|
||||
/// ends every live native session the removed clients own.
|
||||
///
|
||||
/// Idempotent, hence a 200 rather than the single unpair's 204/404: an already-empty store
|
||||
/// satisfies the request, and the count still tells the operator what it meant.
|
||||
#[utoipa::path(
|
||||
delete,
|
||||
path = "/native/clients",
|
||||
tag = "native",
|
||||
operation_id = "unpairAllNativeClients",
|
||||
responses(
|
||||
(status = OK, description = "Every native client unpaired (possibly none)", body = UnpairAllResult),
|
||||
(status = SERVICE_UNAVAILABLE, description = "Native host not enabled", body = ApiError),
|
||||
(status = UNAUTHORIZED, description = "Missing or invalid bearer token", body = ApiError),
|
||||
(status = INTERNAL_SERVER_ERROR, description = "Could not persist the trust store", body = ApiError),
|
||||
)
|
||||
)]
|
||||
pub(crate) async fn unpair_all_native_clients(State(st): State<Arc<MgmtState>>) -> Response {
|
||||
let Some(np) = &st.native else {
|
||||
return api_error(StatusCode::SERVICE_UNAVAILABLE, "native host not enabled");
|
||||
};
|
||||
match np.remove_all() {
|
||||
Ok(removed) => {
|
||||
// Revocation reaches LIVE sessions too — the same guarantee the single unpair gives,
|
||||
// applied across the set.
|
||||
let stopped: usize = removed
|
||||
.iter()
|
||||
.map(|fp| crate::session_status::stop_by_fingerprint(&fp.to_ascii_lowercase()))
|
||||
.sum();
|
||||
if stopped > 0 {
|
||||
tracing::info!(stopped, "unpair-all: live native session(s) stopped");
|
||||
}
|
||||
let unpaired = removed.len() as u32;
|
||||
tracing::info!(unpaired, "management API: all native clients unpaired");
|
||||
Json(UnpairAllResult { unpaired }).into_response()
|
||||
}
|
||||
Err(e) => api_error(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
&format!("could not persist trust store: {e}"),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// List devices awaiting pairing approval
|
||||
///
|
||||
/// Unpaired devices that tried to connect while the host requires pairing. Approve one to pair
|
||||
|
||||
@@ -21,6 +21,18 @@ pub(crate) struct ApiError {
|
||||
error: String,
|
||||
}
|
||||
|
||||
/// What a bulk unpair removed. Shared by the two collection DELETEs (`/clients` and
|
||||
/// `/native/clients`) so the console sees one schema across both pairing planes.
|
||||
///
|
||||
/// A count rather than 204: "unpair everything" is idempotent, so an empty store is a success, and
|
||||
/// the operator still wants to be told whether that meant three devices or none.
|
||||
#[derive(Serialize, ToSchema)]
|
||||
pub(crate) struct UnpairAllResult {
|
||||
/// Clients removed from the trust store — 0 when nothing was paired.
|
||||
#[schema(example = 3)]
|
||||
pub(crate) unpaired: u32,
|
||||
}
|
||||
|
||||
pub(crate) fn api_error(status: StatusCode, message: &str) -> Response {
|
||||
(
|
||||
status,
|
||||
|
||||
@@ -819,7 +819,8 @@ async fn paired_clients_list_and_unpair() {
|
||||
{
|
||||
let mut p = state.paired.lock().unwrap();
|
||||
p.clear();
|
||||
p.push(der);
|
||||
// Cloned, not moved: the unpair-all section at the end of this test re-seeds it.
|
||||
p.push(der.clone());
|
||||
}
|
||||
|
||||
let (status, body) = send(&app, get_req("/api/v1/clients")).await;
|
||||
@@ -888,6 +889,71 @@ async fn paired_clients_list_and_unpair() {
|
||||
serde_json::from_slice::<Vec<Vec<u8>>>(&disk).unwrap(),
|
||||
Vec::<Vec<u8>>::new()
|
||||
);
|
||||
|
||||
// ---- the COLLECTION delete: unpair everything at once -----------------------------------
|
||||
//
|
||||
// Re-seed two clients (the store was just emptied) and clear the teardown flags, so what the
|
||||
// bulk delete does to a live session is attributable to IT and not left over from above.
|
||||
let second = crate::identity::ephemeral().unwrap();
|
||||
let (_, second_pem) = x509_parser::pem::parse_x509_pem(second.cert_pem.as_bytes()).unwrap();
|
||||
let second_der = second_pem.contents.clone();
|
||||
let second_fp = hex::encode(Sha256::digest(&second_der));
|
||||
{
|
||||
use std::sync::atomic::Ordering;
|
||||
let mut p = state.paired.lock().unwrap();
|
||||
p.clear();
|
||||
p.push(der.clone());
|
||||
p.push(second_der);
|
||||
state.quit.store(false, Ordering::SeqCst);
|
||||
state.streaming.store(true, Ordering::SeqCst);
|
||||
// A live session owned by the SECOND client — the bulk delete must end whichever of the
|
||||
// removed certs owns it, not just the first one it happens to walk past.
|
||||
let mut owner = [0u8; 32];
|
||||
owner.copy_from_slice(&hex::decode(&second_fp).unwrap());
|
||||
*state.launch.lock().unwrap() = Some(LaunchSession {
|
||||
gcm_key: [0; 16],
|
||||
rikeyid: 0,
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
fps: 60,
|
||||
appid: 1,
|
||||
peer_ip: None,
|
||||
owner_fp: Some(owner),
|
||||
});
|
||||
}
|
||||
|
||||
let del_all = || {
|
||||
axum::http::Request::delete("/api/v1/clients")
|
||||
.body(Body::empty())
|
||||
.unwrap()
|
||||
};
|
||||
let (status, body) = send(&app, del_all()).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(body["unpaired"], 2, "both clients must be reported removed");
|
||||
|
||||
let (_, body) = send(&app, get_req("/api/v1/clients")).await;
|
||||
assert_eq!(body, serde_json::json!([]));
|
||||
{
|
||||
use std::sync::atomic::Ordering;
|
||||
assert!(
|
||||
state.launch.lock().unwrap().is_none(),
|
||||
"unpair-all must end the live session of any client it revokes"
|
||||
);
|
||||
assert!(state.quit.load(Ordering::SeqCst));
|
||||
}
|
||||
// Persisted, for the same reason the single unpair is: a resurrected pairing would re-open
|
||||
// the control port on the next boot.
|
||||
let disk = std::fs::read(tmp.path().join("paired.json")).unwrap();
|
||||
assert_eq!(
|
||||
serde_json::from_slice::<Vec<Vec<u8>>>(&disk).unwrap(),
|
||||
Vec::<Vec<u8>>::new()
|
||||
);
|
||||
|
||||
// Idempotent: emptying an empty store is a 200 with a zero count, NOT the single delete's 404.
|
||||
// ("unpair everything" is already satisfied — there is no missing resource to report.)
|
||||
let (status, body) = send(&app, del_all()).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(body["unpaired"], 0);
|
||||
}
|
||||
|
||||
#[cfg(feature = "gamestream")]
|
||||
@@ -1248,8 +1314,13 @@ fn every_route_is_classified_for_the_plugin_and_cert_lanes() {
|
||||
// ---- paired-device rosters: readable by a plugin, never by another paired client, and
|
||||
// removal is pairing administration in both lanes.
|
||||
("GET", "/api/v1/clients", true, false),
|
||||
// The bulk form is the same authority as the single one — and, sharing its path with a
|
||||
// plugin-readable GET, worth an explicit row: both gates match on (method, path), so the
|
||||
// roster's read permission must never carry over to emptying it.
|
||||
("DELETE", "/api/v1/clients", false, false),
|
||||
("DELETE", "/api/v1/clients/{fingerprint}", false, false),
|
||||
("GET", "/api/v1/native/clients", true, false),
|
||||
("DELETE", "/api/v1/native/clients", false, false),
|
||||
(
|
||||
"DELETE",
|
||||
"/api/v1/native/clients/{fingerprint}",
|
||||
@@ -1667,6 +1738,56 @@ async fn native_pairing_arm_show_and_unpair() {
|
||||
assert_eq!(b["armed"], false);
|
||||
}
|
||||
|
||||
/// The collection delete on the native plane: one call empties the trust store, and repeating it
|
||||
/// is a zero-count success rather than an error.
|
||||
#[tokio::test]
|
||||
async fn native_unpair_all_empties_the_trust_store() {
|
||||
let np = Arc::new(
|
||||
crate::native_pairing::NativePairing::load_with(
|
||||
Some(std::env::temp_dir().join(format!("pf-mgmt-np-all-{}.json", std::process::id()))),
|
||||
None,
|
||||
false,
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
let app = test_app_native(test_state(), np.clone());
|
||||
|
||||
np.add("Living room TV", "aa11").unwrap();
|
||||
np.add("Studio Deck", "bb22").unwrap();
|
||||
assert_eq!(np.list().len(), 2);
|
||||
|
||||
let del_all = || {
|
||||
axum::http::Request::delete("/api/v1/native/clients")
|
||||
.body(Body::empty())
|
||||
.unwrap()
|
||||
};
|
||||
let (status, body) = send(&app, del_all()).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(body["unpaired"], 2);
|
||||
|
||||
// Gone from both the API and the store behind it (one persisted write, not two).
|
||||
let (_, body) = send(&app, get_req("/api/v1/native/clients")).await;
|
||||
assert_eq!(body, serde_json::json!([]));
|
||||
assert!(np.list().is_empty());
|
||||
assert!(!np.is_paired("aa11") && !np.is_paired("bb22"));
|
||||
|
||||
// Idempotent — unlike the single delete, which 404s on a fingerprint it cannot find.
|
||||
let (status, body) = send(&app, del_all()).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(body["unpaired"], 0);
|
||||
}
|
||||
|
||||
/// Without a native plane there is no trust store to empty — 503, matching every other
|
||||
/// `/native/*` route (and NOT a silent 200 that would tell the console it had unpaired something).
|
||||
#[tokio::test]
|
||||
async fn native_unpair_all_without_a_native_host_is_unavailable() {
|
||||
let app = test_app(test_state(), None);
|
||||
let req = axum::http::Request::delete("/api/v1/native/clients")
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
assert_eq!(send(&app, req).await.0, StatusCode::SERVICE_UNAVAILABLE);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pending_devices_approve_and_deny() {
|
||||
let np = Arc::new(
|
||||
|
||||
@@ -159,6 +159,12 @@ impl NativePairing {
|
||||
self.store.remove(fp_hex)
|
||||
}
|
||||
|
||||
/// Remove EVERY paired client in one persisted write. Returns the fingerprints removed, so the
|
||||
/// caller can end the sessions they own. On a persist failure nothing is removed.
|
||||
pub fn remove_all(&self) -> Result<Vec<String>> {
|
||||
self.store.remove_all()
|
||||
}
|
||||
|
||||
// -- Delegated approval (roadmap §8b-1) ---------------------------------
|
||||
|
||||
/// Record an unpaired device's knock for delegated approval. Re-knocks from the same fingerprint
|
||||
|
||||
@@ -130,6 +130,28 @@ impl TrustStore {
|
||||
Ok(removed)
|
||||
}
|
||||
|
||||
/// Remove EVERY paired client, in ONE persisted write. Returns the fingerprints removed, so
|
||||
/// the caller can tear down the live sessions they own. On a persist failure the in-memory
|
||||
/// store is rolled back (it never diverges from disk), exactly like [`Self::remove`].
|
||||
///
|
||||
/// Not a loop over [`Self::remove`]: that would rewrite (and fsync-rename) the store once per
|
||||
/// client, and a failure partway would leave the operator with a half-emptied trust store and
|
||||
/// no way to tell which half.
|
||||
pub(super) fn remove_all(&self) -> Result<Vec<String>> {
|
||||
let mut p = self.paired.lock().unwrap();
|
||||
if p.clients.clients.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
// `take` leaves the empty list in place to be persisted, and hands us the snapshot that
|
||||
// doubles as both the rollback value and the removed-fingerprint report.
|
||||
let snapshot = std::mem::take(&mut p.clients.clients);
|
||||
if let Err(e) = save(&p) {
|
||||
p.clients.clients = snapshot;
|
||||
return Err(e);
|
||||
}
|
||||
Ok(snapshot.into_iter().map(|c| c.fingerprint).collect())
|
||||
}
|
||||
|
||||
/// The number of paired clients (for the status snapshot).
|
||||
pub(super) fn count(&self) -> u32 {
|
||||
self.paired.lock().unwrap().clients.clients.len() as u32
|
||||
|
||||
@@ -118,6 +118,7 @@
|
||||
"action_stop_session": "Sitzung beenden",
|
||||
"action_request_idr": "Keyframe anfordern",
|
||||
"action_unpair": "Entkoppeln",
|
||||
"action_unpair_all": "Alle entkoppeln",
|
||||
"connect_title": "Gerät verbinden",
|
||||
"connect_help": "Gib die Adresse in einem Punktfunk-Client ein — oder öffne den Link auf einem Gerät, auf dem bereits einer installiert ist: er führt direkt zu diesem Host. Gekoppelt wird auf der Seite „Kopplung“.",
|
||||
"connect_address": "Host-Adresse",
|
||||
@@ -263,6 +264,9 @@
|
||||
"pairing_native_empty": "Noch keine Geräte gekoppelt.",
|
||||
"pairing_native_unpair_confirm": "Dieses Gerät entkoppeln?",
|
||||
"pairing_native_unpair_body": "Es muss sich erneut koppeln, um zu verbinden.",
|
||||
"pairing_native_unpair_all_confirm": "Alle {count} Geräte entkoppeln?",
|
||||
"pairing_native_unpair_all_body": "Jedes gekoppelte Gerät — punktfunk/1 wie Moonlight — muss sich erneut koppeln, um zu verbinden; was gerade streamt, wird getrennt.",
|
||||
"pairing_native_unpair_all_failed": "Einige Geräte konnten nicht entkoppelt werden.",
|
||||
"pairing_protocol": "Protokoll",
|
||||
"pairing_protocol_native": "punktfunk/1",
|
||||
"pairing_protocol_moonlight": "Moonlight",
|
||||
|
||||
@@ -118,6 +118,7 @@
|
||||
"action_stop_session": "Stop session",
|
||||
"action_request_idr": "Request keyframe",
|
||||
"action_unpair": "Unpair",
|
||||
"action_unpair_all": "Unpair all",
|
||||
"connect_title": "Connect a device",
|
||||
"connect_help": "Type the address into a punktfunk client, or open the link on a device that already has one installed — it opens straight onto this host. Pair from the Pairing page.",
|
||||
"connect_address": "Host address",
|
||||
@@ -263,6 +264,9 @@
|
||||
"pairing_native_empty": "No devices paired yet.",
|
||||
"pairing_native_unpair_confirm": "Unpair this device?",
|
||||
"pairing_native_unpair_body": "It will need to pair again to connect.",
|
||||
"pairing_native_unpair_all_confirm": "Unpair all {count} devices?",
|
||||
"pairing_native_unpair_all_body": "Every paired device — punktfunk/1 and Moonlight alike — will need to pair again to connect, and anything streaming right now is disconnected.",
|
||||
"pairing_native_unpair_all_failed": "Some devices could not be unpaired.",
|
||||
"pairing_protocol": "Protocol",
|
||||
"pairing_protocol_native": "punktfunk/1",
|
||||
"pairing_protocol_moonlight": "Moonlight",
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { toast } from "@unom/ui/toast";
|
||||
import { Trash2 } from "lucide-react";
|
||||
import type { FC } from "react";
|
||||
import {
|
||||
getListPairedClientsQueryKey,
|
||||
useListPairedClients,
|
||||
useUnpairAllClients,
|
||||
useUnpairClient,
|
||||
} from "@/api/gen/clients/clients";
|
||||
import {
|
||||
getListNativeClientsQueryKey,
|
||||
useListNativeClients,
|
||||
useUnpairAllNativeClients,
|
||||
useUnpairNativeClient,
|
||||
} from "@/api/gen/native/native";
|
||||
import { useDialogs } from "@/components/dialogs";
|
||||
@@ -49,6 +52,8 @@ export const PairedDevicesSection: FC = () => {
|
||||
const moonlight = useListPairedClients();
|
||||
const unpairNative = useUnpairNativeClient();
|
||||
const unpairMoonlight = useUnpairClient();
|
||||
const unpairAllNative = useUnpairAllNativeClients();
|
||||
const unpairAllMoonlight = useUnpairAllClients();
|
||||
|
||||
const rows: PairedRow[] = [
|
||||
...(native.data ?? []).map(
|
||||
@@ -94,6 +99,39 @@ export const PairedDevicesSection: FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Unpair EVERY device, in one confirmation.
|
||||
*
|
||||
* Two calls, not one per device: each plane owns a separate trust store behind its own
|
||||
* collection DELETE, and each of those empties its store in a single persisted write host-side.
|
||||
* Only the planes actually holding a row are called — the native endpoint answers 503 on a host
|
||||
* built without it, which would otherwise report a failure for devices that were never there.
|
||||
*/
|
||||
const onUnpairAll = async () => {
|
||||
const ok = await confirm({
|
||||
title: m.pairing_native_unpair_all_confirm({ count: rows.length }),
|
||||
description: m.pairing_native_unpair_all_body(),
|
||||
confirmLabel: m.action_unpair_all(),
|
||||
destructive: true,
|
||||
});
|
||||
if (!ok) return;
|
||||
const calls: Promise<unknown>[] = [];
|
||||
if (rows.some((r) => r.protocol === "native")) {
|
||||
calls.push(unpairAllNative.mutateAsync());
|
||||
}
|
||||
if (rows.some((r) => r.protocol === "moonlight")) {
|
||||
calls.push(unpairAllMoonlight.mutateAsync());
|
||||
}
|
||||
// allSettled, not all: the two planes are independent, so one failing must neither cancel
|
||||
// the other nor throw past this handler.
|
||||
const settled = await Promise.allSettled(calls);
|
||||
qc.invalidateQueries({ queryKey: getListNativeClientsQueryKey() });
|
||||
qc.invalidateQueries({ queryKey: getListPairedClientsQueryKey() });
|
||||
if (settled.some((r) => r.status === "rejected")) {
|
||||
toast.error(m.pairing_native_unpair_all_failed());
|
||||
}
|
||||
};
|
||||
|
||||
// The fingerprint of the row whose unpair is in flight (if any) — so only THAT row's button
|
||||
// disables, not every row's.
|
||||
const pendingFingerprint =
|
||||
@@ -105,6 +143,11 @@ export const PairedDevicesSection: FC = () => {
|
||||
: undefined) ??
|
||||
null;
|
||||
|
||||
// Derived, not state: the two bulk calls are launched together and awaited together, so their
|
||||
// pending flags cover the whole run without a gap in the middle to flicker through.
|
||||
const isUnpairingAll =
|
||||
unpairAllNative.isPending || unpairAllMoonlight.isPending;
|
||||
|
||||
return (
|
||||
<PairedDevices
|
||||
rows={rows}
|
||||
@@ -115,7 +158,9 @@ export const PairedDevicesSection: FC = () => {
|
||||
moonlight.refetch();
|
||||
}}
|
||||
onUnpair={onUnpair}
|
||||
onUnpairAll={onUnpairAll}
|
||||
pendingFingerprint={pendingFingerprint}
|
||||
isUnpairingAll={isUnpairingAll}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -127,12 +172,39 @@ export const PairedDevices: FC<{
|
||||
error: unknown;
|
||||
refetch: () => void;
|
||||
onUnpair: (protocol: PairedProtocol, fingerprint: string) => void;
|
||||
/** Unpair every row, behind one confirmation. */
|
||||
onUnpairAll: () => void;
|
||||
/** Fingerprint of the row whose unpair is in flight, or null — only that row disables. */
|
||||
pendingFingerprint: string | null;
|
||||
}> = ({ rows, isLoading, error, refetch, onUnpair, pendingFingerprint }) => (
|
||||
/** A bulk unpair is walking the list — every control in the card disables until it finishes. */
|
||||
isUnpairingAll: boolean;
|
||||
}> = ({
|
||||
rows,
|
||||
isLoading,
|
||||
error,
|
||||
refetch,
|
||||
onUnpair,
|
||||
onUnpairAll,
|
||||
pendingFingerprint,
|
||||
isUnpairingAll,
|
||||
}) => (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
{/* flex-row: CardHeader stacks by default, and this one carries a trailing action. */}
|
||||
<CardHeader className="flex-row items-center justify-between gap-4 space-y-0">
|
||||
<h2 className="text-lg font-medium">{m.pairing_native_devices()}</h2>
|
||||
{/* Nothing to unpair in bulk when the list is empty (or still loading) — an enabled
|
||||
button there would open a confirmation reading "Unpair all 0 devices?". */}
|
||||
{rows.length > 0 && (
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
disabled={isUnpairingAll}
|
||||
onClick={onUnpairAll}
|
||||
>
|
||||
<Trash2 className="size-4" />
|
||||
{m.action_unpair_all()}
|
||||
</Button>
|
||||
)}
|
||||
</CardHeader>
|
||||
|
||||
<CardContent>
|
||||
@@ -172,7 +244,9 @@ export const PairedDevices: FC<{
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
aria-label={m.action_unpair()}
|
||||
disabled={pendingFingerprint === r.fingerprint}
|
||||
disabled={
|
||||
isUnpairingAll || pendingFingerprint === r.fingerprint
|
||||
}
|
||||
onClick={() => onUnpair(r.protocol, r.fingerprint)}
|
||||
>
|
||||
<Trash2 className="size-4 text-destructive" />
|
||||
|
||||
@@ -77,7 +77,9 @@ export const Armed: Story = {
|
||||
error={null}
|
||||
refetch={noop}
|
||||
onUnpair={noop}
|
||||
onUnpairAll={noop}
|
||||
pendingFingerprint={null}
|
||||
isUnpairingAll={false}
|
||||
/>
|
||||
),
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user