@ledgerhq/device-transport-kit-web-hid 0.0.0-webhid-20250129103551 → 0.0.0-wrong-error-when-in-experimental-provider-20251021162636
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/lib/esm/api/model/HIDDevice.stub.js +1 -1
- package/lib/esm/api/model/HIDDevice.stub.js.map +2 -2
- package/lib/esm/api/transport/WebHidApduSender.js +2 -0
- package/lib/esm/api/transport/WebHidApduSender.js.map +7 -0
- package/lib/esm/api/transport/WebHidApduSender.test.js +2 -0
- package/lib/esm/api/transport/WebHidApduSender.test.js.map +7 -0
- package/lib/esm/api/transport/WebHidTransport.js +1 -1
- package/lib/esm/api/transport/WebHidTransport.js.map +3 -3
- package/lib/esm/api/transport/WebHidTransport.test.js +1 -1
- package/lib/esm/api/transport/WebHidTransport.test.js.map +3 -3
- package/lib/esm/package.json +16 -16
- package/lib/types/api/model/HIDDevice.stub.d.ts.map +1 -1
- package/lib/types/api/transport/WebHidApduSender.d.ts +25 -0
- package/lib/types/api/transport/WebHidApduSender.d.ts.map +1 -0
- package/lib/types/api/transport/WebHidApduSender.test.d.ts +2 -0
- package/lib/types/api/transport/WebHidApduSender.test.d.ts.map +1 -0
- package/lib/types/api/transport/WebHidTransport.d.ts +8 -5
- package/lib/types/api/transport/WebHidTransport.d.ts.map +1 -1
- package/lib/types/tsconfig.prod.tsbuildinfo +1 -1
- package/package.json +18 -18
- package/lib/esm/api/transport/WebHidDeviceConnection.js +0 -2
- package/lib/esm/api/transport/WebHidDeviceConnection.js.map +0 -7
- package/lib/esm/api/transport/WebHidDeviceConnection.stub.js +0 -2
- package/lib/esm/api/transport/WebHidDeviceConnection.stub.js.map +0 -7
- package/lib/esm/api/transport/WebHidDeviceConnection.test.js +0 -2
- package/lib/esm/api/transport/WebHidDeviceConnection.test.js.map +0 -7
- package/lib/types/api/transport/WebHidDeviceConnection.d.ts +0 -50
- package/lib/types/api/transport/WebHidDeviceConnection.d.ts.map +0 -1
- package/lib/types/api/transport/WebHidDeviceConnection.stub.d.ts +0 -5
- package/lib/types/api/transport/WebHidDeviceConnection.stub.d.ts.map +0 -1
- package/lib/types/api/transport/WebHidDeviceConnection.test.d.ts +0 -2
- package/lib/types/api/transport/WebHidDeviceConnection.test.d.ts.map +0 -1
package/README.md
CHANGED
|
@@ -32,7 +32,7 @@ This library works in [any browser supporting the WebHID API](https://developer.
|
|
|
32
32
|
|
|
33
33
|
### Pre-requisites
|
|
34
34
|
|
|
35
|
-
To use this transport, ensure you have the Device
|
|
35
|
+
To use this transport, ensure you have the Device Management Kit installed in your project.
|
|
36
36
|
|
|
37
37
|
### Main Features
|
|
38
38
|
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=
|
|
1
|
+
const e=vi.fn().mockResolvedValue(void 0),o=(n={})=>({opened:!1,productId:16401,vendorId:11415,productName:"Ledger Nano X",collections:[],open:vi.fn().mockResolvedValue(void 0),oninputreport:e,close:vi.fn().mockResolvedValue(void 0),sendReport:vi.fn().mockResolvedValue(e()),sendFeatureReport:vi.fn(),forget:vi.fn(),receiveFeatureReport:vi.fn(),addEventListener:vi.fn(),removeEventListener:vi.fn(),dispatchEvent:vi.fn(),...n});export{o as hidDeviceStubBuilder};
|
|
2
2
|
//# sourceMappingURL=HIDDevice.stub.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/api/model/HIDDevice.stub.ts"],
|
|
4
|
-
"sourcesContent": ["const oninputreport =
|
|
5
|
-
"mappings": "AAAA,MAAMA,EAAgB,
|
|
4
|
+
"sourcesContent": ["const oninputreport = vi.fn().mockResolvedValue(undefined);\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: vi.fn().mockResolvedValue(undefined),\n oninputreport,\n close: vi.fn().mockResolvedValue(undefined),\n sendReport: vi.fn().mockResolvedValue(oninputreport()),\n sendFeatureReport: vi.fn(),\n forget: vi.fn(),\n receiveFeatureReport: vi.fn(),\n addEventListener: vi.fn(),\n removeEventListener: vi.fn(),\n dispatchEvent: vi.fn(),\n ...props,\n});\n"],
|
|
5
|
+
"mappings": "AAAA,MAAMA,EAAgB,GAAG,GAAG,EAAE,kBAAkB,MAAS,EAE5CC,EAAuB,CAClCC,EAA4B,CAAC,KACd,CACf,OAAQ,GACR,UAAW,MACX,SAAU,MACV,YAAa,gBACb,YAAa,CAAC,EACd,KAAM,GAAG,GAAG,EAAE,kBAAkB,MAAS,EACzC,cAAAF,EACA,MAAO,GAAG,GAAG,EAAE,kBAAkB,MAAS,EAC1C,WAAY,GAAG,GAAG,EAAE,kBAAkBA,EAAc,CAAC,EACrD,kBAAmB,GAAG,GAAG,EACzB,OAAQ,GAAG,GAAG,EACd,qBAAsB,GAAG,GAAG,EAC5B,iBAAkB,GAAG,GAAG,EACxB,oBAAqB,GAAG,GAAG,EAC3B,cAAe,GAAG,GAAG,EACrB,GAAGE,CACL",
|
|
6
6
|
"names": ["oninputreport", "hidDeviceStubBuilder", "props"]
|
|
7
7
|
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{FramerUtils as c,OpeningConnectionError as a,SendApduTimeoutError as u}from"@ledgerhq/device-management-kit";import*as v from"@sentry/minimal";import{Left as s,Maybe as p,Nothing as m,Right as g}from"purify-ts";import{FRAME_SIZE as h}from"../data/WebHidConfig";import{WebHidSendReportError as l}from"../model/Errors";class b{dependencies;apduSender;apduReceiver;sendApduPromiseResolver;logger;constructor({dependencies:e,apduSenderFactory:d,apduReceiverFactory:n},r){const i=p.of(c.numberToByteArray(Math.floor(Math.random()*65535),2));this.logger=r("WebHidApduSender"),this.apduSender=d({frameSize:h,channel:i,padding:!0}),this.apduReceiver=n({channel:i}),this.sendApduPromiseResolver=m,this.dependencies=e,this.logger.info("\u{1F50C} Connected to device")}async sendApdu(e,d,n){this.logger.debug("[sendApdu]",{data:{apdu:e,abortTimeout:n}});let r;const i=new Promise(t=>{this.sendApduPromiseResolver=p.of((...o)=>(r&&clearTimeout(r),t(...o)))});for(const t of this.apduSender.getFrames(e))try{await this.dependencies.device.sendReport(0,new Uint8Array(t.getRawData()))}catch(o){return this.logger.info("Error sending frame",{data:{error:o}}),Promise.resolve(s(new l(o)))}return n&&(r=setTimeout(()=>{this.logger.debug("[sendApdu] Abort timeout",{data:{abortTimeout:n}}),this.sendApduPromiseResolver.map(t=>t(s(new u("Abort timeout"))))},n)),i}receiveHidInputReport(e){const d=new Uint8Array(e.data.buffer);this.apduReceiver.handleFrame(d).map(r=>{r.map(i=>{this.logger.debug("Received APDU Response",{data:{response:i}}),this.sendApduPromiseResolver.map(t=>t(g(i)))})}).mapLeft(r=>{this.sendApduPromiseResolver.map(i=>i(s(r)))})}getDependencies(){return this.dependencies}setDependencies(e){this.dependencies=e}async setupConnection(){try{this.dependencies.device.oninputreport=e=>this.receiveHidInputReport(e),await this.dependencies.device.open()}catch(e){if(e instanceof DOMException&&e.name==="InvalidStateError")this.logger.info("Device is already opened");else{const d=new a(e);throw this.logger.error("Error while opening device",{data:{error:e}}),v.captureException(d),e}}}closeConnection(){this.logger.info("\u{1F51A} Disconnect");try{this.dependencies.device.close()}catch(e){this.logger.error("Error while closing device",{data:{device:this.dependencies.device,error:e}})}}}export{b as WebHidApduSender};
|
|
2
|
+
//# sourceMappingURL=WebHidApduSender.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../src/api/transport/WebHidApduSender.ts"],
|
|
4
|
+
"sourcesContent": ["import {\n type ApduReceiverService,\n type ApduReceiverServiceFactory,\n type ApduResponse,\n type ApduSenderService,\n type ApduSenderServiceFactory,\n type DeviceApduSender,\n type DmkError,\n FramerUtils,\n type LoggerPublisherService,\n OpeningConnectionError,\n SendApduTimeoutError,\n} from \"@ledgerhq/device-management-kit\";\nimport * as Sentry from \"@sentry/minimal\";\nimport { type Either, Left, Maybe, Nothing, Right } from \"purify-ts\";\n\nimport { FRAME_SIZE } from \"@api/data/WebHidConfig\";\nimport { WebHidSendReportError } from \"@api/model/Errors\";\n\nexport type WebHidApduSenderConstructorArgs = {\n dependencies: WebHidApduSenderDependencies;\n apduSenderFactory: ApduSenderServiceFactory;\n apduReceiverFactory: ApduReceiverServiceFactory;\n};\n\nexport type WebHidApduSenderDependencies = {\n device: HIDDevice;\n};\n\nexport class WebHidApduSender\n implements DeviceApduSender<WebHidApduSenderDependencies>\n{\n private dependencies: WebHidApduSenderDependencies;\n private readonly apduSender: ApduSenderService;\n private readonly apduReceiver: ApduReceiverService;\n private sendApduPromiseResolver: Maybe<\n (value: Either<DmkError, ApduResponse>) => void\n >;\n private readonly logger: LoggerPublisherService;\n\n constructor(\n {\n dependencies,\n apduSenderFactory,\n apduReceiverFactory,\n }: WebHidApduSenderConstructorArgs,\n loggerServiceFactory: (tag: string) => LoggerPublisherService,\n ) {\n const channel = Maybe.of(\n FramerUtils.numberToByteArray(Math.floor(Math.random() * 0xffff), 2),\n );\n this.logger = loggerServiceFactory(\"WebHidApduSender\");\n this.apduSender = apduSenderFactory({\n frameSize: FRAME_SIZE,\n channel,\n padding: true,\n });\n this.apduReceiver = apduReceiverFactory({ channel });\n this.sendApduPromiseResolver = Nothing;\n this.dependencies = dependencies;\n this.logger.info(\"\uD83D\uDD0C Connected to device\");\n }\n\n async sendApdu(\n apdu: Uint8Array,\n _triggersDisconnection?: boolean,\n abortTimeout?: number,\n ): Promise<Either<DmkError, ApduResponse>> {\n this.logger.debug(\"[sendApdu]\", {\n data: { apdu, abortTimeout },\n });\n\n let timeout: ReturnType<typeof setTimeout> | undefined;\n\n const resultPromise = new Promise<Either<DmkError, ApduResponse>>(\n (resolve) => {\n this.sendApduPromiseResolver = Maybe.of((...args) => {\n if (timeout) {\n clearTimeout(timeout);\n }\n return resolve(...args);\n });\n },\n );\n\n for (const frame of this.apduSender.getFrames(apdu)) {\n try {\n await this.dependencies.device.sendReport(\n 0,\n new Uint8Array(frame.getRawData()),\n );\n } catch (error) {\n this.logger.info(\"Error sending frame\", { data: { error } });\n return Promise.resolve(Left(new WebHidSendReportError(error)));\n }\n }\n\n if (abortTimeout) {\n timeout = setTimeout(() => {\n this.logger.debug(\"[sendApdu] Abort timeout\", {\n data: { abortTimeout },\n });\n this.sendApduPromiseResolver.map((resolve) =>\n resolve(Left(new SendApduTimeoutError(\"Abort timeout\"))),\n );\n }, abortTimeout);\n }\n\n return resultPromise;\n }\n\n private receiveHidInputReport(event: HIDInputReportEvent) {\n const data = new Uint8Array(event.data.buffer);\n const maybeApduResponse = this.apduReceiver.handleFrame(data);\n\n maybeApduResponse\n .map((response) => {\n response.map((apduResponse) => {\n this.logger.debug(\"Received APDU Response\", {\n data: { response: apduResponse },\n });\n this.sendApduPromiseResolver.map((resolve) =>\n resolve(Right(apduResponse)),\n );\n });\n })\n .mapLeft((error) => {\n this.sendApduPromiseResolver.map((resolve) => resolve(Left(error)));\n });\n }\n\n public getDependencies() {\n return this.dependencies;\n }\n\n public setDependencies(dependencies: WebHidApduSenderDependencies) {\n this.dependencies = dependencies;\n }\n\n public async setupConnection() {\n try {\n this.dependencies.device.oninputreport = (event) =>\n this.receiveHidInputReport(event);\n await this.dependencies.device.open();\n } catch (error) {\n if (error instanceof DOMException && error.name === \"InvalidStateError\") {\n this.logger.info(`Device is already opened`);\n } else {\n const connectionError = new OpeningConnectionError(error);\n this.logger.error(`Error while opening device`, {\n data: { error },\n });\n Sentry.captureException(connectionError);\n throw error;\n }\n }\n }\n\n public closeConnection() {\n this.logger.info(\"\uD83D\uDD1A Disconnect\");\n try {\n this.dependencies.device.close();\n } catch (error) {\n this.logger.error(\"Error while closing device\", {\n data: { device: this.dependencies.device, error },\n });\n }\n }\n}\n"],
|
|
5
|
+
"mappings": "AAAA,OAQE,eAAAA,EAEA,0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AK,OAAO,MAAM,6BAA8B,CAC9C,KAAM,CAAE,OAAQ,KAAK,aAAa,OAAQ,MAAAA,CAAM,CAClD,CAAC,CACH,CACF,CACF",
|
|
6
|
+
"names": ["FramerUtils", "OpeningConnectionError", "SendApduTimeoutError", "Sentry", "Left", "Maybe", "Nothing", "Right", "FRAME_SIZE", "WebHidSendReportError", "WebHidApduSender", "dependencies", "apduSenderFactory", "apduReceiverFactory", "loggerServiceFactory", "channel", "apdu", "_triggersDisconnection", "abortTimeout", "timeout", "resultPromise", "resolve", "args", "frame", "error", "event", "data", "response", "apduResponse", "connectionError"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{SendApduTimeoutError as u}from"@ledgerhq/device-management-kit";import{Left as p,Maybe as l,Right as x}from"purify-ts";import{WebHidSendReportError as m}from"../model/Errors";import{WebHidApduSender as f}from"./WebHidApduSender";describe("WebHidApduSender",()=>{const c={getFrames:vi.fn()},i={handleFrame:vi.fn()},d={info:vi.fn(),debug:vi.fn(),error:vi.fn()},t={oninputreport:vi.fn(),open:vi.fn(),close:vi.fn(),sendReport:vi.fn()};let n;beforeEach(()=>{vi.clearAllMocks();const e=vi.fn().mockReturnValue(d),r=vi.fn().mockReturnValue(c),o=vi.fn().mockReturnValue(i);n=new f({dependencies:{device:t},apduSenderFactory:r,apduReceiverFactory:o},e)}),afterEach(()=>{vi.restoreAllMocks()}),it("should get dependencies",()=>{const e=n.getDependencies();expect(e).toEqual({device:t})}),it("should set dependencies",()=>{const e={oninputreport:null,open:vi.fn(),close:vi.fn(),sendReport:vi.fn()};n.setDependencies({device:e});const r=n.getDependencies();expect(r).toEqual({device:e})}),it("should setup connection",async()=>{await n.setupConnection(),expect(t.open).toHaveBeenCalled(),expect(t.oninputreport).toBeDefined()}),it("should handle setup connection error",async()=>{const e=new Error("Failed to open device");t.open=vi.fn().mockRejectedValue(e),expect(n.setupConnection()).rejects.toThrowError()}),it("should close connection",()=>{n.closeConnection(),expect(t.close).toHaveBeenCalled()}),it("should handle close connection error",()=>{const e=new Error("Failed to close device");t.close=vi.fn().mockImplementation(()=>{throw e}),n.closeConnection(),expect(d.error).toHaveBeenCalledWith("Error while closing device",{data:{device:t,error:e}})}),it("should send APDU successfully",async()=>{const e=new Uint8Array([0,1,2,3]),r=[{getRawData:()=>new Uint8Array([0,1])},{getRawData:()=>new Uint8Array([2,3])}],o={data:new Uint8Array([144,0])};c.getFrames.mockReturnValue(r),t.sendReport.mockResolvedValue({}),i.handleFrame.mockReturnValue(x(l.of(o))),await n.setupConnection();const a=n.sendApdu(e);t.oninputreport({data:{buffer:Buffer.from([])}});const s=await a;expect(t.sendReport).toHaveBeenCalled(),expect(s.isRight()).toBe(!0),expect(s.extract()).toEqual(o)}),it("should handle send APDU error",async()=>{const e=new Uint8Array([0,1,2,3]),r=[{getRawData:()=>new Uint8Array([0,1])},{getRawData:()=>new Uint8Array([2,3])}],o=new Error("Failed to send report");c.getFrames.mockReturnValue(r),t.sendReport.mockRejectedValue(o),await n.setupConnection();const a=await n.sendApdu(e);expect(a.isLeft()).toBe(!0),expect(a.extract()).toBeInstanceOf(m)}),it("should handle received response error",async()=>{const e=new Uint8Array([0,1,2,3]),r=[{getRawData:()=>new Uint8Array([0,1])},{getRawData:()=>new Uint8Array([2,3])}],o=new Error("Error while receiving APDU");c.getFrames.mockReturnValue(r),t.sendReport.mockResolvedValue({}),i.handleFrame.mockReturnValue(p(o)),await n.setupConnection();const a=n.sendApdu(e);t.oninputreport({data:{buffer:Buffer.from([])}});const s=await a;expect(t.sendReport).toHaveBeenCalled(),expect(s.isLeft()).toBe(!0),expect(s.extract()).toStrictEqual(o)}),it("should handle send APDU timeout",async()=>{const e=new Uint8Array([0,1,2,3]),r=[{getRawData:()=>new Uint8Array([0,1])},{getRawData:()=>new Uint8Array([2,3])}];c.getFrames.mockReturnValue(r),t.sendReport.mockResolvedValue({}),await n.setupConnection();const o=await n.sendApdu(e,!1,100);expect(o.isLeft()).toBe(!0),expect(o.extract()).toBeInstanceOf(u)})});
|
|
2
|
+
//# sourceMappingURL=WebHidApduSender.test.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../src/api/transport/WebHidApduSender.test.ts"],
|
|
4
|
+
"sourcesContent": ["import {\n type ApduResponse,\n type LoggerPublisherService,\n SendApduTimeoutError,\n} from \"@ledgerhq/device-management-kit\";\nimport { Left, Maybe, Right } from \"purify-ts\";\n\nimport { WebHidSendReportError } from \"@api/model/Errors\";\n\nimport { WebHidApduSender } from \"./WebHidApduSender\";\n\ndescribe(\"WebHidApduSender\", () => {\n const mockApduSender = {\n getFrames: vi.fn(),\n };\n\n const mockApduReceiver = {\n handleFrame: vi.fn(),\n };\n\n const mockLogger = {\n info: vi.fn(),\n debug: vi.fn(),\n error: vi.fn(),\n };\n\n const mockDevice = {\n oninputreport: vi.fn(),\n open: vi.fn(),\n close: vi.fn(),\n sendReport: vi.fn(),\n };\n\n let webHidApduSender: WebHidApduSender;\n\n beforeEach(() => {\n vi.clearAllMocks();\n const mockLoggerFactory = vi\n .fn()\n .mockReturnValue(mockLogger as unknown as LoggerPublisherService);\n const mockApduSenderFactory = vi.fn().mockReturnValue(mockApduSender);\n const mockApduReceiverFactory = vi.fn().mockReturnValue(mockApduReceiver);\n webHidApduSender = new WebHidApduSender(\n {\n dependencies: { device: mockDevice as unknown as HIDDevice },\n apduSenderFactory: mockApduSenderFactory,\n apduReceiverFactory: mockApduReceiverFactory,\n },\n mockLoggerFactory,\n );\n });\n\n afterEach(() => {\n vi.restoreAllMocks();\n });\n\n it(\"should get dependencies\", () => {\n const dependencies = webHidApduSender.getDependencies();\n expect(dependencies).toEqual({\n device: mockDevice as unknown as HIDDevice,\n });\n });\n\n it(\"should set dependencies\", () => {\n const newDevice: HIDDevice = {\n oninputreport: null,\n open: vi.fn(),\n close: vi.fn(),\n sendReport: vi.fn(),\n } as unknown as HIDDevice;\n webHidApduSender.setDependencies({ device: newDevice });\n const dependencies = webHidApduSender.getDependencies();\n expect(dependencies).toEqual({ device: newDevice });\n });\n\n it(\"should setup connection\", async () => {\n await webHidApduSender.setupConnection();\n expect(mockDevice.open).toHaveBeenCalled();\n expect(mockDevice.oninputreport).toBeDefined();\n });\n\n it(\"should handle setup connection error\", async () => {\n const error = new Error(\"Failed to open device\");\n mockDevice.open = vi.fn().mockRejectedValue(error);\n expect(webHidApduSender.setupConnection()).rejects.toThrowError();\n });\n\n it(\"should close connection\", () => {\n webHidApduSender.closeConnection();\n expect(mockDevice.close).toHaveBeenCalled();\n });\n\n it(\"should handle close connection error\", () => {\n const error = new Error(\"Failed to close device\");\n mockDevice.close = vi.fn().mockImplementation(() => {\n throw error;\n });\n webHidApduSender.closeConnection();\n expect(mockLogger.error).toHaveBeenCalledWith(\n \"Error while closing device\",\n {\n data: { device: mockDevice, error },\n },\n );\n });\n\n it(\"should send APDU successfully\", async () => {\n const apdu = new Uint8Array([0x00, 0x01, 0x02, 0x03]);\n const frames = [\n { getRawData: () => new Uint8Array([0x00, 0x01]) },\n { getRawData: () => new Uint8Array([0x02, 0x03]) },\n ];\n const apduResponse = { data: new Uint8Array([0x90, 0x00]) } as ApduResponse;\n\n mockApduSender.getFrames.mockReturnValue(frames);\n mockDevice.sendReport.mockResolvedValue({});\n mockApduReceiver.handleFrame.mockReturnValue(Right(Maybe.of(apduResponse)));\n\n // Setup connection\n await webHidApduSender.setupConnection();\n\n // Send APDU\n const promise = webHidApduSender.sendApdu(apdu);\n\n // Receive response\n mockDevice.oninputreport({ data: { buffer: Buffer.from([]) } });\n\n // Await response\n const result = await promise;\n expect(mockDevice.sendReport).toHaveBeenCalled();\n expect(result.isRight()).toBe(true);\n expect(result.extract()).toEqual(apduResponse);\n });\n\n it(\"should handle send APDU error\", async () => {\n const apdu = new Uint8Array([0x00, 0x01, 0x02, 0x03]);\n const frames = [\n { getRawData: () => new Uint8Array([0x00, 0x01]) },\n { getRawData: () => new Uint8Array([0x02, 0x03]) },\n ];\n const error = new Error(\"Failed to send report\");\n\n mockApduSender.getFrames.mockReturnValue(frames);\n mockDevice.sendReport.mockRejectedValue(error);\n\n await webHidApduSender.setupConnection();\n const result = await webHidApduSender.sendApdu(apdu);\n expect(result.isLeft()).toBe(true);\n expect(result.extract()).toBeInstanceOf(WebHidSendReportError);\n });\n\n it(\"should handle received response error\", async () => {\n const apdu = new Uint8Array([0x00, 0x01, 0x02, 0x03]);\n const frames = [\n { getRawData: () => new Uint8Array([0x00, 0x01]) },\n { getRawData: () => new Uint8Array([0x02, 0x03]) },\n ];\n const apduError = new Error(\"Error while receiving APDU\");\n\n mockApduSender.getFrames.mockReturnValue(frames);\n mockDevice.sendReport.mockResolvedValue({});\n mockApduReceiver.handleFrame.mockReturnValue(Left(apduError));\n\n // Setup connection\n await webHidApduSender.setupConnection();\n\n // Send APDU\n const promise = webHidApduSender.sendApdu(apdu);\n\n // Receive response\n mockDevice.oninputreport({ data: { buffer: Buffer.from([]) } });\n\n // Await response\n const result = await promise;\n expect(mockDevice.sendReport).toHaveBeenCalled();\n expect(result.isLeft()).toBe(true);\n expect(result.extract()).toStrictEqual(apduError);\n });\n\n it(\"should handle send APDU timeout\", async () => {\n const apdu = new Uint8Array([0x00, 0x01, 0x02, 0x03]);\n const frames = [\n { getRawData: () => new Uint8Array([0x00, 0x01]) },\n { getRawData: () => new Uint8Array([0x02, 0x03]) },\n ];\n\n mockApduSender.getFrames.mockReturnValue(frames);\n mockDevice.sendReport.mockResolvedValue({});\n\n await webHidApduSender.setupConnection();\n const result = await webHidApduSender.sendApdu(apdu, false, 100);\n expect(result.isLeft()).toBe(true);\n expect(result.extract()).toBeInstanceOf(SendApduTimeoutError);\n });\n});\n"],
|
|
5
|
+
"mappings": "AAAA,OAGE,wBAAAA,MACK,kCACP,OAAS,QAAAC,EAAM,SAAAC,EAAO,SAAAC,MAAa,YAEnC,OAAS,yBAAAC,MAA6B,oBAEtC,OAAS,oBAAAC,MAAwB,qBAE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AK,CAAC,CAAC,CAAE,CAAE,CAAC,EAG9D,MAAMY,EAAS,MAAMD,EACrB,OAAOX,EAAW,UAAU,EAAE,iBAAiB,EAC/C,OAAOY,EAAO,OAAO,CAAC,EAAE,KAAK,EAAI,EACjC,OAAOA,EAAO,QAAQ,CAAC,EAAE,cAAcC,CAAS,CAClD,CAAC,EAED,GAAG,kCAAmC,SAAY,CAChD,MAAML,EAAO,IAAI,WAAW,CAAC,EAAM,EAAM,EAAM,CAAI,CAAC,EAC9CC,EAAS,CACb,CAAE,WAAY,IAAM,IAAI,WAAW,CAAC,EAAM,CAAI,CAAC,CAAE,EACjD,CAAE,WAAY,IAAM,IAAI,WAAW,CAAC,EAAM,CAAI,CAAC,CAAE,CACnD,EAEAZ,EAAe,UAAU,gBAAgBY,CAAM,EAC/CT,EAAW,WAAW,kBAAkB,CAAC,CAAC,EAE1C,MAAMC,EAAiB,gBAAgB,EACvC,MAAMW,EAAS,MAAMX,EAAiB,SAASO,EAAM,GAAO,GAAG,EAC/D,OAAOI,EAAO,OAAO,CAAC,EAAE,KAAK,EAAI,EACjC,OAAOA,EAAO,QAAQ,CAAC,EAAE,eAAerB,CAAoB,CAC9D,CAAC,CACH,CAAC",
|
|
6
|
+
"names": ["SendApduTimeoutError", "Left", "Maybe", "Right", "WebHidSendReportError", "WebHidApduSender", "mockApduSender", "mockApduReceiver", "mockLogger", "mockDevice", "webHidApduSender", "mockLoggerFactory", "mockApduSenderFactory", "mockApduReceiverFactory", "dependencies", "newDevice", "error", "apdu", "frames", "apduResponse", "promise", "result", "apduError"]
|
|
7
|
+
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{DeviceConnectionStateMachine as C,DeviceNotRecognizedError as m,LEDGER_VENDOR_ID as l,NoAccessibleDeviceError as g,OpeningConnectionError as u,TransportConnectedDevice as y,UnknownDeviceError as b}from"@ledgerhq/device-management-kit";import*as a from"@sentry/minimal";import{EitherAsync as _,Left as d,Maybe as f,Right as v}from"purify-ts";import{BehaviorSubject as H,from as E,map as S,switchMap as T}from"rxjs";import{v4 as I}from"uuid";import{RECONNECT_DEVICE_TIMEOUT as A}from"../data/WebHidConfig";import{WebHidTransportNotSupportedError as w}from"../model/Errors";import{WebHidApduSender as M}from"./WebHidApduSender";const P="WEB-HID";class R{constructor(e,i,t,n,o=c=>new C(c),s=(c,p)=>new M(c,p)){this._deviceModelDataSource=e;this._loggerServiceFactory=i;this._apduSenderFactory=t;this._apduReceiverFactory=n;this._deviceConnectionStateMachineFactory=o;this._deviceApduSenderFactory=s;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()?v(navigator.hid):d(new w("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 _.liftEither(this.hidApi).map(async e=>{try{return(await e.getDevices()).filter(t=>t.vendorId===l)}catch(i){const t=new g(i);throw this._logger.error("getDevices: error getting devices",{data:{error:i}}),a.captureException(t),t}})}mapHIDDeviceToTransportDiscoveredDevice(e){const i=this._transportDiscoveredDevices.getValue().find(o=>o.hidDevice===e);if(i)return i;const t=this._deviceConnectionsByHidDevice.get(e);return this.getDeviceModel(e).caseOf({Just:o=>{const s=t?.getDeviceId()??I(),c={id:s,deviceModel:o,hidDevice:e,transport:this.identifier};return this._logger.debug(`Discovered device ${s} ${c.deviceModel.productName}`),c},Nothing:()=>{throw this._logger.warn(`Device not recognized: hidDevice.productId: 0x${e.productId.toString(16)}`),new m(`Device not recognized: hidDevice.productId: 0x${e.productId.toString(16)}`)}})}listenToAvailableDevices(){return this.updateTransportDiscoveredDevices(),this._transportDiscoveredDevices.pipe(S(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}}),a.captureException(i)},Right:i=>{this._transportDiscoveredDevices.next(i.map(t=>this.mapHIDDeviceToTransportDiscoveredDevice(t)))}})}async promptDeviceAccess(){return _.liftEither(this.hidApi).map(async e=>{let i=[];try{i=await e.requestDevice({filters:[{vendorId:l}]}),await this.updateTransportDiscoveredDevices()}catch(n){const o=new g(n);throw this._logger.error("promptDeviceAccess: error requesting device",{data:{error:n}}),a.captureException(o),o}if(this._logger.debug(`promptDeviceAccess: hidDevices len ${i.length}`),i.length===0)throw this._logger.warn("No device was selected"),new g("No selected device");const t=[];for(const n of i)t.push(n),this._logger.debug("promptDeviceAccess: selected device",{data:{hidDevice:n}});return t}).run()}startDiscovering(){return this._logger.debug("startDiscovering"),E(this.promptDeviceAccess()).pipe(T(e=>e.caseOf({Left:i=>{throw this._logger.error("Error while getting accessible device",{data:{error:i}}),a.captureException(i),i},Right:i=>{this._logger.info(`Got access to ${i.length} HID devices`);const t=i.map(n=>this.mapHIDDeviceToTransportDiscoveredDevice(n));return E(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(r=>r.id===e);if(!t)return this._logger.error(`Unknown device ${e}`),d(new b(`Unknown device ${e}`));const{deviceModel:n}=t,o=this._deviceConnectionsByHidDevice.get(t.hidDevice);if(o)return v(new y({id:e,deviceModel:n,type:this.connectionType,sendApdu:(...r)=>o.sendApdu(...r),transport:this.identifier}));const s=this._deviceApduSenderFactory({apduSenderFactory:this._apduSenderFactory,apduReceiverFactory:this._apduReceiverFactory,dependencies:{device:t.hidDevice}},this._loggerServiceFactory),c=this._deviceConnectionStateMachineFactory({deviceId:e,deviceApduSender:s,timeoutDuration:A,tryToReconnect:()=>{this._deviceConnectionsByHidDevice.forEach((r,D)=>{r.getDeviceId()===e&&(this._deviceConnectionsPendingReconnection.add(r),this._deviceConnectionsByHidDevice.delete(D))})},onTerminated:()=>{this._deviceConnectionsPendingReconnection.forEach(r=>{r.getDeviceId()===e&&(this._deviceConnectionsPendingReconnection.delete(r),i(r.getDeviceId()))}),this._deviceConnectionsByHidDevice.forEach((r,D)=>{r.getDeviceId()===e&&(this._deviceConnectionsByHidDevice.delete(D),i(r.getDeviceId()))})}});try{await s.setupConnection()}catch(r){return r instanceof u?d(r):d(new u(r))}this._deviceConnectionsByHidDevice.set(t.hidDevice,c);const p=new y({sendApdu:(...r)=>c.sendApdu(...r),deviceModel:n,id:e,type:this.connectionType,transport:this.identifier});return v(p)}getDeviceModel(e){const{productId:i}=e,t=this._deviceModelDataSource.getAllDeviceModels().find(n=>n.usbProductId===i>>8||n.bootloaderUsbProductId===i);return t?f.of(t):f.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.getDeviceId()===e.connectedDevice.id);return i?(i.closeConnection(),Promise.resolve(v(void 0))):(this._logger.error("No matching device connection found",{data:{connectedDevice:e}}),Promise.resolve(d(new b(`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.eventDeviceDisconnected()}async handleDeviceReconnection(e,i){this._deviceConnectionsPendingReconnection.delete(e),this._deviceConnectionsByHidDevice.set(i,e);try{e.setDependencies({device:i}),await e.setupConnection(),e.eventDeviceConnected()}catch(t){this._logger.error("Error while reconnecting to device",{data:{event,error:t}}),e.closeConnection()}}async 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.getDependencies().device)===this.getHidUsbProductId(e.device));i&&await this.handleDeviceReconnection(i,e.device),this.updateTransportDiscoveredDevices()}destroy(){this.stopListeningToConnectionEvents(),this._deviceConnectionsByHidDevice.forEach(e=>{e.closeConnection()}),this._deviceConnectionsPendingReconnection.clear()}}const U=({deviceModelDataSource:h,loggerServiceFactory:e,apduSenderServiceFactory:i,apduReceiverServiceFactory:t})=>new R(h,e,i,t);export{R as WebHidTransport,P as webHidIdentifier,U as webHidTransportFactory};
|
|
2
2
|
//# sourceMappingURL=WebHidTransport.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
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,
|
|
6
|
-
"names": ["
|
|
4
|
+
"sourcesContent": ["import {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n type ConnectError,\n type ConnectionType,\n DeviceConnectionStateMachine,\n type DeviceConnectionStateMachineParams,\n type DeviceId,\n type DeviceModelDataSource,\n DeviceNotRecognizedError,\n type DisconnectHandler,\n type DmkError,\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 { RECONNECT_DEVICE_TIMEOUT } from \"@api/data/WebHidConfig\";\nimport { WebHidTransportNotSupportedError } from \"@api/model/Errors\";\n\nimport {\n WebHidApduSender,\n type WebHidApduSenderConstructorArgs,\n type WebHidApduSenderDependencies,\n} from \"./WebHidApduSender\";\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 device connection */\n private _deviceConnectionsByHidDevice: Map<\n HIDDevice,\n DeviceConnectionStateMachine<WebHidApduSenderDependencies>\n > = new Map();\n\n /**\n * Set of device connections for which the HIDDevice has been\n * disconnected, so they are waiting for a reconnection\n */\n private _deviceConnectionsPendingReconnection: Set<\n DeviceConnectionStateMachine<WebHidApduSenderDependencies>\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 private readonly _deviceConnectionStateMachineFactory: (\n args: DeviceConnectionStateMachineParams<WebHidApduSenderDependencies>,\n ) => DeviceConnectionStateMachine<WebHidApduSenderDependencies> = (args) =>\n new DeviceConnectionStateMachine(args),\n private readonly _deviceApduSenderFactory: (\n args: WebHidApduSenderConstructorArgs,\n loggerFactory: (tag: string) => LoggerPublisherService,\n ) => WebHidApduSender = (args, loggerFactory) =>\n new WebHidApduSender(args, loggerFactory),\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?.getDeviceId() ?? 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 listenToAvailableDevices(): 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 const { deviceModel } = matchingInternalDevice;\n const existing = this._deviceConnectionsByHidDevice.get(\n matchingInternalDevice.hidDevice,\n );\n if (existing) {\n return Right(\n new TransportConnectedDevice({\n id: deviceId,\n deviceModel,\n type: this.connectionType,\n sendApdu: (...args) => existing.sendApdu(...args),\n transport: this.identifier,\n }),\n );\n }\n\n const deviceApduSender = this._deviceApduSenderFactory(\n {\n apduSenderFactory: this._apduSenderFactory,\n apduReceiverFactory: this._apduReceiverFactory,\n dependencies: { device: matchingInternalDevice.hidDevice },\n },\n this._loggerServiceFactory,\n );\n const deviceConnectionStateMachine =\n this._deviceConnectionStateMachineFactory({\n deviceId,\n deviceApduSender,\n timeoutDuration: RECONNECT_DEVICE_TIMEOUT,\n tryToReconnect: () => {\n this._deviceConnectionsByHidDevice.forEach(\n (deviceConnection, hidDevice) => {\n if (deviceConnection.getDeviceId() === deviceId) {\n this._deviceConnectionsPendingReconnection.add(\n deviceConnection,\n );\n this._deviceConnectionsByHidDevice.delete(hidDevice);\n }\n },\n );\n },\n onTerminated: () => {\n this._deviceConnectionsPendingReconnection.forEach(\n (deviceConnection) => {\n if (deviceConnection.getDeviceId() === deviceId) {\n this._deviceConnectionsPendingReconnection.delete(\n deviceConnection,\n );\n onDisconnect(deviceConnection.getDeviceId());\n }\n },\n );\n this._deviceConnectionsByHidDevice.forEach(\n (deviceConnection, hidDevice) => {\n if (deviceConnection.getDeviceId() === deviceId) {\n this._deviceConnectionsByHidDevice.delete(hidDevice);\n onDisconnect(deviceConnection.getDeviceId());\n }\n },\n );\n },\n });\n\n try {\n await deviceApduSender.setupConnection();\n } catch (error) {\n if (error instanceof OpeningConnectionError) {\n return Left(error);\n }\n // Should not happen\n return Left(new OpeningConnectionError(error));\n }\n\n this._deviceConnectionsByHidDevice.set(\n matchingInternalDevice.hidDevice,\n deviceConnectionStateMachine,\n );\n\n const connectedDevice = new TransportConnectedDevice({\n sendApdu: (...args) => deviceConnectionStateMachine.sendApdu(...args),\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.getDeviceId() === 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.closeConnection();\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.eventDeviceDisconnected();\n }\n }\n\n private async handleDeviceReconnection(\n deviceConnection: DeviceConnectionStateMachine<WebHidApduSenderDependencies>,\n hidDevice: HIDDevice,\n ) {\n this._deviceConnectionsPendingReconnection.delete(deviceConnection);\n this._deviceConnectionsByHidDevice.set(hidDevice, deviceConnection);\n\n try {\n deviceConnection.setDependencies({\n device: hidDevice,\n });\n await deviceConnection.setupConnection();\n deviceConnection.eventDeviceConnected();\n } catch (error) {\n this._logger.error(\"Error while reconnecting to device\", {\n data: { event, error },\n });\n deviceConnection.closeConnection();\n }\n }\n\n /**\n * Handle the connection event of a HID device\n * @param event\n */\n private async 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.getDependencies().device) ===\n this.getHidUsbProductId(event.device),\n );\n\n if (matchingDeviceConnection) {\n await this.handleDeviceReconnection(\n matchingDeviceConnection,\n event.device,\n );\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.closeConnection();\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,OAKE,gCAAAA,EAIA,4BAAAC,EAGA,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,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ClE,KAAK,8BAA8B,IAAIrB,EAAWqB,CAAgB,EAElE,GAAI,CACFA,EAAiB,gBAAgB,CAC/B,OAAQrB,CACV,CAAC,EACD,MAAMqB,EAAiB,gBAAgB,EACvCA,EAAiB,qBAAqB,CACxC,OAASvB,EAAO,CACd,KAAK,QAAQ,MAAM,qCAAsC,CACvD,KAAM,CAAE,MAAO,MAAAA,CAAM,CACvB,CAAC,EACDuB,EAAiB,gBAAgB,CACnC,CACF,CAMA,MAAc,4BAA4BP,EAAc,CACtD,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,MAAMY,EAA2B,MAAM,KACrC,KAAK,qCACP,EAAE,KACCL,GACC,KAAK,mBAAmBA,EAAiB,gBAAgB,EAAE,MAAM,IACjE,KAAK,mBAAmBP,EAAM,MAAM,CACxC,EAEIY,GACF,MAAM,KAAK,yBACTA,EACAZ,EAAM,MACR,EAQF,KAAK,iCAAiC,CACxC,CAEO,SAAU,CACf,KAAK,gCAAgC,EACrC,KAAK,8BAA8B,QAASa,GAAe,CACzDA,EAAW,gBAAgB,CAC7B,CAAC,EACD,KAAK,sCAAsC,MAAM,CACnD,CACF,CAEO,MAAMC,EAA2C,CAAC,CACvD,sBAAAC,EACA,qBAAAC,EACA,yBAAAC,EACA,2BAAAC,CACF,IACE,IAAI5C,EACFyC,EACAC,EACAC,EACAC,CACF",
|
|
6
|
+
"names": ["DeviceConnectionStateMachine", "DeviceNotRecognizedError", "LEDGER_VENDOR_ID", "NoAccessibleDeviceError", "OpeningConnectionError", "TransportConnectedDevice", "UnknownDeviceError", "Sentry", "EitherAsync", "Left", "Maybe", "Right", "BehaviorSubject", "from", "map", "switchMap", "uuid", "RECONNECT_DEVICE_TIMEOUT", "WebHidTransportNotSupportedError", "WebHidApduSender", "webHidIdentifier", "WebHidTransport", "_deviceModelDataSource", "_loggerServiceFactory", "_apduSenderFactory", "_apduReceiverFactory", "_deviceConnectionStateMachineFactory", "args", "_deviceApduSenderFactory", "loggerFactory", "result", "error", "hidApi", "hidDevice", "deviceError", "existingDiscoveredDevice", "internalDevice", "existingDeviceConnection", "deviceModel", "id", "discoveredDevice", "devices", "device", "hidDevices", "discoveredHidDevices", "either", "discoveredDevices", "event", "deviceId", "onDisconnect", "matchingInternalDevice", "existing", "deviceApduSender", "deviceConnectionStateMachine", "deviceConnection", "connectedDevice", "productId", "matchingModel", "params", "matchingDeviceConnection", "connection", "webHidTransportFactory", "deviceModelDataSource", "loggerServiceFactory", "apduSenderServiceFactory", "apduReceiverServiceFactory"]
|
|
7
7
|
}
|
|
@@ -1,2 +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)})})})});
|
|
1
|
+
import{connectedDeviceStubBuilder as L,DeviceModelId as p,DeviceNotRecognizedError as X,NoAccessibleDeviceError as A,OpeningConnectionError as O,StaticDeviceModelDataSource as F,UnknownDeviceError as P}from"@ledgerhq/device-management-kit";import{Left as B,Right as V}from"purify-ts";import{lastValueFrom as b,Subject as q,toArray as j}from"rxjs";import{RECONNECT_DEVICE_TIMEOUT as x}from"../data/WebHidConfig";import{WebHidTransportNotSupportedError as W}from"../model/Errors";import{hidDeviceStubBuilder as v}from"../model/HIDDevice.stub";import{WebHidTransport as _}from"./WebHidTransport";class U{constructor(S,E){this.subscribers=S,this.tag=E}subscribers=[];tag="";error=vi.fn();warn=vi.fn();info=vi.fn();debug=vi.fn()}const R=new F,z=new U([],"web-usb-hid"),a=v(),m=async()=>{const i=await vi.importActual("timers");return new Promise(i.setImmediate)};describe("WebHidTransport",()=>{let i,S,E,h=vi.fn();const k=vi.fn(),y=vi.fn(),M={sendApdu:vi.fn().mockResolvedValue(V({data:new Uint8Array})),getDependencies:vi.fn().mockReturnValue({device:a}),setDependencies:vi.fn(),closeConnection:vi.fn(),setupConnection:vi.fn()},w={getDependencies:vi.fn().mockReturnValue({device:a}),setDependencies:vi.fn(),getDeviceId:vi.fn(),sendApdu:vi.fn().mockResolvedValue(V({data:new Uint8Array})),setupConnection:vi.fn(),eventDeviceConnected:k,eventDeviceDisconnected:y,closeConnection:vi.fn()};function T(){S=vi.fn(),E=vi.fn(),h=vi.fn(s=>({...w,getDeviceId:vi.fn().mockReturnValue(s.deviceId),getDependencies:s.deviceApduSender.getDependencies,setDependencies:s.deviceApduSender.setDependencies}));const d=vi.fn(s=>({...M,getDependencies:()=>s.dependencies,setDependencies:f=>s.dependencies=f}));i=new _(R,()=>z,E,S,h,d)}beforeEach(()=>{T(),vi.useFakeTimers()}),afterEach(()=>{vi.restoreAllMocks()});const D=(d,s)=>{i.startDiscovering().subscribe({next:d,error:s})};describe("When WebHID API is not supported",()=>{it("should not support the transport",()=>{expect(i.isSupported()).toBe(!1)}),it("should emit a startDiscovering error",()=>new Promise((d,s)=>{D(()=>{s("Should not emit any value")},f=>{expect(f).toBeInstanceOf(W),d()})}))}),describe("When WebHID API is supported",()=>{const d=vi.fn(),s=vi.fn(),f=new q,N=new q;function C(t){f.next({device:t})}function I(t){N.next({device:t})}beforeEach(()=>{global.navigator={hid:{getDevices:d,requestDevice:s,addEventListener:(t,e)=>{t==="disconnect"?N.subscribe(e):t==="connect"&&f.subscribe(e)}}},T()}),afterEach(()=>{vi.clearAllMocks(),global.navigator=void 0}),it("should support the transport",()=>{expect(i.isSupported()).toBe(!0)}),describe("startDiscovering",()=>{R.getAllDeviceModels().flatMap(e=>[{testTitle:`should emit device if user grants access through hid.requestDevice (${e.productName})`,hidDevice:v({productId:e.usbProductId<<8,productName:e.productName}),expectedDeviceModel:e},{testTitle:`should emit device if user grants access through hid.requestDevice (${e.productName}, bootloader)`,hidDevice:v({productId:e.bootloaderUsbProductId,productName:e.productName}),expectedDeviceModel:e}]).forEach(e=>{it(e.testTitle,()=>new Promise((o,n)=>{s.mockResolvedValueOnce([e.hidDevice]),D(c=>{try{expect(c).toEqual(expect.objectContaining({deviceModel:e.expectedDeviceModel})),o()}catch(r){n(r)}},c=>{n(c)})}))}),it("should emit devices if new grant accesses",()=>new Promise((e,o)=>{s.mockResolvedValueOnce([a,{...a,productId:20497,productName:"Ledger Nano S Plus"}]);let n=0;D(c=>{try{switch(n){case 0:expect(c).toEqual(expect.objectContaining({deviceModel:expect.objectContaining({id:p.NANO_X,productName:"Ledger Nano X",usbProductId:64})}));break;case 1:expect(c).toEqual(expect.objectContaining({deviceModel:expect.objectContaining({id:p.NANO_SP,productName:"Ledger Nano S Plus",usbProductId:80})})),e();break}n++}catch(r){o(r)}},c=>{o(c)})})),it("should throw DeviceNotRecognizedError if the device is not recognized",()=>new Promise((e,o)=>{s.mockResolvedValueOnce([{...a,productId:16962}]),D(()=>{o("should not return a device")},n=>{expect(n).toBeInstanceOf(X),e()})})),it("should emit an error if the request device is in error",()=>new Promise((e,o)=>{const n="request device error";s.mockImplementationOnce(()=>{throw new Error(n)}),D(()=>{o("should not return a device")},c=>{expect(c).toBeInstanceOf(A),expect(c).toStrictEqual(new A(new Error(n))),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)",()=>new Promise((e,o)=>{s.mockResolvedValueOnce([]),D(n=>{o(`Should not emit any value, but emitted ${JSON.stringify(n)}`)},n=>{try{expect(n).toBeInstanceOf(A),e()}catch(c){o(c)}})})),it("should emit the same discoveredDevice object if its discovered twice in a row",async()=>{s.mockResolvedValue([a]),d.mockResolvedValue([a]);const e=await new Promise((n,c)=>{D(()=>n(),r=>c(r))}),o=await new Promise((n,c)=>{D(()=>n(),r=>c(r))});expect(o).toBe(e)})}),describe("destroy",()=>{it("should stop monitoring connections if the discovery process is halted",()=>{const t=vi.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:vi.fn()},e=await i.connect(t);expect(e).toStrictEqual(B(new P("Unknown device fake")))}),it("should throw OpeningConnectionError if the device cannot be opened",async()=>{const t="cannot be opened";M.setupConnection.mockRejectedValue(new O(t)),s.mockResolvedValueOnce([a]),d.mockResolvedValue([a]);const e=await b(i.startDiscovering()),o=await i.connect({deviceId:e.id,onDisconnect:vi.fn()});expect(o).toStrictEqual(B(new O(t)))}),it("should return a device if available",async()=>{s.mockResolvedValueOnce([a]),d.mockResolvedValue([a]);const t=await b(i.startDiscovering()),e=await i.connect({deviceId:t.id,onDisconnect:vi.fn()});expect(e.isRight()).toStrictEqual(!0),expect(e.extract()).toEqual(expect.objectContaining({id:t.id}))}),it("should return an existing connected device",async()=>{s.mockResolvedValueOnce([a]),d.mockResolvedValue([a]);const t=await b(i.startDiscovering());await i.connect({deviceId:t.id,onDisconnect:vi.fn()});const e=await i.connect({deviceId:t.id,onDisconnect:vi.fn()});expect(e.isRight()).toStrictEqual(!0),expect(e.extract()).toEqual(expect.objectContaining({id:t.id}))})}),describe("disconnect",()=>{it("should throw an error if the device is not connected",async()=>{const t=L(),e=await i.disconnect({connectedDevice:t});expect(e).toStrictEqual(B(new P(`Unknown device ${t.id}`)))}),it("should disconnect if the device is connected",async()=>{s.mockResolvedValueOnce([a]),d.mockResolvedValue([a]);const t=await b(i.startDiscovering()),e=await i.connect({deviceId:t.id,onDisconnect:vi.fn()});expect(e.isRight()).toStrictEqual(!0);const o=await i.disconnect({connectedDevice:e.unsafeCoerce()});expect(o).toStrictEqual(V(void 0))}),it("should call disconnect handler if a connected device is unplugged",async()=>{let t=vi.fn();h.mockImplementationOnce(g=>(t=g.onTerminated,{...w,getDeviceId:vi.fn().mockReturnValue(g.deviceId)}));const e=v(),o=v();s.mockResolvedValueOnce([e,o]),d.mockResolvedValue([e,o]);const n=await b(i.startDiscovering().pipe(j()));expect(n.length).toStrictEqual(2);const c=vi.fn(),r=await i.connect({deviceId:n[0].id,onDisconnect:c}),l=vi.fn(),u=await i.connect({deviceId:n[1].id,onDisconnect:l});expect(r.isRight()).toStrictEqual(!0),expect(u.isRight()).toStrictEqual(!0),t(),expect(c).toHaveBeenCalled(),expect(l).not.toHaveBeenCalled()}),it("should call disconnect handler if a connected device is unplugged while reconnecting",async()=>{let t=vi.fn(),e=vi.fn();h.mockImplementationOnce(H=>(t=H.onTerminated,e=H.tryToReconnect,{...w,getDeviceId:vi.fn().mockReturnValue(H.deviceId)}));const o=v(),n=v();s.mockResolvedValueOnce([o,n]),d.mockResolvedValue([o,n]);const c=await b(i.startDiscovering().pipe(j()));expect(c.length).toStrictEqual(2);const r=vi.fn(),l=await i.connect({deviceId:c[0].id,onDisconnect:r}),u=vi.fn(),g=await i.connect({deviceId:c[1].id,onDisconnect:u});expect(l.isRight()).toStrictEqual(!0),expect(g.isRight()).toStrictEqual(!0),e(),t(),expect(r).toHaveBeenCalled(),expect(u).not.toHaveBeenCalled()})}),describe("reconnect",()=>{it("should stop disconnection if reconnection happen",()=>new Promise((t,e)=>{const o=vi.fn();let n=vi.fn();const c=v(),r=v();s.mockResolvedValueOnce([c]),d.mockResolvedValue([c,r]),h.mockImplementationOnce(l=>(n=l.tryToReconnect,{...w,getDeviceId:vi.fn().mockReturnValue(l.deviceId),getDependencies:l.deviceApduSender.getDependencies,setDependencies:l.deviceApduSender.setDependencies})),D(async l=>{try{await i.connect({deviceId:l.id,onDisconnect:o}),I(c),expect(c.close).toHaveBeenCalled(),await Promise.resolve(),expect(y).toHaveBeenCalled(),n(),vi.advanceTimersByTime(x/3),C(r),await Promise.resolve(),expect(k).toHaveBeenCalled(),vi.advanceTimersByTime(x),expect(o).not.toHaveBeenCalled(),t()}catch(u){e(u)}})})),it("should be able to reconnect twice in a row if the device is unplugged and replugged twice",()=>new Promise((t,e)=>{const o=vi.fn();let n=vi.fn();const c=v(),r=v(),l=v();s.mockResolvedValueOnce([c]),d.mockResolvedValue([c,r,l]),h.mockImplementationOnce(u=>(n=u.tryToReconnect,{...w,getDeviceId:vi.fn().mockReturnValue(u.deviceId),getDependencies:u.deviceApduSender.getDependencies,setDependencies:u.deviceApduSender.setDependencies})),D(async u=>{await i.connect({deviceId:u.id,onDisconnect:o});try{I(c),expect(c.close).toHaveBeenCalled(),await Promise.resolve(),expect(y).toHaveBeenCalled(),n(),vi.advanceTimersByTime(x/3),C(r),await Promise.resolve(),expect(k).toHaveBeenCalled(),vi.advanceTimersByTime(x),expect(o).not.toHaveBeenCalled(),I(r),expect(r.close).toHaveBeenCalled(),await Promise.resolve(),expect(y).toHaveBeenCalled(),n(),vi.advanceTimersByTime(x/3),C(l),await Promise.resolve(),expect(k).toHaveBeenCalled(),vi.advanceTimersByTime(x),expect(o).not.toHaveBeenCalled(),t()}catch(g){e(g)}})}))}),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("listenToAvailableDevices",()=>{it("should emit the devices already connected before listening",async()=>{const t=v();d.mockResolvedValue([t]);const e=vi.fn(),o=vi.fn();let n=[];i.listenToAvailableDevices().subscribe({next:c=>{n=c},complete:e,error:o}),await m(),expect(n).toEqual([expect.objectContaining({deviceModel:expect.objectContaining({id:p.NANO_X})})]),expect(e).not.toHaveBeenCalled(),expect(o).not.toHaveBeenCalled()}),it("should emit the new list of devices after connection and disconnection events",async()=>{T();const t=v({productId:R.getDeviceModel({id:p.NANO_X}).usbProductId<<8}),e=v({productId:R.getDeviceModel({id:p.STAX}).usbProductId<<8});d.mockResolvedValue([t]);const o=vi.fn(),n=vi.fn();let c=[];i.listenToAvailableDevices().subscribe({next:r=>{c=r},complete:o,error:n}),await m(),expect(c).toEqual([expect.objectContaining({deviceModel:expect.objectContaining({id:p.NANO_X})})]),d.mockResolvedValue([t,e]),C(e),await m(),expect(c).toEqual([expect.objectContaining({deviceModel:expect.objectContaining({id:p.NANO_X})}),expect.objectContaining({deviceModel:expect.objectContaining({id:p.STAX})})]),d.mockResolvedValue([e]),I(t),await m(),expect(c).toEqual([expect.objectContaining({deviceModel:expect.objectContaining({id:p.STAX})})]),expect(o).not.toHaveBeenCalled(),expect(n).not.toHaveBeenCalled()}),it("should preserve DeviceId in case the device has been disconnected and reconnected before the timeout",async()=>{const t=v();d.mockResolvedValue([t]);const e=vi.fn(),o=vi.fn();let n=[];i.listenToAvailableDevices().subscribe({next:r=>{n=r},complete:e,error:o}),await m();const c=n[0]?.id;expect(c).toBeTruthy(),expect(n[0]?.deviceModel?.id).toBe(p.NANO_X),await i.connect({deviceId:n[0].id,onDisconnect:vi.fn()}),await m(),d.mockResolvedValue([]),I(t),await m(),expect(n).toEqual([]),d.mockResolvedValue([t]),C(t),await m(),expect(n).toEqual([expect.objectContaining({deviceModel:expect.objectContaining({id:p.NANO_X})})]),expect(n[0]?.id).toBeTruthy(),expect(n[0]?.id).toBe(c)})})})});
|
|
2
2
|
//# sourceMappingURL=WebHidTransport.test.js.map
|