@neuraiproject/neurai-sign-esp32 0.5.12 → 0.6.1

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
@@ -49,6 +49,8 @@ For classic HTML pages without ESM imports, load the global bundle:
49
49
  <script src="./dist/NeuraiSignESP32.global.js"></script>
50
50
  <script>
51
51
  const device = new window.NeuraiSignESP32.NeuraiESP32();
52
+ // The IIFE exposes the DePIN adapter too:
53
+ // window.NeuraiSignESP32.createDepinDeviceIdentity(device, options)
52
54
  </script>
53
55
  ```
54
56
 
@@ -262,6 +264,93 @@ await device.depinSessionEnd();
262
264
  > the freshness of `timestamp` — the host supplies it and the chip only validates
263
265
  > the message structure and channel/sender scope.
264
266
 
267
+ ### DePIN protocol 2: use the device as a messaging identity
268
+
269
+ The calls above are the raw device commands. For the full **DePIN Messaging
270
+ Protocol 2** flows (challenge → receive → publish → purge) there is an adapter
271
+ that turns the device into an identity consumable by
272
+ [`@neuraiproject/neurai-depin-msg`](https://www.npmjs.com/package/@neuraiproject/neurai-depin-msg)
273
+ `>= 3.1.0`, without the private key ever leaving the chip:
274
+
275
+ ```javascript
276
+ import { createDepinDeviceIdentity } from "@neuraiproject/neurai-sign-esp32";
277
+ import { requestDepinChallenge, receiveDepinMessages } from "@neuraiproject/neurai-depin-msg";
278
+
279
+ // Opens (or reuses) a session for the token and validates the announced
280
+ // identity against the network you expect. ONE physical approval.
281
+ const identity = await createDepinDeviceIdentity(device, {
282
+ token: "&NEURAI.CHAT",
283
+ expectedNetwork: "test", // must match the app's network
284
+ sessionPermissions: ["receive", "publish"], // default: ["receive"]
285
+ ttlMinutes: 15,
286
+ });
287
+
288
+ // From here it is an ordinary depin-msg identity.
289
+ const challenge = await requestDepinChallenge({
290
+ rpc, identity, token: "&NEURAI.CHAT", poolPublicKey,
291
+ });
292
+ const page = await receiveDepinMessages({
293
+ rpc, identity, token: "&NEURAI.CHAT", challenge: challenge.challenge,
294
+ poolPublicKey, network: "test", limit: 25,
295
+ });
296
+ ```
297
+
298
+ **Session permissions.** They are independent capabilities, because a session
299
+ approved for reading must not be able to publish in the owner's name or purge
300
+ the pool:
301
+
302
+ | Permission | Authorises |
303
+ | --- | --- |
304
+ | `receive` | `DEPIN-REQ` (type `receive`) and `DEPIN-GET` — reading |
305
+ | `publish` | `depin_sign` — publishing messages |
306
+ | `admin` | `DEPIN-REQ` (type `admin`) and `DEPIN-CLEAR` — purging |
307
+
308
+ Decryption is inherent to **any** live session, so say so when asking for
309
+ approval. An omitted list grants only `["receive"]`, never `admin`. Requesting
310
+ a different set than the device granted fails instead of silently reusing a
311
+ more privileged session. And `admin` implies a *total* purge: the `mode`
312
+ argument of `depinclearmsg` is not part of the signed `DEPIN-CLEAR` preimage,
313
+ so a purge signature cannot be narrowed after the fact.
314
+
315
+ **Why not `depinSignDigest`.** That command signs an arbitrary 32-byte hash —
316
+ possibly a transaction sighash — which is exactly why it is *not* session-gated
317
+ and always asks for a physical confirmation. The adapter never uses it:
318
+ authentication goes through `depinSignAuth`, where the device receives the
319
+ structured fields, rebuilds `DEPIN-REQ|…` / `DEPIN-GET|…` / `DEPIN-CLEAR|…`
320
+ plus the signed-message envelope itself, and validates them against the session
321
+ before signing. `depinSignDigest` stays for what it was meant for, such as the
322
+ pubkey-reveal transaction.
323
+
324
+ Every signature the device returns is verified on the host before it is used,
325
+ so a device that signs the wrong digest or with another key fails locally
326
+ instead of at the node. Errors are `DepinDeviceIdentityError` with stable
327
+ `code`s (`SESSION_PERMISSION_INSUFFICIENT`, `SESSION_TIME_BUDGET_INSUFFICIENT`,
328
+ `INVALID_DEVICE_SIGNATURE`, `PAYLOAD_TOO_LARGE`…) so a UI can map them to
329
+ concrete actions.
330
+
331
+ **Sizing the session.** `identity.maxDecryptBytes` reports what the device can
332
+ decrypt in one go; pick `limit` so a page fits, because a reply the device
333
+ cannot open costs the whole challenge (`next_challenge` travels *inside* it).
334
+ A round costs roughly 4 device operations for an initial read, 2 for a chained
335
+ one, 2 to publish and 4 to purge — size `ratePerMin` accordingly. Before a
336
+ sequence that spans several calls, reserve time explicitly:
337
+
338
+ ```javascript
339
+ await identity.session.ensure({ minRemainingSeconds: 60 });
340
+ ```
341
+
342
+ > **Firmware requirement.** The adapter needs firmware advertising protocol 2
343
+ > with `depin_identity`, `depin_message`, `depin_auth_sign`,
344
+ > `depin_session_key` and `depin_session_permissions`; it refuses to downgrade.
345
+ > `depin_sign_auth` and session permissions are **not implemented in current
346
+ > firmware yet** — the contract they must satisfy is specified, and exercised
347
+ > by a cryptographically faithful device mock, in this package's tests.
348
+ > `@neuraiproject/neurai-depin-msg@3.1.0` must be published before installing
349
+ > this repository from scratch or publishing `neurai-sign-esp32@0.6.0`. The
350
+ > package has no runtime dependency on `neurai-depin-msg`; it is a `^3.1.0`
351
+ > development dependency used only by the integration tests. The package gate
352
+ > validates the adapter from a clean `neurai-sign-esp32` tarball.
353
+
265
354
  ### Provision an unconfigured device (`setup_seed`)
266
355
 
267
356
  Firmware with the security layer boots **unconfigured** until a seed is stored
@@ -629,7 +718,8 @@ Main class for device interaction.
629
718
  | `depinSign(params)` | Sign a DePIN message on-device (DER over the canonical CDepinMessage); session-gated, rate-limited |
630
719
  | `depinDecrypt(depinMessageHex)` | Decrypt a CDepinMessage addressed to this identity → `plaintext_b64`; session-gated. Uses Base64 automatically on firmware 0.5.11+ |
631
720
  | `depinDecryptPayload(encryptedPayloadHex)` | Decrypt a bare ECIES `encrypted_payload_hex` (decomposed server item) → `plaintext_b64`; session-gated. Uses Base64 automatically on firmware 0.5.11+ and rejects data above its announced limit |
632
- | `depinSignDigest(digestHex)` | Sign a tx sighash with the DePIN key (account 100') → `{ signature, pubkey }`; physical confirmation, for the pubkey-reveal burn |
721
+ | `depinSignAuth(command)` | Sign a protocol-2 authentication preimage (`request`/`get`/`clear`) from STRUCTURED fields: the device rebuilds `DEPIN-REQ|…`/`DEPIN-GET|…`/`DEPIN-CLEAR|…` and validates it against the session. Session-gated, permission-checked |
722
+ | `depinSignDigest(digestHex)` | Sign a tx sighash with the DePIN key (account 100') → `{ signature, pubkey }`; physical confirmation, **not** session-gated, for the pubkey-reveal burn. Never used by the DePIN messaging adapter |
633
723
  | `depinSessionStatus()` | Check whether the cached/`setDepinSessionKey` key still names a live session → `{ active, token?, expires_in_s? }` (proto v2) |
634
724
  | `getDepinSessionKey()` / `setDepinSessionKey(key)` | Read / restore the per-session capability key (persist it in the OS keystore across restarts) |
635
725
  | `depinSessionEnd()` | End the DePIN session (also revoked on lock / disconnect / timeout) |
@@ -683,3 +773,54 @@ Opera 75+. Firefox and Safari are not supported.
683
773
  For non-browser platforms (React Native / Android USB, Node test doubles, …)
684
774
  inject a custom transport instead — see
685
775
  [React Native / Android USB](#react-native--android-usb).
776
+
777
+
778
+ ## Exact amounts (0.6.1)
779
+
780
+ `IUTXO.satoshis`, `IPQUTXO.satoshis`, output `value`, PQ `amount` and
781
+ `sighashAmount` accept `bigint`, integer strings, or safe integer numbers. These
782
+ are **raw protocol units**, not decimal XNA or asset units. Values must be
783
+ non-negative and no greater than `2100000000000000000n`. Already unsafe numbers
784
+ are rejected; converting a rounded number to bigint cannot restore its digits.
785
+
786
+ ```ts
787
+ const output = { address: destination, value: 10000000000000001n };
788
+ // The same exact amount can be passed as value: '10000000000000001'.
789
+ ```
790
+
791
+ Both high-level builders sum funds, calculate change and subtract fees in bigint.
792
+ `feeRate` accepts a number or decimal string in satoshis per byte. Fractional
793
+ rates are multiplied exactly and rounded upward to a whole satoshi once.
794
+
795
+ Asset transactions prepared externally should use `buildPSBTFromRawTransaction`
796
+ (legacy) or `signPqRawTransaction` (PQ). Their asset payload quantities remain
797
+ encoded in the transaction bytes at scale 10^8, independent of asset divisibility.
798
+ The high-level address/value output builders construct XNA payment outputs;
799
+ they do not create asset transfer payloads. For asset-wrapped PQ inputs, pass
800
+ `amount: 0` to the raw signing API, or `sighashAmount: 0` when using the builder.
801
+ An asset quantity must never count toward XNA funding: an explicit zero prevout
802
+ value contributes zero to fees and payment funding, so separate XNA inputs are
803
+ required.
804
+
805
+ Display metadata uses decimal **strings** for large asset quantities and fees:
806
+
807
+ ```ts
808
+ const display = buildAssetTransferDisplayMetadata({
809
+ assetName: 'LARGE',
810
+ assetAmount: '100000000.00000001',
811
+ destinationAddress: destination,
812
+ feeAmount: '0.00000249',
813
+ });
814
+ ```
815
+
816
+ Plain strings retain their formatting. Invalid amounts, excess decimals and
817
+ unsafe large fractional numbers are rejected instead of silently rounded.
818
+ Direct signing calls validate display amounts too.
819
+
820
+ Before handing `sign_tx` to a transport, the library encodes safe raw amounts as
821
+ JSON numbers and larger ones as integer strings. Custom transports must preserve
822
+ those strings. The reviewed firmware reads `amount` using ArduinoJson
823
+ `as<unsigned long long>()`, which supports exact integer strings. Its local
824
+ ArduinoJson parser was checked on the host up to MAX_MONEY; this does not replace
825
+ an on-device signing and display check of the firmware installed on your ESP32.
826
+ No global bigint JSON serializer is required.