@neuraiproject/neurai-sign-esp32 0.5.0 → 0.5.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -337,6 +337,80 @@ Suggested flow:
337
337
  > Serve from the repo root — serving only `examples/` leaves `../dist/browser.js`
338
338
  > unreachable and the page cannot load the library.
339
339
 
340
+ ## React Native / Android USB
341
+
342
+ The same library drives a NeuraiHW device from a React Native app over USB-C on
343
+ **Android** (iOS does not expose generic USB serial to apps). The device class
344
+ talks to a small transport interface, so the only platform-specific part is
345
+ moving raw bytes — all protocol logic (the 256-byte / 8 ms chunked writes, line
346
+ buffering, JSON parsing, timeouts) is shared.
347
+
348
+ The package does **not** depend on any native USB module. You adapt your chosen
349
+ module (e.g. `react-native-usb-serialport-for-android`, `react-native-serialport`,
350
+ or your own TurboModule) to the tiny `IUsbSerialDriver` interface and pass it in.
351
+
352
+ ```ts
353
+ import {
354
+ createNeuraiESP32OverUsb,
355
+ bytesToBase64,
356
+ base64ToBytes,
357
+ type IUsbSerialDriver,
358
+ } from "@neuraiproject/neurai-sign-esp32/react-native";
359
+
360
+ // Adapt your native module here. This sketch assumes a module that exchanges
361
+ // data as base64 strings (the common case on Android).
362
+ const usbDriver: IUsbSerialDriver = {
363
+ async open({ baudRate }) {
364
+ const native = await MyUsbModule.open({ baudRate }); // your module
365
+ return {
366
+ write: (data) => native.send(bytesToBase64(data)),
367
+ onReceive: (handler) => {
368
+ const sub = native.onData((b64: string) => handler(base64ToBytes(b64)));
369
+ return { remove: () => sub.remove() };
370
+ },
371
+ close: () => native.close(),
372
+ };
373
+ },
374
+ };
375
+
376
+ const device = createNeuraiESP32OverUsb(usbDriver);
377
+ await device.connect();
378
+ const info = await device.getInfo();
379
+ const { address } = await device.getAddress(); // user confirms on the device
380
+ const result = await device.signTransaction({ utxos, outputs, changeAddress: address });
381
+ console.log(result.txHex);
382
+ await device.disconnect();
383
+ ```
384
+
385
+ From here the API is identical to the browser flow (`getInfo`, `getAddress`,
386
+ `signTransaction`, `signMessage`, `getBip32Pubkey`, PQ support…).
387
+
388
+ ### Building a custom transport
389
+
390
+ `createNeuraiESP32OverUsb` is sugar over the same building blocks the Web Serial
391
+ transport uses. To target any other platform, implement `IByteChannel` (four
392
+ methods: `isOpen`, `onData`, `open`, `write`, `close`) and wrap it in a
393
+ `SerialProtocol`:
394
+
395
+ ```ts
396
+ import { NeuraiESP32, SerialProtocol, type IByteChannel } from "@neuraiproject/neurai-sign-esp32";
397
+
398
+ class MyByteChannel implements IByteChannel { /* … */ }
399
+
400
+ const device = new NeuraiESP32({ transport: new SerialProtocol(new MyByteChannel()) });
401
+ ```
402
+
403
+ You do **not** need to replicate the chunked-write workaround in your channel —
404
+ `SerialProtocol` handles it for every transport.
405
+
406
+ ### Android setup notes
407
+
408
+ - Add `<uses-feature android:name="android.hardware.usb.host" />` to the app
409
+ manifest, and request runtime USB permission for the device.
410
+ - The ESP32-S3 enumerates with USB vendor id `0x303a` (and CDC bridges such as
411
+ `0x10c4`, `0x1a86`, `0x0403`, `0x067b` for other boards).
412
+ - Open the port at **115200** baud, 8-N-1.
413
+
340
414
  ## Build outputs
341
415
 
342
416
  After `npm run build`, the package publishes:
@@ -344,8 +418,9 @@ After `npm run build`, the package publishes:
344
418
  - `dist/index.js`: primary ESM entry
