webbluetooth_node/lib.rs
1//! Web Bluetooth for Node.js and Deno.
2//!
3//! Neither runtime has `navigator.bluetooth` — that is a browser API, and a
4//! server-side JavaScript runtime has no device picker and no permission
5//! prompt to build one on. So unlike the WebAssembly backend, which *uses*
6//! the browser's Web Bluetooth, this one *provides* it: the same
7//! CoreBluetooth, BlueZ, WinRT and HCI implementations the Rust crate uses,
8//! exposed to JavaScript.
9//!
10//! # Why not neon, or napi-rs
11//!
12//! Node-API is a C ABI with an explicit stability guarantee — that is the
13//! entire reason it exists. A module built against it keeps working across
14//! Node major versions without recompiling, and Deno and Bun implement the
15//! same ABI. Declaring it is no more exotic than the JNI, COM and
16//! Objective-C-runtime declarations elsewhere in this workspace, and it keeps
17//! the dependency count where the rest of the project keeps it: zero.
18//!
19//! # One addon, both runtimes
20//!
21//! Deno implements Node-API, so the same `.node` file loads in both:
22//!
23//! ```js
24//! // Node
25//! const bluetooth = require('./webbluetooth.node');
26//!
27//! // Deno — needs --allow-ffi --unstable-ffi
28//! import { createRequire } from 'node:module';
29//! const bluetooth = createRequire(import.meta.url)('./webbluetooth.node');
30//! ```
31//!
32//! # The consent problem
33//!
34//! In a browser `requestDevice` shows the user a picker. Here there is nobody
35//! to show. The default is [`webbluetooth::chooser::FirstMatch`], which takes
36//! the first device matching the filters — convenient, automatic, and a
37//! removal of the consent step the Web Bluetooth security model is built on.
38//! A caller that has a user to ask should pass a `chooser` callback and ask
39//! them.
40
41// Internals, not API. The crate's entire public surface is
42// `napi_register_module_v1`, which the runtime looks up by name — everything
43// else takes a `napi_env`, which is a raw pointer only valid on the runtime's
44// own thread, and is nobody's business to call from outside.
45pub(crate) mod api;
46pub(crate) mod emit;
47pub(crate) mod exec;
48pub(crate) mod napi;
49pub(crate) mod object;
50pub(crate) mod value;
51
52use napi::*;
53use std::ffi::c_char;
54use value::{Result, Thrown};
55
56/// The runtime, and the state that outlives a single call.
57///
58/// One per module instance. Node can load an addon into several contexts
59/// (worker threads, `vm` realms), and each gets its own.
60pub struct Instance {
61 /// The Bluetooth adapter this module is driving, opened on first use.
62 ///
63 /// Deliberately not opened at load. Constructing one touches the radio —
64 /// on Apple it creates a `CBCentralManager`, and a process that does that
65 /// without a Bluetooth usage description in *its own* image is terminated
66 /// by the system. A host like `node` has no such description and cannot be
67 /// given one by an addon: the embedded `__info_plist` belongs to this
68 /// dylib, and TCC reads the running image's.
69 ///
70 /// So `require()` must not do it. Loading a module is not consent to use a
71 /// radio, and a module that kills its host merely by being imported is
72 /// wrong even where the system tolerates it.
73 bluetooth: std::sync::OnceLock<webbluetooth::Bluetooth>,
74 /// Somewhere to run futures. Node's loop is not ours to block, so the
75 /// crate's futures run on a thread of their own and results come back
76 /// through a threadsafe function.
77 pub runtime: emit::Runtime,
78}
79
80impl Instance {
81 fn new() -> Self {
82 Self {
83 bluetooth: std::sync::OnceLock::new(),
84 runtime: emit::Runtime::new(),
85 }
86 }
87
88 /// The adapter, opening it the first time something asks.
89 pub fn bluetooth(&self) -> &webbluetooth::Bluetooth {
90 self.bluetooth.get_or_init(webbluetooth::Bluetooth::new)
91 }
92}
93
94/// Read the arguments of a call.
95///
96/// # Safety
97/// `info` must be the callback info the runtime passed to this callback.
98unsafe fn args(env: napi_env, info: napi_callback_info, count: usize) -> Result<Vec<napi_value>> {
99 let mut argc = count;
100 let mut argv = vec![std::ptr::null_mut(); count];
101 value::ok(
102 unsafe {
103 napi_get_cb_info(
104 env,
105 info,
106 &mut argc,
107 argv.as_mut_ptr(),
108 std::ptr::null_mut(),
109 std::ptr::null_mut(),
110 )
111 },
112 "napi_get_cb_info",
113 )?;
114 // Missing arguments come back as undefined rather than short, so the
115 // vector is always `count` long and each callback checks what it needs.
116 Ok(argv)
117}
118
119/// `getAvailability()` — resolves to a boolean.
120unsafe extern "C" fn get_availability(env: napi_env, info: napi_callback_info) -> napi_value {
121 let instance = match unsafe { instance_from(env, info) } {
122 Ok(i) => i,
123 Err(e) => return value::throw(env, &e.0),
124 };
125 let bluetooth = instance.bluetooth().clone();
126 match instance
127 .runtime
128 .promise(env, async move { Ok(bluetooth.get_availability().await) })
129 {
130 Ok(promise) => promise,
131 Err(e) => value::throw(env, &e.0),
132 }
133}
134
135/// One argument, or an error naming which was missing.
136fn required(argv: &[napi_value], at: usize, what: &str) -> Result<napi_value> {
137 argv.get(at)
138 .copied()
139 .filter(|v| !v.is_null())
140 .ok_or_else(|| Thrown(format!("argument {} ({what}) is required", at + 1)))
141}
142
143/// Read a `RequestDeviceOptions` from the object a caller passed.
144///
145/// The shape is Web Bluetooth's, so a page's options object works unchanged:
146/// `{ filters: [{ services, name, namePrefix }], optionalServices, acceptAllDevices }`.
147unsafe fn request_options(
148 env: napi_env,
149 value: napi_value,
150) -> Result<webbluetooth::RequestDeviceOptions> {
151 use webbluetooth::{DeviceFilter, RequestDeviceOptions};
152
153 let bad = |e: webbluetooth::Error| Thrown(e.to_string());
154 let mut options = RequestDeviceOptions::new();
155
156 let uuids = |env, list: napi_value| -> Result<Vec<String>> {
157 let mut len = 0;
158 value::ok(
159 unsafe { napi_get_array_length(env, list, &mut len) },
160 "array length",
161 )?;
162 let mut out = Vec::new();
163 for i in 0..len {
164 let mut item = std::ptr::null_mut();
165 value::ok(
166 unsafe { napi_get_element(env, list, i, &mut item) },
167 "array element",
168 )?;
169 out.push(value::as_string(env, item)?);
170 }
171 Ok(out)
172 };
173
174 if let Some(filters) = value::get(env, value, "filters")? {
175 let mut count = 0;
176 value::ok(
177 unsafe { napi_get_array_length(env, filters, &mut count) },
178 "filters length",
179 )?;
180 for i in 0..count {
181 let mut entry = std::ptr::null_mut();
182 value::ok(
183 unsafe { napi_get_element(env, filters, i, &mut entry) },
184 "filter",
185 )?;
186 let mut filter = DeviceFilter::new();
187 if let Some(services) = value::get(env, entry, "services")? {
188 filter = filter.services(uuids(env, services)?).map_err(bad)?;
189 }
190 if let Some(name) = value::get(env, entry, "name")? {
191 filter = filter.name(value::as_string(env, name)?);
192 }
193 if let Some(prefix) = value::get(env, entry, "namePrefix")? {
194 filter = filter.name_prefix(value::as_string(env, prefix)?);
195 }
196 options = options.filter(filter);
197 }
198 }
199 if let Some(optional) = value::get(env, value, "optionalServices")? {
200 options = options
201 .optional_services(uuids(env, optional)?)
202 .map_err(bad)?;
203 }
204 if let Some(all) = value::get(env, value, "acceptAllDevices")? {
205 if value::as_bool(env, all)? {
206 options = options.accept_all_devices();
207 }
208 }
209 Ok(options)
210}
211
212/// `requestDevice(options)` — resolves to a `BluetoothDevice`.
213unsafe extern "C" fn request_device(env: napi_env, info: napi_callback_info) -> napi_value {
214 let result = (|| -> Result<napi_value> {
215 let instance = unsafe { instance_from(env, info) }?;
216 let argv = unsafe { args(env, info, 1) }?;
217 let options = unsafe { request_options(env, required(&argv, 0, "options")?) }?;
218
219 let bluetooth = instance.bluetooth().clone();
220 // The whole object graph, built on the runtime's thread once the
221 // device exists — `gatt`, and everything reachable from it.
222 instance.runtime.promise_with(
223 env,
224 async move { bluetooth.request_device(options).await },
225 move |env, device| api::device_object(env, instance, device),
226 )
227 })();
228 match result {
229 Ok(promise) => promise,
230 Err(e) => value::throw(env, &e.0),
231 }
232}
233
234/// The module's state, reached from a callback.
235///
236/// # Safety
237/// `info` must be this callback's info; the data pointer is the `Instance`
238/// installed by [`napi_register_module_v1`], which lives as long as the module.
239unsafe fn instance_from(env: napi_env, info: napi_callback_info) -> Result<&'static Instance> {
240 let mut argc = 0usize;
241 let mut data: *mut std::ffi::c_void = std::ptr::null_mut();
242 value::ok(
243 unsafe {
244 napi_get_cb_info(
245 env,
246 info,
247 &mut argc,
248 std::ptr::null_mut(),
249 std::ptr::null_mut(),
250 &mut data,
251 )
252 },
253 "napi_get_cb_info",
254 )?;
255 if data.is_null() {
256 return Err(Thrown("the module state is missing".into()));
257 }
258 // SAFETY: the pointer was leaked at registration and is never freed, so it
259 // outlives every callback that can observe it.
260 Ok(unsafe { &*(data as *const Instance) })
261}
262
263/// Describe one exported function.
264fn method(
265 name: &'static std::ffi::CStr,
266 callback: napi_callback,
267 data: *mut std::ffi::c_void,
268) -> napi_property_descriptor {
269 napi_property_descriptor {
270 utf8name: name.as_ptr() as *const c_char,
271 name: std::ptr::null_mut(),
272 method: Some(callback),
273 getter: None,
274 setter: None,
275 value: std::ptr::null_mut(),
276 // writable | enumerable | configurable.
277 //
278 // `napi_default` is none of those, which loads fine and then behaves
279 // oddly: the methods work but `Object.keys(module)` is empty and
280 // `const { requestDevice } = require(...)` finds nothing, because a
281 // non-enumerable property is invisible to both. Module exports are
282 // expected to be ordinary properties.
283 attributes: 1 | 2 | 4,
284 data,
285 }
286}
287
288/// What Node calls when it loads the addon.
289///
290/// The symbol name is the ABI: the runtime looks it up by string, which is why
291/// it is `#[no_mangle]` and why the version suffix is part of the name.
292///
293/// # Safety
294/// Called once per module instance by the runtime.
295#[no_mangle]
296pub unsafe extern "C" fn napi_register_module_v1(env: napi_env, exports: napi_value) -> napi_value {
297 // Leaked deliberately: the runtime has no hook that reliably runs at
298 // unload on every platform, and the alternative — a finalizer that may or
299 // may not fire — would be a use-after-free rather than a leak.
300 let instance: &'static Instance = Box::leak(Box::new(Instance::new()));
301 let data = instance as *const Instance as *mut std::ffi::c_void;
302
303 // The module's own surface is small on purpose: everything else hangs off
304 // the device these return, as an object graph rather than a set of flat
305 // calls a wrapper has to reassemble.
306 let methods = [
307 method(c"getAvailability", get_availability, data),
308 method(c"requestDevice", request_device, data),
309 ];
310
311 if value::ok(
312 unsafe { napi_define_properties(env, exports, methods.len(), methods.as_ptr()) },
313 "napi_define_properties",
314 )
315 .is_err()
316 {
317 return value::throw(env, "could not install the module's exports");
318 }
319 exports
320}
321
322#[cfg(test)]
323mod tests {
324 use super::*;
325
326 /// The runtime finds the entry point by name. A typo here is a module that
327 /// loads and then reports "is not a valid Node.js addon", with nothing to
328 /// point at.
329 #[test]
330 fn the_registration_symbol_is_the_one_node_looks_up() {
331 // The coercion is the assertion: it only compiles if a function of
332 // exactly this name and signature exists. A typo here is a module that
333 // loads and then reports "is not a valid Node.js addon", with nothing
334 // to point at.
335 let _entry: unsafe extern "C" fn(napi_env, napi_value) -> napi_value =
336 napi_register_module_v1;
337 }
338
339 /// Exports have to be enumerable, or destructuring a `require()` result
340 /// silently yields `undefined` for every name.
341 #[test]
342 fn an_export_is_an_ordinary_enumerable_property() {
343 let d = method(c"getAvailability", get_availability, std::ptr::null_mut());
344 const ENUMERABLE: i32 = 2;
345 assert_eq!(
346 d.attributes & ENUMERABLE,
347 ENUMERABLE,
348 "exports must show up in Object.keys()"
349 );
350 }
351
352 #[test]
353 fn a_method_descriptor_names_its_callback() {
354 let d = method(c"getAvailability", get_availability, std::ptr::null_mut());
355 assert!(d.method.is_some());
356 assert!(d.getter.is_none() && d.setter.is_none());
357 assert!(!d.utf8name.is_null());
358 }
359}