@ledgerhq/device-transport-kit-web-hid 0.0.0-rnble-transport-20250219100517 → 0.0.0-rnble-transport-20250225105039
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/esm/api/transport/WebHidTransport.js +1 -1
- package/lib/esm/api/transport/WebHidTransport.js.map +2 -2
- package/lib/esm/api/transport/WebHidTransport.test.js +1 -1
- package/lib/esm/api/transport/WebHidTransport.test.js.map +2 -2
- package/lib/types/api/transport/WebHidTransport.d.ts +1 -1
- package/lib/types/api/transport/WebHidTransport.d.ts.map +1 -1
- package/lib/types/tsconfig.prod.tsbuildinfo +1 -1
- package/package.json +4 -4
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{DeviceNotRecognizedError as
|
|
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};
|
|
2
2
|
//# sourceMappingURL=WebHidTransport.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/api/transport/WebHidTransport.ts"],
|
|
4
|
-
"sourcesContent": ["import {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n type ConnectError,\n type ConnectionType,\n type DeviceId,\n type DeviceModelDataSource,\n DeviceNotRecognizedError,\n type DisconnectHandler,\n type DmkError,\n FramerUtils,\n LEDGER_VENDOR_ID,\n type LoggerPublisherService,\n NoAccessibleDeviceError,\n OpeningConnectionError,\n type Transport,\n TransportConnectedDevice,\n type TransportDeviceModel,\n type TransportDiscoveredDevice,\n type TransportFactory,\n type TransportIdentifier,\n UnknownDeviceError,\n} from \"@ledgerhq/device-management-kit\";\nimport * as Sentry from \"@sentry/minimal\";\nimport { type Either, EitherAsync, Left, Maybe, Right } from \"purify-ts\";\nimport { BehaviorSubject, from, map, type Observable, switchMap } from \"rxjs\";\nimport { v4 as uuid } from \"uuid\";\n\nimport { FRAME_SIZE } from \"@api/data/WebHidConfig\";\nimport { WebHidTransportNotSupportedError } from \"@api/model/Errors\";\nimport { WebHidDeviceConnection } from \"@api/transport/WebHidDeviceConnection\";\n\ntype PromptDeviceAccessError =\n | NoAccessibleDeviceError\n | WebHidTransportNotSupportedError;\n\ntype WebHidTransportDiscoveredDevice = TransportDiscoveredDevice & {\n hidDevice: HIDDevice;\n};\n\nexport const webHidIdentifier: TransportIdentifier = \"WEB-HID\";\n\nexport class WebHidTransport implements Transport {\n /** List of HID devices that have been discovered */\n private _transportDiscoveredDevices: BehaviorSubject<\n Array<WebHidTransportDiscoveredDevice>\n > = new BehaviorSubject<Array<WebHidTransportDiscoveredDevice>>([]);\n\n /** Map of *connected* HIDDevice to their WebHidDeviceConnection */\n private _deviceConnectionsByHidDevice: Map<\n HIDDevice,\n WebHidDeviceConnection\n > = new Map();\n\n /**\n * Set of WebHidDeviceConnection for which the HIDDevice has been\n * disconnected, so they are waiting for a reconnection\n */\n private _deviceConnectionsPendingReconnection: Set<WebHidDeviceConnection> =\n new Set();\n\n /** AbortController to stop listening to HID connection events */\n private _connectionListenersAbortController: AbortController =\n new AbortController();\n private _logger: LoggerPublisherService;\n private readonly connectionType: ConnectionType = \"USB\";\n private readonly identifier: TransportIdentifier = webHidIdentifier;\n\n constructor(\n private readonly _deviceModelDataSource: DeviceModelDataSource,\n private readonly _loggerServiceFactory: (\n tag: string,\n ) => LoggerPublisherService,\n private readonly _apduSenderFactory: ApduSenderServiceFactory,\n private readonly _apduReceiverFactory: ApduReceiverServiceFactory,\n ) {\n this._logger = _loggerServiceFactory(\"WebWebHidTransport\");\n\n this.startListeningToConnectionEvents();\n }\n\n /**\n * Get the WebHID API if supported or error\n * @returns `Either<WebHidTransportNotSupportedError, HID>`\n */\n private get hidApi(): Either<WebHidTransportNotSupportedError, HID> {\n if (this.isSupported()) {\n return Right(navigator.hid);\n }\n\n return Left(new WebHidTransportNotSupportedError(\"WebHID not supported\"));\n }\n\n isSupported() {\n try {\n const result = !!navigator?.hid;\n this._logger.debug(`isSupported: ${result}`);\n return result;\n } catch (error) {\n this._logger.error(`isSupported: error`, { data: { error } });\n return false;\n }\n }\n\n getIdentifier(): TransportIdentifier {\n return this.identifier;\n }\n\n /**\n * Wrapper around `navigator.hid.getDevices()`.\n * It will return the list of plugged in HID devices to which the user has\n * previously granted access through `navigator.hid.requestDevice()`.\n */\n private async getDevices(): Promise<Either<DmkError, HIDDevice[]>> {\n return EitherAsync.liftEither(this.hidApi).map(async (hidApi) => {\n try {\n const allDevices = await hidApi.getDevices();\n\n return allDevices.filter(\n (hidDevice) => hidDevice.vendorId === LEDGER_VENDOR_ID,\n );\n } catch (error) {\n const deviceError = new NoAccessibleDeviceError(error);\n this._logger.error(`getDevices: error getting devices`, {\n data: { error },\n });\n Sentry.captureException(deviceError);\n throw deviceError;\n }\n });\n }\n\n /**\n * Map a HIDDevice to an TransportDiscoveredDevice, either by creating a new one or returning an existing one\n */\n private mapHIDDeviceToTransportDiscoveredDevice(\n hidDevice: HIDDevice,\n ): WebHidTransportDiscoveredDevice {\n const existingDiscoveredDevice = this._transportDiscoveredDevices\n .getValue()\n .find((internalDevice) => internalDevice.hidDevice === hidDevice);\n\n if (existingDiscoveredDevice) {\n return existingDiscoveredDevice;\n }\n\n const existingDeviceConnection =\n this._deviceConnectionsByHidDevice.get(hidDevice);\n\n const maybeDeviceModel = this.getDeviceModel(hidDevice);\n return maybeDeviceModel.caseOf({\n Just: (deviceModel) => {\n const id = existingDeviceConnection?.deviceId ?? uuid();\n\n const discoveredDevice = {\n id,\n deviceModel,\n hidDevice,\n transport: this.identifier,\n };\n\n this._logger.debug(\n `Discovered device ${id} ${discoveredDevice.deviceModel.productName}`,\n );\n\n return discoveredDevice;\n },\n Nothing: () => {\n // [ASK] Or we just ignore the not recognized device ? And log them\n this._logger.warn(\n `Device not recognized: hidDevice.productId: 0x${hidDevice.productId.toString(16)}`,\n );\n throw new DeviceNotRecognizedError(\n `Device not recognized: hidDevice.productId: 0x${hidDevice.productId.toString(16)}`,\n );\n },\n });\n }\n\n /**\n * Listen to known devices (devices to which the user has granted access)\n */\n public listenToKnownDevices(): Observable<TransportDiscoveredDevice[]> {\n this.updateTransportDiscoveredDevices();\n return this._transportDiscoveredDevices.pipe(\n map((devices) => devices.map(({ hidDevice, ...device }) => device)),\n );\n }\n\n private async updateTransportDiscoveredDevices(): Promise<void> {\n const eitherDevices = await this.getDevices();\n\n eitherDevices.caseOf({\n Left: (error) => {\n this._logger.error(\"Error while getting accessible device\", {\n data: { error },\n });\n Sentry.captureException(error);\n },\n Right: (hidDevices) => {\n this._transportDiscoveredDevices.next(\n hidDevices.map((hidDevice) =>\n this.mapHIDDeviceToTransportDiscoveredDevice(hidDevice),\n ),\n );\n },\n });\n }\n\n /**\n * Wrapper around navigator.hid.requestDevice()\n * In a browser, it will show a native dialog to select a HID device.\n */\n private async promptDeviceAccess(): Promise<\n Either<PromptDeviceAccessError, HIDDevice[]>\n > {\n return EitherAsync.liftEither(this.hidApi)\n .map(async (hidApi) => {\n // `requestDevice` returns an array. but normally the user can select only one device at a time.\n let hidDevices: HIDDevice[] = [];\n\n try {\n hidDevices = await hidApi.requestDevice({\n filters: [{ vendorId: LEDGER_VENDOR_ID }],\n });\n await this.updateTransportDiscoveredDevices();\n } catch (error) {\n const deviceError = new NoAccessibleDeviceError(error);\n this._logger.error(`promptDeviceAccess: error requesting device`, {\n data: { error },\n });\n Sentry.captureException(deviceError);\n throw deviceError;\n }\n\n this._logger.debug(\n `promptDeviceAccess: hidDevices len ${hidDevices.length}`,\n );\n\n // Granted access to 0 device (by clicking on cancel for ex) results in an error\n if (hidDevices.length === 0) {\n this._logger.warn(\"No device was selected\");\n throw new NoAccessibleDeviceError(\"No selected device\");\n }\n\n const discoveredHidDevices: HIDDevice[] = [];\n\n for (const hidDevice of hidDevices) {\n discoveredHidDevices.push(hidDevice);\n\n this._logger.debug(`promptDeviceAccess: selected device`, {\n data: { hidDevice },\n });\n }\n\n return discoveredHidDevices;\n })\n .run();\n }\n\n startDiscovering(): Observable<TransportDiscoveredDevice> {\n this._logger.debug(\"startDiscovering\");\n\n return from(this.promptDeviceAccess()).pipe(\n switchMap((either) => {\n return either.caseOf({\n Left: (error) => {\n this._logger.error(\"Error while getting accessible device\", {\n data: { error },\n });\n Sentry.captureException(error);\n throw error;\n },\n Right: (hidDevices) => {\n this._logger.info(`Got access to ${hidDevices.length} HID devices`);\n\n const discoveredDevices = hidDevices.map((hidDevice) => {\n return this.mapHIDDeviceToTransportDiscoveredDevice(hidDevice);\n });\n\n return from(discoveredDevices);\n },\n });\n }),\n );\n }\n\n stopDiscovering(): void {\n /**\n * This does nothing because the startDiscovering method is just a\n * promise wrapped into an observable. So there is no need to stop it.\n */\n }\n\n private startListeningToConnectionEvents(): void {\n this._logger.debug(\"startListeningToConnectionEvents\");\n\n this.hidApi.map((hidApi) => {\n hidApi.addEventListener(\n \"connect\",\n (event) => this.handleDeviceConnectionEvent(event),\n { signal: this._connectionListenersAbortController.signal },\n );\n\n hidApi.addEventListener(\n \"disconnect\",\n (event) => this.handleDeviceDisconnectionEvent(event),\n { signal: this._connectionListenersAbortController.signal },\n );\n });\n }\n\n private stopListeningToConnectionEvents(): void {\n this._logger.debug(\"stopListeningToConnectionEvents\");\n this._connectionListenersAbortController.abort();\n }\n\n /**\n * Connect to a HID USB device and update the internal state of the associated device\n */\n async connect({\n deviceId,\n onDisconnect,\n }: {\n deviceId: DeviceId;\n onDisconnect: DisconnectHandler;\n }): Promise<Either<ConnectError, TransportConnectedDevice>> {\n this._logger.debug(\"connect\", { data: { deviceId } });\n\n const matchingInternalDevice = this._transportDiscoveredDevices\n .getValue()\n .find((internalDevice) => internalDevice.id === deviceId);\n\n if (!matchingInternalDevice) {\n this._logger.error(`Unknown device ${deviceId}`);\n return Left(new UnknownDeviceError(`Unknown device ${deviceId}`));\n }\n\n try {\n if (\n this._deviceConnectionsByHidDevice.get(matchingInternalDevice.hidDevice)\n ) {\n throw new Error(\"Device already opened\");\n }\n await matchingInternalDevice.hidDevice.open();\n } catch (error) {\n if (error instanceof DOMException && error.name === \"InvalidStateError\") {\n this._logger.debug(`Device ${deviceId} is already opened`);\n } else {\n const connectionError = new OpeningConnectionError(error);\n this._logger.debug(`Error while opening device: ${deviceId}`, {\n data: { error },\n });\n Sentry.captureException(connectionError);\n return Left(connectionError);\n }\n }\n\n const { deviceModel } = matchingInternalDevice;\n\n const channel = Maybe.of(\n FramerUtils.numberToByteArray(Math.floor(Math.random() * 0xffff), 2),\n );\n const deviceConnection = new WebHidDeviceConnection(\n {\n device: matchingInternalDevice.hidDevice,\n deviceId,\n apduSender: this._apduSenderFactory({\n frameSize: FRAME_SIZE,\n channel,\n padding: true,\n }),\n apduReceiver: this._apduReceiverFactory({ channel }),\n onConnectionTerminated: () => {\n onDisconnect(deviceId);\n this._deviceConnectionsPendingReconnection.delete(deviceConnection);\n this._deviceConnectionsByHidDevice.delete(\n matchingInternalDevice.hidDevice,\n );\n deviceConnection.device.close();\n },\n },\n this._loggerServiceFactory,\n );\n\n this._deviceConnectionsByHidDevice.set(\n matchingInternalDevice.hidDevice,\n deviceConnection,\n );\n\n const connectedDevice = new TransportConnectedDevice({\n sendApdu: (apdu, triggersDisconnection) =>\n deviceConnection.sendApdu(apdu, triggersDisconnection),\n deviceModel,\n id: deviceId,\n type: this.connectionType,\n transport: this.identifier,\n });\n\n return Right(connectedDevice);\n }\n\n private getDeviceModel(hidDevice: HIDDevice): Maybe<TransportDeviceModel> {\n const { productId } = hidDevice;\n const matchingModel = this._deviceModelDataSource.getAllDeviceModels().find(\n (deviceModel) =>\n // outside of bootloader mode, the value that we need to identify a device model is the first byte of the actual hidDevice.productId\n deviceModel.usbProductId === productId >> 8 ||\n deviceModel.bootloaderUsbProductId === productId,\n );\n return matchingModel ? Maybe.of(matchingModel) : Maybe.zero();\n }\n\n private getHidUsbProductId(hidDevice: HIDDevice): number {\n return this.getDeviceModel(hidDevice).caseOf({\n Just: (deviceModel) => deviceModel.usbProductId,\n Nothing: () => hidDevice.productId >> 8,\n });\n }\n\n /**\n * Disconnect from a HID USB device\n */\n async disconnect(params: {\n connectedDevice: TransportConnectedDevice;\n }): Promise<Either<DmkError, void>> {\n this._logger.debug(\"disconnect\", { data: { connectedDevice: params } });\n\n const matchingDeviceConnection = Array.from(\n this._deviceConnectionsByHidDevice.values(),\n ).find(\n (deviceConnection) =>\n deviceConnection.deviceId === params.connectedDevice.id,\n );\n\n if (!matchingDeviceConnection) {\n this._logger.error(\"No matching device connection found\", {\n data: { connectedDevice: params },\n });\n return Promise.resolve(\n Left(\n new UnknownDeviceError(`Unknown device ${params.connectedDevice.id}`),\n ),\n );\n }\n\n matchingDeviceConnection.disconnect();\n return Promise.resolve(Right(undefined));\n }\n\n /**\n * Type guard to check if the event is a HID connection event\n * @param event\n * @private\n */\n private isHIDConnectionEvent(event: Event): event is HIDConnectionEvent {\n return (\n \"device\" in event &&\n typeof event.device === \"object\" &&\n event.device !== null &&\n \"productId\" in event.device &&\n typeof event.device.productId === \"number\"\n );\n }\n\n /**\n * Handle the disconnection event of a HID device\n * @param event\n */\n private async handleDeviceDisconnectionEvent(event: Event) {\n if (!this.isHIDConnectionEvent(event)) {\n this._logger.error(\"Invalid event\", { data: { event } });\n return;\n }\n\n this._logger.info(\"[handleDeviceDisconnectionEvent] Device disconnected\", {\n data: { event },\n });\n\n this.updateTransportDiscoveredDevices();\n\n try {\n await event.device.close();\n } catch (error) {\n this._logger.error(\"Error while closing device \", {\n data: { event, error },\n });\n }\n\n const matchingDeviceConnection = this._deviceConnectionsByHidDevice.get(\n event.device,\n );\n\n if (matchingDeviceConnection) {\n matchingDeviceConnection.lostConnection();\n this._deviceConnectionsPendingReconnection.add(matchingDeviceConnection);\n this._deviceConnectionsByHidDevice.delete(event.device);\n }\n }\n\n private handleDeviceReconnection(\n deviceConnection: WebHidDeviceConnection,\n hidDevice: HIDDevice,\n ) {\n this._deviceConnectionsPendingReconnection.delete(deviceConnection);\n this._deviceConnectionsByHidDevice.set(hidDevice, deviceConnection);\n\n try {\n deviceConnection.reconnectHidDevice(hidDevice);\n } catch (error) {\n this._logger.error(\"Error while reconnecting to device\", {\n data: { event, error },\n });\n deviceConnection.disconnect();\n }\n }\n\n /**\n * Handle the connection event of a HID device\n * @param event\n */\n private handleDeviceConnectionEvent(event: Event) {\n if (!this.isHIDConnectionEvent(event)) {\n this._logger.error(\"Invalid event\", { data: { event } });\n return;\n }\n\n this._logger.info(\"[handleDeviceConnectionEvent] Device connected\", {\n data: { event },\n });\n\n const matchingDeviceConnection = Array.from(\n this._deviceConnectionsPendingReconnection,\n ).find(\n (deviceConnection) =>\n this.getHidUsbProductId(deviceConnection.device) ===\n this.getHidUsbProductId(event.device),\n );\n\n if (matchingDeviceConnection) {\n this.handleDeviceReconnection(matchingDeviceConnection, event.device);\n }\n\n /**\n * Note: we do this after handling the reconnection to allow the newly\n * discovered device to keep the same DeviceId as the previous one in case\n * of a reconnection.\n */\n this.updateTransportDiscoveredDevices();\n }\n\n public destroy() {\n this.stopListeningToConnectionEvents();\n this._deviceConnectionsByHidDevice.forEach((connection) => {\n connection.disconnect();\n });\n this._deviceConnectionsPendingReconnection.clear();\n }\n}\n\nexport const webHidTransportFactory: TransportFactory = ({\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n}) =>\n new WebHidTransport(\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n );\n"],
|
|
5
|
-
"mappings": "AAAA,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,C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C,CACH,CAKO,
|
|
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,CAC1E,CAEA,aAAc,CACZ,GAAI,CACF,MAAMQ,EAAS,CAAC,CAAC,WAAW,IAC5B,YAAK,QAAQ,MAAM,gBAAgBA,CAAM,EAAE,EACpCA,CACT,OAASC,EAAO,CACd,YAAK,Q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M6B,EAA2B,KAAK,8BAA8B,IAClEb,EAAM,MACR,EAEIa,IACFA,EAAyB,eAAe,EACxC,KAAK,sCAAsC,IAAIA,CAAwB,EACvE,KAAK,8BAA8B,OAAOb,EAAM,MAAM,EAE1D,CAEQ,yBACNM,EACApB,EACA,CACA,KAAK,sCAAsC,OAAOoB,CAAgB,EAClE,KAAK,8BAA8B,IAAIpB,EAAWoB,CAAgB,EAElE,GAAI,CACFA,EAAiB,mBAAmBpB,CAAS,CAC/C,OAASF,EAAO,CACd,KAAK,QAAQ,MAAM,qCAAsC,CACvD,KAAM,CAAE,MAAO,MAAAA,CAAM,CACvB,CAAC,EACDsB,EAAiB,WAAW,CAC9B,CACF,CAMQ,4BAA4BN,EAAc,CAChD,GAAI,CAAC,KAAK,qBAAqBA,CAAK,EAAG,CACrC,KAAK,QAAQ,MAAM,gBAAiB,CAAE,KAAM,CAAE,MAAAA,CAAM,CAAE,CAAC,EACvD,MACF,CAEA,KAAK,QAAQ,KAAK,iDAAkD,CAClE,KAAM,CAAE,MAAAA,CAAM,CAChB,CAAC,EAED,MAAMa,EAA2B,MAAM,KACrC,KAAK,qCACP,EAAE,KACCP,GACC,KAAK,mBAAmBA,EAAiB,MAAM,IAC/C,KAAK,mBAAmBN,EAAM,MAAM,CACxC,EAEIa,GACF,KAAK,yBAAyBA,EAA0Bb,EAAM,MAAM,EAQtE,KAAK,iCAAiC,CACxC,CAEO,SAAU,CACf,KAAK,gCAAgC,EACrC,KAAK,8BAA8B,QAASc,GAAe,CACzDA,EAAW,WAAW,CACxB,CAAC,EACD,KAAK,sCAAsC,MAAM,CACnD,CACF,CAEO,MAAMC,EAA2C,CAAC,CACvD,sBAAAC,EACA,qBAAAC,EACA,yBAAAC,EACA,2BAAAC,CACF,IACE,IAAIzC,EACFsC,EACAC,EACAC,EACAC,CACF",
|
|
6
6
|
"names": ["DeviceNotRecognizedError", "FramerUtils", "LEDGER_VENDOR_ID", "NoAccessibleDeviceError", "OpeningConnectionError", "TransportConnectedDevice", "UnknownDeviceError", "Sentry", "EitherAsync", "Left", "Maybe", "Right", "BehaviorSubject", "from", "map", "switchMap", "uuid", "FRAME_SIZE", "WebHidTransportNotSupportedError", "WebHidDeviceConnection", "webHidIdentifier", "WebHidTransport", "_deviceModelDataSource", "_loggerServiceFactory", "_apduSenderFactory", "_apduReceiverFactory", "result", "error", "hidApi", "hidDevice", "deviceError", "existingDiscoveredDevice", "internalDevice", "existingDeviceConnection", "deviceModel", "id", "discoveredDevice", "devices", "device", "hidDevices", "discoveredHidDevices", "either", "discoveredDevices", "event", "deviceId", "onDisconnect", "matchingInternalDevice", "connectionError", "channel", "deviceConnection", "connectedDevice", "apdu", "triggersDisconnection", "productId", "matchingModel", "params", "matchingDeviceConnection", "connection", "webHidTransportFactory", "deviceModelDataSource", "loggerServiceFactory", "apduSenderServiceFactory", "apduReceiverServiceFactory"]
|
|
7
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 w,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 V}from"./WebHidTransport";class M{constructor(D,f){this.subscribers=D,this.tag=f}subscribers=[];tag="";error=vi.fn();warn=vi.fn();info=vi.fn();debug=vi.fn()}const x=new R,A=new M([],"web-usb-hid"),a=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 V(x,()=>A,f,D)}beforeEach(()=>{E(),vi.useFakeTimers()}),afterEach(()=>{vi.restoreAllMocks()});const v=(s,d)=>{r.startDiscovering().subscribe({next:s,error:d})};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,d)=>{v(()=>{d("Should not emit any value")},g=>{expect(g).toBeInstanceOf(O),s()})}))}),describe("When WebHID API is supported",()=>{const s=vi.fn(),d=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:d,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",()=>{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,()=>new Promise((n,o)=>{d.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)=>{d.mockResolvedValueOnce([a,{...a,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)=>{d.mockResolvedValueOnce([{...a,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";d.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)=>{d.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()=>{d.mockResolvedValue([a]),s.mockResolvedValue([a]);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(w(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(w(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={...a,open:()=>{throw new Error(n)}};d.mockResolvedValueOnce([o]),s.mockResolvedValue([o]),v(t=>{r.connect({deviceId:t.id,onDisconnect:vi.fn()}).then(c=>{expect(c).toStrictEqual(w(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={...a,opened:!1,open:()=>(n.opened=!0,Promise.resolve())};d.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)=>{d.mockResolvedValueOnce([a]),s.mockResolvedValue([a]),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(w(new k(`Unknown device ${i.id}`)))}),it("should disconnect if the device is connected",()=>new Promise((i,e)=>{d.mockResolvedValueOnce([a]),s.mockResolvedValue([a]),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();d.mockResolvedValueOnce([a]),s.mockResolvedValue([a]),r.startDiscovering().subscribe({next:o=>{const t={sendApdu:vi.fn(),device:a,deviceId:o.id,disconnect:n,lostConnection:vi.fn().mockImplementation(()=>{setTimeout(()=>{t.disconnect()},p)})};r.connect({deviceId:o.id,onDisconnect:n}).then(async()=>{h(a),expect(a.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();d.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();d.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:a},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("listenToKnownDevices",()=>{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.listenToKnownDevices().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:x.getDeviceModel({id:u.NANO_X}).usbProductId<<8}),e=l({productId:x.getDeviceModel({id:u.STAX}).usbProductId<<8});s.mockResolvedValue([i]);const n=vi.fn(),o=vi.fn();let t=[];r.listenToKnownDevices().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.listenToKnownDevices().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 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)})})})});
|
|
2
2
|
//# sourceMappingURL=WebHidTransport.test.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/api/transport/WebHidTransport.test.ts"],
|
|
4
|
-
"sourcesContent": ["/* eslint @typescript-eslint/consistent-type-imports: off */\nimport {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n connectedDeviceStubBuilder,\n type DeviceModel,\n DeviceModelId,\n DeviceNotRecognizedError,\n type LoggerPublisherService,\n type LoggerSubscriberService,\n NoAccessibleDeviceError,\n OpeningConnectionError,\n StaticDeviceModelDataSource,\n type TransportDeviceModel,\n type TransportDiscoveredDevice,\n UnknownDeviceError,\n} from \"@ledgerhq/device-management-kit\";\nimport { Left, Right } from \"purify-ts\";\nimport { Subject } from \"rxjs\";\n\nimport { RECONNECT_DEVICE_TIMEOUT } from \"@api/data/WebHidConfig\";\nimport { WebHidTransportNotSupportedError } from \"@api/model/Errors\";\nimport { hidDeviceStubBuilder } from \"@api/model/HIDDevice.stub\";\n\nimport { WebHidTransport } from \"./WebHidTransport\";\n\nclass LoggerPublisherServiceStub implements LoggerPublisherService {\n constructor(subscribers: LoggerSubscriberService[], tag: string) {\n this.subscribers = subscribers;\n this.tag = tag;\n }\n subscribers: LoggerSubscriberService[] = [];\n tag: string = \"\";\n error = vi.fn();\n warn = vi.fn();\n info = vi.fn();\n debug = vi.fn();\n}\n\n// Our StaticDeviceModelDataSource can directly be used in our unit tests\nconst usbDeviceModelDataSource = new StaticDeviceModelDataSource();\nconst logger = new LoggerPublisherServiceStub([], \"web-usb-hid\");\n\nconst stubDevice: HIDDevice = hidDeviceStubBuilder();\n\n/**\n * Flushes all pending promises\n */\nconst flushPromises = async () => {\n const timers = await vi.importActual<typeof import(\"timers\")>(\"timers\");\n return new Promise(timers.setImmediate);\n};\n\ndescribe(\"WebHidTransport\", () => {\n let transport: WebHidTransport;\n let apduReceiverServiceFactoryStub: ApduReceiverServiceFactory;\n let apduSenderServiceFactoryStub: ApduSenderServiceFactory;\n\n function initializeTransport() {\n apduReceiverServiceFactoryStub = vi.fn();\n apduSenderServiceFactoryStub = vi.fn();\n transport = new WebHidTransport(\n usbDeviceModelDataSource,\n () => logger,\n apduSenderServiceFactoryStub,\n apduReceiverServiceFactoryStub,\n );\n }\n\n beforeEach(() => {\n initializeTransport();\n vi.useFakeTimers();\n });\n\n afterEach(() => {\n vi.restoreAllMocks();\n });\n\n const discoverDevice = (\n onSuccess: (discoveredDevice: TransportDiscoveredDevice) => void,\n onError?: (error: unknown) => void,\n ) => {\n transport.startDiscovering().subscribe({\n next: onSuccess,\n error: onError,\n });\n };\n\n describe(\"When WebHID API is not supported\", () => {\n it(\"should not support the transport\", () => {\n expect(transport.isSupported()).toBe(false);\n });\n\n it(\"should emit a startDiscovering error\", () =>\n new Promise<void>((resolve, reject) => {\n discoverDevice(\n () => {\n reject(\"Should not emit any value\");\n },\n (error) => {\n expect(error).toBeInstanceOf(WebHidTransportNotSupportedError);\n resolve();\n },\n );\n }));\n });\n\n describe(\"When WebHID API is supported\", () => {\n const mockedGetDevices = vi.fn();\n const mockedRequestDevice = vi.fn();\n\n const connectionEventsSubject = new Subject<HIDConnectionEvent>();\n const disconnectionEventsSubject = new Subject<HIDConnectionEvent>();\n\n function emitHIDConnectionEvent(device: HIDDevice) {\n connectionEventsSubject.next({\n device,\n } as HIDConnectionEvent);\n }\n\n function emitHIDDisconnectionEvent(device: HIDDevice) {\n disconnectionEventsSubject.next({\n device,\n } as HIDConnectionEvent);\n }\n\n beforeEach(() => {\n global.navigator = {\n hid: {\n getDevices: mockedGetDevices,\n requestDevice: mockedRequestDevice,\n addEventListener: (\n eventName: string,\n callback: (event: HIDConnectionEvent) => void,\n ) => {\n if (eventName === \"disconnect\") {\n disconnectionEventsSubject.subscribe(callback);\n } else if (eventName === \"connect\") {\n connectionEventsSubject.subscribe(callback);\n }\n },\n },\n } as unknown as Navigator;\n initializeTransport();\n });\n\n afterEach(() => {\n vi.clearAllMocks();\n global.navigator = undefined as unknown as Navigator;\n });\n\n it(\"should support the transport\", () => {\n expect(transport.isSupported()).toBe(true);\n });\n\n describe(\"startDiscovering\", () => {\n const testCases = usbDeviceModelDataSource\n .getAllDeviceModels()\n .flatMap((deviceModel) => {\n return [\n {\n testTitle: `should emit device if user grants access through hid.requestDevice (${deviceModel.productName})`,\n hidDevice: hidDeviceStubBuilder({\n productId: deviceModel.usbProductId << 8,\n productName: deviceModel.productName,\n }),\n expectedDeviceModel: deviceModel,\n },\n {\n testTitle: `should emit device if user grants access through hid.requestDevice (${deviceModel.productName}, bootloader)`,\n hidDevice: hidDeviceStubBuilder({\n productId: deviceModel.bootloaderUsbProductId,\n productName: deviceModel.productName,\n }),\n expectedDeviceModel: deviceModel,\n },\n ];\n });\n\n testCases.forEach((testCase) => {\n it(\n testCase.testTitle,\n () =>\n new Promise<void>((resolve, reject) => {\n mockedRequestDevice.mockResolvedValueOnce([testCase.hidDevice]);\n\n discoverDevice(\n (discoveredDevice) => {\n try {\n expect(discoveredDevice).toEqual(\n expect.objectContaining({\n deviceModel: testCase.expectedDeviceModel,\n }),\n );\n\n resolve();\n } catch (expectError) {\n reject(expectError as Error);\n }\n },\n (error) => {\n reject(error as Error);\n },\n );\n }),\n );\n });\n\n // It does not seem possible for a user to select several devices on the browser popup.\n // But if it was possible, we should emit them\n it(\"should emit devices if new grant accesses\", () =>\n new Promise<void>((resolve, reject) => {\n mockedRequestDevice.mockResolvedValueOnce([\n stubDevice,\n {\n ...stubDevice,\n productId: 0x5011,\n productName: \"Ledger Nano S Plus\",\n },\n ]);\n\n let count = 0;\n discoverDevice(\n (discoveredDevice) => {\n try {\n switch (count) {\n case 0:\n expect(discoveredDevice).toEqual(\n expect.objectContaining({\n deviceModel: expect.objectContaining({\n id: DeviceModelId.NANO_X,\n productName: \"Ledger Nano X\",\n usbProductId: 0x40,\n }) as DeviceModel,\n }),\n );\n break;\n case 1:\n expect(discoveredDevice).toEqual(\n expect.objectContaining({\n deviceModel: expect.objectContaining({\n id: DeviceModelId.NANO_SP,\n productName: \"Ledger Nano S Plus\",\n usbProductId: 0x50,\n }) as DeviceModel,\n }),\n );\n\n resolve();\n break;\n }\n\n count++;\n } catch (expectError) {\n reject(expectError as Error);\n }\n },\n (error) => {\n reject(error as Error);\n },\n );\n }));\n\n it(\"should throw DeviceNotRecognizedError if the device is not recognized\", () =>\n new Promise<void>((resolve, reject) => {\n mockedRequestDevice.mockResolvedValueOnce([\n {\n ...stubDevice,\n productId: 0x4242,\n },\n ]);\n\n discoverDevice(\n () => {\n reject(\"should not return a device\");\n },\n (error) => {\n expect(error).toBeInstanceOf(DeviceNotRecognizedError);\n resolve();\n },\n );\n }));\n\n it(\"should emit an error if the request device is in error\", () =>\n new Promise<void>((resolve, reject) => {\n const message = \"request device error\";\n mockedRequestDevice.mockImplementationOnce(() => {\n throw new Error(message);\n });\n\n discoverDevice(\n () => {\n reject(\"should not return a device\");\n },\n (error) => {\n expect(error).toBeInstanceOf(NoAccessibleDeviceError);\n expect(error).toStrictEqual(\n new NoAccessibleDeviceError(new Error(message)),\n );\n resolve();\n },\n );\n }));\n\n // [ASK] Is this the behavior we want when the user does not select any device ?\n it(\"should emit an error if the user did not grant us access to a device (clicking on cancel on the browser popup for ex)\", () =>\n new Promise<void>((resolve, reject) => {\n // When the user does not select any device, the `requestDevice` will return an empty array\n mockedRequestDevice.mockResolvedValueOnce([]);\n\n discoverDevice(\n (discoveredDevice) => {\n reject(\n `Should not emit any value, but emitted ${JSON.stringify(\n discoveredDevice,\n )}`,\n );\n },\n (error) => {\n try {\n expect(error).toBeInstanceOf(NoAccessibleDeviceError);\n resolve();\n } catch (expectError) {\n reject(expectError as Error);\n }\n },\n );\n }));\n\n it(\"should emit the same discoveredDevice object if its discovered twice in a row\", async () => {\n mockedRequestDevice.mockResolvedValue([stubDevice]);\n mockedGetDevices.mockResolvedValue([stubDevice]);\n\n const firstDiscoveredDevice = await new Promise<void>(\n (resolve, reject) => {\n discoverDevice(\n () => resolve(),\n (err) => reject(err),\n );\n },\n );\n const secondDiscoveredDevice = await new Promise<void>(\n (resolve, reject) => {\n discoverDevice(\n () => resolve(),\n (err) => reject(err),\n );\n },\n );\n expect(secondDiscoveredDevice).toBe(firstDiscoveredDevice);\n });\n });\n\n describe(\"destroy\", () => {\n it(\"should stop monitoring connections if the discovery process is halted\", () => {\n const abortSpy = vi.spyOn(AbortController.prototype, \"abort\");\n\n transport.destroy();\n\n expect(abortSpy).toHaveBeenCalled();\n });\n });\n\n describe(\"connect\", () => {\n it(\"should throw UnknownDeviceError if no internal device\", async () => {\n const connectParams = {\n deviceId: \"fake\",\n onDisconnect: vi.fn(),\n };\n\n const connect = await transport.connect(connectParams);\n\n expect(connect).toStrictEqual(\n Left(new UnknownDeviceError(\"Unknown device fake\")),\n );\n });\n\n it(\"should throw OpeningConnectionError if the device is already opened\", async () => {\n const device = {\n deviceId: \"fake\",\n onDisconnect: vi.fn(),\n };\n\n const connect = await transport.connect(device);\n\n expect(connect).toStrictEqual(\n Left(new UnknownDeviceError(\"Unknown device fake\")),\n );\n });\n\n it(\"should throw OpeningConnectionError if the device cannot be opened\", () =>\n new Promise<void>((resolve, reject) => {\n const message = \"cannot be opened\";\n const mockedDevice = {\n ...stubDevice,\n open: () => {\n throw new Error(message);\n },\n };\n mockedRequestDevice.mockResolvedValueOnce([mockedDevice]);\n mockedGetDevices.mockResolvedValue([mockedDevice]);\n\n discoverDevice(\n (discoveredDevice) => {\n transport\n .connect({\n deviceId: discoveredDevice.id,\n onDisconnect: vi.fn(),\n })\n .then((value) => {\n expect(value).toStrictEqual(\n Left(new OpeningConnectionError(new Error(message))),\n );\n resolve();\n })\n .catch((error) => {\n reject(error);\n });\n },\n (error) => {\n reject(error as Error);\n },\n );\n }));\n\n it(\"should return the opened device\", () =>\n new Promise<void>((resolve, reject) => {\n const mockedDevice = {\n ...stubDevice,\n opened: false,\n open: () => {\n mockedDevice.opened = true;\n return Promise.resolve();\n },\n };\n\n mockedRequestDevice.mockResolvedValue([mockedDevice]);\n mockedGetDevices.mockResolvedValue([mockedDevice]);\n\n discoverDevice(\n (discoveredDevice) => {\n transport\n .connect({\n deviceId: discoveredDevice.id,\n onDisconnect: vi.fn(),\n })\n .then((connectedDevice) => {\n connectedDevice\n .ifRight((device) => {\n expect(device).toEqual(\n expect.objectContaining({ id: discoveredDevice.id }),\n );\n resolve();\n })\n .ifLeft(() => {\n reject(connectedDevice);\n });\n })\n .catch((error) => {\n reject(error);\n });\n },\n (error) => {\n reject(error as Error);\n },\n );\n }));\n\n it(\"should return a device if available\", () =>\n new Promise<void>((resolve, reject) => {\n mockedRequestDevice.mockResolvedValueOnce([stubDevice]);\n mockedGetDevices.mockResolvedValue([stubDevice]);\n\n discoverDevice(\n (discoveredDevice) => {\n transport\n .connect({\n deviceId: discoveredDevice.id,\n onDisconnect: vi.fn(),\n })\n .then((connectedDevice) => {\n connectedDevice\n .ifRight((device) => {\n expect(device).toEqual(\n expect.objectContaining({ id: discoveredDevice.id }),\n );\n resolve();\n })\n .ifLeft(() => {\n reject(connectedDevice);\n });\n })\n .catch((error) => {\n reject(error);\n });\n },\n (error) => {\n reject(error as Error);\n },\n );\n }));\n });\n\n describe(\"disconnect\", () => {\n it(\"should throw an error if the device is not connected\", async () => {\n // given\n const connectedDevice = connectedDeviceStubBuilder();\n\n // when\n const disconnect = await transport.disconnect({\n connectedDevice,\n });\n\n expect(disconnect).toStrictEqual(\n Left(new UnknownDeviceError(`Unknown device ${connectedDevice.id}`)),\n );\n });\n\n it(\"should disconnect if the device is connected\", () =>\n new Promise<void>((resolve, reject) => {\n mockedRequestDevice.mockResolvedValueOnce([stubDevice]);\n mockedGetDevices.mockResolvedValue([stubDevice]);\n\n discoverDevice(\n (discoveredDevice) => {\n transport\n .connect({\n deviceId: discoveredDevice.id,\n onDisconnect: vi.fn(),\n })\n .then((connectedDevice) => {\n connectedDevice\n .ifRight((device) => {\n transport\n .disconnect({ connectedDevice: device })\n .then((value) => {\n expect(value).toStrictEqual(Right(undefined));\n resolve();\n })\n .catch((error) => {\n reject(error);\n });\n })\n .ifLeft(() => {\n reject(connectedDevice);\n });\n })\n .catch((error) => {\n reject(error);\n });\n },\n (error) => {\n reject(error as Error);\n },\n );\n }));\n\n it(\"should call disconnect handler if a connected device is unplugged\", () =>\n new Promise<void>((resolve, reject) => {\n // given\n const onDisconnect = vi.fn();\n mockedRequestDevice.mockResolvedValueOnce([stubDevice]);\n mockedGetDevices.mockResolvedValue([stubDevice]);\n\n // when\n transport.startDiscovering().subscribe({\n next: (discoveredDevice) => {\n const mock = {\n sendApdu: vi.fn(),\n device: stubDevice,\n deviceId: discoveredDevice.id,\n disconnect: onDisconnect,\n lostConnection: vi.fn().mockImplementation(() => {\n setTimeout(() => {\n mock.disconnect();\n }, RECONNECT_DEVICE_TIMEOUT);\n }),\n };\n\n transport\n .connect({\n deviceId: discoveredDevice.id,\n onDisconnect,\n })\n .then(async () => {\n emitHIDDisconnectionEvent(stubDevice);\n\n expect(stubDevice.close).toHaveBeenCalled();\n await Promise.resolve(); // wait for the next tick so the stubDevice.close promise is resolved\n expect(onDisconnect).not.toHaveBeenCalled();\n vi.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT / 2);\n expect(onDisconnect).not.toHaveBeenCalled();\n vi.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT / 2);\n expect(onDisconnect).toHaveBeenCalled();\n resolve();\n })\n .catch((error) => {\n reject(error);\n });\n },\n });\n }));\n });\n\n describe(\"reconnect\", () => {\n it(\"should stop disconnection if reconnection happen\", () =>\n new Promise<void>((resolve, reject) => {\n // given\n const onDisconnect = vi.fn();\n\n const hidDevice1 = hidDeviceStubBuilder();\n const hidDevice2 = hidDeviceStubBuilder();\n\n mockedRequestDevice.mockResolvedValueOnce([hidDevice1]);\n mockedGetDevices.mockResolvedValue([hidDevice1, hidDevice2]);\n\n discoverDevice(async (discoveredDevice) => {\n const mock = {\n sendApdu: vi.fn(),\n device: hidDevice2,\n deviceId: discoveredDevice.id,\n disconnect: onDisconnect,\n lostConnection: vi.fn().mockImplementation(() => {\n setTimeout(() => {\n mock.disconnect();\n }, RECONNECT_DEVICE_TIMEOUT);\n }),\n };\n\n try {\n await transport.connect({\n deviceId: discoveredDevice.id,\n onDisconnect,\n });\n\n /* Disconnection */\n emitHIDDisconnectionEvent(hidDevice1);\n expect(hidDevice1.close).toHaveBeenCalled();\n await Promise.resolve(); // wait for the next tick so the hidDevice1.close promise is resolved\n\n vi.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT / 3);\n\n /* Reconnection */\n emitHIDConnectionEvent(hidDevice2);\n\n expect(hidDevice2.open).toHaveBeenCalled();\n await Promise.resolve(); // wait for the next tick so the hidDevice2.open promise is resolved\n\n vi.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT);\n expect(onDisconnect).not.toHaveBeenCalled();\n resolve();\n } catch (error) {\n reject(error as Error);\n }\n });\n }));\n\n it(\"should be able to reconnect twice in a row if the device is unplugged and replugged twice\", () =>\n new Promise<void>((resolve, reject) => {\n // given\n const onDisconnect = vi.fn();\n\n const hidDevice1 = hidDeviceStubBuilder();\n const hidDevice2 = hidDeviceStubBuilder();\n const hidDevice3 = hidDeviceStubBuilder();\n\n mockedRequestDevice.mockResolvedValueOnce([hidDevice1]);\n mockedGetDevices.mockResolvedValue([\n hidDevice1,\n hidDevice2,\n hidDevice3,\n ]);\n\n // when\n discoverDevice(async (discoveredDevice) => {\n await transport.connect({\n deviceId: discoveredDevice.id,\n onDisconnect,\n });\n try {\n /* First disconnection */\n emitHIDDisconnectionEvent(hidDevice1);\n expect(hidDevice1.close).toHaveBeenCalled();\n await Promise.resolve(); // wait for the next tick so the hidDevice1.close promise is resolved\n vi.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT / 3);\n\n /* First reconnection */\n emitHIDConnectionEvent(hidDevice2);\n\n expect(hidDevice2.open).toHaveBeenCalled();\n await Promise.resolve(); // wait for the next tick so the hidDevice2.open promise is resolved\n vi.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT);\n expect(onDisconnect).not.toHaveBeenCalled();\n\n /* Second disconnection */\n emitHIDDisconnectionEvent(hidDevice2);\n expect(hidDevice2.close).toHaveBeenCalled();\n await Promise.resolve(); // wait for the next tick so the hidDevice2.close promise is resolved\n vi.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT / 3);\n\n /* Second reconnection */\n emitHIDConnectionEvent(hidDevice3);\n\n expect(hidDevice3.open).toHaveBeenCalled();\n await Promise.resolve(); // wait for the next tick so the hidDevice3.open promise is resolved\n vi.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT);\n expect(onDisconnect).not.toHaveBeenCalled();\n\n resolve();\n } catch (error) {\n reject(error as Error);\n }\n });\n }));\n });\n\n describe(\"Connection event typeguard\", () => {\n it(\"should validate type of an HIDConnectionEvent\", () => {\n // given\n const event = {\n device: stubDevice,\n } as HIDConnectionEvent;\n // when\n // @ts-expect-error trying to access private member\n const result = transport.isHIDConnectionEvent(event);\n // then\n expect(result).toBe(true);\n });\n\n it(\"should not validate type of another event\", () => {\n // given\n const event = new Event(\"disconnect\", {});\n // when\n // @ts-expect-error trying to access private member\n const result = transport.isHIDConnectionEvent(event);\n // then\n expect(result).toBe(false);\n });\n });\n\n describe(\"listenToKnownDevices\", () => {\n it(\"should emit the devices already connected before listening\", async () => {\n // given\n const hidDevice = hidDeviceStubBuilder();\n mockedGetDevices.mockResolvedValue([hidDevice]);\n\n const onComplete = vi.fn();\n const onError = vi.fn();\n\n let observedDevices: TransportDiscoveredDevice[] = [];\n // when\n transport.listenToKnownDevices().subscribe({\n next: (knownDevices) => {\n observedDevices = knownDevices;\n },\n complete: onComplete,\n error: onError,\n });\n\n await flushPromises();\n\n expect(observedDevices).toEqual([\n expect.objectContaining({\n deviceModel: expect.objectContaining({\n id: DeviceModelId.NANO_X,\n }) as TransportDeviceModel,\n }),\n ]);\n expect(onComplete).not.toHaveBeenCalled();\n expect(onError).not.toHaveBeenCalled();\n });\n\n it(\"should emit the new list of devices after connection and disconnection events\", async () => {\n initializeTransport();\n // given\n const hidDevice1 = hidDeviceStubBuilder({\n productId:\n usbDeviceModelDataSource.getDeviceModel({\n id: DeviceModelId.NANO_X,\n }).usbProductId << 8,\n });\n const hidDevice2 = hidDeviceStubBuilder({\n productId:\n usbDeviceModelDataSource.getDeviceModel({ id: DeviceModelId.STAX })\n .usbProductId << 8,\n });\n mockedGetDevices.mockResolvedValue([hidDevice1]);\n\n const onComplete = vi.fn();\n const onError = vi.fn();\n\n let observedDevices: TransportDiscoveredDevice[] = [];\n // when\n transport.listenToKnownDevices().subscribe({\n next: (knownDevices) => {\n observedDevices = knownDevices;\n },\n complete: onComplete,\n error: onError,\n });\n\n await flushPromises();\n\n expect(observedDevices).toEqual([\n expect.objectContaining({\n deviceModel: expect.objectContaining({\n id: DeviceModelId.NANO_X,\n }) as TransportDeviceModel,\n }),\n ]);\n\n // When a new device is connected\n mockedGetDevices.mockResolvedValue([hidDevice1, hidDevice2]);\n emitHIDConnectionEvent(hidDevice2);\n await flushPromises();\n\n expect(observedDevices).toEqual([\n expect.objectContaining({\n deviceModel: expect.objectContaining({\n id: DeviceModelId.NANO_X,\n }) as TransportDeviceModel,\n }),\n expect.objectContaining({\n deviceModel: expect.objectContaining({\n id: DeviceModelId.STAX,\n }) as TransportDeviceModel,\n }),\n ]);\n\n // When a device is disconnected\n mockedGetDevices.mockResolvedValue([hidDevice2]);\n emitHIDDisconnectionEvent(hidDevice1);\n await flushPromises();\n\n expect(observedDevices).toEqual([\n expect.objectContaining({\n deviceModel: expect.objectContaining({\n id: DeviceModelId.STAX,\n }) as TransportDeviceModel,\n }),\n ]);\n\n expect(onComplete).not.toHaveBeenCalled();\n expect(onError).not.toHaveBeenCalled();\n });\n\n it(\"should preserve DeviceId in case the device has been disconnected and reconnected before the timeout\", async () => {\n // given\n const hidDevice = hidDeviceStubBuilder();\n\n mockedGetDevices.mockResolvedValue([hidDevice]);\n\n const onComplete = vi.fn();\n const onError = vi.fn();\n let observedDevices: TransportDiscoveredDevice[] = [];\n // when\n transport.listenToKnownDevices().subscribe({\n next: (knownDevices) => {\n observedDevices = knownDevices;\n },\n complete: onComplete,\n error: onError,\n });\n\n await flushPromises();\n\n const firstObservedDeviceId = observedDevices[0]?.id;\n expect(firstObservedDeviceId).toBeTruthy();\n expect(observedDevices[0]?.deviceModel?.id).toBe(DeviceModelId.NANO_X);\n\n // Start a connection with the device\n await transport.connect({\n deviceId: observedDevices[0]!.id,\n onDisconnect: vi.fn(),\n });\n await flushPromises();\n\n // When the device is disconnected\n mockedGetDevices.mockResolvedValue([]);\n emitHIDDisconnectionEvent(hidDevice);\n await flushPromises();\n\n expect(observedDevices).toEqual([]);\n\n // When the device is reconnected\n mockedGetDevices.mockResolvedValue([hidDevice]);\n emitHIDConnectionEvent(hidDevice);\n await flushPromises();\n\n expect(observedDevices).toEqual([\n expect.objectContaining({\n deviceModel: expect.objectContaining({\n id: DeviceModelId.NANO_X,\n }) as TransportDeviceModel,\n }),\n ]);\n\n expect(observedDevices[0]?.id).toBeTruthy();\n expect(observedDevices[0]?.id).toBe(firstObservedDeviceId);\n });\n });\n });\n});\n"],
|
|
5
|
-
"mappings": "AACA,OAGE,8BAAAA,EAEA,iBAAAC,EACA,4BAAAC,EAGA,2BAAAC,EACA,0BAAAC,EACA,+BAAAC,EAGA,sBAAAC,MACK,kCACP,OAAS,QAAAC,EAAM,SAAAC,MAAa,YAC5B,OAAS,WAAAC,MAAe,OAExB,OAAS,4BAAAC,MAAgC,yBACzC,OAAS,oCAAAC,MAAwC,oBACjD,OAAS,wBAAAC,MAA4B,4BAErC,OAAS,mBAAAC,MAAuB,oBAEhC,MAAMC,CAA6D,CACjE,YAAYC,EAAwCC,EAAa,CAC/D,KAAK,YAAcD,EACnB,KAAK,IAAMC,CACb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,EAAgB,CAAC,GAAG,aAAa,EAAE,EAAE,KAAKjE,EAAc,MAAM,EAGrE,MAAMqB,EAAU,QAAQ,CACtB,SAAU4C,EAAgB,CAAC,EAAG,GAC9B,aAAc,GAAG,GAAG,CACtB,CAAC,EACD,MAAM9C,EAAc,EAGpBY,EAAiB,kBAAkB,CAAC,CAAC,EACrCM,EAA0B0B,CAAS,EACnC,MAAM5C,EAAc,EAEpB,OAAO8C,CAAe,EAAE,QAAQ,CAAC,CAAC,EAGlClC,EAAiB,kBAAkB,CAACgC,CAAS,CAAC,EAC9C5B,EAAuB4B,CAAS,EAChC,MAAM5C,EAAc,EAEpB,OAAO8C,CAAe,EAAE,QAAQ,CAC9B,OAAO,iBAAiB,CACtB,YAAa,OAAO,iBAAiB,CACnC,GAAIjE,EAAc,MACpB,CAAC,CACH,CAAC,CACH,CAAC,EAED,OAAOiE,EAAgB,CAAC,GAAG,EAAE,EAAE,WAAW,EAC1C,OAAOA,EAAgB,CAAC,GAAG,EAAE,EAAE,KAAKE,CAAqB,CAC3D,CAAC,CACH,CAAC,CACH,CAAC,CACH,CAAC",
|
|
4
|
+
"sourcesContent": ["/* eslint @typescript-eslint/consistent-type-imports: off */\nimport {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n connectedDeviceStubBuilder,\n type DeviceModel,\n DeviceModelId,\n DeviceNotRecognizedError,\n type LoggerPublisherService,\n type LoggerSubscriberService,\n NoAccessibleDeviceError,\n OpeningConnectionError,\n StaticDeviceModelDataSource,\n type TransportDeviceModel,\n type TransportDiscoveredDevice,\n UnknownDeviceError,\n} from \"@ledgerhq/device-management-kit\";\nimport { Left, Right } from \"purify-ts\";\nimport { Subject } from \"rxjs\";\n\nimport { RECONNECT_DEVICE_TIMEOUT } from \"@api/data/WebHidConfig\";\nimport { WebHidTransportNotSupportedError } from \"@api/model/Errors\";\nimport { hidDeviceStubBuilder } from \"@api/model/HIDDevice.stub\";\n\nimport { WebHidTransport } from \"./WebHidTransport\";\n\nclass LoggerPublisherServiceStub implements LoggerPublisherService {\n constructor(subscribers: LoggerSubscriberService[], tag: string) {\n this.subscribers = subscribers;\n this.tag = tag;\n }\n subscribers: LoggerSubscriberService[] = [];\n tag: string = \"\";\n error = vi.fn();\n warn = vi.fn();\n info = vi.fn();\n debug = vi.fn();\n}\n\n// Our StaticDeviceModelDataSource can directly be used in our unit tests\nconst usbDeviceModelDataSource = new StaticDeviceModelDataSource();\nconst logger = new LoggerPublisherServiceStub([], \"web-usb-hid\");\n\nconst stubDevice: HIDDevice = hidDeviceStubBuilder();\n\n/**\n * Flushes all pending promises\n */\nconst flushPromises = async () => {\n const timers = await vi.importActual<typeof import(\"timers\")>(\"timers\");\n return new Promise(timers.setImmediate);\n};\n\ndescribe(\"WebHidTransport\", () => {\n let transport: WebHidTransport;\n let apduReceiverServiceFactoryStub: ApduReceiverServiceFactory;\n let apduSenderServiceFactoryStub: ApduSenderServiceFactory;\n\n function initializeTransport() {\n apduReceiverServiceFactoryStub = vi.fn();\n apduSenderServiceFactoryStub = vi.fn();\n transport = new WebHidTransport(\n usbDeviceModelDataSource,\n () => logger,\n apduSenderServiceFactoryStub,\n apduReceiverServiceFactoryStub,\n );\n }\n\n beforeEach(() => {\n initializeTransport();\n vi.useFakeTimers();\n });\n\n afterEach(() => {\n vi.restoreAllMocks();\n });\n\n const discoverDevice = (\n onSuccess: (discoveredDevice: TransportDiscoveredDevice) => void,\n onError?: (error: unknown) => void,\n ) => {\n transport.startDiscovering().subscribe({\n next: onSuccess,\n error: onError,\n });\n };\n\n describe(\"When WebHID API is not supported\", () => {\n it(\"should not support the transport\", () => {\n expect(transport.isSupported()).toBe(false);\n });\n\n it(\"should emit a startDiscovering error\", () =>\n new Promise<void>((resolve, reject) => {\n discoverDevice(\n () => {\n reject(\"Should not emit any value\");\n },\n (error) => {\n expect(error).toBeInstanceOf(WebHidTransportNotSupportedError);\n resolve();\n },\n );\n }));\n });\n\n describe(\"When WebHID API is supported\", () => {\n const mockedGetDevices = vi.fn();\n const mockedRequestDevice = vi.fn();\n\n const connectionEventsSubject = new Subject<HIDConnectionEvent>();\n const disconnectionEventsSubject = new Subject<HIDConnectionEvent>();\n\n function emitHIDConnectionEvent(device: HIDDevice) {\n connectionEventsSubject.next({\n device,\n } as HIDConnectionEvent);\n }\n\n function emitHIDDisconnectionEvent(device: HIDDevice) {\n disconnectionEventsSubject.next({\n device,\n } as HIDConnectionEvent);\n }\n\n beforeEach(() => {\n global.navigator = {\n hid: {\n getDevices: mockedGetDevices,\n requestDevice: mockedRequestDevice,\n addEventListener: (\n eventName: string,\n callback: (event: HIDConnectionEvent) => void,\n ) => {\n if (eventName === \"disconnect\") {\n disconnectionEventsSubject.subscribe(callback);\n } else if (eventName === \"connect\") {\n connectionEventsSubject.subscribe(callback);\n }\n },\n },\n } as unknown as Navigator;\n initializeTransport();\n });\n\n afterEach(() => {\n vi.clearAllMocks();\n global.navigator = undefined as unknown as Navigator;\n });\n\n it(\"should support the transport\", () => {\n expect(transport.isSupported()).toBe(true);\n });\n\n describe(\"startDiscovering\", () => {\n const testCases = usbDeviceModelDataSource\n .getAllDeviceModels()\n .flatMap((deviceModel) => {\n return [\n {\n testTitle: `should emit device if user grants access through hid.requestDevice (${deviceModel.productName})`,\n hidDevice: hidDeviceStubBuilder({\n productId: deviceModel.usbProductId << 8,\n productName: deviceModel.productName,\n }),\n expectedDeviceModel: deviceModel,\n },\n {\n testTitle: `should emit device if user grants access through hid.requestDevice (${deviceModel.productName}, bootloader)`,\n hidDevice: hidDeviceStubBuilder({\n productId: deviceModel.bootloaderUsbProductId,\n productName: deviceModel.productName,\n }),\n expectedDeviceModel: deviceModel,\n },\n ];\n });\n\n testCases.forEach((testCase) => {\n it(\n testCase.testTitle,\n () =>\n new Promise<void>((resolve, reject) => {\n mockedRequestDevice.mockResolvedValueOnce([testCase.hidDevice]);\n\n discoverDevice(\n (discoveredDevice) => {\n try {\n expect(discoveredDevice).toEqual(\n expect.objectContaining({\n deviceModel: testCase.expectedDeviceModel,\n }),\n );\n\n resolve();\n } catch (expectError) {\n reject(expectError as Error);\n }\n },\n (error) => {\n reject(error as Error);\n },\n );\n }),\n );\n });\n\n // It does not seem possible for a user to select several devices on the browser popup.\n // But if it was possible, we should emit them\n it(\"should emit devices if new grant accesses\", () =>\n new Promise<void>((resolve, reject) => {\n mockedRequestDevice.mockResolvedValueOnce([\n stubDevice,\n {\n ...stubDevice,\n productId: 0x5011,\n productName: \"Ledger Nano S Plus\",\n },\n ]);\n\n let count = 0;\n discoverDevice(\n (discoveredDevice) => {\n try {\n switch (count) {\n case 0:\n expect(discoveredDevice).toEqual(\n expect.objectContaining({\n deviceModel: expect.objectContaining({\n id: DeviceModelId.NANO_X,\n productName: \"Ledger Nano X\",\n usbProductId: 0x40,\n }) as DeviceModel,\n }),\n );\n break;\n case 1:\n expect(discoveredDevice).toEqual(\n expect.objectContaining({\n deviceModel: expect.objectContaining({\n id: DeviceModelId.NANO_SP,\n productName: \"Ledger Nano S Plus\",\n usbProductId: 0x50,\n }) as DeviceModel,\n }),\n );\n\n resolve();\n break;\n }\n\n count++;\n } catch (expectError) {\n reject(expectError as Error);\n }\n },\n (error) => {\n reject(error as Error);\n },\n );\n }));\n\n it(\"should throw DeviceNotRecognizedError if the device is not recognized\", () =>\n new Promise<void>((resolve, reject) => {\n mockedRequestDevice.mockResolvedValueOnce([\n {\n ...stubDevice,\n productId: 0x4242,\n },\n ]);\n\n discoverDevice(\n () => {\n reject(\"should not return a device\");\n },\n (error) => {\n expect(error).toBeInstanceOf(DeviceNotRecognizedError);\n resolve();\n },\n );\n }));\n\n it(\"should emit an error if the request device is in error\", () =>\n new Promise<void>((resolve, reject) => {\n const message = \"request device error\";\n mockedRequestDevice.mockImplementationOnce(() => {\n throw new Error(message);\n });\n\n discoverDevice(\n () => {\n reject(\"should not return a device\");\n },\n (error) => {\n expect(error).toBeInstanceOf(NoAccessibleDeviceError);\n expect(error).toStrictEqual(\n new NoAccessibleDeviceError(new Error(message)),\n );\n resolve();\n },\n );\n }));\n\n // [ASK] Is this the behavior we want when the user does not select any device ?\n it(\"should emit an error if the user did not grant us access to a device (clicking on cancel on the browser popup for ex)\", () =>\n new Promise<void>((resolve, reject) => {\n // When the user does not select any device, the `requestDevice` will return an empty array\n mockedRequestDevice.mockResolvedValueOnce([]);\n\n discoverDevice(\n (discoveredDevice) => {\n reject(\n `Should not emit any value, but emitted ${JSON.stringify(\n discoveredDevice,\n )}`,\n );\n },\n (error) => {\n try {\n expect(error).toBeInstanceOf(NoAccessibleDeviceError);\n resolve();\n } catch (expectError) {\n reject(expectError as Error);\n }\n },\n );\n }));\n\n it(\"should emit the same discoveredDevice object if its discovered twice in a row\", async () => {\n mockedRequestDevice.mockResolvedValue([stubDevice]);\n mockedGetDevices.mockResolvedValue([stubDevice]);\n\n const firstDiscoveredDevice = await new Promise<void>(\n (resolve, reject) => {\n discoverDevice(\n () => resolve(),\n (err) => reject(err),\n );\n },\n );\n const secondDiscoveredDevice = await new Promise<void>(\n (resolve, reject) => {\n discoverDevice(\n () => resolve(),\n (err) => reject(err),\n );\n },\n );\n expect(secondDiscoveredDevice).toBe(firstDiscoveredDevice);\n });\n });\n\n describe(\"destroy\", () => {\n it(\"should stop monitoring connections if the discovery process is halted\", () => {\n const abortSpy = vi.spyOn(AbortController.prototype, \"abort\");\n\n transport.destroy();\n\n expect(abortSpy).toHaveBeenCalled();\n });\n });\n\n describe(\"connect\", () => {\n it(\"should throw UnknownDeviceError if no internal device\", async () => {\n const connectParams = {\n deviceId: \"fake\",\n onDisconnect: vi.fn(),\n };\n\n const connect = await transport.connect(connectParams);\n\n expect(connect).toStrictEqual(\n Left(new UnknownDeviceError(\"Unknown device fake\")),\n );\n });\n\n it(\"should throw OpeningConnectionError if the device is already opened\", async () => {\n const device = {\n deviceId: \"fake\",\n onDisconnect: vi.fn(),\n };\n\n const connect = await transport.connect(device);\n\n expect(connect).toStrictEqual(\n Left(new UnknownDeviceError(\"Unknown device fake\")),\n );\n });\n\n it(\"should throw OpeningConnectionError if the device cannot be opened\", () =>\n new Promise<void>((resolve, reject) => {\n const message = \"cannot be opened\";\n const mockedDevice = {\n ...stubDevice,\n open: () => {\n throw new Error(message);\n },\n };\n mockedRequestDevice.mockResolvedValueOnce([mockedDevice]);\n mockedGetDevices.mockResolvedValue([mockedDevice]);\n\n discoverDevice(\n (discoveredDevice) => {\n transport\n .connect({\n deviceId: discoveredDevice.id,\n onDisconnect: vi.fn(),\n })\n .then((value) => {\n expect(value).toStrictEqual(\n Left(new OpeningConnectionError(new Error(message))),\n );\n resolve();\n })\n .catch((error) => {\n reject(error);\n });\n },\n (error) => {\n reject(error as Error);\n },\n );\n }));\n\n it(\"should return the opened device\", () =>\n new Promise<void>((resolve, reject) => {\n const mockedDevice = {\n ...stubDevice,\n opened: false,\n open: () => {\n mockedDevice.opened = true;\n return Promise.resolve();\n },\n };\n\n mockedRequestDevice.mockResolvedValue([mockedDevice]);\n mockedGetDevices.mockResolvedValue([mockedDevice]);\n\n discoverDevice(\n (discoveredDevice) => {\n transport\n .connect({\n deviceId: discoveredDevice.id,\n onDisconnect: vi.fn(),\n })\n .then((connectedDevice) => {\n connectedDevice\n .ifRight((device) => {\n expect(device).toEqual(\n expect.objectContaining({ id: discoveredDevice.id }),\n );\n resolve();\n })\n .ifLeft(() => {\n reject(connectedDevice);\n });\n })\n .catch((error) => {\n reject(error);\n });\n },\n (error) => {\n reject(error as Error);\n },\n );\n }));\n\n it(\"should return a device if available\", () =>\n new Promise<void>((resolve, reject) => {\n mockedRequestDevice.mockResolvedValueOnce([stubDevice]);\n mockedGetDevices.mockResolvedValue([stubDevice]);\n\n discoverDevice(\n (discoveredDevice) => {\n transport\n .connect({\n deviceId: discoveredDevice.id,\n onDisconnect: vi.fn(),\n })\n .then((connectedDevice) => {\n connectedDevice\n .ifRight((device) => {\n expect(device).toEqual(\n expect.objectContaining({ id: discoveredDevice.id }),\n );\n resolve();\n })\n .ifLeft(() => {\n reject(connectedDevice);\n });\n })\n .catch((error) => {\n reject(error);\n });\n },\n (error) => {\n reject(error as Error);\n },\n );\n }));\n });\n\n describe(\"disconnect\", () => {\n it(\"should throw an error if the device is not connected\", async () => {\n // given\n const connectedDevice = connectedDeviceStubBuilder();\n\n // when\n const disconnect = await transport.disconnect({\n connectedDevice,\n });\n\n expect(disconnect).toStrictEqual(\n Left(new UnknownDeviceError(`Unknown device ${connectedDevice.id}`)),\n );\n });\n\n it(\"should disconnect if the device is connected\", () =>\n new Promise<void>((resolve, reject) => {\n mockedRequestDevice.mockResolvedValueOnce([stubDevice]);\n mockedGetDevices.mockResolvedValue([stubDevice]);\n\n discoverDevice(\n (discoveredDevice) => {\n transport\n .connect({\n deviceId: discoveredDevice.id,\n onDisconnect: vi.fn(),\n })\n .then((connectedDevice) => {\n connectedDevice\n .ifRight((device) => {\n transport\n .disconnect({ connectedDevice: device })\n .then((value) => {\n expect(value).toStrictEqual(Right(undefined));\n resolve();\n })\n .catch((error) => {\n reject(error);\n });\n })\n .ifLeft(() => {\n reject(connectedDevice);\n });\n })\n .catch((error) => {\n reject(error);\n });\n },\n (error) => {\n reject(error as Error);\n },\n );\n }));\n\n it(\"should call disconnect handler if a connected device is unplugged\", () =>\n new Promise<void>((resolve, reject) => {\n // given\n const onDisconnect = vi.fn();\n mockedRequestDevice.mockResolvedValueOnce([stubDevice]);\n mockedGetDevices.mockResolvedValue([stubDevice]);\n\n // when\n transport.startDiscovering().subscribe({\n next: (discoveredDevice) => {\n const mock = {\n sendApdu: vi.fn(),\n device: stubDevice,\n deviceId: discoveredDevice.id,\n disconnect: onDisconnect,\n lostConnection: vi.fn().mockImplementation(() => {\n setTimeout(() => {\n mock.disconnect();\n }, RECONNECT_DEVICE_TIMEOUT);\n }),\n };\n\n transport\n .connect({\n deviceId: discoveredDevice.id,\n onDisconnect,\n })\n .then(async () => {\n emitHIDDisconnectionEvent(stubDevice);\n\n expect(stubDevice.close).toHaveBeenCalled();\n await Promise.resolve(); // wait for the next tick so the stubDevice.close promise is resolved\n expect(onDisconnect).not.toHaveBeenCalled();\n vi.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT / 2);\n expect(onDisconnect).not.toHaveBeenCalled();\n vi.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT / 2);\n expect(onDisconnect).toHaveBeenCalled();\n resolve();\n })\n .catch((error) => {\n reject(error);\n });\n },\n });\n }));\n });\n\n describe(\"reconnect\", () => {\n it(\"should stop disconnection if reconnection happen\", () =>\n new Promise<void>((resolve, reject) => {\n // given\n const onDisconnect = vi.fn();\n\n const hidDevice1 = hidDeviceStubBuilder();\n const hidDevice2 = hidDeviceStubBuilder();\n\n mockedRequestDevice.mockResolvedValueOnce([hidDevice1]);\n mockedGetDevices.mockResolvedValue([hidDevice1, hidDevice2]);\n\n discoverDevice(async (discoveredDevice) => {\n const mock = {\n sendApdu: vi.fn(),\n device: hidDevice2,\n deviceId: discoveredDevice.id,\n disconnect: onDisconnect,\n lostConnection: vi.fn().mockImplementation(() => {\n setTimeout(() => {\n mock.disconnect();\n }, RECONNECT_DEVICE_TIMEOUT);\n }),\n };\n\n try {\n await transport.connect({\n deviceId: discoveredDevice.id,\n onDisconnect,\n });\n\n /* Disconnection */\n emitHIDDisconnectionEvent(hidDevice1);\n expect(hidDevice1.close).toHaveBeenCalled();\n await Promise.resolve(); // wait for the next tick so the hidDevice1.close promise is resolved\n\n vi.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT / 3);\n\n /* Reconnection */\n emitHIDConnectionEvent(hidDevice2);\n\n expect(hidDevice2.open).toHaveBeenCalled();\n await Promise.resolve(); // wait for the next tick so the hidDevice2.open promise is resolved\n\n vi.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT);\n expect(onDisconnect).not.toHaveBeenCalled();\n resolve();\n } catch (error) {\n reject(error as Error);\n }\n });\n }));\n\n it(\"should be able to reconnect twice in a row if the device is unplugged and replugged twice\", () =>\n new Promise<void>((resolve, reject) => {\n // given\n const onDisconnect = vi.fn();\n\n const hidDevice1 = hidDeviceStubBuilder();\n const hidDevice2 = hidDeviceStubBuilder();\n const hidDevice3 = hidDeviceStubBuilder();\n\n mockedRequestDevice.mockResolvedValueOnce([hidDevice1]);\n mockedGetDevices.mockResolvedValue([\n hidDevice1,\n hidDevice2,\n hidDevice3,\n ]);\n\n // when\n discoverDevice(async (discoveredDevice) => {\n await transport.connect({\n deviceId: discoveredDevice.id,\n onDisconnect,\n });\n try {\n /* First disconnection */\n emitHIDDisconnectionEvent(hidDevice1);\n expect(hidDevice1.close).toHaveBeenCalled();\n await Promise.resolve(); // wait for the next tick so the hidDevice1.close promise is resolved\n vi.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT / 3);\n\n /* First reconnection */\n emitHIDConnectionEvent(hidDevice2);\n\n expect(hidDevice2.open).toHaveBeenCalled();\n await Promise.resolve(); // wait for the next tick so the hidDevice2.open promise is resolved\n vi.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT);\n expect(onDisconnect).not.toHaveBeenCalled();\n\n /* Second disconnection */\n emitHIDDisconnectionEvent(hidDevice2);\n expect(hidDevice2.close).toHaveBeenCalled();\n await Promise.resolve(); // wait for the next tick so the hidDevice2.close promise is resolved\n vi.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT / 3);\n\n /* Second reconnection */\n emitHIDConnectionEvent(hidDevice3);\n\n expect(hidDevice3.open).toHaveBeenCalled();\n await Promise.resolve(); // wait for the next tick so the hidDevice3.open promise is resolved\n vi.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT);\n expect(onDisconnect).not.toHaveBeenCalled();\n\n resolve();\n } catch (error) {\n reject(error as Error);\n }\n });\n }));\n });\n\n describe(\"Connection event typeguard\", () => {\n it(\"should validate type of an HIDConnectionEvent\", () => {\n // given\n const event = {\n device: stubDevice,\n } as HIDConnectionEvent;\n // when\n // @ts-expect-error trying to access private member\n const result = transport.isHIDConnectionEvent(event);\n // then\n expect(result).toBe(true);\n });\n\n it(\"should not validate type of another event\", () => {\n // given\n const event = new Event(\"disconnect\", {});\n // when\n // @ts-expect-error trying to access private member\n const result = transport.isHIDConnectionEvent(event);\n // then\n expect(result).toBe(false);\n });\n });\n\n describe(\"listenToAvailableDevices\", () => {\n it(\"should emit the devices already connected before listening\", async () => {\n // given\n const hidDevice = hidDeviceStubBuilder();\n mockedGetDevices.mockResolvedValue([hidDevice]);\n\n const onComplete = vi.fn();\n const onError = vi.fn();\n\n let observedDevices: TransportDiscoveredDevice[] = [];\n // when\n transport.listenToAvailableDevices().subscribe({\n next: (knownDevices) => {\n observedDevices = knownDevices;\n },\n complete: onComplete,\n error: onError,\n });\n\n await flushPromises();\n\n expect(observedDevices).toEqual([\n expect.objectContaining({\n deviceModel: expect.objectContaining({\n id: DeviceModelId.NANO_X,\n }) as TransportDeviceModel,\n }),\n ]);\n expect(onComplete).not.toHaveBeenCalled();\n expect(onError).not.toHaveBeenCalled();\n });\n\n it(\"should emit the new list of devices after connection and disconnection events\", async () => {\n initializeTransport();\n // given\n const hidDevice1 = hidDeviceStubBuilder({\n productId:\n usbDeviceModelDataSource.getDeviceModel({\n id: DeviceModelId.NANO_X,\n }).usbProductId << 8,\n });\n const hidDevice2 = hidDeviceStubBuilder({\n productId:\n usbDeviceModelDataSource.getDeviceModel({ id: DeviceModelId.STAX })\n .usbProductId << 8,\n });\n mockedGetDevices.mockResolvedValue([hidDevice1]);\n\n const onComplete = vi.fn();\n const onError = vi.fn();\n\n let observedDevices: TransportDiscoveredDevice[] = [];\n // when\n transport.listenToAvailableDevices().subscribe({\n next: (knownDevices) => {\n observedDevices = knownDevices;\n },\n complete: onComplete,\n error: onError,\n });\n\n await flushPromises();\n\n expect(observedDevices).toEqual([\n expect.objectContaining({\n deviceModel: expect.objectContaining({\n id: DeviceModelId.NANO_X,\n }) as TransportDeviceModel,\n }),\n ]);\n\n // When a new device is connected\n mockedGetDevices.mockResolvedValue([hidDevice1, hidDevice2]);\n emitHIDConnectionEvent(hidDevice2);\n await flushPromises();\n\n expect(observedDevices).toEqual([\n expect.objectContaining({\n deviceModel: expect.objectContaining({\n id: DeviceModelId.NANO_X,\n }) as TransportDeviceModel,\n }),\n expect.objectContaining({\n deviceModel: expect.objectContaining({\n id: DeviceModelId.STAX,\n }) as TransportDeviceModel,\n }),\n ]);\n\n // When a device is disconnected\n mockedGetDevices.mockResolvedValue([hidDevice2]);\n emitHIDDisconnectionEvent(hidDevice1);\n await flushPromises();\n\n expect(observedDevices).toEqual([\n expect.objectContaining({\n deviceModel: expect.objectContaining({\n id: DeviceModelId.STAX,\n }) as TransportDeviceModel,\n }),\n ]);\n\n expect(onComplete).not.toHaveBeenCalled();\n expect(onError).not.toHaveBeenCalled();\n });\n\n it(\"should preserve DeviceId in case the device has been disconnected and reconnected before the timeout\", async () => {\n // given\n const hidDevice = hidDeviceStubBuilder();\n\n mockedGetDevices.mockResolvedValue([hidDevice]);\n\n const onComplete = vi.fn();\n const onError = vi.fn();\n let observedDevices: TransportDiscoveredDevice[] = [];\n // when\n transport.listenToAvailableDevices().subscribe({\n next: (knownDevices) => {\n observedDevices = knownDevices;\n },\n complete: onComplete,\n error: onError,\n });\n\n await flushPromises();\n\n const firstObservedDeviceId = observedDevices[0]?.id;\n expect(firstObservedDeviceId).toBeTruthy();\n expect(observedDevices[0]?.deviceModel?.id).toBe(DeviceModelId.NANO_X);\n\n // Start a connection with the device\n await transport.connect({\n deviceId: observedDevices[0]!.id,\n onDisconnect: vi.fn(),\n });\n await flushPromises();\n\n // When the device is disconnected\n mockedGetDevices.mockResolvedValue([]);\n emitHIDDisconnectionEvent(hidDevice);\n await flushPromises();\n\n expect(observedDevices).toEqual([]);\n\n // When the device is reconnected\n mockedGetDevices.mockResolvedValue([hidDevice]);\n emitHIDConnectionEvent(hidDevice);\n await flushPromises();\n\n expect(observedDevices).toEqual([\n expect.objectContaining({\n deviceModel: expect.objectContaining({\n id: DeviceModelId.NANO_X,\n }) as TransportDeviceModel,\n }),\n ]);\n\n expect(observedDevices[0]?.id).toBeTruthy();\n expect(observ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ionError", "StaticDeviceModelDataSource", "UnknownDeviceError", "Left", "Right", "Subject", "RECONNECT_DEVICE_TIMEOUT", "WebHidTransportNotSupportedError", "hidDeviceStubBuilder", "WebHidTransport", "LoggerPublisherServiceStub", "subscribers", "tag", "usbDeviceModelDataSource", "logger", "stubDevice", "flushPromises", "timers", "transport", "apduReceiverServiceFactoryStub", "apduSenderServiceFactoryStub", "initializeTransport", "discoverDevice", "onSuccess", "onError", "resolve", "reject", "error", "mockedGetDevices", "mockedRequestDevice", "connectionEventsSubject", "disconnectionEventsSubject", "emitHIDConnectionEvent", "device", "emitHIDDisconnectionEvent", "eventName", "callback", "deviceModel", "testCase", "discoveredDevice", "expectError", "count", "message", "firstDiscoveredDevice", "err", "secondDiscoveredDevice", "abortSpy", "connectParams", "connect", "mockedDevice", "value", "connectedDevice", "disconnect", "onDisconnect", "mock", "hidDevice1", "hidDevice2", "hidDevice3", "event", "result", "hidDevice", "onComplete", "observedDevices", "knownDevices", "firstObservedDeviceId"]
|
|
7
7
|
}
|
|
@@ -42,7 +42,7 @@ export declare class WebHidTransport implements Transport {
|
|
|
42
42
|
/**
|
|
43
43
|
* Listen to known devices (devices to which the user has granted access)
|
|
44
44
|
*/
|
|
45
|
-
|
|
45
|
+
listenToAvailableDevices(): Observable<TransportDiscoveredDevice[]>;
|
|
46
46
|
private updateTransportDiscoveredDevices;
|
|
47
47
|
/**
|
|
48
48
|
* Wrapper around navigator.hid.requestDevice()
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WebHidTransport.d.ts","sourceRoot":"","sources":["../../../../src/api/transport/WebHidTransport.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,0BAA0B,EAC/B,KAAK,wBAAwB,EAC7B,KAAK,YAAY,EAEjB,KAAK,QAAQ,EACb,KAAK,qBAAqB,EAE1B,KAAK,iBAAiB,EACtB,KAAK,QAAQ,EAGb,KAAK,sBAAsB,EAG3B,KAAK,SAAS,EACd,wBAAwB,EAExB,KAAK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