345
419
  - `dist/index.cjs`: CommonJS entry
346
420
  - `dist/browser.js`: explicit browser ESM entry
421
+ - `dist/react-native.js`: React Native entry (no Web Serial; adds the USB transport)
347
422
  - `dist/NeuraiSignESP32.global.js`: IIFE bundle exposing `globalThis.NeuraiSignESP32`
348
- - `dist/index.d.ts`: public types
423
+ - `dist/index.d.ts` / `dist/react-native.d.ts`: public types
349
424
 
350
425
  ## UTXO requirements
351
426
 
@@ -469,5 +544,9 @@ Check if a PSBT base64 string is parseable. Returns boolean.
469
544
 
470
545
  ## Browser support
471
546
 
472
- Requires Web Serial API: Chrome 89+, Edge 89+, Opera 75+.
473
- Firefox and Safari are not supported.
547
+ The default transport requires the Web Serial API: Chrome 89+, Edge 89+,
548
+ Opera 75+. Firefox and Safari are not supported.
549
+
550
+ For non-browser platforms (React Native / Android USB, Node test doubles, …)
551
+ inject a custom transport instead — see
552
+ [React Native / Android USB](#react-native--android-usb).
@@ -2,95 +2,48 @@ var NeuraiSignESP32Bundle = (function () {
2
2
  'use strict';
3
3
 
4
4
  /**
5
- * Web Serial API communication layer for ESP32 hardware wallet.
5
+ * Transport-agnostic NeuraiHW protocol layer.
6
6
  *
7
- * Handles USB Serial connection, JSON command/response protocol,
8
- * and line-based buffering matching the NeuraiHW firmware protocol.
7
+ * `SerialProtocol` implements the full NeuraiHW JSON command/response protocol
8
+ * — the chunked-write firmware workaround, line buffering, JSON parsing, the
9
+ * response queue and the various timeout strategies — on top of a byte-level
10
+ * {@link IByteChannel}. This is the shared logic behind every transport: the
11
+ * Web Serial `SerialConnection` and the React Native USB channel both reuse it,
12
+ * so the platform-specific code only has to move raw bytes.
13
+ *
14
+ * If you build your own channel, you do NOT need to replicate the 256-byte /
15
+ * 8 ms chunked writes — that lives here and applies to every channel.
9
16
  */
10
- const DEFAULT_FILTERS = [
11
- { usbVendorId: 0x303a, usbProductId: 0x1001 },
12
- { usbVendorId: 0x303a },
13
- { usbVendorId: 0x10c4, usbProductId: 0xea60 },
14
- { usbVendorId: 0x1a86, usbProductId: 0x7523 },
15
- { usbVendorId: 0x0403, usbProductId: 0x6001 },
16
- { usbVendorId: 0x067b, usbProductId: 0x2303 },
17
- { usbVendorId: 0x2886 },
18
- ];
19
- const DEFAULT_BAUD_RATE = 115200;
20
- class SerialConnection {
21
- constructor(options) {
22
- this.port = null;
23
- this.reader = null;
24
- this.writer = null;
25
- this.readableStreamClosed = null;
26
- this.writableStreamClosed = null;
27
- this.isReading = false;
17
+ class SerialProtocol {
18
+ constructor(channel) {
28
19
  this.responseQueue = [];
29
- this.baudRate = options?.baudRate ?? DEFAULT_BAUD_RATE;
30
- this.filters = options?.filters ?? DEFAULT_FILTERS;
20
+ this.decoder = new TextDecoder();
21
+ this.encoder = new TextEncoder();
22
+ this.buffer = "";
23
+ this.opened = false;
24
+ this.channel = channel;
25
+ this.channel.onData((chunk) => this.handleBytes(chunk));
31
26
  }
32
- static isSupported() {
33
- return typeof navigator !== "undefined" && "serial" in navigator;
27
+ get connected() {
28
+ return this.opened && this.channel.isOpen;
34
29
  }
35
30
  async open() {
36
- if (!SerialConnection.isSupported()) {
37
- throw new Error("Web Serial API not supported. Use Chrome, Edge, or Opera.");
38
- }
39
- this.port = await navigator.serial.requestPort({ filters: this.filters });
40
- await this.port.open({
41
- baudRate: this.baudRate,
42
- dataBits: 8,
43
- stopBits: 1,
44
- parity: "none",
45
- flowControl: "none",
46
- bufferSize: 8192,
47
- });
48
- const decoder = new TextDecoderStream();
49
- this.readableStreamClosed = this.port.readable.pipeTo(decoder.writable);
50
- this.reader = decoder.readable.getReader();
51
- const encoder = new TextEncoderStream();
52
- this.writableStreamClosed = encoder.readable.pipeTo(this.port.writable);
53
- this.writer = encoder.writable.getWriter();
54
- this.isReading = true;
55
- void this.readLoop();
31
+ await this.channel.open();
32
+ this.opened = true;
33
+ // The device emits several plain-text boot lines before the first JSON
34
+ // message; wait for it to settle, then drop anything buffered so far.
56
35
  await this.delay(1200);
57
36
  this.responseQueue = [];
37
+ this.buffer = "";
58
38
  }
59
39
  async close() {
60
- this.isReading = false;
61
- if (this.reader) {
62
- await this.reader.cancel();
63
- await this.readableStreamClosed?.catch(() => { });
64
- this.reader = null;
65
- }
66
- if (this.writer) {
67
- await this.writer.close();
68
- await this.writableStreamClosed;
69
- this.writer = null;
70
- }
71
- if (this.port) {
72
- await this.port.close();
73
- this.port = null;
74
- }
40
+ this.opened = false;
41
+ await this.channel.close();
75
42
  this.responseQueue = [];
76
- }
77
- get connected() {
78
- return this.port !== null && this.writer !== null;
43
+ this.buffer = "";
79
44
  }
80
45
  async sendCommand(command, timeoutMs = 65000) {
81
- if (!this.writer) {
82
- throw new Error("Serial port not connected");
83
- }
84
- this.responseQueue = [];
85
- const json = JSON.stringify(command);
86
- console.debug("[NeuraiESP32 Serial] Sending command", {
87
- action: command.action,
88
- payloadLength: json.length + 1,
89
- timeoutMs,
90
- });
91
- await this.writeChunked(json);
92
- await this.writer.ready;
93
- await this.writer.write("\n");
46
+ await this.writeCommand(command, timeoutMs);
94
47
  const response = await this.waitForResponse(timeoutMs);
95
48
  if (!response) {
96
49
  throw new Error("Device response timeout");
@@ -98,19 +51,7 @@ var NeuraiSignESP32Bundle = (function () {
98
51
  return response;
99
52
  }
100
53
  async sendCommandFinal(command, timeoutMs = 65000) {
101
- if (!this.writer) {
102
- throw new Error("Serial port not connected");
103
- }
104
- this.responseQueue = [];
105
- const json = JSON.stringify(command);
106
- console.debug("[NeuraiESP32 Serial] Sending command", {
107
- action: command.action,
108
- payloadLength: json.length + 1,
109
- timeoutMs,
110
- });
111
- await this.writeChunked(json);
112
- await this.writer.ready;
113
- await this.writer.write("\n");
54
+ await this.writeCommand(command, timeoutMs);
114
55
  const startTime = Date.now();
115
56
  while (Date.now() - startTime < timeoutMs) {
116
57
  const response = await this.waitForResponse(timeoutMs - (Date.now() - startTime));
@@ -134,20 +75,7 @@ var NeuraiSignESP32Bundle = (function () {
134
75
  * @param maxTotalMs hard ceiling across the whole operation (safety net)
135
76
  */
136
77
  async sendCommandHeartbeat(command, perResponseTimeoutMs = 30000, maxTotalMs = 600000) {
137
- if (!this.writer) {
138
- throw new Error("Serial port not connected");
139
- }
140
- this.responseQueue = [];
141
- const json = JSON.stringify(command);
142
- console.debug("[NeuraiESP32 Serial] Sending command", {
143
- action: command.action,
144
- payloadLength: json.length + 1,
145
- perResponseTimeoutMs,
146
- maxTotalMs,
147
- });
148
- await this.writeChunked(json);
149
- await this.writer.ready;
150
- await this.writer.write("\n");
78
+ await this.writeCommand(command, perResponseTimeoutMs);
151
79
  const startTime = Date.now();
152
80
  for (;;) {
153
81
  if (Date.now() - startTime > maxTotalMs) {
@@ -164,37 +92,42 @@ var NeuraiSignESP32Bundle = (function () {
164
92
  return response;
165
93
  }
166
94
  }
167
- async readLoop() {
168
- let buffer = "";
169
- while (this.isReading && this.reader) {
170
- try {
171
- const { value, done } = await this.reader.read();
172
- if (done)
173
- break;
174
- buffer += value;
175
- const lines = buffer.split("\n");
176
- buffer = lines.pop() ?? "";
177
- for (const rawLine of lines) {
178
- const line = rawLine.trim().replace(/\r/g, "");
179
- if (line.length === 0)
180
- continue;
181
- if (line.startsWith("{")) {
182
- try {
183
- const data = JSON.parse(line);
184
- console.debug("[NeuraiESP32 Serial] JSON line received", data);
185
- this.responseQueue.push(data);
186
- }
187
- catch {
188
- console.debug("[NeuraiESP32 Serial] Invalid JSON line", line);
189
- }
190
- }
191
- else {
192
- console.debug("[NeuraiESP32 Serial] Non-JSON serial line", line);
193
- }
95
+ async writeCommand(command, timeoutMs) {
96
+ if (!this.channel.isOpen) {
97
+ throw new Error("Serial port not connected");
98
+ }
99
+ this.responseQueue = [];
100
+ const json = JSON.stringify(command);
101
+ console.debug("[NeuraiESP32 Serial] Sending command", {
102
+ action: command.action,
103
+ payloadLength: json.length + 1,
104
+ timeoutMs,
105
+ });
106
+ await this.writeChunked(json);
107
+ // The newline terminator is sent separately, after all chunks, so the
108
+ // firmware only processes the command once the full JSON has arrived.
109
+ await this.channel.write(this.encoder.encode("\n"));
110
+ }
111
+ handleBytes(chunk) {
112
+ this.buffer += this.decoder.decode(chunk, { stream: true });
113
+ const lines = this.buffer.split("\n");
114
+ this.buffer = lines.pop() ?? "";
115
+ for (const rawLine of lines) {
116
+ const line = rawLine.trim().replace(/\r/g, "");
117
+ if (line.length === 0)
118
+ continue;
119
+ if (line.startsWith("{")) {
120
+ try {
121
+ const data = JSON.parse(line);
122
+ console.debug("[NeuraiESP32 Serial] JSON line received", data);
123
+ this.responseQueue.push(data);
124
+ }
125
+ catch {
126
+ console.debug("[NeuraiESP32 Serial] Invalid JSON line", line);
194
127
  }
195
128
  }
196
- catch {
197
- break;
129
+ else {
130
+ console.debug("[NeuraiESP32 Serial] Non-JSON serial line", line);
198
131
  }
199
132
  }
200
133
  }
@@ -225,54 +158,44 @@ var NeuraiSignESP32Bundle = (function () {
225
158
  check();
226
159
  });
227
160
  }
161
+ /**
162
+ * Split an outgoing message into small chunks. The ESP32 CDC serial buffer can
163
+ * lose data when the host sends a large payload in a single write, so every
164
+ * message is written in 256-byte chunks with an 8 ms pause between each one.
165
+ */
228
166
  async writeChunked(data, chunkSize = 256, pauseMs = 8) {
229
- if (!this.writer) {
230
- throw new Error("Serial port not connected");
231
- }
232
- const totalChunks = Math.ceil(data.length / chunkSize);
167
+ const bytes = this.encoder.encode(data);
168
+ const totalChunks = Math.ceil(bytes.length / chunkSize) || 1;
233
169
  const startedAt = Date.now();
234
- let totalReadyMs = 0;
235
- let totalWriteMs = 0;
236
- let totalPauseMs = 0;
237
170
  console.debug("[NeuraiESP32 Serial][writeChunked] start", {
238
- totalBytes: data.length,
171
+ totalBytes: bytes.length,
239
172
  chunkSize,
240
173
  pauseMs,
241
174
  totalChunks,
242
175
  });
243
- for (let offset = 0, chunkIndex = 0; offset < data.length; offset += chunkSize, chunkIndex += 1) {
244
- const chunk = data.slice(offset, offset + chunkSize);
245
- const readyStartedAt = Date.now();
246
- await this.writer.ready;
247
- const readyMs = Date.now() - readyStartedAt;
248
- totalReadyMs += readyMs;
176
+ for (let offset = 0, chunkIndex = 0; offset < bytes.length; offset += chunkSize, chunkIndex += 1) {
177
+ const chunk = bytes.subarray(offset, offset + chunkSize);
249
178
  const writeStartedAt = Date.now();
250
- await this.writer.write(chunk);
179
+ await this.channel.write(chunk);
251
180
  const writeMs = Date.now() - writeStartedAt;
252
- totalWriteMs += writeMs;
253
181
  let actualPauseMs = 0;
254
- if (pauseMs > 0 && offset + chunkSize < data.length) {
182
+ if (pauseMs > 0 && offset + chunkSize < bytes.length) {
255
183
  const pauseStartedAt = Date.now();
256
184
  await this.delay(pauseMs);
257
185
  actualPauseMs = Date.now() - pauseStartedAt;
258
- totalPauseMs += actualPauseMs;
259
186
  }
260
187
  console.debug("[NeuraiESP32 Serial][writeChunked] chunk", {
261
188
  chunkIndex: chunkIndex + 1,
262
189
  totalChunks,
263
190
  chunkBytes: chunk.length,
264
- readyMs,
265
191
  writeMs,
266
192
  pauseMs: actualPauseMs,
267
193
  });
268
194
  }
269
195
  console.debug("[NeuraiESP32 Serial][writeChunked] complete", {
270
- totalBytes: data.length,
196
+ totalBytes: bytes.length,
271
197
  totalChunks,
272
198
  totalMs: Date.now() - startedAt,
273
- totalReadyMs,
274
- totalWriteMs,
275
- totalPauseMs,
276
199
  });
277
200
  }
278
201
  delay(ms) {
@@ -280,6 +203,126 @@ var NeuraiSignESP32Bundle = (function () {
280
203
  }
281
204
  }
282
205
 
206
+ /**
207
+ * Web Serial API byte channel for the ESP32 hardware wallet.
208
+ *
209
+ * This is the browser-specific half of the transport: it opens a USB serial
210
+ * port via the Web Serial API and moves raw bytes. All protocol logic (chunked
211
+ * writes, line buffering, JSON parsing, timeouts) lives in {@link SerialProtocol}.
212
+ */
213
+ const DEFAULT_FILTERS = [
214
+ { usbVendorId: 0x303a, usbProductId: 0x1001 },
215
+ { usbVendorId: 0x303a },
216
+ { usbVendorId: 0x10c4, usbProductId: 0xea60 },
217
+ { usbVendorId: 0x1a86, usbProductId: 0x7523 },
218
+ { usbVendorId: 0x0403, usbProductId: 0x6001 },
219
+ { usbVendorId: 0x067b, usbProductId: 0x2303 },
220
+ { usbVendorId: 0x2886 },
221
+ ];
222
+ const DEFAULT_BAUD_RATE = 115200;
223
+ class WebSerialByteChannel {
224
+ constructor(options) {
225
+ this.port = null;
226
+ this.reader = null;
227
+ this.writer = null;
228
+ this.handler = null;
229
+ this.reading = false;
230
+ this.baudRate = options?.baudRate ?? DEFAULT_BAUD_RATE;
231
+ this.filters = options?.filters ?? DEFAULT_FILTERS;
232
+ }
233
+ static isSupported() {
234
+ return typeof navigator !== "undefined" && "serial" in navigator;
235
+ }
236
+ get isOpen() {
237
+ return this.port !== null && this.writer !== null;
238
+ }
239
+ onData(handler) {
240
+ this.handler = handler;
241
+ }
242
+ async open() {
243
+ if (!WebSerialByteChannel.isSupported()) {
244
+ throw new Error("Web Serial API not supported. Use Chrome, Edge, or Opera.");
245
+ }
246
+ this.port = await navigator.serial.requestPort({ filters: this.filters });
247
+ await this.port.open({
248
+ baudRate: this.baudRate,
249
+ dataBits: 8,
250
+ stopBits: 1,
251
+ parity: "none",
252
+ flowControl: "none",
253
+ bufferSize: 8192,
254
+ });
255
+ this.reader = this.port.readable.getReader();
256
+ this.writer = this.port.writable.getWriter();
257
+ this.reading = true;
258
+ void this.readLoop();
259
+ }
260
+ async write(data) {
261
+ if (!this.writer) {
262
+ throw new Error("Serial port not connected");
263
+ }
264
+ await this.writer.ready;
265
+ await this.writer.write(data);
266
+ }
267
+ async close() {
268
+ this.reading = false;
269
+ if (this.reader) {
270
+ await this.reader.cancel().catch(() => { });
271
+ try {
272
+ this.reader.releaseLock();
273
+ }
274
+ catch {
275
+ // already released
276
+ }
277
+ this.reader = null;
278
+ }
279
+ if (this.writer) {
280
+ await this.writer.close().catch(() => { });
281
+ this.writer = null;
282
+ }
283
+ if (this.port) {
284
+ await this.port.close().catch(() => { });
285
+ this.port = null;
286
+ }
287
+ }
288
+ async readLoop() {
289
+ while (this.reading && this.reader) {
290
+ try {
291
+ const { value, done } = await this.reader.read();
292
+ if (done)
293
+ break;
294
+ if (value && value.length > 0) {
295
+ this.handler?.(value);
296
+ }
297
+ }
298
+ catch {
299
+ break;
300
+ }
301
+ }
302
+ }
303
+ }
304
+
305
+ /**
306
+ * Web Serial connection for the ESP32 hardware wallet.
307
+ *
308
+ * `SerialConnection` is the default, browser-targeted transport: it drives the
309
+ * NeuraiHW JSON protocol ({@link SerialProtocol}) over a Web Serial byte channel
310
+ * ({@link WebSerialByteChannel}). Its public API is unchanged — it remains the
311
+ * out-of-the-box transport `NeuraiESP32` uses when none is injected.
312
+ *
313
+ * To run the library on another platform (e.g. React Native / Android USB),
314
+ * implement an `IByteChannel`, wrap it in a `SerialProtocol`, and pass that as
315
+ * `transport` to `NeuraiESP32`. See `src/channels/` and the README.
316
+ */
317
+ class SerialConnection extends SerialProtocol {
318
+ constructor(options) {
319
+ super(new WebSerialByteChannel(options));
320
+ }
321
+ static isSupported() {
322
+ return WebSerialByteChannel.isSupported();
323
+ }
324
+ }
325
+
283
326
  var buffer = {};
284
327
 
285
328
  var base64Js = {};
@@ -12866,9 +12909,14 @@ var NeuraiSignESP32Bundle = (function () {
12866
12909
  * ```
12867
12910
  */
12868
12911
  class NeuraiESP32 {
12912
+ /**
12913
+ * @param options Pass `{ transport }` to drive the device over a custom
12914
+ * transport (e.g. React Native / Android USB). Without it, the default Web
12915
+ * Serial transport is used and `baudRate`/`filters` configure it.
12916
+ */
12869
12917
  constructor(options) {
12870
12918
  this.deviceInfo = null;
12871
- this.serial = new SerialConnection(options);
12919
+ this.serial = options?.transport ?? new SerialConnection(options);
12872
12920
  }
12873
12921
  static isSupported() {
12874
12922
  return SerialConnection.isSupported();