@ledgerhq/device-transport-kit-web-hid 0.0.0-webhid-20250124160621 → 0.0.0-webhid-20250129103551
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 +77 -0
- package/lib/esm/api/transport/WebHidDeviceConnection.js +1 -1
- package/lib/esm/api/transport/WebHidDeviceConnection.js.map +3 -3
- package/lib/esm/api/transport/WebHidDeviceConnection.test.js +1 -1
- package/lib/esm/api/transport/WebHidDeviceConnection.test.js.map +3 -3
- package/lib/esm/package.json +1 -1
- package/lib/types/api/transport/WebHidDeviceConnection.d.ts +1 -3
- package/lib/types/api/transport/WebHidDeviceConnection.d.ts.map +1 -1
- package/lib/types/tsconfig.prod.tsbuildinfo +1 -1
- package/package.json +3 -3
package/README.md
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
# Transport Device Kit Web HID
|
|
2
|
+
|
|
3
|
+
> [!CAUTION]
|
|
4
|
+
> This is still under development and we are free to make new interfaces which may lead to breaking changes.
|
|
5
|
+
|
|
6
|
+
- [Transport Device Kit Web HID Documentation](#transport-device-kit-web-hid)
|
|
7
|
+
- [Description](#description)
|
|
8
|
+
- [Installation](#installation)
|
|
9
|
+
- [Usage](#usage)
|
|
10
|
+
- [Compatibility](#compatibility)
|
|
11
|
+
- [Pre-requisites](#pre-requisites)
|
|
12
|
+
- [Main Features](#main-features)
|
|
13
|
+
- [How To](#how-to)
|
|
14
|
+
|
|
15
|
+
## Description
|
|
16
|
+
|
|
17
|
+
This transport is used to interact with a Ledger device through the Web HID (usb) implementation by the Device Management Kit.
|
|
18
|
+
|
|
19
|
+
## Installation
|
|
20
|
+
|
|
21
|
+
To install the core package, run the following command:
|
|
22
|
+
|
|
23
|
+
```sh
|
|
24
|
+
npm install @ledgerhq/device-transport-kit-web-hid
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Usage
|
|
28
|
+
|
|
29
|
+
### Compatibility
|
|
30
|
+
|
|
31
|
+
This library works in [any browser supporting the WebHID API](https://developer.mozilla.org/en-US/docs/Web/API/WebHID_API#browser_compatibility).
|
|
32
|
+
|
|
33
|
+
### Pre-requisites
|
|
34
|
+
|
|
35
|
+
To use this transport, ensure you have the Device Magement Kit installed in your project.
|
|
36
|
+
|
|
37
|
+
### Main Features
|
|
38
|
+
|
|
39
|
+
- Exposing a transport factory to be injected into the DeviceManagementKit
|
|
40
|
+
- Exposing the transport directly for a custom configuration
|
|
41
|
+
|
|
42
|
+
### How To
|
|
43
|
+
|
|
44
|
+
To use the transport, you need to inject it in the DeviceManagementKitBuilder before the build. This will allow the Devivce Management Kit to find and interact with devices on the Web HID protocol.
|
|
45
|
+
|
|
46
|
+
```typescript
|
|
47
|
+
import { DeviceManagementKitBuilder } from "@ledgerhq/device-management-kit"
|
|
48
|
+
import { webHidTransportFactory, WebHidTransport } from "@ledgerhq/device-transport-kit-web-hid"
|
|
49
|
+
|
|
50
|
+
// Easy setup with the factory
|
|
51
|
+
const dmk = new DeviceManagementKitBuilder()
|
|
52
|
+
.addTransport(webHidTransportFactory)
|
|
53
|
+
.build();
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
// With custom config
|
|
57
|
+
const dmk = new DeviceManagementKitBuilder()
|
|
58
|
+
.addTransport(({
|
|
59
|
+
deviceModelDataSource: DeviceModelDataSource;
|
|
60
|
+
loggerServiceFactory: (tag: string) => LoggerPublisherService;
|
|
61
|
+
config: DmkConfig;
|
|
62
|
+
apduSenderServiceFactory: ApduSenderServiceFactory;
|
|
63
|
+
apduReceiverServiceFactory: ApduReceiverServiceFactory;
|
|
64
|
+
}) => {
|
|
65
|
+
// custom code
|
|
66
|
+
return new WebHidTransport(
|
|
67
|
+
deviceModelDataSource,
|
|
68
|
+
loggerServiceFactory,
|
|
69
|
+
config,
|
|
70
|
+
apduSenderServiceFactory,
|
|
71
|
+
apduReceiverServiceFactory,
|
|
72
|
+
);
|
|
73
|
+
})
|
|
74
|
+
.build();
|
|
75
|
+
|
|
76
|
+
// You can then make use of the Device Management Kit
|
|
77
|
+
```
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{CommandUtils as g,ReconnectionFailedError as
|
|
1
|
+
import{CommandUtils as g,ReconnectionFailedError as h}from"@ledgerhq/device-management-kit";import{Left as s,Maybe as m,Nothing as d,Right as u}from"purify-ts";import{firstValueFrom as l,from as b,retry as _,Subject as p}from"rxjs";import{RECONNECT_DEVICE_TIMEOUT as f}from"../data/WebHidConfig";import{WebHidSendReportError as c}from"../model/Errors";class C{_device;_deviceId;_apduSender;_apduReceiver;_sendApduSubject=new p;_logger;_pendingApdu=d;_pendingApduSubscription=null;_onConnectionTerminated;reconnectionSubject=new p;waitingForReconnection=!1;lostConnectionTimeout=null;terminated=!1;constructor({device:t,deviceId:n,apduSender:o,apduReceiver:r,onConnectionTerminated:e},i){this._apduSender=o,this._apduReceiver=r,this._onConnectionTerminated=e,this._logger=i("WebHidDeviceConnection"),this._device=t,this._device.oninputreport=a=>this.receiveHidInputReport(a),this._deviceId=n,this._logger.info("\u{1F50C} Connected to device")}get device(){return this._device}get deviceId(){return this._deviceId}async sendApdu(t,n){this._sendApduSubject=new p,this._pendingApdu=m.of(t),this._logger.debug("Sending APDU",{data:{apdu:t},tag:"apdu-sender"});const o=new Promise(e=>{this._sendApduSubject.subscribe({next:async i=>{this._pendingApdu=d,n&&g.isSuccessResponse(i)?(await this.waitForReconnection()).caseOf({Left:v=>e(s(v)),Right:()=>e(u(i))}):e(u(i))},error:i=>{this._pendingApdu=d,e(s(i))}})});if(this.waitingForReconnection||!this.device.opened){const e=this.device.opened&&this._pendingApdu.isJust(),i=await this.waitForReconnection(e);if(i.isLeft())return i}const r=this._apduSender.getFrames(t);for(const e of r){this._logger.debug("Sending Frame",{data:{frame:e.getRawData()}});try{await l(b(this._device.sendReport(0,e.getRawData())).pipe(_({count:3,delay:500})))}catch(i){return this._logger.error("Error sending frame",{data:{error:i}}),Promise.resolve(s(new c(i)))}}return o}receiveHidInputReport(t){const n=new Uint8Array(t.data.buffer);this._logger.debug("Received Frame",{data:{frame:n},tag:"apdu-receiver"}),this._apduReceiver.handleFrame(n).caseOf({Right:r=>{r.map(e=>{this._logger.debug("Received APDU Response",{data:{response:e}}),this._sendApduSubject.next(e),this._sendApduSubject.complete()})},Left:r=>{this._sendApduSubject.error(r)}})}waitForReconnection(t=!1){return this.terminated?Promise.resolve(s(new h)):new Promise(n=>{const o=this.reconnectionSubject.subscribe({next:r=>{t&&(this._pendingApduSubscription?.unsubscribe(),this._sendApduSubject.error(new c(new Error("Device disconnected while waiting for device response")))),n(r==="success"?u(void 0):s(r)),o.unsubscribe()}})})}lostConnection(){this._logger.info("\u23F1\uFE0F Lost connection, starting timer"),this.waitingForReconnection=!0,this.lostConnectionTimeout=setTimeout(()=>{this._logger.info("\u274C Disconnection timeout, terminating connection"),this.disconnect()},f)}async reconnectHidDevice(t){this._device=t,this._device.oninputreport=n=>this.receiveHidInputReport(n),this.lostConnectionTimeout&&clearTimeout(this.lostConnectionTimeout),this._pendingApdu.isJust()&&this._sendApduSubject.error(new c),await t.open(),this._logger.info("\u23F1\uFE0F\u{1F50C} Device reconnected"),this.waitingForReconnection=!1,this.reconnectionSubject.next("success")}disconnect(){this._pendingApdu.isJust()&&this._sendApduSubject.error(new c),this._logger.info("\u{1F51A} Disconnect"),this.lostConnectionTimeout&&clearTimeout(this.lostConnectionTimeout),this.terminated=!0,this._onConnectionTerminated(),this.reconnectionSubject.next(new h)}}export{C as WebHidDeviceConnection};
|
|
2
2
|
//# sourceMappingURL=WebHidDeviceConnection.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/api/transport/WebHidDeviceConnection.ts"],
|
|
4
|
-
"sourcesContent": ["import {\n type ApduReceiverService,\n type ApduResponse,\n type ApduSenderService,\n CommandUtils,\n type DeviceConnection,\n type DeviceId,\n type DmkError,\n type LoggerPublisherService,\n ReconnectionFailedError,\n} from \"@ledgerhq/device-management-kit\";\nimport { type Either, Left, Maybe, Nothing, Right } from \"purify-ts\";\nimport { Subject } from \"rxjs\";\n\nimport { RECONNECT_DEVICE_TIMEOUT } from \"@api/data/WebHidConfig\";\nimport { WebHidSendReportError } from \"@api/model/Errors\";\n\ntype WebHidDeviceConnectionConstructorArgs = {\n device: HIDDevice;\n deviceId: DeviceId;\n apduSender: ApduSenderService;\n apduReceiver: ApduReceiverService;\n onConnectionTerminated: () => void;\n};\n\ntype Timer = ReturnType<typeof setTimeout>;\n\n/**\n * Class to manage the connection with a USB HID device.\n * It sends APDU commands to the device and receives the responses.\n * It handles temporary disconnections and reconnections.\n */\nexport class WebHidDeviceConnection implements DeviceConnection {\n private _device: HIDDevice;\n private _deviceId: DeviceId;\n private readonly _apduSender: ApduSenderService;\n private readonly _apduReceiver: ApduReceiverService;\n private _sendApduSubject: Subject<ApduResponse> = new Subject();\n private readonly _logger: LoggerPublisherService;\n private _pendingApdu: Maybe<Uint8Array> = Nothing;\n\n /** Callback to notify the connection termination */\n private _onConnectionTerminated: () => void;\n /** Subject to notify the reconnection status */\n private reconnectionSubject: Subject<\"success\" | DmkError> = new Subject();\n /** Flag to indicate if the connection is waiting for a reconnection */\n private waitingForReconnection = false;\n /** Timeout to wait for the device to reconnect */\n private lostConnectionTimeout: Timer | null = null;\n /**
|
|
5
|
-
"mappings": "AAAA,OAIE,gBAAAA,EAKA,2BAAAC,MACK,kCACP,OAAsB,QAAAC,EAAM,SAAAC,EAAO,WAAAC,EAAS,SAAAC,MAAa,YACzD,OAAS,WAAAC,
|
|
6
|
-
"names": ["CommandUtils", "ReconnectionFailedError", "Left", "Maybe", "Nothing", "Right", "Subject", "RECONNECT_DEVICE_TIMEOUT", "WebHidSendReportError", "WebHidDeviceConnection", "device", "deviceId", "apduSender", "apduReceiver", "onConnectionTerminated", "loggerServiceFactory", "event", "apdu", "triggersDisconnection", "resultPromise", "resolve", "r", "err", "waitingForDeviceResponse", "reconnectionRes", "frames", "frame", "error", "
|
|
4
|
+
"sourcesContent": ["import {\n type ApduReceiverService,\n type ApduResponse,\n type ApduSenderService,\n CommandUtils,\n type DeviceConnection,\n type DeviceId,\n type DmkError,\n type LoggerPublisherService,\n ReconnectionFailedError,\n} from \"@ledgerhq/device-management-kit\";\nimport { type Either, Left, Maybe, Nothing, Right } from \"purify-ts\";\nimport { firstValueFrom, from, retry, Subject, type Subscription } from \"rxjs\";\n\nimport { RECONNECT_DEVICE_TIMEOUT } from \"@api/data/WebHidConfig\";\nimport { WebHidSendReportError } from \"@api/model/Errors\";\n\ntype WebHidDeviceConnectionConstructorArgs = {\n device: HIDDevice;\n deviceId: DeviceId;\n apduSender: ApduSenderService;\n apduReceiver: ApduReceiverService;\n onConnectionTerminated: () => void;\n};\n\ntype Timer = ReturnType<typeof setTimeout>;\n\n/**\n * Class to manage the connection with a USB HID device.\n * It sends APDU commands to the device and receives the responses.\n * It handles temporary disconnections and reconnections.\n */\nexport class WebHidDeviceConnection implements DeviceConnection {\n private _device: HIDDevice;\n private _deviceId: DeviceId;\n private readonly _apduSender: ApduSenderService;\n private readonly _apduReceiver: ApduReceiverService;\n private _sendApduSubject: Subject<ApduResponse> = new Subject();\n private readonly _logger: LoggerPublisherService;\n private _pendingApdu: Maybe<Uint8Array> = Nothing;\n private _pendingApduSubscription: Subscription | null = null;\n\n /** Callback to notify the connection termination */\n private _onConnectionTerminated: () => void;\n /** Subject to notify the reconnection status */\n private reconnectionSubject: Subject<\"success\" | DmkError> = new Subject();\n /** Flag to indicate if the connection is waiting for a reconnection */\n private waitingForReconnection = false;\n /** Timeout to wait for the device to reconnect */\n private lostConnectionTimeout: Timer | null = null;\n /** Flag to indicate if the connection is terminated */\n private terminated = false;\n\n constructor(\n {\n device,\n deviceId,\n apduSender,\n apduReceiver,\n onConnectionTerminated,\n }: WebHidDeviceConnectionConstructorArgs,\n loggerServiceFactory: (tag: string) => LoggerPublisherService,\n ) {\n this._apduSender = apduSender;\n this._apduReceiver = apduReceiver;\n this._onConnectionTerminated = onConnectionTerminated;\n this._logger = loggerServiceFactory(\"WebHidDeviceConnection\");\n this._device = device;\n this._device.oninputreport = (event) => this.receiveHidInputReport(event);\n this._deviceId = deviceId;\n this._logger.info(\"\uD83D\uDD0C Connected to device\");\n }\n\n public get device() {\n return this._device;\n }\n\n public get deviceId() {\n return this._deviceId;\n }\n\n async sendApdu(\n apdu: Uint8Array,\n triggersDisconnection?: boolean,\n ): Promise<Either<DmkError, ApduResponse>> {\n this._sendApduSubject = new Subject();\n this._pendingApdu = Maybe.of(apdu);\n this._logger.debug(\"Sending APDU\", {\n data: { apdu },\n tag: \"apdu-sender\",\n });\n\n const resultPromise = new Promise<Either<DmkError, ApduResponse>>(\n (resolve) => {\n this._sendApduSubject.subscribe({\n next: async (r) => {\n this._pendingApdu = Nothing;\n if (triggersDisconnection && CommandUtils.isSuccessResponse(r)) {\n // Anticipate the disconnection and wait for the reconnection before resolving\n const reconnectionRes = await this.waitForReconnection();\n reconnectionRes.caseOf({\n Left: (err) => resolve(Left(err)),\n Right: () => resolve(Right(r)),\n });\n } else {\n resolve(Right(r));\n }\n },\n error: (err) => {\n this._pendingApdu = Nothing;\n resolve(Left(err));\n },\n });\n },\n );\n\n if (this.waitingForReconnection || !this.device.opened) {\n const waitingForDeviceResponse =\n this.device.opened && this._pendingApdu.isJust();\n const reconnectionRes = await this.waitForReconnection(\n waitingForDeviceResponse,\n );\n if (reconnectionRes.isLeft()) {\n return reconnectionRes;\n }\n }\n\n const frames = this._apduSender.getFrames(apdu);\n for (const frame of frames) {\n this._logger.debug(\"Sending Frame\", {\n data: { frame: frame.getRawData() },\n });\n\n try {\n // const p = new Promise((resolve, reject) => {\n // this._pendingApduSubscription = from(\n // this._device.sendReport(0, frame.getRawData()),\n // )\n // .pipe(\n // retry({\n // count: 3,\n // delay: 500,\n // }),\n // )\n // .subscribe({\n // next: resolve,\n // error: reject,\n // });\n // });\n\n // await p;\n\n await firstValueFrom(\n from(this._device.sendReport(0, frame.getRawData())).pipe(\n retry({\n count: 3,\n delay: 500,\n }),\n ),\n );\n } catch (error) {\n this._logger.error(\"Error sending frame\", { data: { error } });\n return Promise.resolve(Left(new WebHidSendReportError(error)));\n }\n }\n\n return resultPromise;\n }\n\n private receiveHidInputReport(event: HIDInputReportEvent) {\n const data = new Uint8Array(event.data.buffer);\n this._logger.debug(\"Received Frame\", {\n data: { frame: data },\n tag: \"apdu-receiver\",\n });\n const response = this._apduReceiver.handleFrame(data);\n response.caseOf({\n Right: (maybeApduResponse) => {\n maybeApduResponse.map((apduResponse) => {\n this._logger.debug(\"Received APDU Response\", {\n data: { response: apduResponse },\n });\n this._sendApduSubject.next(apduResponse);\n this._sendApduSubject.complete();\n });\n },\n Left: (err) => {\n this._sendApduSubject.error(err);\n },\n });\n }\n\n private waitForReconnection(\n waitingForDeviceResponse: boolean = false,\n ): Promise<Either<DmkError, void>> {\n if (this.terminated) {\n return Promise.resolve(Left(new ReconnectionFailedError()));\n }\n\n return new Promise<Either<DmkError, void>>((resolve) => {\n const sub = this.reconnectionSubject.subscribe({\n next: (res) => {\n if (waitingForDeviceResponse) {\n this._pendingApduSubscription?.unsubscribe();\n this._sendApduSubject.error(\n new WebHidSendReportError(\n new Error(\n \"Device disconnected while waiting for device response\",\n ),\n ),\n );\n }\n\n if (res === \"success\") {\n resolve(Right(undefined));\n } else {\n resolve(Left(res));\n }\n\n sub.unsubscribe();\n },\n });\n });\n }\n\n /**\n * Method called when the HIDDevice gets disconnected.\n * It starts a timeout to wait for the device to reconnect.\n * */\n public lostConnection() {\n this._logger.info(\"\u23F1\uFE0F Lost connection, starting timer\");\n this.waitingForReconnection = true;\n this.lostConnectionTimeout = setTimeout(() => {\n this._logger.info(\"\u274C Disconnection timeout, terminating connection\");\n this.disconnect();\n }, RECONNECT_DEVICE_TIMEOUT);\n }\n\n /** Reconnect the device after a disconnection */\n public async reconnectHidDevice(device: HIDDevice) {\n this._device = device;\n this._device.oninputreport = (event) => this.receiveHidInputReport(event);\n\n if (this.lostConnectionTimeout) {\n clearTimeout(this.lostConnectionTimeout);\n }\n\n if (this._pendingApdu.isJust()) {\n this._sendApduSubject.error(new WebHidSendReportError());\n }\n\n await device.open();\n\n this._logger.info(\"\u23F1\uFE0F\uD83D\uDD0C Device reconnected\");\n this.waitingForReconnection = false;\n this.reconnectionSubject.next(\"success\");\n }\n\n public disconnect() {\n if (this._pendingApdu.isJust()) {\n this._sendApduSubject.error(new WebHidSendReportError());\n }\n\n this._logger.info(\"\uD83D\uDD1A Disconnect\");\n if (this.lostConnectionTimeout) clearTimeout(this.lostConnectionTimeout);\n this.terminated = true;\n this._onConnectionTerminated();\n this.reconnectionSubject.next(new ReconnectionFailedError());\n }\n}\n"],
|
|
5
|
+
"mappings": "AAAA,OAIE,gBAAAA,EAKA,2BAAAC,MACK,kCACP,OAAsB,QAAAC,EAAM,SAAAC,EAAO,WAAAC,EAAS,SAAAC,MAAa,YACzD,OAAS,kBAAAC,EAAgB,QAAAC,EAAM,SAAAC,EAAO,WAAAC,MAAkC,OAExE,OAAS,4BAAAC,MAAgC,yBACzC,OAAS,yBAAAC,MAA6B,oBAiB/B,MAAMC,CAAmD,CACtD,QACA,UACS,YACA,cACT,iBAA0C,IAAIH,EACrC,QACT,aAAkCL,EAClC,yBAAgD,KAGhD,wBAEA,oBAAqD,IAAIK,EAEzD,uBAAyB,GAEzB,sBAAsC,KAEtC,WAAa,GAErB,YACE,CACE,OAAAI,EACA,SAAAC,EACA,WAAAC,EACA,aAAAC,EACA,uBAAAC,CACF,EACAC,EACA,CACA,KAAK,YAAcH,EACnB,KAAK,cAAgBC,EACrB,KAAK,wBAA0BC,EAC/B,KAAK,QAAUC,EAAqB,wBAAwB,EAC5D,KAAK,QAAUL,EACf,KAAK,QAAQ,cAAiBM,GAAU,KAAK,sBAAsBA,CAAK,EACxE,KAAK,UAAYL,EACjB,KAAK,QAAQ,KAAK,+BAAwB,CAC5C,CAEA,IAAW,QAAS,CAClB,OAAO,KAAK,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AAmB,CACjD,KAAK,QAAUA,EACf,KAAK,QAAQ,cAAiBM,GAAU,KAAK,sBAAsBA,CAAK,EAEpE,KAAK,uBACP,aAAa,KAAK,qBAAqB,EAGrC,KAAK,aAAa,OAAO,GAC3B,KAAK,iBAAiB,MAAM,IAAIR,CAAuB,EAGzD,MAAME,EAAO,KAAK,EAElB,KAAK,QAAQ,KAAK,0CAAyB,EAC3C,KAAK,uBAAyB,GAC9B,KAAK,oBAAoB,KAAK,SAAS,CACzC,CAEO,YAAa,CACd,KAAK,aAAa,OAAO,GAC3B,KAAK,iBAAiB,MAAM,IAAIF,CAAuB,EAGzD,KAAK,QAAQ,KAAK,sBAAe,EAC7B,KAAK,uBAAuB,aAAa,KAAK,qBAAqB,EACvE,KAAK,WAAa,GAClB,KAAK,wBAAwB,EAC7B,KAAK,oBAAoB,KAAK,IAAIV,CAAyB,CAC7D,CACF",
|
|
6
|
+
"names": ["CommandUtils", "ReconnectionFailedError", "Left", "Maybe", "Nothing", "Right", "firstValueFrom", "from", "retry", "Subject", "RECONNECT_DEVICE_TIMEOUT", "WebHidSendReportError", "WebHidDeviceConnection", "device", "deviceId", "apduSender", "apduReceiver", "onConnectionTerminated", "loggerServiceFactory", "event", "apdu", "triggersDisconnection", "resultPromise", "resolve", "r", "err", "waitingForDeviceResponse", "reconnectionRes", "frames", "frame", "error", "data", "maybeApduResponse", "apduResponse", "sub", "res"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{defaultApduReceiverServiceStubBuilder as A,defaultApduSenderServiceStubBuilder as y,ReconnectionFailedError as
|
|
1
|
+
import{defaultApduReceiverServiceStubBuilder as A,defaultApduSenderServiceStubBuilder as y,ReconnectionFailedError as v}from"@ledgerhq/device-management-kit";import{Left as l,Right as w}from"purify-ts";import{RECONNECT_DEVICE_TIMEOUT as m}from"../data/WebHidConfig";import{WebHidSendReportError as h}from"../model/Errors";import{hidDeviceStubBuilder as b}from"../model/HIDDevice.stub";import{WebHidDeviceConnection as c}from"./WebHidDeviceConnection";jest.useFakeTimers();const S=new Uint8Array([170,170,5,0,0,0,2,85,21,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),p=new Uint8Array([170,170,5,0,0,0,2,144,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);class g{tag;constructor(r,o){this.subscribers=r,this.tag=o}subscribers=[];error=jest.fn();warn=jest.fn();debug=jest.fn();info=jest.fn()}const x=()=>new Promise(jest.requireActual("timers").setImmediate);jest.useFakeTimers();describe("WebHidDeviceConnection",()=>{let e,r,o;const s=()=>{},a="test-device-id",i=t=>new g([],t);beforeEach(()=>{e=b({opened:!0}),r=y(void 0,i),o=A(void 0,i)}),it("should get device",()=>{const n=new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:s,deviceId:a},i).device;expect(n).toStrictEqual(e)}),it("should send APDU through hid report",()=>{new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:s,deviceId:a},i).sendApdu(new Uint8Array(0)),expect(e.sendReport).toHaveBeenCalled()}),it("should receive APDU through hid report",async()=>{e.sendReport=jest.fn(()=>Promise.resolve(e.oninputreport({type:"inputreport",data:new DataView(Uint8Array.from(p).buffer)})));const n=await new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:s,deviceId:a},i).sendApdu(Uint8Array.from([]));expect(n).toEqual(w({statusCode:new Uint8Array([144,0]),data:new Uint8Array([])}))}),describe("anticipating loss of connection after sending an APDU",()=>{it("sendApdu(whatever, true) should wait for reconnection before resolving if the response is a success",async()=>{e.sendReport=jest.fn(()=>Promise.resolve(e.oninputreport({type:"inputreport",data:new DataView(Uint8Array.from(p).buffer)})));const t=new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:s,deviceId:a},i);let n=!1;const d=t.sendApdu(Uint8Array.from([]),!0).then(f=>(n=!0,f));t.lostConnection(),await x(),expect(n).toBe(!1),t.reconnectHidDevice(e),await x(),expect(n).toBe(!0);const u=await d;expect(u).toEqual(w({statusCode:new Uint8Array([144,0]),data:new Uint8Array([])}))}),it("sendApdu(whatever, true) should not wait for reconnection if the response is not a success",async()=>{e.sendReport=jest.fn(()=>Promise.resolve(e.oninputreport({type:"inputreport",data:new DataView(Uint8Array.from(S).buffer)})));const n=await new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:s,deviceId:a},i).sendApdu(Uint8Array.from([]),!0);expect(n).toEqual(w({statusCode:new Uint8Array([85,21]),data:new Uint8Array([])}))}),it("sendApdu(whatever, true) should return an error if the device gets disconnected while waiting for reconnection",async()=>{e.sendReport=jest.fn(()=>Promise.resolve(e.oninputreport({type:"inputreport",data:new DataView(Uint8Array.from(p).buffer)})));const t=new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:s,deviceId:a},i),n=t.sendApdu(Uint8Array.from([]),!0);t.lostConnection(),jest.advanceTimersByTime(m),await x();const d=await n;expect(d).toEqual(l(new v))})}),describe("connection lost before sending an APDU",()=>{it("sendApdu(whatever, false) should return an error if the device connection has been lost and times out",async()=>{e.sendReport=jest.fn(()=>Promise.resolve(e.oninputreport({type:"inputreport",data:new DataView(Uint8Array.from(p).buffer)})));const t=new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:s,deviceId:a},i);t.lostConnection(),jest.advanceTimersByTime(m),await x();const n=await t.sendApdu(Uint8Array.from([]),!1);await x(),expect(n).toEqual(l(new v))}),it("sendApdu(whatever, false) should wait for reconnection to resolve",async()=>{e.sendReport=jest.fn(()=>Promise.resolve(e.oninputreport({type:"inputreport",data:new DataView(Uint8Array.from(p).buffer)})));const t=new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:s,deviceId:a},i);t.lostConnection();let n=!1;const d=t.sendApdu(Uint8Array.from([]),!1).then(f=>(n=!0,f));await x(),expect(n).toBe(!1),t.reconnectHidDevice(e),await x(),expect(n).toBe(!0);const u=await d;expect(u).toEqual(l(new h(new Error("Device disconnected while waiting for device response"))))})})});
|
|
2
2
|
//# sourceMappingURL=WebHidDeviceConnection.test.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/api/transport/WebHidDeviceConnection.test.ts"],
|
|
4
|
-
"sourcesContent": ["import {\n type ApduReceiverService,\n type ApduSenderService,\n defaultApduReceiverServiceStubBuilder,\n defaultApduSenderServiceStubBuilder,\n type DeviceId,\n type LoggerPublisherService,\n type LoggerSubscriberService,\n ReconnectionFailedError,\n} from \"@ledgerhq/device-management-kit\";\nimport { Left, Right } from \"purify-ts\";\n\nimport { RECONNECT_DEVICE_TIMEOUT } from \"@api/data/WebHidConfig\";\nimport { hidDeviceStubBuilder } from \"@api/model/HIDDevice.stub\";\n\nimport { WebHidDeviceConnection } from \"./WebHidDeviceConnection\";\n\njest.useFakeTimers();\n\nconst RESPONSE_LOCKED_DEVICE = new Uint8Array([\n 0xaa, 0xaa, 0x05, 0x00, 0x00, 0x00, 0x02, 0x55, 0x15, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n]);\n\nconst RESPONSE_SUCCESS = new Uint8Array([\n 0xaa, 0xaa, 0x05, 0x00, 0x00, 0x00, 0x02, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n]);\n\nclass LoggerPublisherServiceStub implements LoggerPublisherService {\n tag: string;\n constructor(subscribers: LoggerSubscriberService[], tag: string) {\n this.subscribers = subscribers;\n this.tag = tag;\n }\n subscribers: LoggerSubscriberService[] = [];\n error = jest.fn();\n warn = jest.fn();\n debug = jest.fn();\n info = jest.fn();\n}\n\n/**\n * Flushes all pending promises\n */\nconst flushPromises = () =>\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n new Promise(jest.requireActual(\"timers\").setImmediate);\n\njest.useFakeTimers();\n\ndescribe(\"WebHidDeviceConnection\", () => {\n let device: HIDDevice;\n let apduSender: ApduSenderService;\n let apduReceiver: ApduReceiverService;\n const onConnectionTerminated = () => {};\n const deviceId: DeviceId = \"test-device-id\";\n const logger = (tag: string) => new LoggerPublisherServiceStub([], tag);\n\n beforeEach(() => {\n device = hidDeviceStubBuilder({ opened: true });\n apduSender = defaultApduSenderServiceStubBuilder(undefined, logger);\n apduReceiver = defaultApduReceiverServiceStubBuilder(undefined, logger);\n });\n\n it(\"should get device\", () => {\n // given\n const connection = new WebHidDeviceConnection(\n { device, apduSender, apduReceiver, onConnectionTerminated, deviceId },\n logger,\n );\n // when\n const cDevice = connection.device;\n // then\n expect(cDevice).toStrictEqual(device);\n });\n\n it(\"should send APDU through hid report\", () => {\n // given\n const connection = new WebHidDeviceConnection(\n { device, apduSender, apduReceiver, onConnectionTerminated, deviceId },\n logger,\n );\n // when\n connection.sendApdu(new Uint8Array(0));\n // then\n expect(device.sendReport).toHaveBeenCalled();\n });\n\n it(\"should receive APDU through hid report\", async () => {\n // given\n device.sendReport = jest.fn(() =>\n Promise.resolve(\n device.oninputreport!({\n type: \"inputreport\",\n data: new DataView(Uint8Array.from(RESPONSE_SUCCESS).buffer),\n } as HIDInputReportEvent),\n ),\n );\n const connection = new WebHidDeviceConnection(\n { device, apduSender, apduReceiver, onConnectionTerminated, deviceId },\n logger,\n );\n // when\n const response = await connection.sendApdu(Uint8Array.from([]));\n // then\n expect(response).toEqual(\n Right({\n statusCode: new Uint8Array([0x90, 0x00]),\n data: new Uint8Array([]),\n }),\n );\n });\n\n describe(\"anticipating loss of connection after sending an APDU\", () => {\n
|
|
5
|
-
"mappings": "AAAA,OAGE,yCAAAA,EACA,uCAAAC,EAIA,2BAAAC,MACK,kCACP,OAAS,QAAAC,EAAM,SAAAC,MAAa,YAE5B,OAAS,4BAAAC,MAAgC,yBACzC,OAAS,wBAAAC,MAA4B,4BAErC,OAAS,0BAAAC,MAA8B,2BAEvC,KAAK,cAAc,EAEnB,MAAMC,EAAyB,IAAI,WAAW,CAC5C,IAAM,IAAM,EAAM,EAAM,EAAM,EAAM,EAAM,GAAM,GAAM,EAAM,EAAM,EAAM,EACxE,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EACxE,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EACxE,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EACxE,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,CAClD,CAAC,EAEKC,EAAmB,IAAI,WAAW,CACtC,IAAM,IAAM,EAAM,EAAM,EAAM,EAAM,EAAM,IAAM,EAAM,EAAM,EAAM,EAAM,EACxE,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EACxE,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EACxE,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EACxE,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,CAClD,CAAC,EAED,MAAMC,CAA6D,CACjE,IACA,YAAYC,EAAwCC,EAAa,CAC/D,KAAK,YAAcD,EACnB,KAAK,IAAMC,CACb,CACA,YAAyC,CAAC,EAC1C,MAAQ,KAAK,GAAG,EAChB,KAAO,KAAK,GAAG,EACf,MAAQ,KAAK,GAAG,EAChB,KAAO,KAAK,GAAG,CACjB,CAKA,MAAMC,EAAgB,IAEpB,IAAI,QAAQ,KAAK,cAAc,QAAQ,EAAE,YAAY,EAEvD,KAAK,cAAc,EAEnB,SAAS,yBAA0B,IAAM,CACvC,IAAIC,EACAC,EACAC,EACJ,MAAMC,EAAyB,IAAM,CAAC,EAChCC,EAAqB,iBACrBC,EAAUP,GAAgB,IAAIF,EAA2B,CAAC,EAAGE,CAAG,EAEtE,WAAW,IAAM,CACfE,EAASR,EAAqB,CAAE,OAAQ,EAAK,CAAC,EAC9CS,
|
|
6
|
-
"names": ["defaultApduReceiverServiceStubBuilder", "defaultApduSenderServiceStubBuilder", "ReconnectionFailedError", "Left", "Right", "RECONNECT_DEVICE_TIMEOUT", "hidDeviceStubBuilder", "WebHidDeviceConnection", "RESPONSE_LOCKED_DEVICE", "RESPONSE_SUCCESS", "LoggerPublisherServiceStub", "subscribers", "tag", "flushPromises", "device", "apduSender", "apduReceiver", "onConnectionTerminated", "deviceId", "logger", "cDevice", "response", "connection", "hasResolved", "responsePromise"]
|
|
4
|
+
"sourcesContent": ["import {\n type ApduReceiverService,\n type ApduSenderService,\n defaultApduReceiverServiceStubBuilder,\n defaultApduSenderServiceStubBuilder,\n type DeviceId,\n type LoggerPublisherService,\n type LoggerSubscriberService,\n ReconnectionFailedError,\n} from \"@ledgerhq/device-management-kit\";\nimport { Left, Right } from \"purify-ts\";\n\nimport { RECONNECT_DEVICE_TIMEOUT } from \"@api/data/WebHidConfig\";\nimport { WebHidSendReportError } from \"@api/model/Errors\";\nimport { hidDeviceStubBuilder } from \"@api/model/HIDDevice.stub\";\n\nimport { WebHidDeviceConnection } from \"./WebHidDeviceConnection\";\n\njest.useFakeTimers();\n\nconst RESPONSE_LOCKED_DEVICE = new Uint8Array([\n 0xaa, 0xaa, 0x05, 0x00, 0x00, 0x00, 0x02, 0x55, 0x15, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n]);\n\nconst RESPONSE_SUCCESS = new Uint8Array([\n 0xaa, 0xaa, 0x05, 0x00, 0x00, 0x00, 0x02, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n]);\n\nclass LoggerPublisherServiceStub implements LoggerPublisherService {\n tag: string;\n constructor(subscribers: LoggerSubscriberService[], tag: string) {\n this.subscribers = subscribers;\n this.tag = tag;\n }\n subscribers: LoggerSubscriberService[] = [];\n error = jest.fn();\n warn = jest.fn();\n debug = jest.fn();\n info = jest.fn();\n}\n\n/**\n * Flushes all pending promises\n */\nconst flushPromises = () =>\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n new Promise(jest.requireActual(\"timers\").setImmediate);\n\njest.useFakeTimers();\n\ndescribe(\"WebHidDeviceConnection\", () => {\n let device: HIDDevice;\n let apduSender: ApduSenderService;\n let apduReceiver: ApduReceiverService;\n const onConnectionTerminated = () => {};\n const deviceId: DeviceId = \"test-device-id\";\n const logger = (tag: string) => new LoggerPublisherServiceStub([], tag);\n\n beforeEach(() => {\n device = hidDeviceStubBuilder({ opened: true });\n apduSender = defaultApduSenderServiceStubBuilder(undefined, logger);\n apduReceiver = defaultApduReceiverServiceStubBuilder(undefined, logger);\n });\n\n it(\"should get device\", () => {\n // given\n const connection = new WebHidDeviceConnection(\n { device, apduSender, apduReceiver, onConnectionTerminated, deviceId },\n logger,\n );\n // when\n const cDevice = connection.device;\n // then\n expect(cDevice).toStrictEqual(device);\n });\n\n it(\"should send APDU through hid report\", () => {\n // given\n const connection = new WebHidDeviceConnection(\n { device, apduSender, apduReceiver, onConnectionTerminated, deviceId },\n logger,\n );\n // when\n connection.sendApdu(new Uint8Array(0));\n // then\n expect(device.sendReport).toHaveBeenCalled();\n });\n\n it(\"should receive APDU through hid report\", async () => {\n // given\n device.sendReport = jest.fn(() =>\n Promise.resolve(\n device.oninputreport!({\n type: \"inputreport\",\n data: new DataView(Uint8Array.from(RESPONSE_SUCCESS).buffer),\n } as HIDInputReportEvent),\n ),\n );\n const connection = new WebHidDeviceConnection(\n { device, apduSender, apduReceiver, onConnectionTerminated, deviceId },\n logger,\n );\n // when\n const response = await connection.sendApdu(Uint8Array.from([]));\n // then\n expect(response).toEqual(\n Right({\n statusCode: new Uint8Array([0x90, 0x00]),\n data: new Uint8Array([]),\n }),\n );\n });\n\n describe(\"anticipating loss of connection after sending an APDU\", () => {\n it(\"sendApdu(whatever, true) should wait for reconnection before resolving if the response is a success\", async () => {\n // given\n device.sendReport = jest.fn(() =>\n Promise.resolve(\n device.oninputreport!({\n type: \"inputreport\",\n data: new DataView(Uint8Array.from(RESPONSE_SUCCESS).buffer),\n } as HIDInputReportEvent),\n ),\n );\n\n const connection = new WebHidDeviceConnection(\n { device, apduSender, apduReceiver, onConnectionTerminated, deviceId },\n logger,\n );\n\n let hasResolved = false;\n\n const responsePromise = connection\n .sendApdu(Uint8Array.from([]), true)\n .then((response) => {\n hasResolved = true;\n return response;\n });\n\n connection.lostConnection();\n\n // before reconnecting\n await flushPromises();\n expect(hasResolved).toBe(false);\n\n // when reconnecting\n connection.reconnectHidDevice(device);\n await flushPromises();\n expect(hasResolved).toBe(true);\n\n const response = await responsePromise;\n\n expect(response).toEqual(\n Right({\n statusCode: new Uint8Array([0x90, 0x00]),\n data: new Uint8Array([]),\n }),\n );\n });\n\n it(\"sendApdu(whatever, true) should not wait for reconnection if the response is not a success\", async () => {\n // given\n device.sendReport = jest.fn(() =>\n Promise.resolve(\n device.oninputreport!({\n type: \"inputreport\",\n data: new DataView(Uint8Array.from(RESPONSE_LOCKED_DEVICE).buffer),\n } as HIDInputReportEvent),\n ),\n );\n const connection = new WebHidDeviceConnection(\n { device, apduSender, apduReceiver, onConnectionTerminated, deviceId },\n logger,\n );\n\n // when\n const response = await connection.sendApdu(Uint8Array.from([]), true);\n\n // then\n expect(response).toEqual(\n Right({\n statusCode: new Uint8Array([0x55, 0x15]),\n data: new Uint8Array([]),\n }),\n );\n });\n\n it(\"sendApdu(whatever, true) should return an error if the device gets disconnected while waiting for reconnection\", async () => {\n // given\n device.sendReport = jest.fn(() =>\n Promise.resolve(\n device.oninputreport!({\n type: \"inputreport\",\n data: new DataView(Uint8Array.from(RESPONSE_SUCCESS).buffer),\n } as HIDInputReportEvent),\n ),\n );\n const connection = new WebHidDeviceConnection(\n { device, apduSender, apduReceiver, onConnectionTerminated, deviceId },\n logger,\n );\n\n const responsePromise = connection.sendApdu(Uint8Array.from([]), true);\n\n // when disconnecting\n connection.lostConnection();\n jest.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT);\n await flushPromises();\n\n // then\n const response = await responsePromise;\n expect(response).toEqual(Left(new ReconnectionFailedError()));\n });\n });\n\n describe(\"connection lost before sending an APDU\", () => {\n it(\"sendApdu(whatever, false) should return an error if the device connection has been lost and times out\", async () => {\n // given\n device.sendReport = jest.fn(() =>\n Promise.resolve(\n device.oninputreport!({\n type: \"inputreport\",\n data: new DataView(Uint8Array.from(RESPONSE_SUCCESS).buffer),\n } as HIDInputReportEvent),\n ),\n );\n const connection = new WebHidDeviceConnection(\n { device, apduSender, apduReceiver, onConnectionTerminated, deviceId },\n logger,\n );\n\n // when losing connection\n connection.lostConnection();\n jest.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT);\n await flushPromises();\n\n // then\n const response = await connection.sendApdu(Uint8Array.from([]), false);\n await flushPromises();\n expect(response).toEqual(Left(new ReconnectionFailedError()));\n });\n\n it(\"sendApdu(whatever, false) should wait for reconnection to resolve\", async () => {\n // given\n device.sendReport = jest.fn(() =>\n Promise.resolve(\n device.oninputreport!({\n type: \"inputreport\",\n data: new DataView(Uint8Array.from(RESPONSE_SUCCESS).buffer),\n } as HIDInputReportEvent),\n ),\n );\n const connection = new WebHidDeviceConnection(\n { device, apduSender, apduReceiver, onConnectionTerminated, deviceId },\n logger,\n );\n\n // when losing connection\n connection.lostConnection();\n\n let hasResolved = false;\n const responsePromise = connection\n .sendApdu(Uint8Array.from([]), false)\n .then((response) => {\n hasResolved = true;\n return response;\n });\n\n // before reconnecting\n await flushPromises();\n expect(hasResolved).toBe(false);\n\n // when reconnecting\n connection.reconnectHidDevice(device);\n await flushPromises();\n expect(hasResolved).toBe(true);\n\n const response = await responsePromise;\n\n expect(response).toEqual(\n Left(\n new WebHidSendReportError(\n new Error(\"Device disconnected while waiting for device response\"),\n ),\n ),\n );\n });\n });\n});\n"],
|
|
5
|
+
"mappings": "AAAA,OAGE,yCAAAA,EACA,uCAAAC,EAIA,2BA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,QAAQnB,EAAK,IAAID,CAAyB,CAAC,CAC9D,CAAC,EAED,GAAG,oEAAqE,SAAY,CAElFa,EAAO,WAAa,KAAK,GAAG,IAC1B,QAAQ,QACNA,EAAO,cAAe,CACpB,KAAM,cACN,KAAM,IAAI,SAAS,WAAW,KAAKL,CAAgB,EAAE,MAAM,CAC7D,CAAwB,CAC1B,CACF,EACA,MAAMa,EAAa,IAAIf,EACrB,CAAE,OAAAO,EAAQ,WAAAC,EAAY,aAAAC,EAAc,uBAAAC,EAAwB,SAAAC,CAAS,EACrEC,CACF,EAGAG,EAAW,eAAe,EAE1B,IAAIC,EAAc,GAClB,MAAMC,EAAkBF,EACrB,SAAS,WAAW,KAAK,CAAC,CAAC,EAAG,EAAK,EACnC,KAAMD,IACLE,EAAc,GACPF,EACR,EAGH,MAAMR,EAAc,EACpB,OAAOU,CAAW,EAAE,KAAK,EAAK,EAG9BD,EAAW,mBAAmBR,CAAM,EACpC,MAAMD,EAAc,EACpB,OAAOU,CAAW,EAAE,KAAK,EAAI,EAE7B,MAAMF,EAAW,MAAMG,EAEvB,OAAOH,CAAQ,EAAE,QACfnB,EACE,IAAIG,EACF,IAAI,MAAM,uDAAuD,CACnE,CACF,CACF,CACF,CAAC,CACH,CAAC,CACH,CAAC",
|
|
6
|
+
"names": ["defaultApduReceiverServiceStubBuilder", "defaultApduSenderServiceStubBuilder", "ReconnectionFailedError", "Left", "Right", "RECONNECT_DEVICE_TIMEOUT", "WebHidSendReportError", "hidDeviceStubBuilder", "WebHidDeviceConnection", "RESPONSE_LOCKED_DEVICE", "RESPONSE_SUCCESS", "LoggerPublisherServiceStub", "subscribers", "tag", "flushPromises", "device", "apduSender", "apduReceiver", "onConnectionTerminated", "deviceId", "logger", "cDevice", "response", "connection", "hasResolved", "responsePromise"]
|
|
7
7
|
}
|
package/lib/esm/package.json
CHANGED
|
@@ -20,6 +20,7 @@ export declare class WebHidDeviceConnection implements DeviceConnection {
|
|
|
20
20
|
private _sendApduSubject;
|
|
21
21
|
private readonly _logger;
|
|
22
22
|
private _pendingApdu;
|
|
23
|
+
private _pendingApduSubscription;
|
|
23
24
|
/** Callback to notify the connection termination */
|
|
24
25
|
private _onConnectionTerminated;
|
|
25
26
|
/** Subject to notify the reconnection status */
|
|
@@ -28,15 +29,12 @@ export declare class WebHidDeviceConnection implements DeviceConnection {
|
|
|
28
29
|
private waitingForReconnection;
|
|
29
30
|
/** Timeout to wait for the device to reconnect */
|
|
30
31
|
private lostConnectionTimeout;
|
|
31
|
-
/** Timestamp when the device was reconnected */
|
|
32
|
-
private timeOfReconnection;
|
|
33
32
|
/** Flag to indicate if the connection is terminated */
|
|
34
33
|
private terminated;
|
|
35
34
|
constructor({ device, deviceId, apduSender, apduReceiver, onConnectionTerminated, }: WebHidDeviceConnectionConstructorArgs, loggerServiceFactory: (tag: string) => LoggerPublisherService);
|
|
36
35
|
get device(): HIDDevice;
|
|
37
36
|
get deviceId(): string;
|
|
38
37
|
sendApdu(apdu: Uint8Array, triggersDisconnection?: boolean): Promise<Either<DmkError, ApduResponse>>;
|
|
39
|
-
private waitUntilDeviceIsReady;
|
|
40
38
|
private receiveHidInputReport;
|
|
41
39
|
private waitForReconnection;
|
|
42
40
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WebHidDeviceConnection.d.ts","sourceRoot":"","sources":["../../../../src/api/transport/WebHidDeviceConnection.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,mBAAmB,EACxB,KAAK,YAAY,EACjB,KAAK,iBAAiB,EAEtB,KAAK,gBAAgB,EACrB,KAAK,QAAQ,EACb,KAAK,QAAQ,EACb,KAAK,sBAAsB,EAE5B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,KAAK,MAAM,EAA+B,MAAM,WAAW,CAAC;AAMrE,KAAK,qCAAqC,GAAG;IAC3C,MAAM,EAAE,SAAS,CAAC;IAClB,QAAQ,EAAE,QAAQ,CAAC;IACnB,UAAU,EAAE,iBAAiB,C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