From c751e85d2c72af0d19b016e5879358b53b56b852 Mon Sep 17 00:00:00 2001 From: Onyx Date: Fri, 20 Nov 2026 19:01:23 +0100 Subject: [PATCH] feat(native-hid): detect VIA keyboards through keyboard-protocol's registry Bridge only loaded @openmouse/protocol's registry, so keyboards that only keyboard-protocol knows (VIA included) were never described or driven. - registry: also load keyboard-protocol's drivers and filters, after the mouse ones so existing matches do not change - hid: HidFilter.vendor_id is optional, so VIA's vendor-less 0xFF60:0x61 filter parses instead of dropping Bridge back to its vendor-id list - hid: the list command takes an optional `usages` list and lists devices with a matching collection. Only vendor-defined usage pages (0xFF00 and up) are honoured, checked in Bridge rather than trusted from the page, so standard keyboards, mice and security keys stay hidden, and only the matching collection of the device is listed - adapter: keep byte 0 of a reply from a path that declares only unnumbered input, and put `device` on input events as WebHID does --- native-hid/src/hid-device-adapter.mjs | 16 ++-- native-hid/src/registry.mjs | 14 +++- native-hid/src/registry.test.mjs | 30 +++++++ src/hid.rs | 111 +++++++++++++++++++++++--- 4 files changed, 152 insertions(+), 19 deletions(-) diff --git a/native-hid/src/hid-device-adapter.mjs b/native-hid/src/hid-device-adapter.mjs index 2d822538..3f0a2726 100644 --- a/native-hid/src/hid-device-adapter.mjs +++ b/native-hid/src/hid-device-adapter.mjs @@ -221,16 +221,17 @@ export class HidDeviceAdapter { } /** @param {Buffer} data */ - _onData(data) { + _onData(data, unnumbered = false) { // Some backends prefix numbered reports with the report id on read, // some don't (mirrors the same ambiguity the Rust Pulsar driver // handles) — there is no fully reliable way to tell from the bytes // alone, so report id 0 is assumed when in doubt; drivers here match // responses by their own payload content, not strictly by report id. - const reportId = data.length > 0 ? data[0] : 0; - const payload = data.length > 0 ? data.subarray(1) : data; + const withId = !unnumbered && data.length > 0; + const reportId = withId ? data[0] : 0; + const payload = withId ? data.subarray(1) : data; const view = new DataView(Uint8Array.from(payload).buffer); - const event = { reportId, data: view }; + const event = { device: this, reportId, data: view }; for (const listener of this._listeners) listener(event); } @@ -296,6 +297,11 @@ function declaresReports(path) { return ["inputReports", "outputReports", "featureReports"].some((kind) => Object.keys(path[kind] ?? {}).length > 0); } +function declaresOnlyUnnumberedInput(path) { + const ids = Object.keys(path.inputReports ?? {}); + return ids.length === 1 && ids[0] === "0"; +} + /** A collection only the operating system may read: a standard mouse or * keyboard (see candidateDevices()). */ function isStandardOnly(path) { @@ -363,7 +369,7 @@ export class DescribedDeviceAdapter extends HidDeviceAdapter { // collection) Windows fails every read, and node-hid gives up on the // handle, taking the feature reports down with it. if (!declaresReports(path) || Object.keys(path.inputReports ?? {}).length > 0) { - device.on("data", this._onData); + device.on("data", declaresOnlyUnnumberedInput(path) ? (data) => this._onData(data, true) : this._onData); } device.on("error", this._onError); this._open.push({ path, device }); diff --git a/native-hid/src/registry.mjs b/native-hid/src/registry.mjs index 48ef47ca..614da110 100644 --- a/native-hid/src/registry.mjs +++ b/native-hid/src/registry.mjs @@ -22,7 +22,19 @@ export async function loadRegistry() { import("@openmouse/protocol/drivers/registry"), import("@openmouse/protocol/drivers/vendors"), ]); - return { drivers: DEVICE_DRIVERS, filters: SUPPORTED_HID_FILTERS }; + try { + const [keyboards, keyboardVendors] = await Promise.all([ + import("@openmouse/keyboard-protocol/drivers/registry"), + import("@openmouse/keyboard-protocol/drivers/vendors"), + ]); + return { + drivers: [...DEVICE_DRIVERS, ...keyboards.DEVICE_DRIVERS], + filters: [...SUPPORTED_HID_FILTERS, ...keyboardVendors.SUPPORTED_HID_FILTERS], + }; + } catch (error) { + console.error(`[native-hid] keyboard registry unavailable: ${error?.message ?? error}`); + return { drivers: DEVICE_DRIVERS, filters: SUPPORTED_HID_FILTERS }; + } } export function brandKey(brand) { diff --git a/native-hid/src/registry.test.mjs b/native-hid/src/registry.test.mjs index 7b8287d0..680fc27a 100644 --- a/native-hid/src/registry.test.mjs +++ b/native-hid/src/registry.test.mjs @@ -66,6 +66,36 @@ test("only paths that declare input reports are listened on", async () => { assert.deepEqual(listening, ["notify"]); }); +test("a path with only unnumbered input keeps its first byte; numbered input still drops the id", async () => { + const handles = []; + class Handle extends EventEmitter { + constructor(path) { + super(); + handles.push([path, this]); + } + close() {} + } + const raw = collection(0xff60, 0x61); + const device = new DescribedDeviceAdapter( + described({ + paths: [ + { path: "via", collections: [raw], inputReports: { 0: 32 }, outputReports: { 0: 32 }, featureReports: {} }, + { path: "notify", collections: [collection(0xff02)], inputReports: { 9: 15 }, outputReports: {}, featureReports: {} }, + ], + }), + { Handle }, + ); + await device.open(); + const seen = []; + device.addEventListener("inputreport", (event) => seen.push([event.reportId, [...new Uint8Array(event.data.buffer)]])); + handles.find(([path]) => path === "via")[1].emit("data", Buffer.from([1, 0, 11, 0])); + handles.find(([path]) => path === "notify")[1].emit("data", Buffer.from([9, 5, 6])); + assert.deepEqual(seen, [ + [0, [1, 0, 11, 0]], + [9, [5, 6]], + ]); +}); + test("a feature report goes only down the path that declares it, padded to its size", async () => { const { Handle, log } = fakeHandles(); const device = new DescribedDeviceAdapter(described(), { Handle }); diff --git a/src/hid.rs b/src/hid.rs index 73762a8a..6df1cda7 100644 --- a/src/hid.rs +++ b/src/hid.rs @@ -140,6 +140,8 @@ enum Command { List { #[serde(rename = "vendorIds")] vendor_ids: Vec, + #[serde(default)] + usages: Vec, }, Open { device: String, @@ -464,15 +466,17 @@ impl HidSession { let id = message.id; let command = message.command.kind(); let vendor_count = match &message.command { - Command::List { vendor_ids } => Some(vendor_ids.len()), + Command::List { vendor_ids, .. } => Some(vendor_ids.len()), _ => None, }; let started = Instant::now(); let outcome = match message.command { - Command::List { vendor_ids } => self.list(vendor_ids).map(|devices| Reply { - devices: Some(devices), - ..Reply::ok(id) - }), + Command::List { vendor_ids, usages } => { + self.list(vendor_ids, usages).map(|devices| Reply { + devices: Some(devices), + ..Reply::ok(id) + }) + } Command::Open { device } => self.open(&device).map(|()| Reply::ok(id)), Command::Close { device } => self.close(&device).map(|()| Reply::ok(id)), Command::Listen { device } => self.listen(&device).map(|()| Reply::ok(id)), @@ -568,11 +572,19 @@ impl HidSession { reply } - fn list(&mut self, vendor_ids: Vec) -> Result, String> { - if vendor_ids.len() > 256 { + fn list( + &mut self, + vendor_ids: Vec, + usages: Vec, + ) -> Result, String> { + if vendor_ids.len() > 256 || usages.len() > 16 { return Err("too many HID vendor ids were requested".into()); } let vendors: HashSet = vendor_ids.into_iter().collect(); + let usages: Vec = usages + .into_iter() + .filter(|usage| usage.usage_page >= VENDOR_DEFINED_USAGE_PAGE) + .collect(); refresh_api(&mut self.api) .map_err(|error| format!("could not refresh HID devices: {error}"))?; @@ -581,7 +593,7 @@ impl HidSession { let present = self.api.device_list().map(device_group_key).collect(); self.reconcile_inventory(&present)?; - if vendors.is_empty() { + if vendors.is_empty() && usages.is_empty() { return Ok(Vec::new()); } @@ -589,7 +601,10 @@ impl HidSession { let mut by_device = std::collections::BTreeMap::, Vec>::new(); let blocked = security_key_paths(&self.api); for info in self.api.device_list() { - if vendors.contains(&info.vendor_id()) + if (vendors.contains(&info.vendor_id()) + || usages + .iter() + .any(|usage| usage.matches(info.usage_page(), info.usage()))) && !blocked.contains(info.path()) && !is_receiver_child(info.path()) { @@ -1455,6 +1470,21 @@ fn enumerated_collections(infos: &[hidapi::DeviceInfo], path: &CString) -> Vec, +} + +impl UsageFilter { + fn matches(&self, usage_page: u16, usage: u16) -> bool { + self.usage_page == usage_page && self.usage.is_none_or(|id| id == usage) + } +} + /// A device filter in the shape OpenMouse passes to /// `navigator.hid.requestDevice` (`SUPPORTED_HID_FILTERS`): a device matches /// when its vendor and product match and one of its top-level collections has @@ -1462,7 +1492,7 @@ fn enumerated_collections(infos: &[hidapi::DeviceInfo], path: &CString) -> Vec, pub product_id: Option, pub usage_page: Option, pub usage: Option, @@ -1470,7 +1500,8 @@ pub(crate) struct HidFilter { impl HidFilter { fn matches_product(&self, vendor_id: u16, product_id: u16) -> bool { - self.vendor_id == vendor_id && self.product_id.is_none_or(|id| id == product_id) + self.vendor_id.is_none_or(|id| id == vendor_id) + && self.product_id.is_none_or(|id| id == product_id) } fn matches_usage(&self, usage_page: u16, usage: u16) -> bool { @@ -2036,7 +2067,7 @@ mod tests { fn a_filter_matches_a_device_by_product_and_any_collection_usage() { use super::{DescribedDevice, HidFilter}; let filter = |product_id, usage_page, usage| HidFilter { - vendor_id: 0x3434, + vendor_id: Some(0x3434), product_id, usage_page, usage, @@ -2052,6 +2083,60 @@ mod tests { assert!(!filter(None, Some(0xffc1), Some(0x02)).matches_device(&receiver)); } + #[test] + fn a_list_request_may_carry_usages_and_older_ones_without_still_parse() { + use super::{Command, UsageFilter}; + let with: Command = serde_json::from_str( + r#"{"type":"list","vendorIds":[],"usages":[{"usagePage":65376,"usage":97}]}"#, + ) + .expect("parses"); + let Command::List { usages, .. } = with else { + panic!("a list command"); + }; + assert_eq!( + usages, + vec![UsageFilter { + usage_page: 0xff60, + usage: Some(0x61) + }] + ); + let without: Command = + serde_json::from_str(r#"{"type":"list","vendorIds":[1]}"#).expect("parses"); + let Command::List { usages, .. } = without else { + panic!("a list command"); + }; + assert!(usages.is_empty()); + } + + #[test] + fn a_usage_filter_matches_its_page_and_usage_only() { + use super::UsageFilter; + let via = UsageFilter { + usage_page: 0xff60, + usage: Some(0x61), + }; + assert!(via.matches(0xff60, 0x61)); + assert!(!via.matches(0xff60, 0x62)); + assert!(!via.matches(0x01, 0x06)); + let page = UsageFilter { + usage_page: 0xff60, + usage: None, + }; + assert!(page.matches(0xff60, 0x01)); + } + + #[test] + fn a_filter_without_a_vendor_matches_any_vendors_collection() { + use super::{DescribedDevice, HidFilter}; + let via: HidFilter = + serde_json::from_str(r#"{"usagePage":65376,"usage":97}"#).expect("parses"); + let board = + DescribedDevice::for_test("k", 0x7470, 0x0002, "", &[(0x01, 0x06), (0xff60, 0x61)]); + let plain = DescribedDevice::for_test("m", 0x7470, 0x0002, "", &[(0x01, 0x06)]); + assert!(via.matches_device(&board)); + assert!(!via.matches_device(&plain)); + } + #[test] fn device_keys_are_stable_and_never_carry_the_serial() { let receiver = grouped_device_key(0x046d, 0xc54d, b"/dev/hidraw2", Some("375D35803234")); @@ -2412,7 +2497,7 @@ mod tests { } // Even an empty vendor filter must refresh the inventory and retire // the remaining synthetic device, while returning no devices. - assert!(session.list(Vec::new()).unwrap().is_empty()); + assert!(session.list(Vec::new(), Vec::new()).unwrap().is_empty()); assert!( !active_device_registry() .lock()