@ledgerhq/device-transport-kit-web-hid 0.0.0-develop-20241219141541
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/LICENSE.MD +202 -0
- package/lib/esm/api/data/WebHidConfig.js +2 -0
- package/lib/esm/api/data/WebHidConfig.js.map +7 -0
- package/lib/esm/api/index.js +2 -0
- package/lib/esm/api/index.js.map +7 -0
- package/lib/esm/api/model/Errors.js +2 -0
- package/lib/esm/api/model/Errors.js.map +7 -0
- package/lib/esm/api/model/HIDDevice.stub.js +2 -0
- package/lib/esm/api/model/HIDDevice.stub.js.map +7 -0
- package/lib/esm/api/transport/WebHidDeviceConnection.js +2 -0
- package/lib/esm/api/transport/WebHidDeviceConnection.js.map +7 -0
- package/lib/esm/api/transport/WebHidDeviceConnection.stub.js +2 -0
- package/lib/esm/api/transport/WebHidDeviceConnection.stub.js.map +7 -0
- package/lib/esm/api/transport/WebHidDeviceConnection.test.js +2 -0
- package/lib/esm/api/transport/WebHidDeviceConnection.test.js.map +7 -0
- package/lib/esm/api/transport/WebHidTransport.js +2 -0
- package/lib/esm/api/transport/WebHidTransport.js.map +7 -0
- package/lib/esm/api/transport/WebHidTransport.test.js +2 -0
- package/lib/esm/api/transport/WebHidTransport.test.js.map +7 -0
- package/lib/esm/index.js +2 -0
- package/lib/esm/index.js.map +7 -0
- package/lib/esm/package.json +58 -0
- package/lib/types/api/data/WebHidConfig.d.ts +3 -0
- package/lib/types/api/data/WebHidConfig.d.ts.map +1 -0
- package/lib/types/api/index.d.ts +3 -0
- package/lib/types/api/index.d.ts.map +1 -0
- package/lib/types/api/model/Errors.d.ts +12 -0
- package/lib/types/api/model/Errors.d.ts.map +1 -0
- package/lib/types/api/model/HIDDevice.stub.d.ts +2 -0
- package/lib/types/api/model/HIDDevice.stub.d.ts.map +1 -0
- package/lib/types/api/transport/WebHidDeviceConnection.d.ts +48 -0
- package/lib/types/api/transport/WebHidDeviceConnection.d.ts.map +1 -0
- package/lib/types/api/transport/WebHidDeviceConnection.stub.d.ts +5 -0
- package/lib/types/api/transport/WebHidDeviceConnection.stub.d.ts.map +1 -0
- package/lib/types/api/transport/WebHidDeviceConnection.test.d.ts +2 -0
- package/lib/types/api/transport/WebHidDeviceConnection.test.d.ts.map +1 -0
- package/lib/types/api/transport/WebHidTransport.d.ts +91 -0
- package/lib/types/api/transport/WebHidTransport.d.ts.map +1 -0
- package/lib/types/api/transport/WebHidTransport.test.d.ts +2 -0
- package/lib/types/api/transport/WebHidTransport.test.d.ts.map +1 -0
- package/lib/types/index.d.ts +2 -0
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/tsconfig.prod.tsbuildinfo +1 -0
- package/package.json +57 -0
package/LICENSE.MD
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2024-present Ledger
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../src/api/data/WebHidConfig.ts"],
|
|
4
|
+
"sourcesContent": ["export const FRAME_SIZE = 64;\nexport const RECONNECT_DEVICE_TIMEOUT = 6000; // in some cases, when opening/closing an app, it takes up to 6s between the HID \"disconnect\" and \"connect\" events\n"],
|
|
5
|
+
"mappings": "AAAO,MAAMA,EAAa,GACbC,EAA2B",
|
|
6
|
+
"names": ["FRAME_SIZE", "RECONNECT_DEVICE_TIMEOUT"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/api/index.ts"],
|
|
4
|
+
"sourcesContent": ["export * from \"@api/model/Errors\";\nexport {\n webHidIdentifier,\n WebHidTransport,\n webHidTransportFactory,\n} from \"@api/transport/WebHidTransport\";\n"],
|
|
5
|
+
"mappings": "AAAA,WAAc,oBACd,OACE,oBAAAA,EACA,mBAAAC,EACA,0BAAAC,MACK",
|
|
6
|
+
"names": ["webHidIdentifier", "WebHidTransport", "webHidTransportFactory"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{GeneralDmkError as o}from"@ledgerhq/device-management-kit";class d extends o{constructor(r){super(r);this.err=r}_tag="WebHidTransportNotSupportedError"}class p extends o{constructor(r){super(r);this.err=r}_tag="WebHidSendReportError"}export{p as WebHidSendReportError,d as WebHidTransportNotSupportedError};
|
|
2
|
+
//# sourceMappingURL=Errors.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../src/api/model/Errors.ts"],
|
|
4
|
+
"sourcesContent": ["import { GeneralDmkError } from \"@ledgerhq/device-management-kit\";\n\nexport class WebHidTransportNotSupportedError extends GeneralDmkError {\n override readonly _tag = \"WebHidTransportNotSupportedError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\nexport class WebHidSendReportError extends GeneralDmkError {\n override readonly _tag = \"WebHidSendReportError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n"],
|
|
5
|
+
"mappings": "AAAA,OAAS,mBAAAA,MAAuB,kCAEzB,MAAMC,UAAyCD,CAAgB,CAEpE,YAAqBE,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,kCAI3B,CACO,MAAMC,UAA8BH,CAAgB,CAEzD,YAAqBE,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,uBAI3B",
|
|
6
|
+
"names": ["GeneralDmkError", "WebHidTransportNotSupportedError", "err", "WebHidSendReportError"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=jest.fn().mockResolvedValue(void 0),n=(t={})=>({opened:!1,productId:16401,vendorId:11415,productName:"Ledger Nano X",collections:[],open:jest.fn().mockResolvedValue(void 0),oninputreport:e,close:jest.fn().mockResolvedValue(void 0),sendReport:jest.fn().mockResolvedValue(e()),sendFeatureReport:jest.fn(),forget:jest.fn(),receiveFeatureReport:jest.fn(),addEventListener:jest.fn(),removeEventListener:jest.fn(),dispatchEvent:jest.fn(),...t});export{n as hidDeviceStubBuilder};
|
|
2
|
+
//# sourceMappingURL=HIDDevice.stub.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../src/api/model/HIDDevice.stub.ts"],
|
|
4
|
+
"sourcesContent": ["const oninputreport = jest.fn().mockResolvedValue(void 0);\n\nexport const hidDeviceStubBuilder = (\n props: Partial<HIDDevice> = {},\n): HIDDevice => ({\n opened: false,\n productId: 0x4011,\n vendorId: 0x2c97,\n productName: \"Ledger Nano X\",\n collections: [],\n open: jest.fn().mockResolvedValue(undefined),\n oninputreport,\n close: jest.fn().mockResolvedValue(undefined),\n sendReport: jest.fn().mockResolvedValue(oninputreport()),\n sendFeatureReport: jest.fn(),\n forget: jest.fn(),\n receiveFeatureReport: jest.fn(),\n addEventListener: jest.fn(),\n removeEventListener: jest.fn(),\n dispatchEvent: jest.fn(),\n ...props,\n});\n"],
|
|
5
|
+
"mappings": "AAAA,MAAMA,EAAgB,KAAK,GAAG,EAAE,kBAAkB,MAAM,EAE3CC,EAAuB,CAClCC,EAA4B,CAAC,KACd,CACf,OAAQ,GACR,UAAW,MACX,SAAU,MACV,YAAa,gBACb,YAAa,CAAC,EACd,KAAM,KAAK,GAAG,EAAE,kBAAkB,MAAS,EAC3C,cAAAF,EACA,MAAO,KAAK,GAAG,EAAE,kBAAkB,MAAS,EAC5C,WAAY,KAAK,GAAG,EAAE,kBAAkBA,EAAc,CAAC,EACvD,kBAAmB,KAAK,GAAG,EAC3B,OAAQ,KAAK,GAAG,EAChB,qBAAsB,KAAK,GAAG,EAC9B,iBAAkB,KAAK,GAAG,EAC1B,oBAAqB,KAAK,GAAG,EAC7B,cAAe,KAAK,GAAG,EACvB,GAAGE,CACL",
|
|
6
|
+
"names": ["oninputreport", "hidDeviceStubBuilder", "props"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{CommandUtils as v,ReconnectionFailedError as u}from"@ledgerhq/device-management-kit";import{Left as c,Right as s}from"purify-ts";import{Subject as d}from"rxjs";import{RECONNECT_DEVICE_TIMEOUT as h}from"../data/WebHidConfig";import{WebHidSendReportError as m}from"../model/Errors";class S{_device;_deviceId;_apduSender;_apduReceiver;_sendApduSubject=new d;_logger;_onConnectionTerminated;reconnectionSubject=new d;waitingForReconnection=!1;lostConnectionTimeout=null;terminated=!1;constructor({device:t,deviceId:i,apduSender:r,apduReceiver:o,onConnectionTerminated:e},n){this._apduSender=r,this._apduReceiver=o,this._onConnectionTerminated=e,this._logger=n("WebHidDeviceConnection"),this._device=t,this._device.oninputreport=a=>this.receiveHidInputReport(a),this._deviceId=i,this._logger.info("\u{1F50C} Connected to device")}get device(){return this._device}get deviceId(){return this._deviceId}async sendApdu(t,i){this._sendApduSubject=new d,this._logger.debug("Sending APDU",{data:{apdu:t},tag:"apdu-sender"});const r=new Promise(e=>{this._sendApduSubject.subscribe({next:async n=>{i&&v.isSuccessResponse(n)?(await this.waitForReconnection()).caseOf({Left:p=>e(c(p)),Right:()=>e(s(n))}):e(s(n))},error:n=>{e(c(n))}})});if(this.waitingForReconnection||!this.device.opened){const e=await this.waitForReconnection();if(e.isLeft())return e}const o=this._apduSender.getFrames(t);for(const e of o){this._logger.debug("Sending Frame",{data:{frame:e.getRawData()}});try{await this._device.sendReport(0,e.getRawData())}catch(n){return this._logger.error("Error sending frame",{data:{error:n}}),Promise.resolve(c(new m(n)))}}return r}receiveHidInputReport(t){const i=new Uint8Array(t.data.buffer);this._logger.debug("Received Frame",{data:{frame:i},tag:"apdu-receiver"}),this._apduReceiver.handleFrame(i).caseOf({Right:o=>{o.map(e=>{this._logger.debug("Received APDU Response",{data:{response:e}}),this._sendApduSubject.next(e),this._sendApduSubject.complete()})},Left:o=>{this._sendApduSubject.error(o)}})}waitForReconnection(){return this.terminated?Promise.resolve(c(new u)):new Promise(t=>{const i=this.reconnectionSubject.subscribe({next:r=>{t(r==="success"?s(void 0):c(r)),i.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()},h)}async reconnectHidDevice(t){this._device=t,this._device.oninputreport=i=>this.receiveHidInputReport(i),this.lostConnectionTimeout&&(this._logger.info("\u23F1\uFE0F\u{1F50C} Device reconnected"),clearTimeout(this.lostConnectionTimeout)),await t.open(),this.waitingForReconnection=!1,this.reconnectionSubject.next("success")}disconnect(){this._logger.info("\u{1F51A} Disconnect"),this.lostConnectionTimeout&&clearTimeout(this.lostConnectionTimeout),this.terminated=!0,this._onConnectionTerminated(),this.reconnectionSubject.next(new u)}}export{S as WebHidDeviceConnection};
|
|
2
|
+
//# sourceMappingURL=WebHidDeviceConnection.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 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, 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\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\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: NodeJS.Timeout | 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\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 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 resolve(Left(err));\n },\n });\n },\n );\n\n if (this.waitingForReconnection || !this.device.opened) {\n const reconnectionRes = await this.waitForReconnection();\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 try {\n await this._device.sendReport(0, frame.getRawData());\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(): Promise<Either<DmkError, void>> {\n if (this.terminated)\n return Promise.resolve(Left(new ReconnectionFailedError()));\n return new Promise<Either<DmkError, void>>((resolve) => {\n const sub = this.reconnectionSubject.subscribe({\n next: (res) => {\n if (res === \"success\") {\n resolve(Right(undefined));\n } else {\n resolve(Left(res));\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 this._logger.info(\"\u23F1\uFE0F\uD83D\uDD0C Device reconnected\");\n clearTimeout(this.lostConnectionTimeout);\n }\n await device.open();\n this.waitingForReconnection = false;\n this.reconnectionSubject.next(\"success\");\n }\n\n public disconnect() {\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,MAAa,YACzC,OAAS,WAAAC,MAAe,OAExB,OAAS,4BAAAC,MAAgC,yBACzC,OAAS,yBAAAC,MAA6B,oBAe/B,MAAMC,CAAmD,CACtD,QACA,UACS,YACA,cACT,iBAA0C,IAAIH,EACrC,QAGT,wBAEA,oBAAqD,IAAIA,EAEzD,uBAAyB,GAEzB,sBAA+C,KAE/C,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,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BAAe,EAC7B,KAAK,uBAAuB,aAAa,KAAK,qBAAqB,EACvE,KAAK,WAAa,GAClB,KAAK,wBAAwB,EAC7B,KAAK,oBAAoB,KAAK,IAAIP,CAAyB,CAC7D,CACF",
|
|
6
|
+
"names": ["CommandUtils", "ReconnectionFailedError", "Left", "Right", "Subject", "RECONNECT_DEVICE_TIMEOUT", "WebHidSendReportError", "WebHidDeviceConnection", "device", "deviceId", "apduSender", "apduReceiver", "onConnectionTerminated", "loggerServiceFactory", "event", "apdu", "triggersDisconnection", "resultPromise", "resolve", "r", "err", "reconnectionRes", "frames", "frame", "error", "data", "maybeApduResponse", "apduResponse", "sub", "res"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../src/api/transport/WebHidDeviceConnection.stub.ts"],
|
|
4
|
+
"sourcesContent": ["import {\n type DeviceConnection,\n type SendApduFnType,\n} from \"@ledgerhq/device-management-kit\";\n\nexport class WebHidDeviceConnectionStub implements DeviceConnection {\n sendApdu: SendApduFnType = jest.fn();\n}\n"],
|
|
5
|
+
"mappings": "AAKO,MAAMA,CAAuD,CAClE,SAA2B,KAAK,GAAG,CACrC",
|
|
6
|
+
"names": ["WebHidDeviceConnectionStub"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{defaultApduReceiverServiceStubBuilder as A,defaultApduSenderServiceStubBuilder as y,ReconnectionFailedError as w}from"@ledgerhq/device-management-kit";import{Left as v,Right as p}from"purify-ts";import{RECONNECT_DEVICE_TIMEOUT as m}from"../data/WebHidConfig";import{hidDeviceStubBuilder as h}from"../model/HIDDevice.stub";import{WebHidDeviceConnection as c}from"./WebHidDeviceConnection";jest.useFakeTimers();const b=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]),u=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 S{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 i=()=>{},a="test-device-id",s=t=>new S([],t);beforeEach(()=>{e=h({opened:!0}),r=y(void 0,s),o=A(void 0,s)}),it("should get device",()=>{const n=new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:i,deviceId:a},s).device;expect(n).toStrictEqual(e)}),it("should send APDU through hid report",()=>{new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:i,deviceId:a},s).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(u).buffer)})));const n=await new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:i,deviceId:a},s).sendApdu(Uint8Array.from([]));expect(n).toEqual(p({statusCode:new Uint8Array([144,0]),data:new Uint8Array([])}))}),describe("anticipating loss of connection after sending an APDU",()=>{test("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(u).buffer)})));const t=new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:i,deviceId:a},s);let n=!1;const d=t.sendApdu(Uint8Array.from([]),!0).then(l=>(n=!0,l));t.lostConnection(),await x(),expect(n).toBe(!1),t.reconnectHidDevice(e),await x(),expect(n).toBe(!0);const f=await d;expect(f).toEqual(p({statusCode:new Uint8Array([144,0]),data:new Uint8Array([])}))}),test("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(b).buffer)})));const n=await new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:i,deviceId:a},s).sendApdu(Uint8Array.from([]),!0);expect(n).toEqual(p({statusCode:new Uint8Array([85,21]),data:new Uint8Array([])}))}),test("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(u).buffer)})));const t=new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:i,deviceId:a},s),n=t.sendApdu(Uint8Array.from([]),!0);t.lostConnection(),jest.advanceTimersByTime(m),await x();const d=await n;expect(d).toEqual(v(new w))})}),describe("connection lost before sending an APDU",()=>{test("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(u).buffer)})));const t=new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:i,deviceId:a},s);t.lostConnection(),jest.advanceTimersByTime(m),await x();const n=await t.sendApdu(Uint8Array.from([]),!1);await x(),expect(n).toEqual(v(new w))}),test("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(u).buffer)})));const t=new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:i,deviceId:a},s);t.lostConnection();let n=!1;const d=t.sendApdu(Uint8Array.from([]),!1).then(l=>(n=!0,l));await x(),expect(n).toBe(!1),t.reconnectHidDevice(e),await x(),expect(n).toBe(!0);const f=await d;expect(f).toEqual(p({statusCode:new Uint8Array([144,0]),data:new Uint8Array([])}))})})});
|
|
2
|
+
//# sourceMappingURL=WebHidDeviceConnection.test.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 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 test(\"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 const connection = new WebHidDeviceConnection(\n { device, apduSender, apduReceiver, onConnectionTerminated, deviceId },\n logger,\n );\n\n let hasResolved = false;\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 test(\"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 test(\"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 test(\"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 test(\"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 Right({\n statusCode: new Uint8Array([0x90, 0x00]),\n data: new Uint8Array([]),\n }),\n );\n });\n });\n});\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,EAA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AC,EAAY,aAAAC,EAAc,uBAAAC,EAAwB,SAAAC,CAAS,EACrEC,CACF,EAGAG,EAAW,eAAe,EAC1B,KAAK,oBAAoBjB,CAAwB,EACjD,MAAMQ,EAAc,EAGpB,MAAMQ,EAAW,MAAMC,EAAW,SAAS,WAAW,KAAK,CAAC,CAAC,EAAG,EAAK,EACrE,MAAMT,EAAc,EACpB,OAAOQ,CAAQ,EAAE,QAAQlB,EAAK,IAAID,CAAyB,CAAC,CAC9D,CAAC,EAED,KAAK,oEAAqE,SAAY,CAEpFY,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,QACfjB,EAAM,CACJ,WAAY,IAAI,WAAW,CAAC,IAAM,CAAI,CAAC,EACvC,KAAM,IAAI,WAAW,CAAC,CAAC,CACzB,CAAC,CACH,CACF,CAAC,CACH,CAAC,CACH,CAAC",
|
|
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"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{DeviceNotRecognizedError as E,FramerUtils as b,LEDGER_VENDOR_ID as l,NoAccessibleDeviceError as p,OpeningConnectionError as _,TransportConnectedDevice as m,UnknownDeviceError as u}from"@ledgerhq/device-management-kit";import*as s from"@sentry/minimal";import{EitherAsync as y,Left as v,Maybe as D,Right as g}from"purify-ts";import{BehaviorSubject as H,from as f,map as C,switchMap as T}from"rxjs";import{v4 as I}from"uuid";import{FRAME_SIZE as w}from"../data/WebHidConfig";import{WebHidTransportNotSupportedError as S}from"../model/Errors";import{WebHidDeviceConnection as A}from"../transport/WebHidDeviceConnection";const P="WEB-HID";class M{constructor(e,i,t,r){this._deviceModelDataSource=e;this._loggerServiceFactory=i;this._apduSenderFactory=t;this._apduReceiverFactory=r;this._logger=i("WebWebHidTransport"),this.startListeningToConnectionEvents()}_transportDiscoveredDevices=new H([]);_deviceConnectionsByHidDevice=new Map;_deviceConnectionsPendingReconnection=new Set;_connectionListenersAbortController=new AbortController;_logger;connectionType="USB";identifier=P;get hidApi(){return this.isSupported()?g(navigator.hid):v(new S("WebHID not supported"))}isSupported(){try{const e=!!navigator?.hid;return this._logger.debug(`isSupported: ${e}`),e}catch(e){return this._logger.error("isSupported: error",{data:{error:e}}),!1}}getIdentifier(){return this.identifier}async getDevices(){return y.liftEither(this.hidApi).map(async e=>{try{return(await e.getDevices()).filter(t=>t.vendorId===l)}catch(i){const t=new p(i);throw this._logger.error("getDevices: error getting devices",{data:{error:i}}),s.captureException(t),t}})}mapHIDDeviceToTransportDiscoveredDevice(e){const i=this._transportDiscoveredDevices.getValue().find(n=>n.hidDevice===e);if(i)return i;const t=this._deviceConnectionsByHidDevice.get(e);return this.getDeviceModel(e).caseOf({Just:n=>{const c=t?.deviceId??I(),d={id:c,deviceModel:n,hidDevice:e,transport:this.identifier};return this._logger.debug(`Discovered device ${c} ${d.deviceModel.productName}`),d},Nothing:()=>{throw this._logger.warn(`Device not recognized: hidDevice.productId: 0x${e.productId.toString(16)}`),new E(`Device not recognized: hidDevice.productId: 0x${e.productId.toString(16)}`)}})}listenToKnownDevices(){return this.updateTransportDiscoveredDevices(),this._transportDiscoveredDevices.pipe(C(e=>e.map(({hidDevice:i,...t})=>t)))}async updateTransportDiscoveredDevices(){(await this.getDevices()).caseOf({Left:i=>{this._logger.error("Error while getting accessible device",{data:{error:i}}),s.captureException(i)},Right:i=>{this._transportDiscoveredDevices.next(i.map(t=>this.mapHIDDeviceToTransportDiscoveredDevice(t)))}})}async promptDeviceAccess(){return y.liftEither(this.hidApi).map(async e=>{let i=[];try{i=await e.requestDevice({filters:[{vendorId:l}]}),await this.updateTransportDiscoveredDevices()}catch(r){const n=new p(r);throw this._logger.error("promptDeviceAccess: error requesting device",{data:{error:r}}),s.captureException(n),n}if(this._logger.debug(`promptDeviceAccess: hidDevices len ${i.length}`),i.length===0)throw this._logger.warn("No device was selected"),new p("No selected device");const t=[];for(const r of i)t.push(r),this._logger.debug("promptDeviceAccess: selected device",{data:{hidDevice:r}});return t}).run()}startDiscovering(){return this._logger.debug("startDiscovering"),f(this.promptDeviceAccess()).pipe(T(e=>e.caseOf({Left:i=>{throw this._logger.error("Error while getting accessible device",{data:{error:i}}),s.captureException(i),i},Right:i=>{this._logger.info(`Got access to ${i.length} HID devices`);const t=i.map(r=>this.mapHIDDeviceToTransportDiscoveredDevice(r));return f(t)}})))}stopDiscovering(){}startListeningToConnectionEvents(){this._logger.debug("startListeningToConnectionEvents"),this.hidApi.map(e=>{e.addEventListener("connect",i=>this.handleDeviceConnectionEvent(i),{signal:this._connectionListenersAbortController.signal}),e.addEventListener("disconnect",i=>this.handleDeviceDisconnectionEvent(i),{signal:this._connectionListenersAbortController.signal})})}stopListeningToConnectionEvents(){this._logger.debug("stopListeningToConnectionEvents"),this._connectionListenersAbortController.abort()}async connect({deviceId:e,onDisconnect:i}){this._logger.debug("connect",{data:{deviceId:e}});const t=this._transportDiscoveredDevices.getValue().find(o=>o.id===e);if(!t)return this._logger.error(`Unknown device ${e}`),v(new u(`Unknown device ${e}`));try{if(this._deviceConnectionsByHidDevice.get(t.hidDevice))throw new Error("Device already opened");await t.hidDevice.open()}catch(o){if(o instanceof DOMException&&o.name==="InvalidStateError")this._logger.debug(`Device ${e} is already opened`);else{const a=new _(o);return this._logger.debug(`Error while opening device: ${e}`,{data:{error:o}}),s.captureException(a),v(a)}}const{deviceModel:r}=t,n=D.of(b.numberToByteArray(Math.floor(Math.random()*65535),2)),c=new A({device:t.hidDevice,deviceId:e,apduSender:this._apduSenderFactory({frameSize:w,channel:n,padding:!0}),apduReceiver:this._apduReceiverFactory({channel:n}),onConnectionTerminated:()=>{i(e),this._deviceConnectionsPendingReconnection.delete(c),this._deviceConnectionsByHidDevice.delete(t.hidDevice),c.device.close()}},this._loggerServiceFactory);this._deviceConnectionsByHidDevice.set(t.hidDevice,c);const d=new m({sendApdu:(o,a)=>c.sendApdu(o,a),deviceModel:r,id:e,type:this.connectionType,transport:this.identifier});return g(d)}getDeviceModel(e){const{productId:i}=e,t=this._deviceModelDataSource.getAllDeviceModels().find(r=>r.usbProductId===i>>8||r.bootloaderUsbProductId===i);return t?D.of(t):D.zero()}getHidUsbProductId(e){return this.getDeviceModel(e).caseOf({Just:i=>i.usbProductId,Nothing:()=>e.productId>>8})}async disconnect(e){this._logger.debug("disconnect",{data:{connectedDevice:e}});const i=Array.from(this._deviceConnectionsByHidDevice.values()).find(t=>t.deviceId===e.connectedDevice.id);return i?(i.disconnect(),Promise.resolve(g(void 0))):(this._logger.error("No matching device connection found",{data:{connectedDevice:e}}),Promise.resolve(v(new u(`Unknown device ${e.connectedDevice.id}`))))}isHIDConnectionEvent(e){return"device"in e&&typeof e.device=="object"&&e.device!==null&&"productId"in e.device&&typeof e.device.productId=="number"}async handleDeviceDisconnectionEvent(e){if(!this.isHIDConnectionEvent(e)){this._logger.error("Invalid event",{data:{event:e}});return}this._logger.info("[handleDeviceDisconnectionEvent] Device disconnected",{data:{event:e}}),this.updateTransportDiscoveredDevices();try{await e.device.close()}catch(t){this._logger.error("Error while closing device ",{data:{event:e,error:t}})}const i=this._deviceConnectionsByHidDevice.get(e.device);i&&(i.lostConnection(),this._deviceConnectionsPendingReconnection.add(i),this._deviceConnectionsByHidDevice.delete(e.device))}handleDeviceReconnection(e,i){this._deviceConnectionsPendingReconnection.delete(e),this._deviceConnectionsByHidDevice.set(i,e);try{e.reconnectHidDevice(i)}catch(t){this._logger.error("Error while reconnecting to device",{data:{event,error:t}}),e.disconnect()}}handleDeviceConnectionEvent(e){if(!this.isHIDConnectionEvent(e)){this._logger.error("Invalid event",{data:{event:e}});return}this._logger.info("[handleDeviceConnectionEvent] Device connected",{data:{event:e}});const i=Array.from(this._deviceConnectionsPendingReconnection).find(t=>this.getHidUsbProductId(t.device)===this.getHidUsbProductId(e.device));i&&this.handleDeviceReconnection(i,e.device),this.updateTransportDiscoveredDevices()}destroy(){this.stopListeningToConnectionEvents(),this._deviceConnectionsByHidDevice.forEach(e=>{e.disconnect()}),this._deviceConnectionsPendingReconnection.clear()}}const $=({deviceModelDataSource:h,loggerServiceFactory:e,apduSenderServiceFactory:i,apduReceiverServiceFactory:t})=>new M(h,e,i,t);export{M as WebHidTransport,P as webHidIdentifier,$ as webHidTransportFactory};
|
|
2
|
+
//# sourceMappingURL=WebHidTransport.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../src/api/transport/WebHidTransport.ts"],
|
|
4
|
+
"sourcesContent": ["import {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n type ConnectError,\n type ConnectionType,\n type DeviceId,\n type DeviceModelDataSource,\n DeviceNotRecognizedError,\n type DisconnectHandler,\n type DmkError,\n FramerUtils,\n LEDGER_VENDOR_ID,\n type LoggerPublisherService,\n NoAccessibleDeviceError,\n OpeningConnectionError,\n type Transport,\n TransportConnectedDevice,\n type TransportDeviceModel,\n type TransportDiscoveredDevice,\n type TransportFactory,\n type TransportIdentifier,\n UnknownDeviceError,\n} from \"@ledgerhq/device-management-kit\";\nimport * as Sentry from \"@sentry/minimal\";\nimport { type Either, EitherAsync, Left, Maybe, Right } from \"purify-ts\";\nimport { BehaviorSubject, from, map, type Observable, switchMap } from \"rxjs\";\nimport { v4 as uuid } from \"uuid\";\n\nimport { FRAME_SIZE } from \"@api/data/WebHidConfig\";\nimport { WebHidTransportNotSupportedError } from \"@api/model/Errors\";\nimport { WebHidDeviceConnection } from \"@api/transport/WebHidDeviceConnection\";\n\ntype PromptDeviceAccessError =\n | NoAccessibleDeviceError\n | WebHidTransportNotSupportedError;\n\ntype WebHidTransportDiscoveredDevice = TransportDiscoveredDevice & {\n hidDevice: HIDDevice;\n};\n\nexport const webHidIdentifier: TransportIdentifier = \"WEB-HID\";\n\nexport class WebHidTransport implements Transport {\n /** List of HID devices that have been discovered */\n private _transportDiscoveredDevices: BehaviorSubject<\n Array<WebHidTransportDiscoveredDevice>\n > = new BehaviorSubject<Array<WebHidTransportDiscoveredDevice>>([]);\n\n /** Map of *connected* HIDDevice to their WebHidDeviceConnection */\n private _deviceConnectionsByHidDevice: Map<\n HIDDevice,\n WebHidDeviceConnection\n > = new Map();\n\n /**\n * Set of WebHidDeviceConnection for which the HIDDevice has been\n * disconnected, so they are waiting for a reconnection\n */\n private _deviceConnectionsPendingReconnection: Set<WebHidDeviceConnection> =\n new Set();\n\n /** AbortController to stop listening to HID connection events */\n private _connectionListenersAbortController: AbortController =\n new AbortController();\n private _logger: LoggerPublisherService;\n private readonly connectionType: ConnectionType = \"USB\";\n private readonly identifier: TransportIdentifier = webHidIdentifier;\n\n constructor(\n private readonly _deviceModelDataSource: DeviceModelDataSource,\n private readonly _loggerServiceFactory: (\n tag: string,\n ) => LoggerPublisherService,\n private readonly _apduSenderFactory: ApduSenderServiceFactory,\n private readonly _apduReceiverFactory: ApduReceiverServiceFactory,\n ) {\n this._logger = _loggerServiceFactory(\"WebWebHidTransport\");\n\n this.startListeningToConnectionEvents();\n }\n\n /**\n * Get the WebHID API if supported or error\n * @returns `Either<WebHidTransportNotSupportedError, HID>`\n */\n private get hidApi(): Either<WebHidTransportNotSupportedError, HID> {\n if (this.isSupported()) {\n return Right(navigator.hid);\n }\n\n return Left(new WebHidTransportNotSupportedError(\"WebHID not supported\"));\n }\n\n isSupported() {\n try {\n const result = !!navigator?.hid;\n this._logger.debug(`isSupported: ${result}`);\n return result;\n } catch (error) {\n this._logger.error(`isSupported: error`, { data: { error } });\n return false;\n }\n }\n\n getIdentifier(): TransportIdentifier {\n return this.identifier;\n }\n\n /**\n * Wrapper around `navigator.hid.getDevices()`.\n * It will return the list of plugged in HID devices to which the user has\n * previously granted access through `navigator.hid.requestDevice()`.\n */\n private async getDevices(): Promise<Either<DmkError, HIDDevice[]>> {\n return EitherAsync.liftEither(this.hidApi).map(async (hidApi) => {\n try {\n const allDevices = await hidApi.getDevices();\n\n return allDevices.filter(\n (hidDevice) => hidDevice.vendorId === LEDGER_VENDOR_ID,\n );\n } catch (error) {\n const deviceError = new NoAccessibleDeviceError(error);\n this._logger.error(`getDevices: error getting devices`, {\n data: { error },\n });\n Sentry.captureException(deviceError);\n throw deviceError;\n }\n });\n }\n\n /**\n * Map a HIDDevice to an TransportDiscoveredDevice, either by creating a new one or returning an existing one\n */\n private mapHIDDeviceToTransportDiscoveredDevice(\n hidDevice: HIDDevice,\n ): WebHidTransportDiscoveredDevice {\n const existingDiscoveredDevice = this._transportDiscoveredDevices\n .getValue()\n .find((internalDevice) => internalDevice.hidDevice === hidDevice);\n\n if (existingDiscoveredDevice) {\n return existingDiscoveredDevice;\n }\n\n const existingDeviceConnection =\n this._deviceConnectionsByHidDevice.get(hidDevice);\n\n const maybeDeviceModel = this.getDeviceModel(hidDevice);\n return maybeDeviceModel.caseOf({\n Just: (deviceModel) => {\n const id = existingDeviceConnection?.deviceId ?? uuid();\n\n const discoveredDevice = {\n id,\n deviceModel,\n hidDevice,\n transport: this.identifier,\n };\n\n this._logger.debug(\n `Discovered device ${id} ${discoveredDevice.deviceModel.productName}`,\n );\n\n return discoveredDevice;\n },\n Nothing: () => {\n // [ASK] Or we just ignore the not recognized device ? And log them\n this._logger.warn(\n `Device not recognized: hidDevice.productId: 0x${hidDevice.productId.toString(16)}`,\n );\n throw new DeviceNotRecognizedError(\n `Device not recognized: hidDevice.productId: 0x${hidDevice.productId.toString(16)}`,\n );\n },\n });\n }\n\n /**\n * Listen to known devices (devices to which the user has granted access)\n */\n public listenToKnownDevices(): Observable<TransportDiscoveredDevice[]> {\n this.updateTransportDiscoveredDevices();\n return this._transportDiscoveredDevices.pipe(\n map((devices) => devices.map(({ hidDevice, ...device }) => device)),\n );\n }\n\n private async updateTransportDiscoveredDevices(): Promise<void> {\n const eitherDevices = await this.getDevices();\n\n eitherDevices.caseOf({\n Left: (error) => {\n this._logger.error(\"Error while getting accessible device\", {\n data: { error },\n });\n Sentry.captureException(error);\n },\n Right: (hidDevices) => {\n this._transportDiscoveredDevices.next(\n hidDevices.map((hidDevice) =>\n this.mapHIDDeviceToTransportDiscoveredDevice(hidDevice),\n ),\n );\n },\n });\n }\n\n /**\n * Wrapper around navigator.hid.requestDevice()\n * In a browser, it will show a native dialog to select a HID device.\n */\n private async promptDeviceAccess(): Promise<\n Either<PromptDeviceAccessError, HIDDevice[]>\n > {\n return EitherAsync.liftEither(this.hidApi)\n .map(async (hidApi) => {\n // `requestDevice` returns an array. but normally the user can select only one device at a time.\n let hidDevices: HIDDevice[] = [];\n\n try {\n hidDevices = await hidApi.requestDevice({\n filters: [{ vendorId: LEDGER_VENDOR_ID }],\n });\n await this.updateTransportDiscoveredDevices();\n } catch (error) {\n const deviceError = new NoAccessibleDeviceError(error);\n this._logger.error(`promptDeviceAccess: error requesting device`, {\n data: { error },\n });\n Sentry.captureException(deviceError);\n throw deviceError;\n }\n\n this._logger.debug(\n `promptDeviceAccess: hidDevices len ${hidDevices.length}`,\n );\n\n // Granted access to 0 device (by clicking on cancel for ex) results in an error\n if (hidDevices.length === 0) {\n this._logger.warn(\"No device was selected\");\n throw new NoAccessibleDeviceError(\"No selected device\");\n }\n\n const discoveredHidDevices: HIDDevice[] = [];\n\n for (const hidDevice of hidDevices) {\n discoveredHidDevices.push(hidDevice);\n\n this._logger.debug(`promptDeviceAccess: selected device`, {\n data: { hidDevice },\n });\n }\n\n return discoveredHidDevices;\n })\n .run();\n }\n\n startDiscovering(): Observable<TransportDiscoveredDevice> {\n this._logger.debug(\"startDiscovering\");\n\n return from(this.promptDeviceAccess()).pipe(\n switchMap((either) => {\n return either.caseOf({\n Left: (error) => {\n this._logger.error(\"Error while getting accessible device\", {\n data: { error },\n });\n Sentry.captureException(error);\n throw error;\n },\n Right: (hidDevices) => {\n this._logger.info(`Got access to ${hidDevices.length} HID devices`);\n\n const discoveredDevices = hidDevices.map((hidDevice) => {\n return this.mapHIDDeviceToTransportDiscoveredDevice(hidDevice);\n });\n\n return from(discoveredDevices);\n },\n });\n }),\n );\n }\n\n stopDiscovering(): void {\n /**\n * This does nothing because the startDiscovering method is just a\n * promise wrapped into an observable. So there is no need to stop it.\n */\n }\n\n private startListeningToConnectionEvents(): void {\n this._logger.debug(\"startListeningToConnectionEvents\");\n\n this.hidApi.map((hidApi) => {\n hidApi.addEventListener(\n \"connect\",\n (event) => this.handleDeviceConnectionEvent(event),\n { signal: this._connectionListenersAbortController.signal },\n );\n\n hidApi.addEventListener(\n \"disconnect\",\n (event) => this.handleDeviceDisconnectionEvent(event),\n { signal: this._connectionListenersAbortController.signal },\n );\n });\n }\n\n private stopListeningToConnectionEvents(): void {\n this._logger.debug(\"stopListeningToConnectionEvents\");\n this._connectionListenersAbortController.abort();\n }\n\n /**\n * Connect to a HID USB device and update the internal state of the associated device\n */\n async connect({\n deviceId,\n onDisconnect,\n }: {\n deviceId: DeviceId;\n onDisconnect: DisconnectHandler;\n }): Promise<Either<ConnectError, TransportConnectedDevice>> {\n this._logger.debug(\"connect\", { data: { deviceId } });\n\n const matchingInternalDevice = this._transportDiscoveredDevices\n .getValue()\n .find((internalDevice) => internalDevice.id === deviceId);\n\n if (!matchingInternalDevice) {\n this._logger.error(`Unknown device ${deviceId}`);\n return Left(new UnknownDeviceError(`Unknown device ${deviceId}`));\n }\n\n try {\n if (\n this._deviceConnectionsByHidDevice.get(matchingInternalDevice.hidDevice)\n ) {\n throw new Error(\"Device already opened\");\n }\n await matchingInternalDevice.hidDevice.open();\n } catch (error) {\n if (error instanceof DOMException && error.name === \"InvalidStateError\") {\n this._logger.debug(`Device ${deviceId} is already opened`);\n } else {\n const connectionError = new OpeningConnectionError(error);\n this._logger.debug(`Error while opening device: ${deviceId}`, {\n data: { error },\n });\n Sentry.captureException(connectionError);\n return Left(connectionError);\n }\n }\n\n const { deviceModel } = matchingInternalDevice;\n\n const channel = Maybe.of(\n FramerUtils.numberToByteArray(Math.floor(Math.random() * 0xffff), 2),\n );\n const deviceConnection = new WebHidDeviceConnection(\n {\n device: matchingInternalDevice.hidDevice,\n deviceId,\n apduSender: this._apduSenderFactory({\n frameSize: FRAME_SIZE,\n channel,\n padding: true,\n }),\n apduReceiver: this._apduReceiverFactory({ channel }),\n onConnectionTerminated: () => {\n onDisconnect(deviceId);\n this._deviceConnectionsPendingReconnection.delete(deviceConnection);\n this._deviceConnectionsByHidDevice.delete(\n matchingInternalDevice.hidDevice,\n );\n deviceConnection.device.close();\n },\n },\n this._loggerServiceFactory,\n );\n\n this._deviceConnectionsByHidDevice.set(\n matchingInternalDevice.hidDevice,\n deviceConnection,\n );\n\n const connectedDevice = new TransportConnectedDevice({\n sendApdu: (apdu, triggersDisconnection) =>\n deviceConnection.sendApdu(apdu, triggersDisconnection),\n deviceModel,\n id: deviceId,\n type: this.connectionType,\n transport: this.identifier,\n });\n\n return Right(connectedDevice);\n }\n\n private getDeviceModel(hidDevice: HIDDevice): Maybe<TransportDeviceModel> {\n const { productId } = hidDevice;\n const matchingModel = this._deviceModelDataSource.getAllDeviceModels().find(\n (deviceModel) =>\n // outside of bootloader mode, the value that we need to identify a device model is the first byte of the actual hidDevice.productId\n deviceModel.usbProductId === productId >> 8 ||\n deviceModel.bootloaderUsbProductId === productId,\n );\n return matchingModel ? Maybe.of(matchingModel) : Maybe.zero();\n }\n\n private getHidUsbProductId(hidDevice: HIDDevice): number {\n return this.getDeviceModel(hidDevice).caseOf({\n Just: (deviceModel) => deviceModel.usbProductId,\n Nothing: () => hidDevice.productId >> 8,\n });\n }\n\n /**\n * Disconnect from a HID USB device\n */\n async disconnect(params: {\n connectedDevice: TransportConnectedDevice;\n }): Promise<Either<DmkError, void>> {\n this._logger.debug(\"disconnect\", { data: { connectedDevice: params } });\n\n const matchingDeviceConnection = Array.from(\n this._deviceConnectionsByHidDevice.values(),\n ).find(\n (deviceConnection) =>\n deviceConnection.deviceId === params.connectedDevice.id,\n );\n\n if (!matchingDeviceConnection) {\n this._logger.error(\"No matching device connection found\", {\n data: { connectedDevice: params },\n });\n return Promise.resolve(\n Left(\n new UnknownDeviceError(`Unknown device ${params.connectedDevice.id}`),\n ),\n );\n }\n\n matchingDeviceConnection.disconnect();\n return Promise.resolve(Right(undefined));\n }\n\n /**\n * Type guard to check if the event is a HID connection event\n * @param event\n * @private\n */\n private isHIDConnectionEvent(event: Event): event is HIDConnectionEvent {\n return (\n \"device\" in event &&\n typeof event.device === \"object\" &&\n event.device !== null &&\n \"productId\" in event.device &&\n typeof event.device.productId === \"number\"\n );\n }\n\n /**\n * Handle the disconnection event of a HID device\n * @param event\n */\n private async handleDeviceDisconnectionEvent(event: Event) {\n if (!this.isHIDConnectionEvent(event)) {\n this._logger.error(\"Invalid event\", { data: { event } });\n return;\n }\n\n this._logger.info(\"[handleDeviceDisconnectionEvent] Device disconnected\", {\n data: { event },\n });\n\n this.updateTransportDiscoveredDevices();\n\n try {\n await event.device.close();\n } catch (error) {\n this._logger.error(\"Error while closing device \", {\n data: { event, error },\n });\n }\n\n const matchingDeviceConnection = this._deviceConnectionsByHidDevice.get(\n event.device,\n );\n\n if (matchingDeviceConnection) {\n matchingDeviceConnection.lostConnection();\n this._deviceConnectionsPendingReconnection.add(matchingDeviceConnection);\n this._deviceConnectionsByHidDevice.delete(event.device);\n }\n }\n\n private handleDeviceReconnection(\n deviceConnection: WebHidDeviceConnection,\n hidDevice: HIDDevice,\n ) {\n this._deviceConnectionsPendingReconnection.delete(deviceConnection);\n this._deviceConnectionsByHidDevice.set(hidDevice, deviceConnection);\n\n try {\n deviceConnection.reconnectHidDevice(hidDevice);\n } catch (error) {\n this._logger.error(\"Error while reconnecting to device\", {\n data: { event, error },\n });\n deviceConnection.disconnect();\n }\n }\n\n /**\n * Handle the connection event of a HID device\n * @param event\n */\n private handleDeviceConnectionEvent(event: Event) {\n if (!this.isHIDConnectionEvent(event)) {\n this._logger.error(\"Invalid event\", { data: { event } });\n return;\n }\n\n this._logger.info(\"[handleDeviceConnectionEvent] Device connected\", {\n data: { event },\n });\n\n const matchingDeviceConnection = Array.from(\n this._deviceConnectionsPendingReconnection,\n ).find(\n (deviceConnection) =>\n this.getHidUsbProductId(deviceConnection.device) ===\n this.getHidUsbProductId(event.device),\n );\n\n if (matchingDeviceConnection) {\n this.handleDeviceReconnection(matchingDeviceConnection, event.device);\n }\n\n /**\n * Note: we do this after handling the reconnection to allow the newly\n * discovered device to keep the same DeviceId as the previous one in case\n * of a reconnection.\n */\n this.updateTransportDiscoveredDevices();\n }\n\n public destroy() {\n this.stopListeningToConnectionEvents();\n this._deviceConnectionsByHidDevice.forEach((connection) => {\n connection.disconnect();\n });\n this._deviceConnectionsPendingReconnection.clear();\n }\n}\n\nexport const webHidTransportFactory: TransportFactory = ({\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n}) =>\n new WebHidTransport(\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n );\n"],
|
|
5
|
+
"mappings": "AAAA,OAOE,4BAAAA,EAGA,eAAAC,EACA,oBAAAC,EAEA,2BAAAC,EACA,0BAAAC,EAEA,4BAAAC,EAKA,sBAAAC,MACK,kCACP,UAAYC,MAAY,kBACxB,OAAsB,eAAAC,EAAa,QAAAC,EAAM,SAAAC,EAAO,SAAAC,MAAa,YAC7D,OAAS,mBAAAC,EAAiB,QAAAC,EAAM,OAAAC,EAAsB,aAAAC,MAAiB,OACvE,OAAS,MAAMC,MAAY,OAE3B,OAAS,cAAAC,MAAkB,yBAC3B,OAAS,oCAAAC,MAAwC,oBACjD,OAAS,0BAAAC,MAA8B,wCAUhC,MAAMC,EAAwC,UAE9C,MAAMC,CAAqC,CA0BhD,YACmBC,EACAC,EAGAC,EACAC,EACjB,CANiB,4BAAAH,EACA,2BAAAC,EAGA,wBAAAC,EACA,0BAAAC,EAEjB,KAAK,QAAUF,EAAsB,oBAAoB,EAEzD,KAAK,iCAAiC,CACxC,CAnCQ,4BAEJ,IAAIX,EAAwD,CAAC,CAAC,EAG1D,8BAGJ,IAAI,IAMA,sCACN,IAAI,IAGE,oCACN,IAAI,gBACE,QACS,eAAiC,MACjC,WAAkCQ,EAmBnD,IAAY,QAAwD,CAClE,OAAI,KAAK,YAAY,EACZT,EAAM,UAAU,GAAG,EAGrBF,EAAK,IAAIS,EAAiC,sBAAsB,CAAC,CAC1E,CAEA,aAAc,CACZ,GAAI,CACF,MAAMQ,EAAS,CAAC,CAAC,WAAW,IAC5B,YAAK,QAAQ,MAAM,gBAAgBA,CAAM,EAAE,EACpCA,CACT,OAASC,EAAO,CACd,YAAK,QAAQ,MAAM,qBAAsB,CAAE,KAAM,CAAE,MAAAA,CAAM,CAAE,CAAC,EACrD,EACT,CACF,CAEA,eAAqC,CACnC,OAAO,KAAK,UACd,CAOA,MAAc,Y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AOb,EAAM,MAAM,EAE1D,CAEQ,yBACNM,EACApB,EACA,CACA,KAAK,sCAAsC,OAAOoB,CAAgB,EAClE,KAAK,8BAA8B,IAAIpB,EAAWoB,CAAgB,EAElE,GAAI,CACFA,EAAiB,mBAAmBpB,CAAS,CAC/C,OAASF,EAAO,CACd,KAAK,QAAQ,MAAM,qCAAsC,CACvD,KAAM,CAAE,MAAO,MAAAA,CAAM,CACvB,CAAC,EACDsB,EAAiB,WAAW,CAC9B,CACF,CAMQ,4BAA4BN,EAAc,CAChD,GAAI,CAAC,KAAK,qBAAqBA,CAAK,EAAG,CACrC,KAAK,QAAQ,MAAM,gBAAiB,CAAE,KAAM,CAAE,MAAAA,CAAM,CAAE,CAAC,EACvD,MACF,CAEA,KAAK,QAAQ,KAAK,iDAAkD,CAClE,KAAM,CAAE,MAAAA,CAAM,CAChB,CAAC,EAED,MAAMa,EAA2B,MAAM,KACrC,KAAK,qCACP,EAAE,KACCP,GACC,KAAK,mBAAmBA,EAAiB,MAAM,IAC/C,KAAK,mBAAmBN,EAAM,MAAM,CACxC,EAEIa,GACF,KAAK,yBAAyBA,EAA0Bb,EAAM,MAAM,EAQtE,KAAK,iCAAiC,CACxC,CAEO,SAAU,CACf,KAAK,gCAAgC,EACrC,KAAK,8BAA8B,QAASc,GAAe,CACzDA,EAAW,WAAW,CACxB,CAAC,EACD,KAAK,sCAAsC,MAAM,CACnD,CACF,CAEO,MAAMC,EAA2C,CAAC,CACvD,sBAAAC,EACA,qBAAAC,EACA,yBAAAC,EACA,2BAAAC,CACF,IACE,IAAIzC,EACFsC,EACAC,EACAC,EACAC,CACF",
|
|
6
|
+
"names": ["DeviceNotRecognizedError", "FramerUtils", "LEDGER_VENDOR_ID", "NoAccessibleDeviceError", "OpeningConnectionError", "TransportConnectedDevice", "UnknownDeviceError", "Sentry", "EitherAsync", "Left", "Maybe", "Right", "BehaviorSubject", "from", "map", "switchMap", "uuid", "FRAME_SIZE", "WebHidTransportNotSupportedError", "WebHidDeviceConnection", "webHidIdentifier", "WebHidTransport", "_deviceModelDataSource", "_loggerServiceFactory", "_apduSenderFactory", "_apduReceiverFactory", "result", "error", "hidApi", "hidDevice", "deviceError", "existingDiscoveredDevice", "internalDevice", "existingDeviceConnection", "deviceModel", "id", "discoveredDevice", "devices", "device", "hidDevices", "discoveredHidDevices", "either", "discoveredDevices", "event", "deviceId", "onDisconnect", "matchingInternalDevice", "connectionError", "channel", "deviceConnection", "connectedDevice", "apdu", "triggersDisconnection", "productId", "matchingModel", "params", "matchingDeviceConnection", "connection", "webHidTransportFactory", "deviceModelDataSource", "loggerServiceFactory", "apduSenderServiceFactory", "apduReceiverServiceFactory"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{connectedDeviceStubBuilder as T,DeviceModelId as u,DeviceNotRecognizedError as S,NoAccessibleDeviceError as E,OpeningConnectionError as B,StaticDeviceModelDataSource as H,UnknownDeviceError as C}from"@ledgerhq/device-management-kit";import{Left as g,Right as R}from"purify-ts";import{Subject as y}from"rxjs";import{RECONNECT_DEVICE_TIMEOUT as p}from"../data/WebHidConfig";import{WebHidTransportNotSupportedError as N}from"../model/Errors";import{hidDeviceStubBuilder as l}from"../model/HIDDevice.stub";import{WebHidTransport as O}from"./WebHidTransport";class V{constructor(D,f){this.subscribers=D,this.tag=f}subscribers=[];tag="";error=jest.fn();warn=jest.fn();info=jest.fn();debug=jest.fn()}const x=new H,P=new V([],"web-usb-hid"),a=l(),m=()=>new Promise(jest.requireActual("timers").setImmediate);describe("WebHidTransport",()=>{let i,D,f;function w(){D=jest.fn(),f=jest.fn(),i=new O(x,()=>P,f,D)}beforeEach(()=>{w(),jest.useFakeTimers()}),afterEach(()=>{jest.restoreAllMocks()});const d=(s,r)=>{i.startDiscovering().subscribe({next:s,error:r})};describe("When WebHID API is not supported",()=>{it("should not support the transport",()=>{expect(i.isSupported()).toBe(!1)}),it("should emit a startDiscovering error",s=>{d(()=>{s("Should not emit any value")},r=>{expect(r).toBeInstanceOf(N),s()})})}),describe("When WebHID API is supported",()=>{const s=jest.fn(),r=jest.fn(),I=new y,k=new y;function b(t){I.next({device:t})}function h(t){k.next({device:t})}beforeEach(()=>{global.navigator={hid:{getDevices:s,requestDevice:r,addEventListener:(t,e)=>{t==="disconnect"?k.subscribe(e):t==="connect"&&I.subscribe(e)}}},w()}),afterEach(()=>{jest.clearAllMocks(),global.navigator=void 0}),it("should support the transport",()=>{expect(i.isSupported()).toBe(!0)}),describe("startDiscovering",()=>{x.getAllDeviceModels().flatMap(e=>[{testTitle:`should emit device if user grants access through hid.requestDevice (${e.productName})`,hidDevice:l({productId:e.usbProductId<<8,productName:e.productName}),expectedDeviceModel:e},{testTitle:`should emit device if user grants access through hid.requestDevice (${e.productName}, bootloader)`,hidDevice:l({productId:e.bootloaderUsbProductId,productName:e.productName}),expectedDeviceModel:e}]).forEach(e=>{it(e.testTitle,c=>{r.mockResolvedValueOnce([e.hidDevice]),d(o=>{try{expect(o).toEqual(expect.objectContaining({deviceModel:e.expectedDeviceModel})),c()}catch(n){c(n)}},o=>{c(o)})})}),it("should emit devices if new grant accesses",e=>{r.mockResolvedValueOnce([a,{...a,productId:20497,productName:"Ledger Nano S Plus"}]);let c=0;d(o=>{try{switch(c){case 0:expect(o).toEqual(expect.objectContaining({deviceModel:expect.objectContaining({id:u.NANO_X,productName:"Ledger Nano X",usbProductId:64})}));break;case 1:expect(o).toEqual(expect.objectContaining({deviceModel:expect.objectContaining({id:u.NANO_SP,productName:"Ledger Nano S Plus",usbProductId:80})})),e();break}c++}catch(n){e(n)}},o=>{e(o)})}),it("should throw DeviceNotRecognizedError if the device is not recognized",e=>{r.mockResolvedValueOnce([{...a,productId:16962}]),d(()=>{e("should not return a device")},c=>{expect(c).toBeInstanceOf(S),e()})}),it("should emit an error if the request device is in error",e=>{const c="request device error";r.mockImplementationOnce(()=>{throw new Error(c)}),d(()=>{e("should not return a device")},o=>{expect(o).toBeInstanceOf(E),expect(o).toStrictEqual(new E(new Error(c))),e()})}),it("should emit an error if the user did not grant us access to a device (clicking on cancel on the browser popup for ex)",e=>{r.mockResolvedValueOnce([]),d(c=>{e(`Should not emit any value, but emitted ${JSON.stringify(c)}`)},c=>{try{expect(c).toBeInstanceOf(E),e()}catch(o){e(o)}})}),it("should emit the same discoveredDevice object if its discovered twice in a row",async()=>{r.mockResolvedValue([a]),s.mockResolvedValue([a]);const e=await new Promise((o,n)=>{d(o,v=>n(v))}),c=await new Promise((o,n)=>{d(o,v=>n(v))});expect(c).toBe(e)})}),describe("destroy",()=>{it("should stop monitoring connections if the discovery process is halted",()=>{const t=jest.spyOn(AbortController.prototype,"abort");i.destroy(),expect(t).toHaveBeenCalled()})}),describe("connect",()=>{it("should throw UnknownDeviceError if no internal device",async()=>{const t={deviceId:"fake",onDisconnect:jest.fn()},e=await i.connect(t);expect(e).toStrictEqual(g(new C("Unknown device fake")))}),it("should throw OpeningConnectionError if the device is already opened",async()=>{const t={deviceId:"fake",onDisconnect:jest.fn()},e=await i.connect(t);expect(e).toStrictEqual(g(new C("Unknown device fake")))}),it("should throw OpeningConnectionError if the device cannot be opened",t=>{const e="cannot be opened",c={...a,open:()=>{throw new Error(e)}};r.mockResolvedValueOnce([c]),s.mockResolvedValue([c]),d(o=>{i.connect({deviceId:o.id,onDisconnect:jest.fn()}).then(n=>{expect(n).toStrictEqual(g(new B(new Error(e)))),t()}).catch(n=>{t(n)})},o=>{t(o)})}),it("should return the opened device",t=>{const e={...a,opened:!1,open:()=>(e.opened=!0,Promise.resolve())};r.mockResolvedValue([e]),s.mockResolvedValue([e]),d(c=>{i.connect({deviceId:c.id,onDisconnect:jest.fn()}).then(o=>{o.ifRight(n=>{expect(n).toEqual(expect.objectContaining({id:c.id})),t()}).ifLeft(()=>{t(o)})}).catch(o=>{t(o)})},c=>{t(c)})}),it("should return a device if available",t=>{r.mockResolvedValueOnce([a]),s.mockResolvedValue([a]),d(e=>{i.connect({deviceId:e.id,onDisconnect:jest.fn()}).then(c=>{c.ifRight(o=>{expect(o).toEqual(expect.objectContaining({id:e.id})),t()}).ifLeft(()=>{t(c)})}).catch(c=>{t(c)})},e=>{t(e)})})}),describe("disconnect",()=>{it("should throw an error if the device is not connected",async()=>{const t=T(),e=await i.disconnect({connectedDevice:t});expect(e).toStrictEqual(g(new C(`Unknown device ${t.id}`)))}),it("should disconnect if the device is connected",t=>{r.mockResolvedValueOnce([a]),s.mockResolvedValue([a]),d(e=>{i.connect({deviceId:e.id,onDisconnect:jest.fn()}).then(c=>{c.ifRight(o=>{i.disconnect({connectedDevice:o}).then(n=>{expect(n).toStrictEqual(R(void 0)),t()}).catch(n=>{t(n)})}).ifLeft(()=>{t(c)})}).catch(c=>{t(c)})},e=>{t(e)})}),it("should call disconnect handler if a connected device is unplugged",t=>{const e=jest.fn();r.mockResolvedValueOnce([a]),s.mockResolvedValue([a]),i.startDiscovering().subscribe({next:c=>{const o={sendApdu:jest.fn(),device:a,deviceId:c.id,disconnect:e,lostConnection:jest.fn().mockImplementation(()=>{setTimeout(()=>{o.disconnect()},p)})};i.connect({deviceId:c.id,onDisconnect:e}).then(async()=>{h(a),expect(a.close).toHaveBeenCalled(),await Promise.resolve(),expect(e).not.toHaveBeenCalled(),jest.advanceTimersByTime(p/2),expect(e).not.toHaveBeenCalled(),jest.advanceTimersByTime(p/2),expect(e).toHaveBeenCalled(),t()}).catch(n=>{t(n)})}})})}),describe("reconnect",()=>{it.only("should stop disconnection if reconnection happen",t=>{const e=jest.fn(),c=l(),o=l();r.mockResolvedValueOnce([c]),s.mockResolvedValue([c,o]),d(async n=>{const v={sendApdu:jest.fn(),device:o,deviceId:n.id,disconnect:e,lostConnection:jest.fn().mockImplementation(()=>{setTimeout(()=>{v.disconnect()},p)})};try{await i.connect({deviceId:n.id,onDisconnect:e}),h(c),expect(c.close).toHaveBeenCalled(),await Promise.resolve(),jest.advanceTimersByTime(p/3),b(o),expect(o.open).toHaveBeenCalled(),await Promise.resolve(),jest.advanceTimersByTime(p),expect(e).not.toHaveBeenCalled(),t()}catch(j){t(j)}})}),it("should be able to reconnect twice in a row if the device is unplugged and replugged twice",t=>{const e=jest.fn(),c=l(),o=l(),n=l();r.mockResolvedValueOnce([c]),s.mockResolvedValue([c,o,n]),d(async v=>{await i.connect({deviceId:v.id,onDisconnect:e});try{h(c),expect(c.close).toHaveBeenCalled(),await Promise.resolve(),jest.advanceTimersByTime(p/3),b(o),expect(o.open).toHaveBeenCalled(),await Promise.resolve(),jest.advanceTimersByTime(p),expect(e).not.toHaveBeenCalled(),h(o),expect(o.close).toHaveBeenCalled(),await Promise.resolve(),jest.advanceTimersByTime(p/3),b(n),expect(n.open).toHaveBeenCalled(),await Promise.resolve(),jest.advanceTimersByTime(p),expect(e).not.toHaveBeenCalled(),t()}catch(j){t(j)}})})}),describe("Connection event typeguard",()=>{it("should validate type of an HIDConnectionEvent",()=>{const t={device:a},e=i.isHIDConnectionEvent(t);expect(e).toBe(!0)}),it("should not validate type of another event",()=>{const t=new Event("disconnect",{}),e=i.isHIDConnectionEvent(t);expect(e).toBe(!1)})}),describe("listenToKnownDevices",()=>{it("should emit the devices already connected before listening",async()=>{const t=l();s.mockResolvedValue([t]);const e=jest.fn(),c=jest.fn();let o=[];i.listenToKnownDevices().subscribe({next:n=>{o=n},complete:e,error:c}),await m(),expect(o).toEqual([expect.objectContaining({deviceModel:expect.objectContaining({id:u.NANO_X})})]),expect(e).not.toHaveBeenCalled(),expect(c).not.toHaveBeenCalled()}),it("should emit the new list of devices after connection and disconnection events",async()=>{w();const t=l({productId:x.getDeviceModel({id:u.NANO_X}).usbProductId<<8}),e=l({productId:x.getDeviceModel({id:u.STAX}).usbProductId<<8});s.mockResolvedValue([t]);const c=jest.fn(),o=jest.fn();let n=[];i.listenToKnownDevices().subscribe({next:v=>{n=v},complete:c,error:o}),await m(),expect(n).toEqual([expect.objectContaining({deviceModel:expect.objectContaining({id:u.NANO_X})})]),s.mockResolvedValue([t,e]),b(e),await m(),expect(n).toEqual([expect.objectContaining({deviceModel:expect.objectContaining({id:u.NANO_X})}),expect.objectContaining({deviceModel:expect.objectContaining({id:u.STAX})})]),s.mockResolvedValue([e]),h(t),await m(),expect(n).toEqual([expect.objectContaining({deviceModel:expect.objectContaining({id:u.STAX})})]),expect(c).not.toHaveBeenCalled(),expect(o).not.toHaveBeenCalled()}),it("should preserve DeviceId in case the device has been disconnected and reconnected before the timeout",async()=>{const t=l();s.mockResolvedValue([t]);const e=jest.fn(),c=jest.fn();let o=[];i.listenToKnownDevices().subscribe({next:v=>{o=v},complete:e,error:c}),await m();const n=o[0]?.id;expect(n).toBeTruthy(),expect(o[0]?.deviceModel?.id).toBe(u.NANO_X),await i.connect({deviceId:o[0].id,onDisconnect:jest.fn()}),await m(),s.mockResolvedValue([]),h(t),await m(),expect(o).toEqual([]),s.mockResolvedValue([t]),b(t),await m(),expect(o).toEqual([expect.objectContaining({deviceModel:expect.objectContaining({id:u.NANO_X})})]),expect(o[0]?.id).toBeTruthy(),expect(o[0]?.id).toBe(n)})})})});
|
|
2
|
+
//# sourceMappingURL=WebHidTransport.test.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../src/api/transport/WebHidTransport.test.ts"],
|
|
4
|
+
"sourcesContent": ["import {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n connectedDeviceStubBuilder,\n type DeviceModel,\n DeviceModelId,\n DeviceNotRecognizedError,\n type LoggerPublisherService,\n type LoggerSubscriberService,\n NoAccessibleDeviceError,\n OpeningConnectionError,\n StaticDeviceModelDataSource,\n type TransportDeviceModel,\n type TransportDiscoveredDevice,\n UnknownDeviceError,\n} from \"@ledgerhq/device-management-kit\";\nimport { Left, Right } from \"purify-ts\";\nimport { Subject } from \"rxjs\";\n\nimport { RECONNECT_DEVICE_TIMEOUT } from \"@api/data/WebHidConfig\";\nimport { WebHidTransportNotSupportedError } from \"@api/model/Errors\";\nimport { hidDeviceStubBuilder } from \"@api/model/HIDDevice.stub\";\n\nimport { WebHidTransport } from \"./WebHidTransport\";\n\nclass LoggerPublisherServiceStub implements LoggerPublisherService {\n constructor(subscribers: LoggerSubscriberService[], tag: string) {\n this.subscribers = subscribers;\n this.tag = tag;\n }\n subscribers: LoggerSubscriberService[] = [];\n tag: string = \"\";\n error = jest.fn();\n warn = jest.fn();\n info = jest.fn();\n debug = jest.fn();\n}\n\n// Our StaticDeviceModelDataSource can directly be used in our unit tests\nconst usbDeviceModelDataSource = new StaticDeviceModelDataSource();\nconst logger = new LoggerPublisherServiceStub([], \"web-usb-hid\");\n\nconst stubDevice: HIDDevice = hidDeviceStubBuilder();\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\ndescribe(\"WebHidTransport\", () => {\n let transport: WebHidTransport;\n let apduReceiverServiceFactoryStub: ApduReceiverServiceFactory;\n let apduSenderServiceFactoryStub: ApduSenderServiceFactory;\n\n function initializeTransport() {\n apduReceiverServiceFactoryStub = jest.fn();\n apduSenderServiceFactoryStub = jest.fn();\n transport = new WebHidTransport(\n usbDeviceModelDataSource,\n () => logger,\n apduSenderServiceFactoryStub,\n apduReceiverServiceFactoryStub,\n );\n }\n\n beforeEach(() => {\n initializeTransport();\n jest.useFakeTimers();\n });\n\n afterEach(() => {\n jest.restoreAllMocks();\n });\n\n const discoverDevice = (\n onSuccess: (discoveredDevice: TransportDiscoveredDevice) => void,\n onError?: (error: unknown) => void,\n ) => {\n transport.startDiscovering().subscribe({\n next: onSuccess,\n error: onError,\n });\n };\n\n describe(\"When WebHID API is not supported\", () => {\n it(\"should not support the transport\", () => {\n expect(transport.isSupported()).toBe(false);\n });\n\n it(\"should emit a startDiscovering error\", (done) => {\n discoverDevice(\n () => {\n done(\"Should not emit any value\");\n },\n (error) => {\n expect(error).toBeInstanceOf(WebHidTransportNotSupportedError);\n done();\n },\n );\n });\n });\n\n describe(\"When WebHID API is supported\", () => {\n const mockedGetDevices = jest.fn();\n const mockedRequestDevice = jest.fn();\n\n const connectionEventsSubject = new Subject<HIDConnectionEvent>();\n const disconnectionEventsSubject = new Subject<HIDConnectionEvent>();\n\n function emitHIDConnectionEvent(device: HIDDevice) {\n connectionEventsSubject.next({\n device,\n } as HIDConnectionEvent);\n }\n\n function emitHIDDisconnectionEvent(device: HIDDevice) {\n disconnectionEventsSubject.next({\n device,\n } as HIDConnectionEvent);\n }\n\n beforeEach(() => {\n global.navigator = {\n hid: {\n getDevices: mockedGetDevices,\n requestDevice: mockedRequestDevice,\n addEventListener: (\n eventName: string,\n callback: (event: HIDConnectionEvent) => void,\n ) => {\n if (eventName === \"disconnect\") {\n disconnectionEventsSubject.subscribe(callback);\n } else if (eventName === \"connect\") {\n connectionEventsSubject.subscribe(callback);\n }\n },\n },\n } as unknown as Navigator;\n initializeTransport();\n });\n\n afterEach(() => {\n jest.clearAllMocks();\n global.navigator = undefined as unknown as Navigator;\n });\n\n it(\"should support the transport\", () => {\n expect(transport.isSupported()).toBe(true);\n });\n\n describe(\"startDiscovering\", () => {\n const testCases = usbDeviceModelDataSource\n .getAllDeviceModels()\n .flatMap((deviceModel) => {\n return [\n {\n testTitle: `should emit device if user grants access through hid.requestDevice (${deviceModel.productName})`,\n hidDevice: hidDeviceStubBuilder({\n productId: deviceModel.usbProductId << 8,\n productName: deviceModel.productName,\n }),\n expectedDeviceModel: deviceModel,\n },\n {\n testTitle: `should emit device if user grants access through hid.requestDevice (${deviceModel.productName}, bootloader)`,\n hidDevice: hidDeviceStubBuilder({\n productId: deviceModel.bootloaderUsbProductId,\n productName: deviceModel.productName,\n }),\n expectedDeviceModel: deviceModel,\n },\n ];\n });\n\n testCases.forEach((testCase) => {\n it(testCase.testTitle, (done) => {\n mockedRequestDevice.mockResolvedValueOnce([testCase.hidDevice]);\n\n discoverDevice(\n (discoveredDevice) => {\n try {\n expect(discoveredDevice).toEqual(\n expect.objectContaining({\n deviceModel: testCase.expectedDeviceModel,\n }),\n );\n\n done();\n } catch (expectError) {\n done(expectError);\n }\n },\n (error) => {\n done(error);\n },\n );\n });\n });\n\n // It does not seem possible for a user to select several devices on the browser popup.\n // But if it was possible, we should emit them\n it(\"should emit devices if new grant accesses\", (done) => {\n mockedRequestDevice.mockResolvedValueOnce([\n stubDevice,\n {\n ...stubDevice,\n productId: 0x5011,\n productName: \"Ledger Nano S Plus\",\n },\n ]);\n\n let count = 0;\n discoverDevice(\n (discoveredDevice) => {\n try {\n switch (count) {\n case 0:\n expect(discoveredDevice).toEqual(\n expect.objectContaining({\n deviceModel: expect.objectContaining({\n id: DeviceModelId.NANO_X,\n productName: \"Ledger Nano X\",\n usbProductId: 0x40,\n }) as DeviceModel,\n }),\n );\n break;\n case 1:\n expect(discoveredDevice).toEqual(\n expect.objectContaining({\n deviceModel: expect.objectContaining({\n id: DeviceModelId.NANO_SP,\n productName: \"Ledger Nano S Plus\",\n usbProductId: 0x50,\n }) as DeviceModel,\n }),\n );\n\n done();\n break;\n }\n\n count++;\n } catch (expectError) {\n done(expectError);\n }\n },\n (error) => {\n done(error);\n },\n );\n });\n\n it(\"should throw DeviceNotRecognizedError if the device is not recognized\", (done) => {\n mockedRequestDevice.mockResolvedValueOnce([\n {\n ...stubDevice,\n productId: 0x4242,\n },\n ]);\n\n discoverDevice(\n () => {\n done(\"should not return a device\");\n },\n (error) => {\n expect(error).toBeInstanceOf(DeviceNotRecognizedError);\n done();\n },\n );\n });\n\n it(\"should emit an error if the request device is in error\", (done) => {\n const message = \"request device error\";\n mockedRequestDevice.mockImplementationOnce(() => {\n throw new Error(message);\n });\n\n discoverDevice(\n () => {\n done(\"should not return a device\");\n },\n (error) => {\n expect(error).toBeInstanceOf(NoAccessibleDeviceError);\n expect(error).toStrictEqual(\n new NoAccessibleDeviceError(new Error(message)),\n );\n done();\n },\n );\n });\n\n // [ASK] Is this the behavior we want when the user does not select any device ?\n it(\"should emit an error if the user did not grant us access to a device (clicking on cancel on the browser popup for ex)\", (done) => {\n // When the user does not select any device, the `requestDevice` will return an empty array\n mockedRequestDevice.mockResolvedValueOnce([]);\n\n discoverDevice(\n (discoveredDevice) => {\n done(\n `Should not emit any value, but emitted ${JSON.stringify(\n discoveredDevice,\n )}`,\n );\n },\n (error) => {\n try {\n expect(error).toBeInstanceOf(NoAccessibleDeviceError);\n done();\n } catch (expectError) {\n done(expectError);\n }\n },\n );\n });\n\n it(\"should emit the same discoveredDevice object if its discovered twice in a row\", async () => {\n mockedRequestDevice.mockResolvedValue([stubDevice]);\n mockedGetDevices.mockResolvedValue([stubDevice]);\n\n const firstDiscoveredDevice = await new Promise((resolve, reject) => {\n discoverDevice(resolve, (err) => reject(err));\n });\n const secondDiscoveredDevice = await new Promise((resolve, reject) => {\n discoverDevice(resolve, (err) => reject(err));\n });\n expect(secondDiscoveredDevice).toBe(firstDiscoveredDevice);\n });\n });\n\n describe(\"destroy\", () => {\n it(\"should stop monitoring connections if the discovery process is halted\", () => {\n const abortSpy = jest.spyOn(AbortController.prototype, \"abort\");\n\n transport.destroy();\n\n expect(abortSpy).toHaveBeenCalled();\n });\n });\n\n describe(\"connect\", () => {\n it(\"should throw UnknownDeviceError if no internal device\", async () => {\n const connectParams = {\n deviceId: \"fake\",\n onDisconnect: jest.fn(),\n };\n\n const connect = await transport.connect(connectParams);\n\n expect(connect).toStrictEqual(\n Left(new UnknownDeviceError(\"Unknown device fake\")),\n );\n });\n\n it(\"should throw OpeningConnectionError if the device is already opened\", async () => {\n const device = {\n deviceId: \"fake\",\n onDisconnect: jest.fn(),\n };\n\n const connect = await transport.connect(device);\n\n expect(connect).toStrictEqual(\n Left(new UnknownDeviceError(\"Unknown device fake\")),\n );\n });\n\n it(\"should throw OpeningConnectionError if the device cannot be opened\", (done) => {\n const message = \"cannot be opened\";\n const mockedDevice = {\n ...stubDevice,\n open: () => {\n throw new Error(message);\n },\n };\n mockedRequestDevice.mockResolvedValueOnce([mockedDevice]);\n mockedGetDevices.mockResolvedValue([mockedDevice]);\n\n discoverDevice(\n (discoveredDevice) => {\n transport\n .connect({\n deviceId: discoveredDevice.id,\n onDisconnect: jest.fn(),\n })\n .then((value) => {\n expect(value).toStrictEqual(\n Left(new OpeningConnectionError(new Error(message))),\n );\n done();\n })\n .catch((error) => {\n done(error);\n });\n },\n (error) => {\n done(error);\n },\n );\n });\n\n it(\"should return the opened device\", (done) => {\n const mockedDevice = {\n ...stubDevice,\n opened: false,\n open: () => {\n mockedDevice.opened = true;\n return Promise.resolve();\n },\n };\n\n mockedRequestDevice.mockResolvedValue([mockedDevice]);\n mockedGetDevices.mockResolvedValue([mockedDevice]);\n\n discoverDevice(\n (discoveredDevice) => {\n transport\n .connect({\n deviceId: discoveredDevice.id,\n onDisconnect: jest.fn(),\n })\n .then((connectedDevice) => {\n connectedDevice\n .ifRight((device) => {\n expect(device).toEqual(\n expect.objectContaining({ id: discoveredDevice.id }),\n );\n done();\n })\n .ifLeft(() => {\n done(connectedDevice);\n });\n })\n .catch((error) => {\n done(error);\n });\n },\n (error) => {\n done(error);\n },\n );\n });\n\n it(\"should return a device if available\", (done) => {\n mockedRequestDevice.mockResolvedValueOnce([stubDevice]);\n mockedGetDevices.mockResolvedValue([stubDevice]);\n\n discoverDevice(\n (discoveredDevice) => {\n transport\n .connect({\n deviceId: discoveredDevice.id,\n onDisconnect: jest.fn(),\n })\n .then((connectedDevice) => {\n connectedDevice\n .ifRight((device) => {\n expect(device).toEqual(\n expect.objectContaining({ id: discoveredDevice.id }),\n );\n done();\n })\n .ifLeft(() => {\n done(connectedDevice);\n });\n })\n .catch((error) => {\n done(error);\n });\n },\n (error) => {\n done(error);\n },\n );\n });\n });\n\n describe(\"disconnect\", () => {\n it(\"should throw an error if the device is not connected\", async () => {\n // given\n const connectedDevice = connectedDeviceStubBuilder();\n\n // when\n const disconnect = await transport.disconnect({\n connectedDevice,\n });\n\n expect(disconnect).toStrictEqual(\n Left(new UnknownDeviceError(`Unknown device ${connectedDevice.id}`)),\n );\n });\n\n it(\"should disconnect if the device is connected\", (done) => {\n mockedRequestDevice.mockResolvedValueOnce([stubDevice]);\n mockedGetDevices.mockResolvedValue([stubDevice]);\n\n discoverDevice(\n (discoveredDevice) => {\n transport\n .connect({\n deviceId: discoveredDevice.id,\n onDisconnect: jest.fn(),\n })\n .then((connectedDevice) => {\n connectedDevice\n .ifRight((device) => {\n transport\n .disconnect({ connectedDevice: device })\n .then((value) => {\n expect(value).toStrictEqual(Right(undefined));\n done();\n })\n .catch((error) => {\n done(error);\n });\n })\n .ifLeft(() => {\n done(connectedDevice);\n });\n })\n .catch((error) => {\n done(error);\n });\n },\n (error) => {\n done(error);\n },\n );\n });\n\n it(\"should call disconnect handler if a connected device is unplugged\", (done) => {\n // given\n const onDisconnect = jest.fn();\n mockedRequestDevice.mockResolvedValueOnce([stubDevice]);\n mockedGetDevices.mockResolvedValue([stubDevice]);\n\n // when\n transport.startDiscovering().subscribe({\n next: (discoveredDevice) => {\n const mock = {\n sendApdu: jest.fn(),\n device: stubDevice,\n deviceId: discoveredDevice.id,\n disconnect: onDisconnect,\n lostConnection: jest.fn().mockImplementation(() => {\n setTimeout(() => {\n mock.disconnect();\n }, RECONNECT_DEVICE_TIMEOUT);\n }),\n };\n\n transport\n .connect({\n deviceId: discoveredDevice.id,\n onDisconnect,\n })\n .then(async () => {\n emitHIDDisconnectionEvent(stubDevice);\n\n expect(stubDevice.close).toHaveBeenCalled();\n await Promise.resolve(); // wait for the next tick so the stubDevice.close promise is resolved\n expect(onDisconnect).not.toHaveBeenCalled();\n jest.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT / 2);\n expect(onDisconnect).not.toHaveBeenCalled();\n jest.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT / 2);\n expect(onDisconnect).toHaveBeenCalled();\n done();\n })\n .catch((error) => {\n done(error);\n });\n },\n });\n });\n });\n\n describe(\"reconnect\", () => {\n it.only(\"should stop disconnection if reconnection happen\", (done) => {\n // given\n const onDisconnect = jest.fn();\n\n const hidDevice1 = hidDeviceStubBuilder();\n const hidDevice2 = hidDeviceStubBuilder();\n\n mockedRequestDevice.mockResolvedValueOnce([hidDevice1]);\n mockedGetDevices.mockResolvedValue([hidDevice1, hidDevice2]);\n\n discoverDevice(async (discoveredDevice) => {\n const mock = {\n sendApdu: jest.fn(),\n device: hidDevice2,\n deviceId: discoveredDevice.id,\n disconnect: onDisconnect,\n lostConnection: jest.fn().mockImplementation(() => {\n setTimeout(() => {\n mock.disconnect();\n }, RECONNECT_DEVICE_TIMEOUT);\n }),\n };\n\n try {\n await transport.connect({\n deviceId: discoveredDevice.id,\n onDisconnect,\n });\n\n /* Disconnection */\n emitHIDDisconnectionEvent(hidDevice1);\n expect(hidDevice1.close).toHaveBeenCalled();\n await Promise.resolve(); // wait for the next tick so the hidDevice1.close promise is resolved\n\n jest.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT / 3);\n\n /* Reconnection */\n emitHIDConnectionEvent(hidDevice2);\n\n expect(hidDevice2.open).toHaveBeenCalled();\n await Promise.resolve(); // wait for the next tick so the hidDevice2.open promise is resolved\n\n jest.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT);\n expect(onDisconnect).not.toHaveBeenCalled();\n done();\n } catch (error) {\n done(error);\n }\n });\n });\n\n it(\"should be able to reconnect twice in a row if the device is unplugged and replugged twice\", (done) => {\n // given\n const onDisconnect = jest.fn();\n\n const hidDevice1 = hidDeviceStubBuilder();\n const hidDevice2 = hidDeviceStubBuilder();\n const hidDevice3 = hidDeviceStubBuilder();\n\n mockedRequestDevice.mockResolvedValueOnce([hidDevice1]);\n mockedGetDevices.mockResolvedValue([\n hidDevice1,\n hidDevice2,\n hidDevice3,\n ]);\n\n // when\n discoverDevice(async (discoveredDevice) => {\n await transport.connect({\n deviceId: discoveredDevice.id,\n onDisconnect,\n });\n try {\n /* First disconnection */\n emitHIDDisconnectionEvent(hidDevice1);\n expect(hidDevice1.close).toHaveBeenCalled();\n await Promise.resolve(); // wait for the next tick so the hidDevice1.close promise is resolved\n jest.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT / 3);\n\n /* First reconnection */\n emitHIDConnectionEvent(hidDevice2);\n\n expect(hidDevice2.open).toHaveBeenCalled();\n await Promise.resolve(); // wait for the next tick so the hidDevice2.open promise is resolved\n jest.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT);\n expect(onDisconnect).not.toHaveBeenCalled();\n\n /* Second disconnection */\n emitHIDDisconnectionEvent(hidDevice2);\n expect(hidDevice2.close).toHaveBeenCalled();\n await Promise.resolve(); // wait for the next tick so the hidDevice2.close promise is resolved\n jest.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT / 3);\n\n /* Second reconnection */\n emitHIDConnectionEvent(hidDevice3);\n\n expect(hidDevice3.open).toHaveBeenCalled();\n await Promise.resolve(); // wait for the next tick so the hidDevice3.open promise is resolved\n jest.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT);\n expect(onDisconnect).not.toHaveBeenCalled();\n\n done();\n } catch (error) {\n done(error);\n }\n });\n });\n });\n\n describe(\"Connection event typeguard\", () => {\n it(\"should validate type of an HIDConnectionEvent\", () => {\n // given\n const event = {\n device: stubDevice,\n } as HIDConnectionEvent;\n // when\n // @ts-expect-error trying to access private member\n const result = transport.isHIDConnectionEvent(event);\n // then\n expect(result).toBe(true);\n });\n it(\"should not validate type of another event\", () => {\n // given\n const event = new Event(\"disconnect\", {});\n // when\n // @ts-expect-error trying to access private member\n const result = transport.isHIDConnectionEvent(event);\n // then\n expect(result).toBe(false);\n });\n });\n\n describe(\"listenToKnownDevices\", () => {\n it(\"should emit the devices already connected before listening\", async () => {\n // given\n const hidDevice = hidDeviceStubBuilder();\n mockedGetDevices.mockResolvedValue([hidDevice]);\n\n const onComplete = jest.fn();\n const onError = jest.fn();\n\n let observedDevices: TransportDiscoveredDevice[] = [];\n // when\n transport.listenToKnownDevices().subscribe({\n next: (knownDevices) => {\n observedDevices = knownDevices;\n },\n complete: onComplete,\n error: onError,\n });\n\n await flushPromises();\n\n expect(observedDevices).toEqual([\n expect.objectContaining({\n deviceModel: expect.objectContaining({\n id: DeviceModelId.NANO_X,\n }) as TransportDeviceModel,\n }),\n ]);\n expect(onComplete).not.toHaveBeenCalled();\n expect(onError).not.toHaveBeenCalled();\n });\n\n it(\"should emit the new list of devices after connection and disconnection events\", async () => {\n initializeTransport();\n // given\n const hidDevice1 = hidDeviceStubBuilder({\n productId:\n usbDeviceModelDataSource.getDeviceModel({\n id: DeviceModelId.NANO_X,\n }).usbProductId << 8,\n });\n const hidDevice2 = hidDeviceStubBuilder({\n productId:\n usbDeviceModelDataSource.getDeviceModel({ id: DeviceModelId.STAX })\n .usbProductId << 8,\n });\n mockedGetDevices.mockResolvedValue([hidDevice1]);\n\n const onComplete = jest.fn();\n const onError = jest.fn();\n\n let observedDevices: TransportDiscoveredDevice[] = [];\n // when\n transport.listenToKnownDevices().subscribe({\n next: (knownDevices) => {\n observedDevices = knownDevices;\n },\n complete: onComplete,\n error: onError,\n });\n\n await flushPromises();\n\n expect(observedDevices).toEqual([\n expect.objectContaining({\n deviceModel: expect.objectContaining({\n id: DeviceModelId.NANO_X,\n }) as TransportDeviceModel,\n }),\n ]);\n\n // When a new device is connected\n mockedGetDevices.mockResolvedValue([hidDevice1, hidDevice2]);\n emitHIDConnectionEvent(hidDevice2);\n await flushPromises();\n\n expect(observedDevices).toEqual([\n expect.objectContaining({\n deviceModel: expect.objectContaining({\n id: DeviceModelId.NANO_X,\n }) as TransportDeviceModel,\n }),\n expect.objectContaining({\n deviceModel: expect.objectContaining({\n id: DeviceModelId.STAX,\n }) as TransportDeviceModel,\n }),\n ]);\n\n // When a device is disconnected\n mockedGetDevices.mockResolvedValue([hidDevice2]);\n emitHIDDisconnectionEvent(hidDevice1);\n await flushPromises();\n\n expect(observedDevices).toEqual([\n expect.objectContaining({\n deviceModel: expect.objectContaining({\n id: DeviceModelId.STAX,\n }) as TransportDeviceModel,\n }),\n ]);\n\n expect(onComplete).not.toHaveBeenCalled();\n expect(onError).not.toHaveBeenCalled();\n });\n\n it(\"should preserve DeviceId in case the device has been disconnected and reconnected before the timeout\", async () => {\n // given\n const hidDevice = hidDeviceStubBuilder();\n\n mockedGetDevices.mockResolvedValue([hidDevice]);\n\n const onComplete = jest.fn();\n const onError = jest.fn();\n let observedDevices: TransportDiscoveredDevice[] = [];\n // when\n transport.listenToKnownDevices().subscribe({\n next: (knownDevices) => {\n observedDevices = knownDevices;\n },\n complete: onComplete,\n error: onError,\n });\n\n await flushPromises();\n\n const firstObservedDeviceId = observedDevices[0]?.id;\n expect(firstObservedDeviceId).toBeTruthy();\n expect(observedDevices[0]?.deviceModel?.id).toBe(DeviceModelId.NANO_X);\n\n // Start a connection with the device\n await transport.connect({\n deviceId: observedDevices[0]!.id,\n onDisconnect: jest.fn(),\n });\n await flushPromises();\n\n // When the device is disconnected\n mockedGetDevices.mockResolvedValue([]);\n emitHIDDisconnectionEvent(hidDevice);\n await flushPromises();\n\n expect(observedDevices).toEqual([]);\n\n // When the device is reconnected\n mockedGetDevices.mockResolvedValue([hidDevice]);\n emitHIDConnectionEvent(hidDevice);\n await flushPromises();\n\n expect(observedDevices).toEqual([\n expect.objectContaining({\n deviceModel: expect.objectContaining({\n id: DeviceModelId.NANO_X,\n }) as TransportDeviceModel,\n }),\n ]);\n\n expect(observedDevices[0]?.id).toBeTruthy();\n expect(observedDevices[0]?.id).toBe(firstObservedDeviceId);\n });\n });\n });\n});\n"],
|
|
5
|
+
"mappings": "AAAA,OAGE,8BAAAA,EAEA,iBAAAC,EACA,4BAAAC,EAGA,2BAAAC,EACA,0BAAAC,EACA,+BAAAC,EAGA,sBAAAC,MACK,kCACP,OAAS,QAAAC,EAAM,SAAAC,MAAa,YAC5B,OAAS,WAAAC,MAAe,OAExB,OAAS,4BAAAC,MAAgC,yBACzC,OAAS,oCAAAC,MAAwC,oBACjD,OAAS,wBAAAC,MAA4B,4BAErC,OAAS,mBAAAC,MAAuB,oBAEhC,MAAMC,CA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iB,CACtB,YAAa,OAAO,iBAAiB,CACnC,GAAIjE,EAAc,MACpB,CAAC,CACH,CAAC,CACH,CAAC,EAED,OAAOiE,EAAgB,CAAC,GAAG,EAAE,EAAE,WAAW,EAC1C,OAAOA,EAAgB,CAAC,GAAG,EAAE,EAAE,KAAKE,CAAqB,CAC3D,CAAC,CACH,CAAC,CACH,CAAC,CACH,CAAC",
|
|
6
|
+
"names": ["connectedDeviceStubBuilder", "DeviceModelId", "DeviceNotRecognizedError", "NoAccessibleDeviceError", "OpeningConnectionError", "StaticDeviceModelDataSource", "UnknownDeviceError", "Left", "Right", "Subject", "RECONNECT_DEVICE_TIMEOUT", "WebHidTransportNotSupportedError", "hidDeviceStubBuilder", "WebHidTransport", "LoggerPublisherServiceStub", "subscribers", "tag", "usbDeviceModelDataSource", "logger", "stubDevice", "flushPromises", "transport", "apduReceiverServiceFactoryStub", "apduSenderServiceFactoryStub", "initializeTransport", "discoverDevice", "onSuccess", "onError", "done", "error", "mockedGetDevices", "mockedRequestDevice", "connectionEventsSubject", "disconnectionEventsSubject", "emitHIDConnectionEvent", "device", "emitHIDDisconnectionEvent", "eventName", "callback", "deviceModel", "testCase", "discoveredDevice", "expectError", "count", "message", "firstDiscoveredDevice", "resolve", "reject", "err", "secondDiscoveredDevice", "abortSpy", "connectParams", "connect", "mockedDevice", "value", "connectedDevice", "disconnect", "onDisconnect", "mock", "hidDevice1", "hidDevice2", "hidDevice3", "event", "result", "hidDevice", "onComplete", "observedDevices", "knownDevices", "firstObservedDeviceId"]
|
|
7
|
+
}
|