@kirknock/node-openxr-inputs
v0.1.1
Published
Windowless keyboard and mouse input for Node.js OpenXR apps: per-key press/release with keycodes and scancodes, mouse buttons, relative motion and scrolling from every attached device, read from Linux evdev via koffi (works the same under X11 and Wayland)
Maintainers
Readme
@kirknock/node-openxr-inputs
Keyboard and mouse input for Node.js OpenXR apps that have no window. It targets apps like the passthrough apps on Monado or WiVRn, started from a terminal and talking to the runtime through koffi. The user wears the headset and types on the PC's physical keyboard and mouse.
- Per-key press / release / autorepeat, with the Linux key code
(
KEY_A= 30), the hardware scancode (MSC_SCAN, e.g. HID usage0x70004) and the XKB keycode. - Mouse buttons, relative motion (raw counts, no acceleration), and wheel scrolling with high-resolution (1/120 detent) values.
- Every keyboard and mouse at once: USB, Bluetooth, PS/2, receivers. Events are tagged with their device. Hotplug and Bluetooth reconnects are handled.
- The same API on X11 and Wayland, and on a bare TTY. It works below the display server, so no window, focus or display connection is needed.
- An optional exclusive grab: while in VR, the desktop and your terminal stop seeing the keystrokes.
- The only native code is libc, called through koffi. You don't need libinput, libevdev, libudev or a compiler.
Linux only, 64-bit (x86_64, aarch64), Node.js ≥ 24. Reading input devices needs a permission that ordinary users don't have by default.
Install
npm install @kirknock/node-openxr-inputs [email protected]koffi is a peer dependency, so the copy your OpenXR bindings already use
is shared.
Usage
import { openInputs, Keys } from "@kirknock/node-openxr-inputs";
const inputs = await openInputs({ grab: false });
for (const w of inputs.startupWarnings) console.warn(w.message); // e.g. permission problems
console.log(inputs.devices().map((d) => `${d.path} ${d.name} (${d.bus})`));
inputs.on("key", (e) => {
// e.device "/dev/input/event5", e.code 30, e.name "KEY_A", e.scancode 0x70004,
// e.xkbKeycode 38, e.state "down" | "up" | "repeat", e.time (ms, CLOCK_MONOTONIC)
if (e.code === Keys.KEY_ESC && e.state === "down") void inputs.close();
});
inputs.on("mouse-button", (e) => console.log(e.name, e.state)); // BTN_LEFT, BTN_RIGHT, BTN_SIDE, ...
inputs.on("mouse-move", (e) => console.log(e.dx, e.dy));
inputs.on("mouse-wheel", (e) => console.log(e.vertical, e.verticalHiRes, e.horizontal));
inputs.on("device-added", (d) => console.log("plugged", d.name));
inputs.on("device-removed", (d) => console.log("unplugged", d.name));
inputs.on("warning", (w) => console.warn(w.message));Polling from the XR frame loop
Render loops usually want state, not callbacks:
function onXrFrame() {
const { dx, dy, verticalHiRes } = inputs.consumeMouseDelta(); // summed over all mice since last frame
camera.yaw += dx * 0.002;
if (inputs.isKeyDown(Keys.KEY_W)) moveForward();
if (inputs.isKeyDown(Keys.BTN_LEFT)) select();
}API
| | |
|---|---|
| openInputs(options?) | Starts reading and resolves when the devices present now are open. |
| options.keyboards / mice | Default true. |
| options.absolutePointers | Default false. Covers VM tablets, touchscreens and pen tablets, and adds pointer-absolute events. |
| options.keyDevices | Default false. Covers devices with only a few keys: media-key receivers, the power button, a YubiKey. |
| options.filter(device) | Narrows the devices further, e.g. d => d.bus === "bluetooth". It also runs for hotplugged devices. |
| options.grab | Default false. Takes the devices exclusively (see below). |
| options.hotplug | Default true. Watches /dev/input. |
| inputs.devices(), inputs.device(path) | The devices being read, as InputDeviceInfo (name, bus, vendor/product, uniq = Bluetooth MAC, capabilities). |
| inputs.isKeyDown(code, device?), inputs.pressedKeys(device?) | Held keys and buttons. |
| inputs.consumeMouseDelta() | Accumulated dx, dy and wheel values since the last call. |
| inputs.setGrab(bool), inputs.isGrabbed(path) | Exclusive access at run time. |
| inputs.close() | Releases grabs and stops the reader thread. |
| listInputDevices() | Synchronous diagnostic: every node, its kind, and whether it can be opened. |
| Keys, RelAxes, AbsAxes, keyName(code) | The constants from <linux/input-event-codes.h>. |
Events: key, mouse-button, mouse-move, mouse-wheel,
pointer-absolute, input (every event), device-added (hotplug only; devices
present at open are in devices()), device-removed,
warning, error, close. Events with synthetic: true are generated by
the library: releases of keys still held when a device is unplugged, and
resyncs after a kernel buffer overflow. Without them, keys could stay stuck
down in your app.
Running the monitor (manual test)
npx openxr-inputs-monitor --list # every /dev/input node, its kind, and whether you may open it
npx openxr-inputs-monitor --duration 60 # print events for 60 s (0 = until Ctrl+C)
npx openxr-inputs-monitor --grab # same, with exclusive access
npx openxr-inputs-monitor --all --json # also tablets/key-only devices, JSON linesFrom a checkout, use npm run monitor -- --duration 30. Press and release
keys on each keyboard, click, move the mouse and scroll. Plug in or turn on a
Bluetooth keyboard while it runs. Example output:
node-openxr-inputs monitor — 2 device(s); stopping in 60s or on Ctrl+C
/dev/input/event5 keyboard bluetooth 0x046d:0xb342 "Keyboard K380" uniq=f4:73:35:00:00:00
/dev/input/event7 mouse+wheel usb 0x046d:0xc52b "Logitech USB Receiver"
[ 1.204s] event5 key down KEY_A code= 30 scancode=0x70004 xkb=38
[ 1.311s] event5 key up KEY_A code= 30 scancode=0x70004 xkb=38
[ 2.020s] event7 button down BTN_LEFT code=0x110 scancode=0x90001
[ 2.400s] event7 move dx= 42 dy= -7 (12 reports)
[ 3.002s] event7 wheel vertical=1 horizontal=0 (hi-res 120/0)
stopped (Ctrl+C). Summary:
event5 keys down=1 up=1 repeat=0 buttons=0 moves=0 (Σdx=0, Σdy=0) wheel=0/0
event7 keys down=0 up=0 repeat=0 buttons=2 moves=12 (Σdx=42, Σdy=-7) wheel=1/0Ctrl+C is detected from the evdev keyboard as well as from the terminal, so
it works while devices are grabbed. Without --grab, the terminal is put in
raw mode so your typing doesn't echo into the shell.
How it works without a window
This is the part that matters for a terminal-started XR app, so here it is in detail.
Where input normally goes. The kernel turns every keyboard and mouse
(USB HID, Bluetooth HID, PS/2, a virtual device) into an evdev device node,
/dev/input/eventN. A display server opens these nodes, through libinput on
both Xorg (xf86-input-libinput) and Wayland compositors (GNOME/mutter, KDE
KWin, wlroots/Sway, …). It reads the raw events, applies the keyboard layout
and pointer acceleration, and delivers the result only to the focused
window. A Node.js process launched from a terminal has no window, so the
display server never sends it anything. Even the terminal only gets
characters, not key releases or mouse motion, and only while it's focused,
which it isn't while you wear a headset.
What this package does instead. It opens the same /dev/input/eventN
nodes the display server opens, at the same level:
keyboard / mouse (USB, Bluetooth, PS/2)
│ HID reports
▼
Linux kernel input core ──► /dev/input/event0 … eventN (evdev: struct input_event)
│ │
│ every open fd gets ├──► libinput ──► Xorg or Wayland compositor ──► focused window
│ its own copy │
│ └──► node-openxr-inputs reader thread (koffi → libc)
▼ │ postMessage
▼
your Node.js OpenXR app (main thread, EventEmitter / polling)- evdev is multi-reader: every open file descriptor gets its own copy of
every event. Reading doesn't take anything from the desktop, and the
desktop doesn't take anything from you. No window, focus, X11 connection or
Wayland protocol is involved, which is why X11 and Wayland behave the same.
(Wayland deliberately offers no protocol for a client to read global
input, and X11 needs a window or a keylogger-style
XInput2raw-event connection. Going below both is the only approach that works the same in both.) - Each
read()returnsstruct input_eventrecords (24 bytes on 64-bit: a timestamp,type,codeandvalue). A key press looks like this:EV_MSC/MSC_SCAN 0x70004(the raw scancode),EV_KEY/KEY_A 1(1 = down, 0 = up, 2 = autorepeat),EV_SYN/SYN_REPORT(end of frame). Mouse motion isEV_REL/REL_X 5,EV_REL/REL_Y -3,SYN_REPORT, and the wheel isREL_WHEELandREL_WHEEL_HI_RES. The decoder (src/decoder.ts) groups records into frames and turns them into the events above. - Key codes are physical positions.
KEY_Zis the key right of left Shift, whatever layout is active. That's what games and VR controls want. Turning keys into text needs a keymap: feede.xkbKeycodeinto xkbcommon. That isn't part of this package. - Timestamps come from the kernel and are switched to
CLOCK_MONOTONIC(EVIOCSCLOCKID), the clock OpenXR runtimes use. Convert them withXR_KHR_convert_timespec_timeif you need XR time.
Threading. A worker_threads worker loads koffi and libc and opens
every wanted node with O_NONBLOCK. It puts them all into one epoll set,
along with:
- an
inotifywatch on/dev/input, which catches new nodes (plugged devices, Bluetooth reconnects) and permission changes applied by udev just after creation; - an
eventfdthat the main thread writes to when it sends a command (grab, accept/reject a device, close).
The worker blocks in epoll_wait, on its own thread only. It reads whatever
is ready, decodes it and posts one batch per wake-up to the main thread. The
main thread's event loop and the libuv threadpool are never blocked or
occupied. Reading each device with fs.createReadStream would instead tie up
one of the four default threadpool threads per device. Unplugging a device
makes read() fail with ENODEV. The device is then closed, and releases
are synthesized for anything still held. If the kernel's per-device buffer
overflows (SYN_DROPPED), the key state is re-read with EVIOCGKEY and the
difference is reported.
Device discovery and classification read sysfs
(/sys/class/input/eventN/device/{name,phys,uniq,id/*,capabilities/*}).
Sysfs is readable by everyone, so the library can name the devices it isn't
allowed to open, which makes the permission warnings specific. A device
counts as a keyboard when it has keys KEY_ESC through KEY_D (the same
test udev uses), and as a mouse when it has REL_X, REL_Y and
BTN_LEFT. Bluetooth keyboards are ordinary evdev devices with
bus: "bluetooth" and their MAC address in uniq. Multi-function devices
(a keyboard with a touchpad, a unifying receiver) appear as several nodes,
each read separately.
Grab (exclusive mode). Without a grab, the desktop still receives
everything you type. So does the focused window, which is often the terminal
running your app, and a stray Ctrl+C there stops it. grab: true /
setGrab(true) issues EVIOCGRAB. While it's in effect, only this process
receives the device's events: the cursor doesn't move and nothing is typed
into other windows. A grab is deferred, per device, until none of that
device's keys is held. Grabbing in the middle of the Enter that started the
app would leave the desktop seeing a key that never comes up, and Enter would
autorepeat forever. The kernel drops a grab automatically when the file
descriptor closes, which includes the process crashing or being killed, so
the desktop can't stay locked out.
Permissions
Device nodes are root:input, mode 0660. Desktop users can't read them,
because that would let any program log every keystroke, passwords included.
Grant access deliberately, using one of the options below (the first is
recommended). Check your situation first:
npx openxr-inputs-monitor --list # EACCES = no access
ls -l /dev/input/event* # crw-rw---- root input ...
id # are you in "input"?Option 1: udev uaccess rule (recommended for a desktop user)
This gives the user sitting at the machine (the active local session) an ACL on every keyboard and mouse node. logind applies and revokes it on login, logout and user switching, and udev re-applies it on every hotplug and Bluetooth reconnect. Nobody else, including SSH sessions, gets access. Only keyboards and mice are covered; game controllers and other devices aren't.
- Install the rule shipped with the package:
It contains:sudo install -m 0644 node_modules/@kirknock/node-openxr-inputs/docs/udev/70-openxr-inputs.rules /etc/udev/rules.d/SUBSYSTEM=="input", KERNEL=="event*", ENV{ID_INPUT_KEYBOARD}=="1", TAG+="uaccess" SUBSYSTEM=="input", KERNEL=="event*", ENV{ID_INPUT_MOUSE}=="1", TAG+="uaccess" - Reload the rules and apply them to devices that are already connected:
sudo udevadm control --reloadsudo udevadm trigger --subsystem-match=input --action=change - Verify. There should be a
user:<you>:rw-line:getfacl /dev/input/event* - Run your app or
npx openxr-inputs-monitorfrom a terminal inside your desktop session. You don't need to log in again.
If the ACL doesn't appear, check that the session is local and active
(loginctl show-session $XDG_SESSION_ID -p Active -p Remote). The ACL is
only granted to active local sessions.
Option 2: add the user to the input group (simplest)
- Add yourself to the group:
sudo usermod -aG input "$USER" - Log out and log back in (or reboot). Group membership is read at login,
so terminals that are already open don't have it. To get it in the current
terminal only, run
newgrp input. - Verify that
idlistsinput, then runnpx openxr-inputs-monitor --list.
This works everywhere, SSH included, but it grants access to every input
device at all times, even when you aren't at the machine. To undo it, run
sudo gpasswd -d "$USER" input and log in again.
Option 3: a dedicated group or service account
Use this for a kiosk or appliance, or when the XR app runs as its own user:
- Create the group and add the account:
sudo groupadd --system openxr-inputsudo usermod -aG openxr-input <user> - Create
/etc/udev/rules.d/70-openxr-inputs.rulesusing theGROUP=variant in the commented part of the shipped rule:
Then reload and trigger as in option 1.SUBSYSTEM=="input", KERNEL=="event*", ENV{ID_INPUT_KEYBOARD}=="1", GROUP="openxr-input", MODE="0660" SUBSYSTEM=="input", KERNEL=="event*", ENV{ID_INPUT_MOUSE}=="1", GROUP="openxr-input", MODE="0660" - Start the app with the group. Either run it in a fresh login, or use
sg openxr-input -c "node app.js", or use a systemd unit withSupplementaryGroups=openxr-input.
Option 4: a one-off test, until the next replug or reboot
sudo setfacl -m u:"$USER":r /dev/input/event*Not recommended
- Running Node as root. Your whole app, every npm dependency, and the
OpenXR runtime connection would then run as root. Monado and WiVRn also
expect the desktop user's session (
XDG_RUNTIME_DIR, IPC sockets). - File capabilities (
setcap cap_dac_read_search+ep $(which node)). This would give every Node script on the machine the ability to read any file.
Security notes
Whatever has read access to /dev/input/event* can log every keystroke,
passwords included, and with a grab it can keep input from reaching the
desktop. Prefer option 1, which only covers keyboards and mice and only the
person at the machine. Run only code you trust with that access.
Troubleshooting
| Symptom | Cause |
|---|---|
| EACCES for every device | Permissions aren't set up yet (see above). After usermod, you haven't logged in again. The warning says which. |
| No events from a Bluetooth keyboard | It's asleep or disconnected. Press a key: it reconnects and appears through hotplug. Check bluetoothctl info <mac>. |
| cannot grab …: EBUSY | Another process, such as a remote-desktop tool or another app, already holds an exclusive grab. |
| A device appears twice (keyboard + "Consumer Control"/"System Control") | That's normal. Media keys come from a separate key-only node; enable keyDevices to read it. |
| Only a tablet under a VM | VMs (QEMU, SPICE) often expose absolute tablets. Use absolutePointers: true. |
Development
npm ci
npm run build # dist/
npm run lint && npm run typecheck
npm test # decoder, classification, ioctl encoding; no devices needed (node:test + tsx)
npm run monitor -- --duration 30 # live test against real devices (needs permissions)
npm run gen:codes # regenerate src/codes.ts from /usr/include/linux/input-event-codes.h
npm run push # build + yalc push to local consumersLayout:
src/native/libc.ts: the koffi bindings (open/read/ioctl/epoll/inotify/eventfd), ioctl numbers and struct sizes. This is the only native code.src/codes.ts: generated byscripts/gen-codes.mjs. Don't edit it by hand.src/device.ts: sysfs discovery and classification (pure, unit tested).src/decoder.ts:input_eventrecords into frames into events (pure, unit tested).src/worker.ts: the reader thread (epoll loop, hotplug, grab, resync).src/protocol.ts: the messages between the worker and the main thread.src/inputs.ts: the public API (openInputs,Inputs,listInputDevices).src/tools/monitor.ts: theopenxr-inputs-monitorCLI and manual test.
Conventions match the other @kirknock/node-openxr-* packages: ESM,
TypeScript strict, type-aware ESLint for correctness only (no formatting
rules), and dependency versions pinned to the shared lockfile. When running
from sources, the worker is loaded as worker.ts and the tsx loader is
inherited through execArgv.
Releases: bump version, commit, and push a tag vX.Y.Z.
.github/workflows/release.yml publishes to npm through trusted publishing,
with provenance.
License
MIT
