@ledgerhq/device-transport-kit-web-hid 0.0.0-rnble-transport-20250219135033 → 0.0.0-webhid-20250124103640

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.
@@ -1,2 +1,2 @@
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};
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
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 = vi.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: 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,MAAM,EAEzCC,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",
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
6
  "names": ["oninputreport", "hidDeviceStubBuilder", "props"]
7
7
  }
@@ -1,2 +1,2 @@
1
- import{CommandUtils as g,ReconnectionFailedError as h}from"@ledgerhq/device-management-kit";import{Left as c,Maybe as m,Nothing as d,Right as u}from"purify-ts";import{firstValueFrom as l,from as _,retry as b,Subject as p}from"rxjs";import{RECONNECT_DEVICE_TIMEOUT as f}from"../data/WebHidConfig";import{WebHidSendReportError as s}from"../model/Errors";class C{_device;_deviceId;_apduSender;_apduReceiver;_sendApduSubject=new p;_logger;_pendingApdu=d;_onConnectionTerminated;reconnectionSubject=new p;waitingForReconnection=!1;lostConnectionTimeout=null;terminated=!1;constructor({device:t,deviceId:n,apduSender:o,apduReceiver:r,onConnectionTerminated:e},i){this._apduSender=o,this._apduReceiver=r,this._onConnectionTerminated=e,this._logger=i("WebHidDeviceConnection"),this._device=t,this._device.oninputreport=a=>this.receiveHidInputReport(a),this._deviceId=n,this._logger.info("\u{1F50C} Connected to device")}get device(){return this._device}get deviceId(){return this._deviceId}async sendApdu(t,n){this._sendApduSubject=new p,this._pendingApdu=m.of(t),this._logger.debug("Sending APDU",{data:{apdu:t},tag:"apdu-sender"});const o=new Promise(e=>{this._sendApduSubject.subscribe({next:async i=>{this._pendingApdu=d,n&&g.isSuccessResponse(i)?(await this.waitForReconnection()).caseOf({Left:v=>e(c(v)),Right:()=>e(u(i))}):e(u(i))},error:i=>{this._pendingApdu=d,e(c(i))}})});if(this.waitingForReconnection||!this.device.opened){const e=this.device.opened&&this._pendingApdu.isJust(),i=await this.waitForReconnection(e);if(i.isLeft())return i}const r=this._apduSender.getFrames(t);for(const e of r){this._logger.debug("Sending Frame",{data:{frame:e.getRawData()}});try{await l(_(this._device.sendReport(0,e.getRawData())).pipe(b({count:3,delay:500})))}catch(i){return this._logger.error("Error sending frame",{data:{error:i}}),Promise.resolve(c(new s(i)))}}return o}receiveHidInputReport(t){const n=new Uint8Array(t.data.buffer);this._logger.debug("Received Frame",{data:{frame:n},tag:"apdu-receiver"}),this._apduReceiver.handleFrame(n).caseOf({Right:r=>{r.map(e=>{this._logger.debug("Received APDU Response",{data:{response:e}}),this._sendApduSubject.next(e),this._sendApduSubject.complete()})},Left:r=>{this._sendApduSubject.error(r)}})}waitForReconnection(t=!1){return this.terminated?Promise.resolve(c(new h)):new Promise(n=>{const o=this.reconnectionSubject.subscribe({next:r=>{t&&this._sendApduSubject.error(new s(new Error("Device disconnected while waiting for device response"))),n(r==="success"?u(void 0):c(r)),o.unsubscribe()}})})}lostConnection(){this._logger.info("\u23F1\uFE0F Lost connection, starting timer"),this.waitingForReconnection=!0,this.lostConnectionTimeout=setTimeout(()=>{this._logger.info("\u274C Disconnection timeout, terminating connection"),this.disconnect()},f)}async reconnectHidDevice(t){this._device=t,this._device.oninputreport=n=>this.receiveHidInputReport(n),this.lostConnectionTimeout&&clearTimeout(this.lostConnectionTimeout),this._pendingApdu.isJust()&&this._sendApduSubject.error(new s),await t.open(),this._logger.info("\u23F1\uFE0F\u{1F50C} Device reconnected"),this.waitingForReconnection=!1,this.reconnectionSubject.next("success")}disconnect(){this._pendingApdu.isJust()&&this._sendApduSubject.error(new s),this._logger.info("\u{1F51A} Disconnect"),this.lostConnectionTimeout&&clearTimeout(this.lostConnectionTimeout),this.terminated=!0,this._onConnectionTerminated(),this.reconnectionSubject.next(new h)}}export{C as WebHidDeviceConnection};
1
+ import{CommandUtils as l,ReconnectionFailedError as h}from"@ledgerhq/device-management-kit";import{Left as c,Maybe as v,Nothing as s,Right as d}from"purify-ts";import{Subject as a}from"rxjs";import{RECONNECT_DEVICE_TIMEOUT as m}from"../data/WebHidConfig";import{WebHidSendReportError as u}from"../model/Errors";class A{_device;_deviceId;_apduSender;_apduReceiver;_sendApduSubject=new a;_logger;_pendingApdu=s;_onConnectionTerminated;reconnectionSubject=new a;waitingForReconnection=!1;lostConnectionTimeout=null;timeSinceDisconnection=s;terminated=!1;constructor({device:t,deviceId:n,apduSender:r,apduReceiver:o,onConnectionTerminated:e},i){this._apduSender=r,this._apduReceiver=o,this._onConnectionTerminated=e,this._logger=i("WebHidDeviceConnection"),this._device=t,this._device.oninputreport=p=>this.receiveHidInputReport(p),this._deviceId=n,this._logger.info("\u{1F50C} Connected to device")}get device(){return this._device}get deviceId(){return this._deviceId}async sendApdu(t,n){this._sendApduSubject=new a,this._pendingApdu=v.of(t),this._logger.debug("Sending APDU",{data:{apdu:t},tag:"apdu-sender"});const r=new Promise(e=>{this._sendApduSubject.subscribe({next:async i=>{this._pendingApdu=s,n&&l.isSuccessResponse(i)?(await this.waitForReconnection()).caseOf({Left:g=>e(c(g)),Right:()=>e(d(i))}):e(d(i))},error:i=>{this._pendingApdu=s,e(c(i))}})});if(this.waitingForReconnection||!this.device.opened){const e=this.device.opened&&this._pendingApdu.isJust(),i=await this.waitForReconnection(e);if(i.isLeft())return i}const 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(i){return this._logger.error("Error sending frame",{data:{error:i}}),Promise.resolve(c(new u(i)))}}return r}receiveHidInputReport(t){const n=new Uint8Array(t.data.buffer);this._logger.debug("Received Frame",{data:{frame:n},tag:"apdu-receiver"}),this._apduReceiver.handleFrame(n).caseOf({Right: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(t=!1){return this.terminated?Promise.resolve(c(new h)):new Promise(n=>{const r=this.reconnectionSubject.subscribe({next:o=>{t&&this._sendApduSubject.error(new u),n(o==="success"?d(void 0):c(o)),r.unsubscribe()}})})}lostConnection(){this._logger.info("\u23F1\uFE0F Lost connection, starting timer"),this.timeSinceDisconnection=v.of(Date.now()),this.waitingForReconnection=!0,this.lostConnectionTimeout=setTimeout(()=>{this._logger.info("\u274C Disconnection timeout, terminating connection"),this.disconnect()},m)}async reconnectHidDevice(t){this._device=t,this._device.oninputreport=n=>this.receiveHidInputReport(n),this.lostConnectionTimeout&&(this._logger.info("\u23F1\uFE0F\u{1F50C} Device reconnected"),clearTimeout(this.lostConnectionTimeout)),await t.open(),this._pendingApdu.isJust()&&(this.timeSinceDisconnection.isJust()&&Date.now()-this.timeSinceDisconnection.extract()>m/2&&this._sendApduSubject.error(new u),this.timeSinceDisconnection=s),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 h)}}export{A as WebHidDeviceConnection};
2
2
  //# sourceMappingURL=WebHidDeviceConnection.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/api/transport/WebHidDeviceConnection.ts"],
4
- "sourcesContent": ["import {\n type ApduReceiverService,\n type ApduResponse,\n type ApduSenderService,\n CommandUtils,\n type DeviceConnection,\n type DeviceId,\n type DmkError,\n type LoggerPublisherService,\n ReconnectionFailedError,\n} from \"@ledgerhq/device-management-kit\";\nimport { type Either, Left, Maybe, Nothing, Right } from \"purify-ts\";\nimport { firstValueFrom, from, retry, Subject } from \"rxjs\";\n\nimport { RECONNECT_DEVICE_TIMEOUT } from \"@api/data/WebHidConfig\";\nimport { WebHidSendReportError } from \"@api/model/Errors\";\n\ntype WebHidDeviceConnectionConstructorArgs = {\n device: HIDDevice;\n deviceId: DeviceId;\n apduSender: ApduSenderService;\n apduReceiver: ApduReceiverService;\n onConnectionTerminated: () => void;\n};\n\ntype Timer = ReturnType<typeof setTimeout>;\n\n/**\n * Class to manage the connection with a USB HID device.\n * It sends APDU commands to the device and receives the responses.\n * It handles temporary disconnections and reconnections.\n */\nexport class WebHidDeviceConnection implements DeviceConnection {\n private _device: HIDDevice;\n private _deviceId: DeviceId;\n private readonly _apduSender: ApduSenderService;\n private readonly _apduReceiver: ApduReceiverService;\n private _sendApduSubject: Subject<ApduResponse> = new Subject();\n private readonly _logger: LoggerPublisherService;\n private _pendingApdu: Maybe<Uint8Array> = Nothing;\n\n /** Callback to notify the connection termination */\n private _onConnectionTerminated: () => void;\n /** Subject to notify the reconnection status */\n private reconnectionSubject: Subject<\"success\" | DmkError> = new Subject();\n /** Flag to indicate if the connection is waiting for a reconnection */\n private waitingForReconnection = false;\n /** Timeout to wait for the device to reconnect */\n private lostConnectionTimeout: Timer | null = null;\n /** Flag to indicate if the connection is terminated */\n private terminated = false;\n\n constructor(\n {\n device,\n deviceId,\n apduSender,\n apduReceiver,\n onConnectionTerminated,\n }: WebHidDeviceConnectionConstructorArgs,\n loggerServiceFactory: (tag: string) => LoggerPublisherService,\n ) {\n this._apduSender = apduSender;\n this._apduReceiver = apduReceiver;\n this._onConnectionTerminated = onConnectionTerminated;\n this._logger = loggerServiceFactory(\"WebHidDeviceConnection\");\n this._device = device;\n this._device.oninputreport = (event) => this.receiveHidInputReport(event);\n this._deviceId = deviceId;\n this._logger.info(\"\uD83D\uDD0C Connected to device\");\n }\n\n public get device() {\n return this._device;\n }\n\n public get deviceId() {\n return this._deviceId;\n }\n\n async sendApdu(\n apdu: Uint8Array,\n triggersDisconnection?: boolean,\n ): Promise<Either<DmkError, ApduResponse>> {\n this._sendApduSubject = new Subject();\n this._pendingApdu = Maybe.of(apdu);\n this._logger.debug(\"Sending APDU\", {\n data: { apdu },\n tag: \"apdu-sender\",\n });\n\n const resultPromise = new Promise<Either<DmkError, ApduResponse>>(\n (resolve) => {\n this._sendApduSubject.subscribe({\n next: async (r) => {\n this._pendingApdu = Nothing;\n if (triggersDisconnection && CommandUtils.isSuccessResponse(r)) {\n // Anticipate the disconnection and wait for the reconnection before resolving\n const reconnectionRes = await this.waitForReconnection();\n reconnectionRes.caseOf({\n Left: (err) => resolve(Left(err)),\n Right: () => resolve(Right(r)),\n });\n } else {\n resolve(Right(r));\n }\n },\n error: (err) => {\n this._pendingApdu = Nothing;\n resolve(Left(err));\n },\n });\n },\n );\n\n if (this.waitingForReconnection || !this.device.opened) {\n const waitingForDeviceResponse =\n this.device.opened && this._pendingApdu.isJust();\n const reconnectionRes = await this.waitForReconnection(\n waitingForDeviceResponse,\n );\n if (reconnectionRes.isLeft()) {\n return reconnectionRes;\n }\n }\n\n const frames = this._apduSender.getFrames(apdu);\n for (const frame of frames) {\n this._logger.debug(\"Sending Frame\", {\n data: { frame: frame.getRawData() },\n });\n\n try {\n await firstValueFrom(\n from(this._device.sendReport(0, frame.getRawData())).pipe(\n retry({\n count: 3,\n delay: 500,\n }),\n ),\n );\n } catch (error) {\n this._logger.error(\"Error sending frame\", { data: { error } });\n return Promise.resolve(Left(new WebHidSendReportError(error)));\n }\n }\n\n return resultPromise;\n }\n\n private receiveHidInputReport(event: HIDInputReportEvent) {\n const data = new Uint8Array(event.data.buffer);\n this._logger.debug(\"Received Frame\", {\n data: { frame: data },\n tag: \"apdu-receiver\",\n });\n const response = this._apduReceiver.handleFrame(data);\n response.caseOf({\n Right: (maybeApduResponse) => {\n maybeApduResponse.map((apduResponse) => {\n this._logger.debug(\"Received APDU Response\", {\n data: { response: apduResponse },\n });\n this._sendApduSubject.next(apduResponse);\n this._sendApduSubject.complete();\n });\n },\n Left: (err) => {\n this._sendApduSubject.error(err);\n },\n });\n }\n\n private waitForReconnection(\n waitingForDeviceResponse: boolean = false,\n ): Promise<Either<DmkError, void>> {\n if (this.terminated) {\n return Promise.resolve(Left(new ReconnectionFailedError()));\n }\n\n return new Promise<Either<DmkError, void>>((resolve) => {\n const sub = this.reconnectionSubject.subscribe({\n next: (res) => {\n if (waitingForDeviceResponse) {\n this._sendApduSubject.error(\n new WebHidSendReportError(\n new Error(\n \"Device disconnected while waiting for device response\",\n ),\n ),\n );\n }\n\n if (res === \"success\") {\n resolve(Right(undefined));\n } else {\n resolve(Left(res));\n }\n\n sub.unsubscribe();\n },\n });\n });\n }\n\n /**\n * Method called when the HIDDevice gets disconnected.\n * It starts a timeout to wait for the device to reconnect.\n * */\n public lostConnection() {\n this._logger.info(\"\u23F1\uFE0F Lost connection, starting timer\");\n this.waitingForReconnection = true;\n this.lostConnectionTimeout = setTimeout(() => {\n this._logger.info(\"\u274C Disconnection timeout, terminating connection\");\n this.disconnect();\n }, RECONNECT_DEVICE_TIMEOUT);\n }\n\n /** Reconnect the device after a disconnection */\n public async reconnectHidDevice(device: HIDDevice) {\n this._device = device;\n this._device.oninputreport = (event) => this.receiveHidInputReport(event);\n\n if (this.lostConnectionTimeout) {\n clearTimeout(this.lostConnectionTimeout);\n }\n\n if (this._pendingApdu.isJust()) {\n this._sendApduSubject.error(new WebHidSendReportError());\n }\n\n await device.open();\n\n this._logger.info(\"\u23F1\uFE0F\uD83D\uDD0C Device reconnected\");\n this.waitingForReconnection = false;\n this.reconnectionSubject.next(\"success\");\n }\n\n public disconnect() {\n if (this._pendingApdu.isJust()) {\n this._sendApduSubject.error(new WebHidSendReportError());\n }\n\n this._logger.info(\"\uD83D\uDD1A Disconnect\");\n if (this.lostConnectionTimeout) clearTimeout(this.lostConnectionTimeout);\n this.terminated = true;\n this._onConnectionTerminated();\n this.reconnectionSubject.next(new ReconnectionFailedError());\n }\n}\n"],
5
- "mappings": "AAAA,OAIE,gBAAAA,EAKA,2BAAAC,MACK,kCACP,OAAsB,QAAAC,EAAM,SAAAC,EAAO,WAAAC,EAAS,SAAAC,MAAa,YACzD,OAAS,kBAAAC,EAAgB,QAAAC,EAAM,SAAAC,EAAO,WAAAC,MAAe,OAErD,OAAS,4BAAAC,MAAgC,yBACzC,OAAS,yBAAAC,MAA6B,oBAiB/B,MAAMC,CAAm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Y,CACtD,MAAMW,EAAM,KAAK,oBAAoB,UAAU,CAC7C,KAAOC,GAAQ,CACTT,GACF,KAAK,iBAAiB,MACpB,IAAIf,EACF,IAAI,MACF,uDACF,CACF,CACF,EAIAY,EADEY,IAAQ,UACF9B,EAAM,MAAS,EAEfH,EAAKiC,CAAG,CAFQ,EAK1BD,EAAI,YAAY,CAClB,CACF,CAAC,CACH,CAAC,CACH,CAMO,gBAAiB,CACtB,KAAK,QAAQ,KAAK,8CAAoC,EACtD,KAAK,uBAAyB,GAC9B,KAAK,sBAAwB,WAAW,IAAM,CAC5C,KAAK,QAAQ,KAAK,sDAAiD,EACnE,KAAK,WAAW,CAClB,EAAGxB,CAAwB,CAC7B,CAGA,MAAa,mBAAmBG,EAAmB,CACjD,KAAK,QAAUA,EACf,KAAK,QAAQ,cAAiBM,GAAU,KAAK,sBAAsBA,CAAK,EAEpE,KAAK,uBACP,aAAa,KAAK,qBAAqB,EAGrC,KAAK,aAAa,OAAO,GAC3B,KAAK,iBAAiB,MAAM,IAAIR,CAAuB,EAGzD,MAAME,EAAO,KAAK,EAElB,KAAK,QAAQ,KAAK,0CAAyB,EAC3C,KAAK,uBAAyB,GAC9B,KAAK,oBAAoB,KAAK,SAAS,CACzC,CAEO,YAAa,CACd,KAAK,aAAa,OAAO,GAC3B,KAAK,iBAAiB,MAAM,IAAIF,CAAuB,EAGzD,KAAK,QAAQ,KAAK,sBAAe,EAC7B,KAAK,uBAAuB,aAAa,KAAK,qBAAqB,EACvE,KAAK,WAAa,GAClB,KAAK,wBAAwB,EAC7B,KAAK,oBAAoB,KAAK,IAAIV,CAAyB,CAC7D,CACF",
6
- "names": ["CommandUtils", "ReconnectionFailedError", "Left", "Maybe", "Nothing", "Right", "firstValueFrom", "from", "retry", "Subject", "RECONNECT_DEVICE_TIMEOUT", "WebHidSendReportError", "WebHidDeviceConnection", "device", "deviceId", "apduSender", "apduReceiver", "onConnectionTerminated", "loggerServiceFactory", "event", "apdu", "triggersDisconnection", "resultPromise", "resolve", "r", "err", "waitingForDeviceResponse", "reconnectionRes", "frames", "frame", "error", "data", "maybeApduResponse", "apduResponse", "sub", "res"]
4
+ "sourcesContent": ["import {\n type ApduReceiverService,\n type ApduResponse,\n type ApduSenderService,\n CommandUtils,\n type DeviceConnection,\n type DeviceId,\n type DmkError,\n type LoggerPublisherService,\n ReconnectionFailedError,\n} from \"@ledgerhq/device-management-kit\";\nimport { type Either, Left, Maybe, Nothing, Right } from \"purify-ts\";\nimport { Subject } from \"rxjs\";\n\nimport { RECONNECT_DEVICE_TIMEOUT } from \"@api/data/WebHidConfig\";\nimport { WebHidSendReportError } from \"@api/model/Errors\";\n\ntype WebHidDeviceConnectionConstructorArgs = {\n device: HIDDevice;\n deviceId: DeviceId;\n apduSender: ApduSenderService;\n apduReceiver: ApduReceiverService;\n onConnectionTerminated: () => void;\n};\n\ntype Timer = ReturnType<typeof setTimeout>;\n\n/**\n * Class to manage the connection with a USB HID device.\n * It sends APDU commands to the device and receives the responses.\n * It handles temporary disconnections and reconnections.\n */\nexport class WebHidDeviceConnection implements DeviceConnection {\n private _device: HIDDevice;\n private _deviceId: DeviceId;\n private readonly _apduSender: ApduSenderService;\n private readonly _apduReceiver: ApduReceiverService;\n private _sendApduSubject: Subject<ApduResponse> = new Subject();\n private readonly _logger: LoggerPublisherService;\n private _pendingApdu: Maybe<Uint8Array> = Nothing;\n\n /** Callback to notify the connection termination */\n private _onConnectionTerminated: () => void;\n /** Subject to notify the reconnection status */\n private reconnectionSubject: Subject<\"success\" | DmkError> = new Subject();\n /** Flag to indicate if the connection is waiting for a reconnection */\n private waitingForReconnection = false;\n /** Timeout to wait for the device to reconnect */\n private lostConnectionTimeout: Timer | null = null;\n /** Time since disconnection */\n private timeSinceDisconnection: Maybe<number> = Nothing;\n /** Flag to indicate if the connection is terminated */\n private terminated = false;\n\n constructor(\n {\n device,\n deviceId,\n apduSender,\n apduReceiver,\n onConnectionTerminated,\n }: WebHidDeviceConnectionConstructorArgs,\n loggerServiceFactory: (tag: string) => LoggerPublisherService,\n ) {\n this._apduSender = apduSender;\n this._apduReceiver = apduReceiver;\n this._onConnectionTerminated = onConnectionTerminated;\n this._logger = loggerServiceFactory(\"WebHidDeviceConnection\");\n this._device = device;\n this._device.oninputreport = (event) => this.receiveHidInputReport(event);\n this._deviceId = deviceId;\n this._logger.info(\"\uD83D\uDD0C Connected to device\");\n }\n\n public get device() {\n return this._device;\n }\n\n public get deviceId() {\n return this._deviceId;\n }\n\n async sendApdu(\n apdu: Uint8Array,\n triggersDisconnection?: boolean,\n ): Promise<Either<DmkError, ApduResponse>> {\n this._sendApduSubject = new Subject();\n this._pendingApdu = Maybe.of(apdu);\n this._logger.debug(\"Sending APDU\", {\n data: { apdu },\n tag: \"apdu-sender\",\n });\n\n const resultPromise = new Promise<Either<DmkError, ApduResponse>>(\n (resolve) => {\n this._sendApduSubject.subscribe({\n next: async (r) => {\n this._pendingApdu = Nothing;\n if (triggersDisconnection && CommandUtils.isSuccessResponse(r)) {\n // Anticipate the disconnection and wait for the reconnection before resolving\n const reconnectionRes = await this.waitForReconnection();\n reconnectionRes.caseOf({\n Left: (err) => resolve(Left(err)),\n Right: () => resolve(Right(r)),\n });\n } else {\n resolve(Right(r));\n }\n },\n error: (err) => {\n this._pendingApdu = Nothing;\n resolve(Left(err));\n },\n });\n },\n );\n\n if (this.waitingForReconnection || !this.device.opened) {\n const waitingForDeviceResponse =\n this.device.opened && this._pendingApdu.isJust();\n\n const reconnectionRes = await this.waitForReconnection(\n waitingForDeviceResponse,\n );\n\n if (reconnectionRes.isLeft()) {\n return reconnectionRes;\n }\n }\n\n const frames = this._apduSender.getFrames(apdu);\n for (const frame of frames) {\n this._logger.debug(\"Sending Frame\", {\n data: { frame: frame.getRawData() },\n });\n 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(\n waitingForDeviceResponse: boolean = false,\n ): Promise<Either<DmkError, void>> {\n if (this.terminated) {\n return Promise.resolve(Left(new ReconnectionFailedError()));\n }\n\n return new Promise<Either<DmkError, void>>((resolve) => {\n const sub = this.reconnectionSubject.subscribe({\n next: (res) => {\n if (waitingForDeviceResponse) {\n this._sendApduSubject.error(new WebHidSendReportError());\n }\n\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.timeSinceDisconnection = Maybe.of(Date.now());\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\n await device.open();\n\n if (this._pendingApdu.isJust()) {\n if (this.timeSinceDisconnection.isJust()) {\n const now = Date.now();\n const timeSinceDisconnection =\n now - this.timeSinceDisconnection.extract();\n // 3 seconds timeout\n if (timeSinceDisconnection > RECONNECT_DEVICE_TIMEOUT / 2) {\n this._sendApduSubject.error(new WebHidSendReportError());\n }\n }\n this.timeSinceDisconnection = Nothing;\n }\n\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,EAAO,WAAAC,EAAS,SAAAC,MAAa,YACzD,OAAS,WAAAC,MAAe,OAExB,OAAS,4BAAAC,MAAgC,yBACzC,OAAS,yBAAAC,MAA6B,oBAiB/B,MAAMC,CAAmD,CACtD,QACA,UACS,YACA,cACT,iBAA0C,IAAIH,EACrC,QACT,aAAkCF,EAGlC,wBAEA,oBAAqD,IAAIE,EAEzD,uBAAyB,GAEzB,sBAAsC,KAEtC,uBAAwCF,EAExC,WAAa,GAErB,YACE,CACE,OAAAM,EACA,SAAAC,EACA,WAAAC,EACA,aAAAC,EACA,uBAAAC,CACF,EACAC,EACA,CACA,KAAK,YAAcH,EACnB,KAAK,cAAgBC,EACrB,KAAK,wBAA0BC,EAC/B,KAAK,QAAUC,EAAqB,wBAAwB,EAC5D,KAAK,QAAUL,EACf,KAAK,QAAQ,cAAiBM,GAAU,KAAK,sBAAsBA,CAAK,EACxE,KAAK,UAAYL,EACjB,KAAK,QAAQ,KAAK,+BAAwB,CAC5C,CAEA,IAAW,QAAS,CAClB,OAAO,KAAK,OACd,CAEA,IAAW,UAAW,CACpB,OAAO,KAAK,SACd,CAEA,MAAM,SACJM,EACAC,EACyC,CACzC,KAAK,iBAAmB,IAAIZ,EAC5B,KAAK,aAAeH,EAAM,GAAGc,CAAI,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,KAAK,IAAI,EAEb,KAAK,uBAAuB,QAAQ,EAEfH,EAA2B,GACtD,KAAK,iBAAiB,MAAM,IAAIC,CAAuB,EAG3D,KAAK,uBAAyBJ,GAGhC,KAAK,uBAAyB,GAC9B,KAAK,oBAAoB,KAAK,SAAS,CACzC,CAEO,YAAa,CAClB,KAAK,QAAQ,KAAK,sBAAe,EAC7B,KAAK,uBAAuB,aAAa,KAAK,qBAAqB,EACvE,KAAK,WAAa,GAClB,KAAK,wBAAwB,EAC7B,KAAK,oBAAoB,KAAK,IAAIH,CAAyB,CAC7D,CACF",
6
+ "names": ["CommandUtils", "ReconnectionFailedError", "Left", "Maybe", "Nothing", "Right", "Subject", "RECONNECT_DEVICE_TIMEOUT", "WebHidSendReportError", "WebHidDeviceConnection", "device", "deviceId", "apduSender", "apduReceiver", "onConnectionTerminated", "loggerServiceFactory", "event", "apdu", "triggersDisconnection", "resultPromise", "resolve", "r", "err", "waitingForDeviceResponse", "reconnectionRes", "frames", "frame", "error", "data", "maybeApduResponse", "apduResponse", "sub", "res"]
7
7
  }
@@ -1,2 +1,2 @@
1
- class n{sendApdu=vi.fn()}export{n as WebHidDeviceConnectionStub};
1
+ class n{sendApdu=jest.fn()}export{n as WebHidDeviceConnectionStub};
2
2
  //# sourceMappingURL=WebHidDeviceConnection.stub.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
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 = vi.fn();\n}\n"],
5
- "mappings": "AAKO,MAAMA,CAAuD,CAClE,SAA2B,GAAG,GAAG,CACnC",
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
6
  "names": ["WebHidDeviceConnectionStub"]
7
7
  }
@@ -1,2 +1,2 @@
1
- import{defaultApduReceiverServiceStubBuilder as A,defaultApduSenderServiceStubBuilder as y,ReconnectionFailedError as w}from"@ledgerhq/device-management-kit";import{Left as f,Right as l}from"purify-ts";import{RECONNECT_DEVICE_TIMEOUT as m}from"../data/WebHidConfig";import{WebHidSendReportError as h}from"../model/Errors";import{hidDeviceStubBuilder as b}from"../model/HIDDevice.stub";import{WebHidDeviceConnection as c}from"./WebHidDeviceConnection";vi.useFakeTimers();const S=new Uint8Array([170,170,5,0,0,0,2,85,21,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),d=new Uint8Array([170,170,5,0,0,0,2,144,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);class g{tag;constructor(r,o){this.subscribers=r,this.tag=o}subscribers=[];error=vi.fn();warn=vi.fn();debug=vi.fn();info=vi.fn()}const x=async()=>{const e=await vi.importActual("timers");return new Promise(e.setImmediate)};vi.useFakeTimers();describe("WebHidDeviceConnection",()=>{let e,r,o;const s=()=>{},a="test-device-id",i=t=>new g([],t);beforeEach(()=>{e=b({opened:!0}),r=y(void 0,i),o=A(void 0,i)}),it("should get device",()=>{const n=new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:s,deviceId:a},i).device;expect(n).toStrictEqual(e)}),it("should send APDU through hid report",()=>{new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:s,deviceId:a},i).sendApdu(new Uint8Array(0)),expect(e.sendReport).toHaveBeenCalled()}),it("should receive APDU through hid report",async()=>{e.sendReport=vi.fn(()=>Promise.resolve(e.oninputreport({type:"inputreport",data:new DataView(Uint8Array.from(d).buffer)})));const n=await new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:s,deviceId:a},i).sendApdu(Uint8Array.from([]));expect(n).toEqual(l({statusCode:new Uint8Array([144,0]),data:new Uint8Array([])}))}),describe("anticipating loss of connection after sending an APDU",()=>{it("sendApdu(whatever, true) should wait for reconnection before resolving if the response is a success",async()=>{e.sendReport=vi.fn(()=>Promise.resolve(e.oninputreport({type:"inputreport",data:new DataView(Uint8Array.from(d).buffer)})));const t=new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:s,deviceId:a},i);let n=!1;const p=t.sendApdu(Uint8Array.from([]),!0).then(v=>(n=!0,v));t.lostConnection(),await x(),expect(n).toBe(!1),t.reconnectHidDevice(e),await x(),expect(n).toBe(!0);const u=await p;expect(u).toEqual(l({statusCode:new Uint8Array([144,0]),data:new Uint8Array([])}))}),it("sendApdu(whatever, true) should not wait for reconnection if the response is not a success",async()=>{e.sendReport=vi.fn(()=>Promise.resolve(e.oninputreport({type:"inputreport",data:new DataView(Uint8Array.from(S).buffer)})));const n=await new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:s,deviceId:a},i).sendApdu(Uint8Array.from([]),!0);expect(n).toEqual(l({statusCode:new Uint8Array([85,21]),data:new Uint8Array([])}))}),it("sendApdu(whatever, true) should return an error if the device gets disconnected while waiting for reconnection",async()=>{e.sendReport=vi.fn(()=>Promise.resolve(e.oninputreport({type:"inputreport",data:new DataView(Uint8Array.from(d).buffer)})));const t=new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:s,deviceId:a},i),n=t.sendApdu(Uint8Array.from([]),!0);t.lostConnection(),vi.advanceTimersByTime(m),await x();const p=await n;expect(p).toEqual(f(new w))})}),describe("connection lost before sending an APDU",()=>{it("sendApdu(whatever, false) should return an error if the device connection has been lost and times out",async()=>{e.sendReport=vi.fn(()=>Promise.resolve(e.oninputreport({type:"inputreport",data:new DataView(Uint8Array.from(d).buffer)})));const t=new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:s,deviceId:a},i);t.lostConnection(),vi.advanceTimersByTime(m),await x();const n=await t.sendApdu(Uint8Array.from([]),!1);await x(),expect(n).toEqual(f(new w))}),it("sendApdu(whatever, false) should wait for reconnection to resolve",async()=>{e.sendReport=vi.fn(()=>Promise.resolve(e.oninputreport({type:"inputreport",data:new DataView(Uint8Array.from(d).buffer)})));const t=new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:s,deviceId:a},i);t.lostConnection();let n=!1;const p=t.sendApdu(Uint8Array.from([]),!1).then(v=>(n=!0,v));await x(),expect(n).toBe(!1),t.reconnectHidDevice(e),await x(),expect(n).toBe(!0);const u=await p;expect(u).toEqual(f(new h))})})});
1
+ import{defaultApduReceiverServiceStubBuilder as A,defaultApduSenderServiceStubBuilder as y,ReconnectionFailedError as v}from"@ledgerhq/device-management-kit";import{Left as l,Right as w}from"purify-ts";import{RECONNECT_DEVICE_TIMEOUT as m}from"../data/WebHidConfig";import{WebHidSendReportError as h}from"../model/Errors";import{hidDeviceStubBuilder as b}from"../model/HIDDevice.stub";import{WebHidDeviceConnection as c}from"./WebHidDeviceConnection";jest.useFakeTimers();const S=new Uint8Array([170,170,5,0,0,0,2,85,21,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),p=new Uint8Array([170,170,5,0,0,0,2,144,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);class g{tag;constructor(r,o){this.subscribers=r,this.tag=o}subscribers=[];error=jest.fn();warn=jest.fn();debug=jest.fn();info=jest.fn()}const x=()=>new Promise(jest.requireActual("timers").setImmediate);jest.useFakeTimers();describe("WebHidDeviceConnection",()=>{let e,r,o;const i=()=>{},a="test-device-id",s=t=>new g([],t);beforeEach(()=>{e=b({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(p).buffer)})));const n=await new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:i,deviceId:a},s).sendApdu(Uint8Array.from([]));expect(n).toEqual(w({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(p).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(f=>(n=!0,f));t.lostConnection(),await x(),expect(n).toBe(!1),t.reconnectHidDevice(e),await x(),expect(n).toBe(!0);const u=await d;expect(u).toEqual(w({statusCode:new Uint8Array([144,0]),data:new Uint8Array([])}))}),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(S).buffer)})));const n=await new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:i,deviceId:a},s).sendApdu(Uint8Array.from([]),!0);expect(n).toEqual(w({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(p).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(l(new v))})}),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(p).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(l(new v))}),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(p).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(f=>(n=!0,f));await x(),expect(n).toBe(!1),t.reconnectHidDevice(e),await x(),expect(n).toBe(!0);const u=await d;expect(u).toEqual(l(new h))})})});
2
2
  //# sourceMappingURL=WebHidDeviceConnection.test.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/api/transport/WebHidDeviceConnection.test.ts"],
4
- "sourcesContent": ["/* eslint @typescript-eslint/consistent-type-imports: off */\nimport {\n type ApduReceiverService,\n type ApduSenderService,\n defaultApduReceiverServiceStubBuilder,\n defaultApduSenderServiceStubBuilder,\n type DeviceId,\n type LoggerPublisherService,\n type LoggerSubscriberService,\n ReconnectionFailedError,\n} from \"@ledgerhq/device-management-kit\";\nimport { Left, Right } from \"purify-ts\";\n\nimport { RECONNECT_DEVICE_TIMEOUT } from \"@api/data/WebHidConfig\";\nimport { WebHidSendReportError } from \"@api/model/Errors\";\nimport { hidDeviceStubBuilder } from \"@api/model/HIDDevice.stub\";\n\nimport { WebHidDeviceConnection } from \"./WebHidDeviceConnection\";\n\nvi.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 = vi.fn();\n warn = vi.fn();\n debug = vi.fn();\n info = vi.fn();\n}\n\n/**\n * Flushes all pending promises\n */\nconst flushPromises = async () => {\n const timers = await vi.importActual<typeof import(\"timers\")>(\"timers\");\n return new Promise(timers.setImmediate);\n};\n\nvi.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 = vi.fn(() =>\n Promise.resolve(\n device.oninputreport!({\n type: \"inputreport\",\n data: new DataView(Uint8Array.from(RESPONSE_SUCCESS).buffer),\n } as HIDInputReportEvent),\n ),\n );\n const connection = new WebHidDeviceConnection(\n { device, apduSender, apduReceiver, onConnectionTerminated, deviceId },\n logger,\n );\n // when\n const response = await connection.sendApdu(Uint8Array.from([]));\n // then\n expect(response).toEqual(\n Right({\n statusCode: new Uint8Array([0x90, 0x00]),\n data: new Uint8Array([]),\n }),\n );\n });\n\n describe(\"anticipating loss of connection after sending an APDU\", () => {\n it(\"sendApdu(whatever, true) should wait for reconnection before resolving if the response is a success\", async () => {\n // given\n device.sendReport = vi.fn(() =>\n Promise.resolve(\n device.oninputreport!({\n type: \"inputreport\",\n data: new DataView(Uint8Array.from(RESPONSE_SUCCESS).buffer),\n } as HIDInputReportEvent),\n ),\n );\n\n const connection = new WebHidDeviceConnection(\n { device, apduSender, apduReceiver, onConnectionTerminated, deviceId },\n logger,\n );\n\n let hasResolved = false;\n\n const responsePromise = connection\n .sendApdu(Uint8Array.from([]), true)\n .then((response) => {\n hasResolved = true;\n return response;\n });\n\n connection.lostConnection();\n\n // before reconnecting\n await flushPromises();\n expect(hasResolved).toBe(false);\n\n // when reconnecting\n connection.reconnectHidDevice(device);\n await flushPromises();\n expect(hasResolved).toBe(true);\n\n const response = await responsePromise;\n\n expect(response).toEqual(\n Right({\n statusCode: new Uint8Array([0x90, 0x00]),\n data: new Uint8Array([]),\n }),\n );\n });\n\n it(\"sendApdu(whatever, true) should not wait for reconnection if the response is not a success\", async () => {\n // given\n device.sendReport = vi.fn(() =>\n Promise.resolve(\n device.oninputreport!({\n type: \"inputreport\",\n data: new DataView(Uint8Array.from(RESPONSE_LOCKED_DEVICE).buffer),\n } as HIDInputReportEvent),\n ),\n );\n const connection = new WebHidDeviceConnection(\n { device, apduSender, apduReceiver, onConnectionTerminated, deviceId },\n logger,\n );\n\n // when\n const response = await connection.sendApdu(Uint8Array.from([]), true);\n\n // then\n expect(response).toEqual(\n Right({\n statusCode: new Uint8Array([0x55, 0x15]),\n data: new Uint8Array([]),\n }),\n );\n });\n\n it(\"sendApdu(whatever, true) should return an error if the device gets disconnected while waiting for reconnection\", async () => {\n // given\n device.sendReport = vi.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 vi.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT);\n await flushPromises();\n\n // then\n const response = await responsePromise;\n expect(response).toEqual(Left(new ReconnectionFailedError()));\n });\n });\n\n describe(\"connection lost before sending an APDU\", () => {\n it(\"sendApdu(whatever, false) should return an error if the device connection has been lost and times out\", async () => {\n // given\n device.sendReport = vi.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 vi.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT);\n await flushPromises();\n\n // then\n const response = await connection.sendApdu(Uint8Array.from([]), false);\n await flushPromises();\n expect(response).toEqual(Left(new ReconnectionFailedError()));\n });\n\n it(\"sendApdu(whatever, false) should wait for reconnection to resolve\", async () => {\n // given\n device.sendReport = vi.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(Left(new WebHidSendReportError()));\n });\n });\n});\n"],
5
- "mappings": "AACA,OAGE,yCAAAA,EACA,uCAAAC,EAIA,2BAAAC,MACK,kCACP,OAAS,QAAAC,EAAM,SAAAC,MAAa,YAE5B,OAAS,4BAAAC,MAAgC,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CAAC,CAC9D,CAAC,EAED,GAAG,oEAAqE,SAAY,CAElFc,EAAO,WAAa,GAAG,GAAG,IACxB,QAAQ,QACNA,EAAO,cAAe,CACpB,KAAM,cACN,KAAM,IAAI,SAAS,WAAW,KAAKN,CAAgB,EAAE,MAAM,CAC7D,CAAwB,CAC1B,CACF,EACA,MAAMc,EAAa,IAAIhB,EACrB,CAAE,OAAAQ,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,MAAMT,EAAc,EACpB,OAAOW,CAAW,EAAE,KAAK,EAAK,EAG9BD,EAAW,mBAAmBR,CAAM,EACpC,MAAMF,EAAc,EACpB,OAAOW,CAAW,EAAE,KAAK,EAAI,EAE7B,MAAMF,EAAW,MAAMG,EAEvB,OAAOH,CAAQ,EAAE,QAAQpB,EAAK,IAAIG,CAAuB,CAAC,CAC5D,CAAC,CACH,CAAC,CACH,CAAC",
6
- "names": ["defaultApduReceiverServiceStubBuilder", "defaultApduSenderServiceStubBuilder", "ReconnectionFailedError", "Left", "Right", "RECONNECT_DEVICE_TIMEOUT", "WebHidSendReportError", "hidDeviceStubBuilder", "WebHidDeviceConnection", "RESPONSE_LOCKED_DEVICE", "RESPONSE_SUCCESS", "LoggerPublisherServiceStub", "subscribers", "tag", "flushPromises", "timers", "device", "apduSender", "apduReceiver", "onConnectionTerminated", "deviceId", "logger", "cDevice", "response", "connection", "hasResolved", "responsePromise"]
4
+ "sourcesContent": ["import {\n type ApduReceiverService,\n type ApduSenderService,\n defaultApduReceiverServiceStubBuilder,\n defaultApduSenderServiceStubBuilder,\n type DeviceId,\n type LoggerPublisherService,\n type LoggerSubscriberService,\n ReconnectionFailedError,\n} from \"@ledgerhq/device-management-kit\";\nimport { Left, Right } from \"purify-ts\";\n\nimport { RECONNECT_DEVICE_TIMEOUT } from \"@api/data/WebHidConfig\";\nimport { WebHidSendReportError } from \"@api/model/Errors\";\nimport { hidDeviceStubBuilder } from \"@api/model/HIDDevice.stub\";\n\nimport { WebHidDeviceConnection } from \"./WebHidDeviceConnection\";\n\njest.useFakeTimers();\n\nconst RESPONSE_LOCKED_DEVICE = new Uint8Array([\n 0xaa, 0xaa, 0x05, 0x00, 0x00, 0x00, 0x02, 0x55, 0x15, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n]);\n\nconst RESPONSE_SUCCESS = new Uint8Array([\n 0xaa, 0xaa, 0x05, 0x00, 0x00, 0x00, 0x02, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n]);\n\nclass LoggerPublisherServiceStub implements LoggerPublisherService {\n tag: string;\n constructor(subscribers: LoggerSubscriberService[], tag: string) {\n this.subscribers = subscribers;\n this.tag = tag;\n }\n subscribers: LoggerSubscriberService[] = [];\n error = jest.fn();\n warn = jest.fn();\n debug = jest.fn();\n info = jest.fn();\n}\n\n/**\n * Flushes all pending promises\n */\nconst flushPromises = () =>\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n new Promise(jest.requireActual(\"timers\").setImmediate);\n\njest.useFakeTimers();\n\ndescribe(\"WebHidDeviceConnection\", () => {\n let device: HIDDevice;\n let apduSender: ApduSenderService;\n let apduReceiver: ApduReceiverService;\n const onConnectionTerminated = () => {};\n const deviceId: DeviceId = \"test-device-id\";\n const logger = (tag: string) => new LoggerPublisherServiceStub([], tag);\n\n beforeEach(() => {\n device = hidDeviceStubBuilder({ opened: true });\n apduSender = defaultApduSenderServiceStubBuilder(undefined, logger);\n apduReceiver = defaultApduReceiverServiceStubBuilder(undefined, logger);\n });\n\n it(\"should get device\", () => {\n // given\n const connection = new WebHidDeviceConnection(\n { device, apduSender, apduReceiver, onConnectionTerminated, deviceId },\n logger,\n );\n // when\n const cDevice = connection.device;\n // then\n expect(cDevice).toStrictEqual(device);\n });\n\n it(\"should send APDU through hid report\", () => {\n // given\n const connection = new WebHidDeviceConnection(\n { device, apduSender, apduReceiver, onConnectionTerminated, deviceId },\n logger,\n );\n // when\n connection.sendApdu(new Uint8Array(0));\n // then\n expect(device.sendReport).toHaveBeenCalled();\n });\n\n it(\"should receive APDU through hid report\", async () => {\n // given\n device.sendReport = jest.fn(() =>\n Promise.resolve(\n device.oninputreport!({\n type: \"inputreport\",\n data: new DataView(Uint8Array.from(RESPONSE_SUCCESS).buffer),\n } as HIDInputReportEvent),\n ),\n );\n const connection = new WebHidDeviceConnection(\n { device, apduSender, apduReceiver, onConnectionTerminated, deviceId },\n logger,\n );\n // when\n const response = await connection.sendApdu(Uint8Array.from([]));\n // then\n expect(response).toEqual(\n Right({\n statusCode: new Uint8Array([0x90, 0x00]),\n data: new Uint8Array([]),\n }),\n );\n });\n\n describe(\"anticipating loss of connection after sending an APDU\", () => {\n 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(Left(new WebHidSendReportError()));\n });\n });\n});\n"],
5
+ "mappings": "AAAA,OAGE,yCAAAA,EACA,uCAAAC,EAIA,2BAAAC,MACK,kCACP,OAAS,QAAAC,EAAM,SAAAC,MAAa,YAE5B,OAAS,4BA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SAAY,CAEpFa,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,QAAQnB,EAAK,IAAIG,CAAuB,CAAC,CAC5D,CAAC,CACH,CAAC,CACH,CAAC",
6
+ "names": ["defaultApduReceiverServiceStubBuilder", "defaultApduSenderServiceStubBuilder", "ReconnectionFailedError", "Left", "Right", "RECONNECT_DEVICE_TIMEOUT", "WebHidSendReportError", "hidDeviceStubBuilder", "WebHidDeviceConnection", "RESPONSE_LOCKED_DEVICE", "RESPONSE_SUCCESS", "LoggerPublisherServiceStub", "subscribers", "tag", "flushPromises", "device", "apduSender", "apduReceiver", "onConnectionTerminated", "deviceId", "logger", "cDevice", "response", "connection", "hasResolved", "responsePromise"]
7
7
  }
@@ -1,2 +1,2 @@
1
- import{DeviceNotRecognizedError as f,FramerUtils as E,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 b,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 f(`Device not recognized: hidDevice.productId: 0x${e.productId.toString(16)}`)}})}listenToAvailableDevices(){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"),b(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 b(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(E.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};
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
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 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 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,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AAAC,CACF,IACE,IAAIzC,EACFsC,EACAC,EACAC,EACAC,CACF",
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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", "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
7
  }
@@ -1,2 +1,2 @@
1
- import{connectedDeviceStubBuilder as B,DeviceModelId as u,DeviceNotRecognizedError as P,NoAccessibleDeviceError as y,OpeningConnectionError as H,StaticDeviceModelDataSource as R,UnknownDeviceError as k}from"@ledgerhq/device-management-kit";import{Left as x,Right as N}from"purify-ts";import{Subject as S}from"rxjs";import{RECONNECT_DEVICE_TIMEOUT as p}from"../data/WebHidConfig";import{WebHidTransportNotSupportedError as O}from"../model/Errors";import{hidDeviceStubBuilder as l}from"../model/HIDDevice.stub";import{WebHidTransport as A}from"./WebHidTransport";class V{constructor(D,f){this.subscribers=D,this.tag=f}subscribers=[];tag="";error=vi.fn();warn=vi.fn();info=vi.fn();debug=vi.fn()}const w=new R,M=new V([],"web-usb-hid"),d=l(),m=async()=>{const r=await vi.importActual("timers");return new Promise(r.setImmediate)};describe("WebHidTransport",()=>{let r,D,f;function E(){D=vi.fn(),f=vi.fn(),r=new A(w,()=>M,f,D)}beforeEach(()=>{E(),vi.useFakeTimers()}),afterEach(()=>{vi.restoreAllMocks()});const v=(s,a)=>{r.startDiscovering().subscribe({next:s,error:a})};describe("When WebHID API is not supported",()=>{it("should not support the transport",()=>{expect(r.isSupported()).toBe(!1)}),it("should emit a startDiscovering error",()=>new Promise((s,a)=>{v(()=>{a("Should not emit any value")},g=>{expect(g).toBeInstanceOf(O),s()})}))}),describe("When WebHID API is supported",()=>{const s=vi.fn(),a=vi.fn(),g=new S,T=new S;function b(i){g.next({device:i})}function h(i){T.next({device:i})}beforeEach(()=>{global.navigator={hid:{getDevices:s,requestDevice:a,addEventListener:(i,e)=>{i==="disconnect"?T.subscribe(e):i==="connect"&&g.subscribe(e)}}},E()}),afterEach(()=>{vi.clearAllMocks(),global.navigator=void 0}),it("should support the transport",()=>{expect(r.isSupported()).toBe(!0)}),describe("startDiscovering",()=>{w.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,()=>new Promise((n,o)=>{a.mockResolvedValueOnce([e.hidDevice]),v(t=>{try{expect(t).toEqual(expect.objectContaining({deviceModel:e.expectedDeviceModel})),n()}catch(c){o(c)}},t=>{o(t)})}))}),it("should emit devices if new grant accesses",()=>new Promise((e,n)=>{a.mockResolvedValueOnce([d,{...d,productId:20497,productName:"Ledger Nano S Plus"}]);let o=0;v(t=>{try{switch(o){case 0:expect(t).toEqual(expect.objectContaining({deviceModel:expect.objectContaining({id:u.NANO_X,productName:"Ledger Nano X",usbProductId:64})}));break;case 1:expect(t).toEqual(expect.objectContaining({deviceModel:expect.objectContaining({id:u.NANO_SP,productName:"Ledger Nano S Plus",usbProductId:80})})),e();break}o++}catch(c){n(c)}},t=>{n(t)})})),it("should throw DeviceNotRecognizedError if the device is not recognized",()=>new Promise((e,n)=>{a.mockResolvedValueOnce([{...d,productId:16962}]),v(()=>{n("should not return a device")},o=>{expect(o).toBeInstanceOf(P),e()})})),it("should emit an error if the request device is in error",()=>new Promise((e,n)=>{const o="request device error";a.mockImplementationOnce(()=>{throw new Error(o)}),v(()=>{n("should not return a device")},t=>{expect(t).toBeInstanceOf(y),expect(t).toStrictEqual(new y(new Error(o))),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,n)=>{a.mockResolvedValueOnce([]),v(o=>{n(`Should not emit any value, but emitted ${JSON.stringify(o)}`)},o=>{try{expect(o).toBeInstanceOf(y),e()}catch(t){n(t)}})})),it("should emit the same discoveredDevice object if its discovered twice in a row",async()=>{a.mockResolvedValue([d]),s.mockResolvedValue([d]);const e=await new Promise((o,t)=>{v(()=>o(),c=>t(c))}),n=await new Promise((o,t)=>{v(()=>o(),c=>t(c))});expect(n).toBe(e)})}),describe("destroy",()=>{it("should stop monitoring connections if the discovery process is halted",()=>{const i=vi.spyOn(AbortController.prototype,"abort");r.destroy(),expect(i).toHaveBeenCalled()})}),describe("connect",()=>{it("should throw UnknownDeviceError if no internal device",async()=>{const i={deviceId:"fake",onDisconnect:vi.fn()},e=await r.connect(i);expect(e).toStrictEqual(x(new k("Unknown device fake")))}),it("should throw OpeningConnectionError if the device is already opened",async()=>{const i={deviceId:"fake",onDisconnect:vi.fn()},e=await r.connect(i);expect(e).toStrictEqual(x(new k("Unknown device fake")))}),it("should throw OpeningConnectionError if the device cannot be opened",()=>new Promise((i,e)=>{const n="cannot be opened",o={...d,open:()=>{throw new Error(n)}};a.mockResolvedValueOnce([o]),s.mockResolvedValue([o]),v(t=>{r.connect({deviceId:t.id,onDisconnect:vi.fn()}).then(c=>{expect(c).toStrictEqual(x(new H(new Error(n)))),i()}).catch(c=>{e(c)})},t=>{e(t)})})),it("should return the opened device",()=>new Promise((i,e)=>{const n={...d,opened:!1,open:()=>(n.opened=!0,Promise.resolve())};a.mockResolvedValue([n]),s.mockResolvedValue([n]),v(o=>{r.connect({deviceId:o.id,onDisconnect:vi.fn()}).then(t=>{t.ifRight(c=>{expect(c).toEqual(expect.objectContaining({id:o.id})),i()}).ifLeft(()=>{e(t)})}).catch(t=>{e(t)})},o=>{e(o)})})),it("should return a device if available",()=>new Promise((i,e)=>{a.mockResolvedValueOnce([d]),s.mockResolvedValue([d]),v(n=>{r.connect({deviceId:n.id,onDisconnect:vi.fn()}).then(o=>{o.ifRight(t=>{expect(t).toEqual(expect.objectContaining({id:n.id})),i()}).ifLeft(()=>{e(o)})}).catch(o=>{e(o)})},n=>{e(n)})}))}),describe("disconnect",()=>{it("should throw an error if the device is not connected",async()=>{const i=B(),e=await r.disconnect({connectedDevice:i});expect(e).toStrictEqual(x(new k(`Unknown device ${i.id}`)))}),it("should disconnect if the device is connected",()=>new Promise((i,e)=>{a.mockResolvedValueOnce([d]),s.mockResolvedValue([d]),v(n=>{r.connect({deviceId:n.id,onDisconnect:vi.fn()}).then(o=>{o.ifRight(t=>{r.disconnect({connectedDevice:t}).then(c=>{expect(c).toStrictEqual(N(void 0)),i()}).catch(c=>{e(c)})}).ifLeft(()=>{e(o)})}).catch(o=>{e(o)})},n=>{e(n)})})),it("should call disconnect handler if a connected device is unplugged",()=>new Promise((i,e)=>{const n=vi.fn();a.mockResolvedValueOnce([d]),s.mockResolvedValue([d]),r.startDiscovering().subscribe({next:o=>{const t={sendApdu:vi.fn(),device:d,deviceId:o.id,disconnect:n,lostConnection:vi.fn().mockImplementation(()=>{setTimeout(()=>{t.disconnect()},p)})};r.connect({deviceId:o.id,onDisconnect:n}).then(async()=>{h(d),expect(d.close).toHaveBeenCalled(),await Promise.resolve(),expect(n).not.toHaveBeenCalled(),vi.advanceTimersByTime(p/2),expect(n).not.toHaveBeenCalled(),vi.advanceTimersByTime(p/2),expect(n).toHaveBeenCalled(),i()}).catch(c=>{e(c)})}})}))}),describe("reconnect",()=>{it("should stop disconnection if reconnection happen",()=>new Promise((i,e)=>{const n=vi.fn(),o=l(),t=l();a.mockResolvedValueOnce([o]),s.mockResolvedValue([o,t]),v(async c=>{const C={sendApdu:vi.fn(),device:t,deviceId:c.id,disconnect:n,lostConnection:vi.fn().mockImplementation(()=>{setTimeout(()=>{C.disconnect()},p)})};try{await r.connect({deviceId:c.id,onDisconnect:n}),h(o),expect(o.close).toHaveBeenCalled(),await Promise.resolve(),vi.advanceTimersByTime(p/3),b(t),expect(t.open).toHaveBeenCalled(),await Promise.resolve(),vi.advanceTimersByTime(p),expect(n).not.toHaveBeenCalled(),i()}catch(I){e(I)}})})),it("should be able to reconnect twice in a row if the device is unplugged and replugged twice",()=>new Promise((i,e)=>{const n=vi.fn(),o=l(),t=l(),c=l();a.mockResolvedValueOnce([o]),s.mockResolvedValue([o,t,c]),v(async C=>{await r.connect({deviceId:C.id,onDisconnect:n});try{h(o),expect(o.close).toHaveBeenCalled(),await Promise.resolve(),vi.advanceTimersByTime(p/3),b(t),expect(t.open).toHaveBeenCalled(),await Promise.resolve(),vi.advanceTimersByTime(p),expect(n).not.toHaveBeenCalled(),h(t),expect(t.close).toHaveBeenCalled(),await Promise.resolve(),vi.advanceTimersByTime(p/3),b(c),expect(c.open).toHaveBeenCalled(),await Promise.resolve(),vi.advanceTimersByTime(p),expect(n).not.toHaveBeenCalled(),i()}catch(I){e(I)}})}))}),describe("Connection event typeguard",()=>{it("should validate type of an HIDConnectionEvent",()=>{const i={device:d},e=r.isHIDConnectionEvent(i);expect(e).toBe(!0)}),it("should not validate type of another event",()=>{const i=new Event("disconnect",{}),e=r.isHIDConnectionEvent(i);expect(e).toBe(!1)})}),describe("listenToAvailableDevices",()=>{it("should emit the devices already connected before listening",async()=>{const i=l();s.mockResolvedValue([i]);const e=vi.fn(),n=vi.fn();let o=[];r.listenToAvailableDevices().subscribe({next:t=>{o=t},complete:e,error:n}),await m(),expect(o).toEqual([expect.objectContaining({deviceModel:expect.objectContaining({id:u.NANO_X})})]),expect(e).not.toHaveBeenCalled(),expect(n).not.toHaveBeenCalled()}),it("should emit the new list of devices after connection and disconnection events",async()=>{E();const i=l({productId:w.getDeviceModel({id:u.NANO_X}).usbProductId<<8}),e=l({productId:w.getDeviceModel({id:u.STAX}).usbProductId<<8});s.mockResolvedValue([i]);const n=vi.fn(),o=vi.fn();let t=[];r.listenToAvailableDevices().subscribe({next:c=>{t=c},complete:n,error:o}),await m(),expect(t).toEqual([expect.objectContaining({deviceModel:expect.objectContaining({id:u.NANO_X})})]),s.mockResolvedValue([i,e]),b(e),await m(),expect(t).toEqual([expect.objectContaining({deviceModel:expect.objectContaining({id:u.NANO_X})}),expect.objectContaining({deviceModel:expect.objectContaining({id:u.STAX})})]),s.mockResolvedValue([e]),h(i),await m(),expect(t).toEqual([expect.objectContaining({deviceModel:expect.objectContaining({id:u.STAX})})]),expect(n).not.toHaveBeenCalled(),expect(o).not.toHaveBeenCalled()}),it("should preserve DeviceId in case the device has been disconnected and reconnected before the timeout",async()=>{const i=l();s.mockResolvedValue([i]);const e=vi.fn(),n=vi.fn();let o=[];r.listenToAvailableDevices().subscribe({next:c=>{o=c},complete:e,error:n}),await m();const t=o[0]?.id;expect(t).toBeTruthy(),expect(o[0]?.deviceModel?.id).toBe(u.NANO_X),await r.connect({deviceId:o[0].id,onDisconnect:vi.fn()}),await m(),s.mockResolvedValue([]),h(i),await m(),expect(o).toEqual([]),s.mockResolvedValue([i]),b(i),await m(),expect(o).toEqual([expect.objectContaining({deviceModel:expect.objectContaining({id:u.NANO_X})})]),expect(o[0]?.id).toBeTruthy(),expect(o[0]?.id).toBe(t)})})})});
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
2
  //# sourceMappingURL=WebHidTransport.test.js.map