@ledgerhq/device-transport-kit-react-native-ble 1.1.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -0
- package/lib/cjs/api/index.js +1 -1
- package/lib/cjs/api/index.js.map +3 -3
- package/lib/cjs/api/model/Errors.js +1 -1
- package/lib/cjs/api/model/Errors.js.map +3 -3
- package/lib/cjs/api/permissions/AndroidPermissionsService.js +2 -0
- package/lib/cjs/api/permissions/AndroidPermissionsService.js.map +7 -0
- package/lib/cjs/api/permissions/AndroidPermissionsService.test.js +2 -0
- package/lib/cjs/api/permissions/AndroidPermissionsService.test.js.map +7 -0
- package/lib/cjs/api/permissions/DefaultPermissionsService.js +2 -0
- package/lib/cjs/api/permissions/DefaultPermissionsService.js.map +7 -0
- package/lib/cjs/api/permissions/IOSPermissionsService.test.js +2 -0
- package/lib/cjs/api/permissions/IOSPermissionsService.test.js.map +7 -0
- package/lib/cjs/api/permissions/PermissionsAndroidNarrowedType.js +2 -0
- package/lib/cjs/api/permissions/PermissionsAndroidNarrowedType.js.map +7 -0
- package/lib/cjs/api/permissions/PermissionsService.js +2 -0
- package/lib/cjs/api/permissions/PermissionsService.js.map +7 -0
- package/lib/cjs/api/transport/RNBleApduSender.js +1 -1
- package/lib/cjs/api/transport/RNBleApduSender.js.map +2 -2
- package/lib/cjs/api/transport/RNBleTransport.js +1 -1
- package/lib/cjs/api/transport/RNBleTransport.js.map +3 -3
- package/lib/cjs/api/transport/RNBleTransport.test.js +1 -1
- package/lib/cjs/api/transport/RNBleTransport.test.js.map +3 -3
- package/lib/cjs/api/transport/RNBleTransportFactory.js +2 -0
- package/lib/cjs/api/transport/RNBleTransportFactory.js.map +7 -0
- package/lib/cjs/package.json +1 -1
- package/lib/esm/api/index.js +1 -1
- package/lib/esm/api/index.js.map +3 -3
- package/lib/esm/api/model/Errors.js +1 -1
- package/lib/esm/api/model/Errors.js.map +3 -3
- package/lib/esm/api/permissions/AndroidPermissionsService.js +2 -0
- package/lib/esm/api/permissions/AndroidPermissionsService.js.map +7 -0
- package/lib/esm/api/permissions/AndroidPermissionsService.test.js +2 -0
- package/lib/esm/api/permissions/AndroidPermissionsService.test.js.map +7 -0
- package/lib/esm/api/permissions/DefaultPermissionsService.js +2 -0
- package/lib/esm/api/permissions/DefaultPermissionsService.js.map +7 -0
- package/lib/esm/api/permissions/IOSPermissionsService.test.js +2 -0
- package/lib/esm/api/permissions/IOSPermissionsService.test.js.map +7 -0
- package/lib/esm/api/permissions/PermissionsAndroidNarrowedType.js +1 -0
- package/lib/esm/api/permissions/PermissionsAndroidNarrowedType.js.map +7 -0
- package/lib/esm/api/permissions/PermissionsService.js +1 -0
- package/lib/esm/api/permissions/PermissionsService.js.map +7 -0
- package/lib/esm/api/transport/RNBleApduSender.js +1 -1
- package/lib/esm/api/transport/RNBleApduSender.js.map +2 -2
- package/lib/esm/api/transport/RNBleTransport.js +1 -1
- package/lib/esm/api/transport/RNBleTransport.js.map +3 -3
- package/lib/esm/api/transport/RNBleTransport.test.js +1 -1
- package/lib/esm/api/transport/RNBleTransport.test.js.map +3 -3
- package/lib/esm/api/transport/RNBleTransportFactory.js +2 -0
- package/lib/esm/api/transport/RNBleTransportFactory.js.map +7 -0
- package/lib/esm/package.json +1 -1
- package/lib/types/api/index.d.ts +2 -1
- package/lib/types/api/index.d.ts.map +1 -1
- package/lib/types/api/model/Errors.d.ts +10 -0
- package/lib/types/api/model/Errors.d.ts.map +1 -1
- package/lib/types/api/permissions/AndroidPermissionsService.d.ts +12 -0
- package/lib/types/api/permissions/AndroidPermissionsService.d.ts.map +1 -0
- package/lib/types/api/permissions/AndroidPermissionsService.test.d.ts +2 -0
- package/lib/types/api/permissions/AndroidPermissionsService.test.d.ts.map +1 -0
- package/lib/types/api/permissions/DefaultPermissionsService.d.ts +6 -0
- package/lib/types/api/permissions/DefaultPermissionsService.d.ts.map +1 -0
- package/lib/types/api/permissions/IOSPermissionsService.test.d.ts +2 -0
- package/lib/types/api/permissions/IOSPermissionsService.test.d.ts.map +1 -0
- package/lib/types/api/permissions/PermissionsAndroidNarrowedType.d.ts +20 -0
- package/lib/types/api/permissions/PermissionsAndroidNarrowedType.d.ts.map +1 -0
- package/lib/types/api/permissions/PermissionsService.d.ts +5 -0
- package/lib/types/api/permissions/PermissionsService.d.ts.map +1 -0
- package/lib/types/api/transport/RNBleApduSender.d.ts.map +1 -1
- package/lib/types/api/transport/RNBleTransport.d.ts +22 -15
- package/lib/types/api/transport/RNBleTransport.d.ts.map +1 -1
- package/lib/types/api/transport/RNBleTransportFactory.d.ts +3 -0
- package/lib/types/api/transport/RNBleTransportFactory.d.ts.map +1 -0
- package/lib/types/tsconfig.prod.tsbuildinfo +1 -1
- package/package.json +10 -10
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/api/transport/RNBleApduSender.ts"],
|
|
4
|
-
"sourcesContent": ["import {\n type BleManager,\n type Characteristic,\n type Device,\n type Subscription as BleCharacteristicSubscription,\n} from \"react-native-ble-plx\";\nimport {\n type ApduReceiverService,\n type ApduReceiverServiceFactory,\n type ApduResponse,\n type ApduSenderService,\n type ApduSenderServiceFactory,\n type BleDeviceInfos,\n type DeviceApduSender,\n type DeviceId,\n DeviceNotInitializedError,\n type DmkError,\n type LoggerPublisherService,\n SendApduTimeoutError,\n} from \"@ledgerhq/device-management-kit\";\nimport { Base64 } from \"js-base64\";\nimport { type Either, Left, Maybe, Nothing, Right } from \"purify-ts\";\nimport { BehaviorSubject, type Subscription } from \"rxjs\";\n\nimport { PairingRefusedError, UnknownBleError } from \"@api/model/Errors\";\n\nconst FRAME_HEADER_SIZE = 3;\n\nexport type RNBleInternalDevice = {\n id: DeviceId;\n bleDeviceInfos: BleDeviceInfos;\n};\n\nexport type RNBleApduSenderConstructorArgs = {\n dependencies: RNBleApduSenderDependencies;\n apduSenderFactory: ApduSenderServiceFactory;\n apduReceiverFactory: ApduReceiverServiceFactory;\n};\n\nexport type RNBleApduSenderDependencies = {\n device: Device;\n internalDevice: RNBleInternalDevice;\n manager: BleManager;\n};\n\nexport class RNBleApduSender\n implements DeviceApduSender<RNBleApduSenderDependencies>\n{\n private _dependencies: RNBleApduSenderDependencies;\n private _isDeviceReady: BehaviorSubject<boolean>;\n private _logger: LoggerPublisherService;\n private _apduSender: Maybe<ApduSenderService>;\n private readonly _apduSenderFactory: ApduSenderServiceFactory;\n private readonly _apduReceiver: ApduReceiverService;\n private _sendApduPromiseResolver: Maybe<\n (value: Either<DmkError, ApduResponse>) => void\n >;\n\n private _writeCharacteristic!: Characteristic;\n private _characteristicSubscription:\n | BleCharacteristicSubscription\n | undefined = undefined;\n\n constructor(\n {\n apduSenderFactory,\n apduReceiverFactory,\n dependencies,\n }: RNBleApduSenderConstructorArgs,\n loggerServiceFactory: (tag: string) => LoggerPublisherService,\n ) {\n this._dependencies = dependencies;\n this._isDeviceReady = new BehaviorSubject<boolean>(false);\n this._logger = loggerServiceFactory(\"RNBleApduSender\");\n this._apduSenderFactory = apduSenderFactory;\n this._apduSender = Nothing;\n this._apduReceiver = apduReceiverFactory();\n this._sendApduPromiseResolver = Nothing;\n }\n\n private onReceiveSetupApduResponse(value: Uint8Array) {\n const mtuResponse = new Uint8Array(value);\n const { device } = this._dependencies;\n // ledger mtu is the 5th byte of the response\n const [ledgerMtu] = mtuResponse.slice(5);\n let frameSize = device.mtu - FRAME_HEADER_SIZE;\n if (ledgerMtu && ledgerMtu !== frameSize) {\n // should never happen since ble mtu is negotiated on device connect with 156 bytes and ledger should return mtu size minus header size\n frameSize = ledgerMtu;\n }\n this._apduSender = Maybe.of(this._apduSenderFactory({ frameSize }));\n this._isDeviceReady.next(true);\n }\n\n private receiveApdu(apdu: Uint8Array) {\n const maybeApduResponse = this._apduReceiver.handleFrame(apdu);\n\n maybeApduResponse\n .map((response) => {\n response.map((apduResponse) => {\n this.
|
|
5
|
-
"mappings": "AAMA,OASE,6BAAAA,EAGA,wBAAAC,MACK,kCACP,OAAS,UAAAC,MAAc,YACvB,OAAsB,QAAAC,EAAM,SAAAC,EAAO,WAAAC,EAAS,SAAAC,MAAa,YACzD,OAAS,mBAAAC,MAA0C,OAEnD,OAAS,uBAAAC,EAAqB,mBAAAC,MAAuB,oBAErD,MAAMC,EAAoB,EAmBnB,MAAMC,CAEb,CACU,cACA,eACA,QACA,YACS,mBACA,cACT,yBAIA,qBACA,4BAEQ,OAEhB,YACE,CACE,kBAAAC,EACA,oBAAAC,EACA,aAAAC,CACF,EACAC,EACA,CACA,KAAK,cAAgBD,EACrB,KAAK,eAAiB,IAAIP,EAAyB,EAAK,EACxD,KAAK,QAAUQ,EAAqB,iBAAiB,EACrD,KAAK,mBAAqBH,EAC1B,KAAK,YAAcP,EACnB,KAAK,cAAgBQ,EAAoB,EACzC,KAAK,yBAA2BR,CAClC,CAEQ,2BAA2BW,EAAmB,CACpD,MAAMC,EAAc,IAAI,WAAWD,CAAK,EAClC,CAAE,OAAAE,CAAO,EAAI,KAAK,cAElB,CAACC,CAAS,EAAIF,EAAY,MAAM,CAAC,EACvC,IAAIG,EAAYF,EAAO,IAAMR,EACzBS,GAAaA,IAAcC,IAE7BA,EAAYD,GAEd,KAAK,YAAcf,EAAM,GAAG,KAAK,mBAAmB,CAAE,UAAAgB,CAAU,CAAC,CAAC,EAClE,KAAK,eAAe,KAAK,EAAI,CAC/B,CAEQ,YAAYC,EAAkB,CACV,KAAK,cAAc,YAAYA,CAAI,EAG1D,IAAKC,GAAa,CACjBA,EAAS,IAAKC,GAAiB,CAC7B,KAAK,
|
|
4
|
+
"sourcesContent": ["import {\n type BleManager,\n type Characteristic,\n type Device,\n type Subscription as BleCharacteristicSubscription,\n} from \"react-native-ble-plx\";\nimport {\n type ApduReceiverService,\n type ApduReceiverServiceFactory,\n type ApduResponse,\n type ApduSenderService,\n type ApduSenderServiceFactory,\n type BleDeviceInfos,\n type DeviceApduSender,\n type DeviceId,\n DeviceNotInitializedError,\n type DmkError,\n type LoggerPublisherService,\n SendApduTimeoutError,\n} from \"@ledgerhq/device-management-kit\";\nimport { Base64 } from \"js-base64\";\nimport { type Either, Left, Maybe, Nothing, Right } from \"purify-ts\";\nimport { BehaviorSubject, type Subscription } from \"rxjs\";\n\nimport { PairingRefusedError, UnknownBleError } from \"@api/model/Errors\";\n\nconst FRAME_HEADER_SIZE = 3;\n\nexport type RNBleInternalDevice = {\n id: DeviceId;\n bleDeviceInfos: BleDeviceInfos;\n};\n\nexport type RNBleApduSenderConstructorArgs = {\n dependencies: RNBleApduSenderDependencies;\n apduSenderFactory: ApduSenderServiceFactory;\n apduReceiverFactory: ApduReceiverServiceFactory;\n};\n\nexport type RNBleApduSenderDependencies = {\n device: Device;\n internalDevice: RNBleInternalDevice;\n manager: BleManager;\n};\n\nexport class RNBleApduSender\n implements DeviceApduSender<RNBleApduSenderDependencies>\n{\n private _dependencies: RNBleApduSenderDependencies;\n private _isDeviceReady: BehaviorSubject<boolean>;\n private _logger: LoggerPublisherService;\n private _apduSender: Maybe<ApduSenderService>;\n private readonly _apduSenderFactory: ApduSenderServiceFactory;\n private readonly _apduReceiver: ApduReceiverService;\n private _sendApduPromiseResolver: Maybe<\n (value: Either<DmkError, ApduResponse>) => void\n >;\n\n private _writeCharacteristic!: Characteristic;\n private _characteristicSubscription:\n | BleCharacteristicSubscription\n | undefined = undefined;\n\n constructor(\n {\n apduSenderFactory,\n apduReceiverFactory,\n dependencies,\n }: RNBleApduSenderConstructorArgs,\n loggerServiceFactory: (tag: string) => LoggerPublisherService,\n ) {\n this._dependencies = dependencies;\n this._isDeviceReady = new BehaviorSubject<boolean>(false);\n this._logger = loggerServiceFactory(\"RNBleApduSender\");\n this._apduSenderFactory = apduSenderFactory;\n this._apduSender = Nothing;\n this._apduReceiver = apduReceiverFactory();\n this._sendApduPromiseResolver = Nothing;\n }\n\n private onReceiveSetupApduResponse(value: Uint8Array) {\n const mtuResponse = new Uint8Array(value);\n const { device } = this._dependencies;\n // ledger mtu is the 5th byte of the response\n const [ledgerMtu] = mtuResponse.slice(5);\n let frameSize = device.mtu - FRAME_HEADER_SIZE;\n if (ledgerMtu && ledgerMtu !== frameSize) {\n // should never happen since ble mtu is negotiated on device connect with 156 bytes and ledger should return mtu size minus header size\n frameSize = ledgerMtu;\n }\n this._apduSender = Maybe.of(this._apduSenderFactory({ frameSize }));\n this._isDeviceReady.next(true);\n }\n\n private receiveApdu(apdu: Uint8Array) {\n const maybeApduResponse = this._apduReceiver.handleFrame(apdu);\n\n maybeApduResponse\n .map((response) => {\n response.map((apduResponse) => {\n this._sendApduPromiseResolver.map((resolve) =>\n resolve(Right(apduResponse)),\n );\n });\n })\n .mapLeft((error) => {\n this._sendApduPromiseResolver.map((resolve) => resolve(Left(error)));\n });\n }\n\n private onMonitor(characteristic: Characteristic) {\n if (!characteristic.value) {\n return;\n }\n\n const apdu = Base64.toUint8Array(characteristic.value);\n if (!this._isDeviceReady.value) {\n this.onReceiveSetupApduResponse(apdu);\n } else {\n this.receiveApdu(apdu);\n }\n }\n\n private write(value: string) {\n if (this._writeCharacteristic.isWritableWithoutResponse) {\n return this._writeCharacteristic.writeWithoutResponse(value);\n }\n\n return this._writeCharacteristic.writeWithResponse(value);\n }\n\n public getDependencies() {\n return this._dependencies;\n }\n\n public setDependencies(dependencies: RNBleApduSenderDependencies) {\n this._dependencies = dependencies;\n\n //Set dependencies mean we are reconnecting to a new device\n // So we need to reset the state of the sender\n this._isDeviceReady = new BehaviorSubject<boolean>(false);\n if (this._characteristicSubscription) {\n this._characteristicSubscription.remove();\n this._characteristicSubscription = undefined;\n }\n }\n\n public async setupConnection() {\n this._characteristicSubscription =\n this._dependencies.device.monitorCharacteristicForService(\n this._dependencies.internalDevice.bleDeviceInfos.serviceUuid,\n this._dependencies.internalDevice.bleDeviceInfos.notifyUuid,\n (error, characteristic) => {\n if (error?.message.includes(\"notify change failed\")) {\n // iOS pairing refused error\n this._isDeviceReady.error(new PairingRefusedError(error));\n this._logger.error(\"Pairing failed\", {\n data: { error },\n });\n return;\n } else if (error) {\n this._isDeviceReady.error(new UnknownBleError(error));\n this._logger.error(\"Error monitoring characteristic\", {\n data: { error },\n });\n }\n if (!error && characteristic) {\n this.onMonitor(characteristic);\n }\n },\n );\n\n // Setup Write characteristic\n const characteristics =\n await this._dependencies.manager.characteristicsForDevice(\n this._dependencies.device.id,\n this._dependencies.internalDevice.bleDeviceInfos.serviceUuid,\n );\n\n let tmpWriteCharacteristic = characteristics.find(\n (characteristic) =>\n characteristic.uuid ===\n this._dependencies.internalDevice.bleDeviceInfos.writeCmdUuid,\n );\n if (tmpWriteCharacteristic) {\n this._writeCharacteristic = tmpWriteCharacteristic;\n } else {\n tmpWriteCharacteristic = characteristics.find(\n (characteristic) =>\n characteristic.uuid ===\n this._dependencies.internalDevice.bleDeviceInfos.writeUuid,\n );\n\n //This should never happen\n if (tmpWriteCharacteristic) {\n this._writeCharacteristic = tmpWriteCharacteristic;\n } else {\n this._logger.error(\"No write characteristic found\");\n throw new Error(\"No write characteristic found\");\n }\n }\n\n const requestMtuFrame = Uint8Array.from([0x08, 0x00, 0x00, 0x00, 0x00]);\n await this.write(Base64.fromUint8Array(requestMtuFrame)).catch((error) => {\n // Android pairing refused error\n this._logger.error(\"Pairing failed\", {\n data: { error },\n });\n throw new PairingRefusedError(error);\n });\n let sub: Subscription | undefined;\n await new Promise<void>((resolve, reject) => {\n if (sub) {\n sub.unsubscribe();\n }\n\n sub = this._isDeviceReady.subscribe({\n next: (isReady) => {\n if (isReady) {\n resolve(); // FIXME: we should instead return a Right\n }\n },\n error: (error) => {\n reject(error); // FIXME: we should instead return a Left so it's properly typed\n },\n });\n });\n }\n\n async sendApdu(\n apdu: Uint8Array,\n _triggersDisconnection?: boolean,\n abortTimeout?: number,\n ): Promise<Either<DmkError, ApduResponse>> {\n if (!this._isDeviceReady.value) {\n return Promise.resolve(\n Left(new DeviceNotInitializedError(\"Unknown MTU\")),\n );\n }\n\n let timeout: ReturnType<typeof setTimeout> | undefined;\n\n const resultPromise = new Promise<Either<DmkError, ApduResponse>>(\n (resolve) => {\n this._sendApduPromiseResolver = Maybe.of((...args) => {\n if (timeout) {\n clearTimeout(timeout);\n }\n return resolve(...args);\n });\n },\n );\n\n const frames = this._apduSender.caseOf({\n Just: (apduSender) => apduSender.getFrames(apdu),\n Nothing: () => [],\n });\n\n for (const frame of frames) {\n try {\n await this.write(Base64.fromUint8Array(frame.getRawData()));\n } catch (error) {\n this._logger.info(\"Error sending frame\", { data: { error } });\n }\n }\n\n if (abortTimeout) {\n timeout = setTimeout(() => {\n this._logger.debug(\"[sendApdu] Abort timeout triggered\");\n this._sendApduPromiseResolver.map((resolve) =>\n resolve(Left(new SendApduTimeoutError(\"Abort timeout\"))),\n );\n }, abortTimeout);\n }\n\n return resultPromise;\n }\n\n public closeConnection() {\n this._dependencies.device.cancelConnection();\n }\n}\n"],
|
|
5
|
+
"mappings": "AAMA,OASE,6BAAAA,EAGA,wBAAAC,MACK,kCACP,OAAS,UAAAC,MAAc,YACvB,OAAsB,QAAAC,EAAM,SAAAC,EAAO,WAAAC,EAAS,SAAAC,MAAa,YACzD,OAAS,mBAAAC,MAA0C,OAEnD,OAAS,uBAAAC,EAAqB,mBAAAC,MAAuB,oBAErD,MAAMC,EAAoB,EAmBnB,MAAMC,CAEb,CACU,cACA,eACA,QACA,YACS,mBACA,cACT,yBAIA,qBACA,4BAEQ,OAEhB,YACE,CACE,kBAAAC,EACA,oBAAAC,EACA,aAAAC,CACF,EACAC,EACA,CACA,KAAK,cAAgBD,EACrB,KAAK,eAAiB,IAAIP,EAAyB,EAAK,EACxD,KAAK,QAAUQ,EAAqB,iBAAiB,EACrD,KAAK,mBAAqBH,EAC1B,KAAK,YAAcP,EACnB,KAAK,cAAgBQ,EAAoB,EACzC,KAAK,yBAA2BR,CAClC,CAEQ,2BAA2BW,EAAmB,CACpD,MAAMC,EAAc,IAAI,WAAWD,CAAK,EAClC,CAAE,OAAAE,CAAO,EAAI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Y,EACAC,EACyC,CACzC,GAAI,CAAC,KAAK,eAAe,MACvB,OAAO,QAAQ,QACb/B,EAAK,IAAIH,EAA0B,aAAa,CAAC,CACnD,EAGF,IAAImC,EAEJ,MAAMC,EAAgB,IAAI,QACvBZ,GAAY,CACX,KAAK,yBAA2BpB,EAAM,GAAG,IAAIiC,KACvCF,GACF,aAAaA,CAAO,EAEfX,EAAQ,GAAGa,CAAI,EACvB,CACH,CACF,EAEMC,EAAS,KAAK,YAAY,OAAO,CACrC,KAAOC,GAAeA,EAAW,UAAUlB,CAAI,EAC/C,QAAS,IAAM,CAAC,CAClB,CAAC,EAED,UAAWmB,KAASF,EAClB,GAAI,CACF,MAAM,KAAK,MAAMpC,EAAO,eAAesC,EAAM,WAAW,CAAC,CAAC,CAC5D,OAASf,EAAO,CACd,KAAK,QAAQ,KAAK,sBAAuB,CAAE,KAAM,CAAE,MAAAA,CAAM,CAAE,CAAC,CAC9D,CAGF,OAAIS,IACFC,EAAU,WAAW,IAAM,CACzB,KAAK,QAAQ,MAAM,oCAAoC,EACvD,KAAK,yBAAyB,IAAKX,GACjCA,EAAQrB,EAAK,IAAIF,EAAqB,eAAe,CAAC,CAAC,CACzD,CACF,EAAGiC,CAAY,GAGVE,CACT,CAEO,iBAAkB,CACvB,KAAK,cAAc,OAAO,iBAAiB,CAC7C,CACF",
|
|
6
6
|
"names": ["DeviceNotInitializedError", "SendApduTimeoutError", "Base64", "Left", "Maybe", "Nothing", "Right", "BehaviorSubject", "PairingRefusedError", "UnknownBleError", "FRAME_HEADER_SIZE", "RNBleApduSender", "apduSenderFactory", "apduReceiverFactory", "dependencies", "loggerServiceFactory", "value", "mtuResponse", "device", "ledgerMtu", "frameSize", "apdu", "response", "apduResponse", "resolve", "error", "characteristic", "characteristics", "tmpWriteCharacteristic", "requestMtuFrame", "sub", "reject", "isReady", "_triggersDisconnection", "abortTimeout", "timeout", "resultPromise", "args", "frames", "apduSender", "frame"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{PermissionsAndroid as N,Platform as f}from"react-native";import{BleError as A,BleManager as B,State as M}from"react-native-ble-plx";import{DeviceConnectionStateMachine as w,OpeningConnectionError as b,TransportConnectedDevice as y,UnknownDeviceError as O}from"@ledgerhq/device-management-kit";import{Either as I,EitherAsync as T,Left as R,Maybe as c,Nothing as u,Right as h}from"purify-ts";import{BehaviorSubject as S,filter as U,finalize as L,from as D,map as F,retry as P,switchMap as p,throttleTime as j,throwError as x}from"rxjs";import{BLE_DISCONNECT_TIMEOUT_ANDROID as z,BLE_DISCONNECT_TIMEOUT_IOS as H,CONNECTION_LOST_DELAY as q,DEFAULT_MTU as C}from"../model/Const";import{BleNotSupported as k,DeviceConnectionNotFound as G,NoDeviceModelFoundError as J,PeerRemovedPairingError as $}from"../model/Errors";import{RNBleApduSender as V}from"../transport/RNBleApduSender";const te="RN_BLE";class Y{constructor(e,i,n,t,s,r=f,v=N,a=d=>new w(d),g=(d,l)=>new V(d,l)){this._deviceModelDataSource=e;this._loggerServiceFactory=i;this._apduSenderFactory=n;this._apduReceiverFactory=t;this._manager=s;this._platform=r;this._permissionsAndroid=v;this._deviceConnectionStateMachineFactory=a;this._deviceApduSenderFactory=g;this._logger=i("ReactNativeBleTransport"),this._isSupported=c.zero(),this._deviceConnectionsById=new Map,this._reconnectionSubscription=c.zero(),this._manager.onStateChange(d=>{this._bleStateSubject.next(d)},!0)}_logger;_isSupported;_deviceConnectionsById;identifier="RN_BLE";_reconnectionSubscription;_bleStateSubject=new S(M.Unknown);startDiscovering(){return D([])}async stopDiscovering(){await this._stopScanning()}_maybeScanningSubject=u;_scannedDevicesSubject=new S([]);_startedScanningSubscriber=void 0;_startScanning(){this._startedScanningSubscriber==null&&(this._scannedDevicesSubject.next([]),this._startedScanningSubscriber=D(this._bleStateSubject).pipe(U(e=>e==="PoweredOn"),p(()=>this.requestPermission()),p(e=>{if(!e)return x(()=>new k("BLE not supported"));const i=new S([]);this._maybeScanningSubject=c.of(i);const n=new Map;this._logger.info("[RNBleTransport][startScanning] startDeviceScan"),this._manager.startDeviceScan(this._deviceModelDataSource.getBluetoothServices(),{allowDuplicates:!0},(s,r)=>{if(s||!r){i.error(s||new Error("scan error"));return}n.set(r.id,{device:r,timestamp:Date.now()}),i.next(Array.from(n.values()))});const t=setInterval(()=>{i.next(Array.from(n.values()))},1e3);return i.asObservable().pipe(L(()=>{this._logger.debug("[RNBleTransport][startScanning] finalize"),i.complete(),clearInterval(t),this._maybeScanningSubject=u,this._manager.stopDeviceScan()}))}),j(1e3)).subscribe({next:e=>{this._logger.debug("[RNBleTransport][startScanning] onNext called with devices",{data:{devices:e}}),this._scannedDevicesSubject.next(e)},error:e=>{this._logger.error("Error while scanning",{data:{error:e}})}}))}async _stopScanning(){this._maybeScanningSubject.map(e=>{e.complete(),this._maybeScanningSubject=u}),await this._manager.stopDeviceScan(),this._startedScanningSubscriber?.unsubscribe(),this._startedScanningSubscriber=void 0}listenToAvailableDevices(){return this._startScanning(),this._scannedDevicesSubject.asObservable().pipe(F(e=>{const i=Array.from(this._deviceConnectionsById.values()).map(r=>this._mapDeviceToTransportDiscoveredDevice(r.getDependencies().device,[r.getDependencies().internalDevice.bleDeviceInfos.serviceUuid])),n=I.rights(i),t=e.filter(({timestamp:r})=>r>Date.now()-q).sort((r,v)=>(v.device.rssi??-1/0)-(r.device.rssi??-1/0)).map(({device:r})=>this._mapDeviceToTransportDiscoveredDevice(r,r.serviceUUIDs)).filter(r=>!!r),s=I.rights(t);return[...n,...s]}))}_mapServicesUUIDsToBluetoothDeviceInfo(e){for(const i of e||[]){const n=this._deviceModelDataSource.getBluetoothServicesInfos()[i];if(n)return h(n)}return R(new J(`No device model found for [uuids=${e}]`))}_mapServicesUUIDsToDeviceModel(e){return this._mapServicesUUIDsToBluetoothDeviceInfo(e).map(n=>n.deviceModel)}_mapDeviceToTransportDiscoveredDevice(e,i){return this._mapServicesUUIDsToDeviceModel(i).map(t=>({id:e.id,name:e.localName||e.name||"",deviceModel:t,transport:this.identifier,rssi:e.rssi||void 0}))}async connect(e){const i=this._deviceConnectionsById.get(e.deviceId);if(i){const n=i.getDependencies().internalDevice.bleDeviceInfos.deviceModel;return h(new y({id:e.deviceId,deviceModel:n,type:"BLE",sendApdu:(...t)=>i.sendApdu(...t),transport:this.identifier}))}return await this._stopScanning(),await this._safeCancel(e.deviceId),T(async({throwE:n})=>{let t,s=[];try{await this._manager.connectToDevice(e.deviceId,{requestMTU:C}),t=await this._manager.discoverAllServicesAndCharacteristicsForDevice(e.deviceId),s=(await t.services()).map(o=>o.uuid)}catch(o){return o instanceof A&&o.iosErrorCode===14?n(new $(o)):n(new b(o))}const r=this._manager.onDeviceDisconnected(t.id,(o,E)=>{this._handleDeviceDisconnected(o,E)}),v=this._mapServicesUUIDsToBluetoothDeviceInfo(s).caseOf({Right:o=>o,Left:o=>n(new b(o))}),a=v.deviceModel,g={id:t.id,bleDeviceInfos:v},d=this._deviceApduSenderFactory({apduSenderFactory:this._apduSenderFactory,apduReceiverFactory:this._apduReceiverFactory,dependencies:{device:t,internalDevice:g,manager:this._manager}},this._loggerServiceFactory),l=f.OS==="ios"?H:z,m=this._deviceConnectionStateMachineFactory({deviceId:e.deviceId,deviceApduSender:d,timeoutDuration:l,tryToReconnect:()=>{this.tryToReconnect(e.deviceId)},onTerminated:()=>{try{this._safeCancel(e.deviceId),e.onDisconnect(e.deviceId),this._deviceConnectionsById.delete(e.deviceId),r.remove(),this._reconnectionSubscription.isJust()&&(this._reconnectionSubscription.map(o=>o.unsubscribe()),this._reconnectionSubscription=c.zero())}catch(o){this._logger.error("Error in termination of device connection",{data:{e:o}})}}});return await d.setupConnection().catch(o=>{throw this._safeCancel(e.deviceId),r.remove(),o}),this._deviceConnectionsById.set(e.deviceId,m),new y({id:t.id,deviceModel:a,type:"BLE",sendApdu:(...o)=>m.sendApdu(...o),transport:this.identifier})}).run()}async disconnect(e){const i=e.connectedDevice.id,n=this._deviceConnectionsById.get(i);if(!n)throw new O(`No connected device found with id ${i}`);return n.closeConnection(),Promise.resolve(h(void 0))}isSupported(){return this._isSupported.caseOf({Just:e=>e,Nothing:()=>{throw new Error("Should initialize permission")}})}getIdentifier(){return this.identifier}async requestPermission(){if(this._platform.OS==="ios")return this._isSupported=c.of(!0),!0;if(this._platform.OS==="android"&&this._permissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION){if(parseInt(this._platform.Version.toString(),10)<31){const i=await this._permissionsAndroid.request(this._permissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);this._isSupported=c.of(i===this._permissionsAndroid.RESULTS.GRANTED)}if(this._permissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN&&this._permissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT){const i=await this._permissionsAndroid.requestMultiple([this._permissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN,this._permissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT,this._permissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION]);return this._isSupported=c.of(i["android.permission.BLUETOOTH_CONNECT"]===this._permissionsAndroid.RESULTS.GRANTED&&i["android.permission.BLUETOOTH_SCAN"]===this._permissionsAndroid.RESULTS.GRANTED&&i["android.permission.ACCESS_FINE_LOCATION"]===this._permissionsAndroid.RESULTS.GRANTED),!0}}return this._logger.error("Permission have not been granted",{data:{isSupported:this._isSupported.extract()}}),this._isSupported=c.of(!1),!1}_handleDeviceDisconnected(e,i){if(this._logger.debug("[RNBLE][_handleDeviceDisconnected]",{data:{error:e,device:i}}),!i){this._logger.debug("[_handleDeviceDisconnected] disconnected handler didn't find device");return}if(!i?.id||!this._deviceConnectionsById.has(i?.id))return;if(e){this._logger.error("device disconnected error",{data:{error:e,device:i}});return}const n=i.id;this._reconnectionSubscription.isJust()||c.fromNullable(this._deviceConnectionsById.get(n)).map(t=>t.eventDeviceDisconnected())}tryToReconnect(e){const i=D([0]).pipe(p(async()=>{await this._stopScanning(),await this._safeCancel(e)}),p(async()=>{this._logger.debug("[_handleDeviceDisconnected] reconnecting to device",{data:{id:e}});const n=await this._manager.connectToDevice(e,{requestMTU:C,timeout:2e3});this._logger.debug("[_handleDeviceDisconnected] reconnected to device",{data:{id:e}});const t=await n.discoverAllServicesAndCharacteristics();return this._logger.debug("[_handleDeviceDisconnected] discovered all services and characteristics",{data:{reconnectedDeviceUsable:t}}),await this._handleDeviceReconnected(t),t}),P(5));this._reconnectionSubscription=c.of(i.subscribe({next:n=>this._logger.debug("[_handleDeviceDisconnected] Reconnected to device",{data:{id:n.id}}),complete:()=>{this._reconnectionSubscription=c.zero()},error:n=>{this._logger.error("[_handleDeviceDisconnected] All reconnection attempts failed",{data:{e:n}}),c.fromNullable(this._deviceConnectionsById.get(e)).map(t=>t.closeConnection()),this._reconnectionSubscription=c.zero()}}))}async _handleDeviceReconnected(e){const i=c.fromNullable(this._deviceConnectionsById.get(e.id)).toEither(new G);return T(async({liftEither:n,throwE:t})=>{const s=await n(i),r=(await e.services()).map(a=>a.uuid),v=this._mapServicesUUIDsToBluetoothDeviceInfo(r).caseOf({Right:a=>({id:e.id,bleDeviceInfos:a}),Left:a=>(this._logger.error("Error in mapping services UUIDs to Bluetooth device info",{data:{error:a}}),t(a))});s.setDependencies({device:e,manager:this._manager,internalDevice:v}),await s.setupConnection().catch(a=>{throw this._safeCancel(e.id),a}),s.eventDeviceConnected()}).run()}async _safeCancel(e){if(typeof this._manager.cancelDeviceConnection=="function"){const i=await this._manager.connectedDevices(this._deviceModelDataSource.getBluetoothServices());for(const n of i)n.id===e&&await this._manager.cancelDeviceConnection(e)}}}const re=({deviceModelDataSource:_,loggerServiceFactory:e,apduSenderServiceFactory:i,apduReceiverServiceFactory:n})=>new Y(_,e,i,n,new B);export{Y as RNBleTransport,re as RNBleTransportFactory,te as rnBleTransportIdentifier};
|
|
1
|
+
import{Platform as b}from"react-native";import{BleError as y,BleErrorCode as N,State as u}from"react-native-ble-plx";import{DeviceConnectionStateMachine as P,OpeningConnectionError as m,TransportConnectedDevice as I,UnknownDeviceError as U}from"@ledgerhq/device-management-kit";import{Either as w,EitherAsync as C,Left as T,Maybe as v,Right as S}from"purify-ts";import{BehaviorSubject as D,defer as F,finalize as O,first as q,from as _,retry as L,switchMap as h,tap as f,throttleTime as k}from"rxjs";import{BLE_DISCONNECT_TIMEOUT_ANDROID as j,BLE_DISCONNECT_TIMEOUT_IOS as $,CONNECTION_LOST_DELAY as x,DEFAULT_MTU as B}from"../model/Const";import{BleNotSupported as R,BlePermissionsNotGranted as M,BlePoweredOff as z,DeviceConnectionNotFound as H,NoDeviceModelFoundError as E,PeerRemovedPairingError as A}from"../model/Errors";import{RNBleApduSender as G}from"../transport/RNBleApduSender";const ne="RN_BLE";class te{constructor(e,n,i,t,o,a,r,s=1e3,p=d=>new P(d),g=(d,l)=>new G(d,l)){this._deviceModelDataSource=e;this._loggerServiceFactory=n;this._apduSenderFactory=i;this._apduReceiverFactory=t;this._manager=o;this._platform=a;this._permissionsService=r;this._scanThrottleDelayMs=s;this._deviceConnectionStateMachineFactory=p;this._deviceApduSenderFactory=g;this._logger=n("ReactNativeBleTransport"),this._deviceConnectionsById=new Map,this._reconnectionSubscription=v.zero();let d=!1;this._manager.onStateChange(l=>{this._logger.debug(`[manager.onStateChange] called with state: ${l}`),this._bleStateSubject.next(l),d=l===u.Unknown,d&&(this._logger.debug('[manager.onStateChange] forcing state update from "Unknown"'),this._manager.state().then(c=>{d&&(this._logger.debug(`[manager.onStateChange] forcing state update to: "${c}"`),this._bleStateSubject.next(c))}))},!0)}_logger;_deviceConnectionsById;identifier="RN_BLE";_reconnectionSubscription;_bleStateSubject=new D(u.Unknown);observeBleState(){return this._bleStateSubject.asObservable()}startDiscovering(){return _([])}async stopDiscovering(){await this._stopScanning()}_scannedDevicesSubject=new D([]);_startedScanningSubscriber=void 0;_waitForScanningPrerequisites(){return _([!0]).pipe(f(()=>{if(!this.isSupported())throw new R("BLE not supported");this._logger.debug("[waitForScanningPrerequisites] Prerequisite: isSupported=true")}),h(async()=>this.checkAndRequestPermissions()),f(e=>{if(this._logger.debug(`[_waitForScanningPrerequisites] Prerequisite: hasPermissions=${e}`),!e)throw new M("Permissions not granted")}),h(()=>this.observeBleState()),q(e=>{const n=e===u.PoweredOn;if(this._logger.info(`[waitForScanningPrerequisites] Prerequisite: BLE state=${e}, canStartScanning=${n}`),e===u.PoweredOff)throw new z;if(e===u.Unauthorized)throw new M('Ble State is "Unauthorized"');if(e===u.Unsupported)throw new R;return n}))}_startScanning(){if(this._startedScanningSubscriber!=null){this._logger.info("[startScanning] !! startScanning already started");return}this._scannedDevicesSubject.next([]),this._logger.info("[startScanning] startScanning"),this._startedScanningSubscriber=_([!0]).pipe(h(()=>{const e=new D([]),n=new Map;this._logger.info("[startScanning] startDeviceScan"),this._manager.startDeviceScan(this._deviceModelDataSource.getBluetoothServices(),{allowDuplicates:!0},(t,o)=>{if(t){this._logger.error("[startScanning] Error in startDeviceScan callback",{data:{error:t,rnDevice:o}}),e.error(t);return}if(!o){this._logger.warn("[startScanning] Null Device in startDeviceScan callback",{data:{rnDevice:o}}),e.error(new Error("Null device in startDeviceScan callback"));return}n.set(o.id,{device:o,timestamp:Date.now()}),e.next(Array.from(n.values()))}).catch(t=>{e.error(t),this._logger.error("[startScanning] Error while calling startDeviceScan",{data:{error:t}})}),this._logger.debug("[startScanning] after startDeviceScan");const i=setInterval(()=>{e.next(Array.from(n.values()))},1e3);return e.pipe(O(()=>{this._logger.debug("[startScanning] finalize"),e.complete(),clearInterval(i),this._stopScanning()}))}),k(this._scanThrottleDelayMs)).subscribe({next:e=>{this._scannedDevicesSubject.next(e)},error:e=>{this._logger.error("[startScanning] Error while scanning",{data:{error:e}}),this._scannedDevicesSubject.error(e)}})}async _stopScanning(){this._logger.debug("[stopScanning] stopScanning"),await this._manager.stopDeviceScan(),this._startedScanningSubscriber?.unsubscribe(),this._startedScanningSubscriber=void 0,this._scannedDevicesSubject.complete(),this._scannedDevicesSubject=new D([])}listenToAvailableDevices(){return this._waitForScanningPrerequisites().pipe(f(()=>this._startScanning()),h(()=>this._scannedDevicesSubject),h(async e=>{const n=e.filter(({timestamp:r})=>r>Date.now()-x).sort((r,s)=>(s.device.rssi??-1/0)-(r.device.rssi??-1/0)).map(({device:r})=>this._mapDeviceToTransportDiscoveredDevice(r,r.serviceUUIDs)).filter(r=>!!r),i=w.rights(n),t=await this._manager.connectedDevices(this._deviceModelDataSource.getBluetoothServices()).catch(r=>{throw this._logger.error("[listenToAvailableDevices] Error calling manager.connectedDevices",{data:{error:r}}),r}),o=await Promise.all(t.map(async r=>{try{const p=(await r.services()).map(g=>g.uuid);return this._mapDeviceToTransportDiscoveredDevice(r,p)}catch(s){return this._logger.error("[listenToAvailableDevices] Error in mapping device to transport discovered device",{data:{e:s}}),T(new E(`Error in mapping device to transport discovered device: ${s}`))}})),a=w.rights(o);return this._logger.debug("[listenToAvailableDevices]",{data:{rawConnectedDevices:t.map(r=>r.name),connectedDevices:a.map(r=>r.name),scannedDevices:i.map(r=>r.name)}}),[...a,...i]}))}_mapServicesUUIDsToBluetoothDeviceInfo(e){for(const n of e||[]){const i=this._deviceModelDataSource.getBluetoothServicesInfos()[n];if(i)return S(i)}return T(new E(`No device model found for [uuids=${e}]`))}_mapServicesUUIDsToDeviceModel(e){return this._mapServicesUUIDsToBluetoothDeviceInfo(e).map(i=>i.deviceModel)}_mapDeviceToTransportDiscoveredDevice(e,n){return this._mapServicesUUIDsToDeviceModel(n).map(t=>({id:e.id,name:e.localName||e.name||"",deviceModel:t,transport:this.identifier,rssi:e.rssi||void 0}))}async connect(e){this._logger.debug("[connect] Called",{data:{deviceId:e.deviceId}});const n=this._deviceConnectionsById.get(e.deviceId);if(n){this._logger.debug("[connect] Existing device connection found",{data:{deviceId:e.deviceId}});const i=n.getDependencies().internalDevice.bleDeviceInfos.deviceModel;return S(new I({id:e.deviceId,deviceModel:i,type:"BLE",sendApdu:(...t)=>n.sendApdu(...t),transport:this.identifier}))}return this._logger.debug("[connect] No existing device connection found, establishing one",{data:{deviceId:e.deviceId}}),await this._stopScanning(),await this._safeCancel(e.deviceId),C(async({throwE:i})=>{let t,o=[];try{await this._manager.connectToDevice(e.deviceId,{requestMTU:B}),t=await this._manager.discoverAllServicesAndCharacteristicsForDevice(e.deviceId),o=(await t.services()).map(c=>c.uuid)}catch(c){return c instanceof y&&c.iosErrorCode===14?i(new A(c)):c instanceof y&&c.errorCode===N.OperationCancelled&&b.OS==="android"?i(new A(c)):i(new m(c))}const a=this._listenToDeviceDisconnected(e.deviceId),r=this._mapServicesUUIDsToBluetoothDeviceInfo(o).caseOf({Right:c=>c,Left:c=>i(new m(c))}),s=r.deviceModel,p={id:t.id,bleDeviceInfos:r},g=this._deviceApduSenderFactory({apduSenderFactory:this._apduSenderFactory,apduReceiverFactory:this._apduReceiverFactory,dependencies:{device:t,internalDevice:p,manager:this._manager}},this._loggerServiceFactory),d=b.OS==="ios"?$:j,l=this._deviceConnectionStateMachineFactory({deviceId:e.deviceId,deviceApduSender:g,timeoutDuration:d,tryToReconnect:()=>this.tryToReconnect(e.deviceId),onTerminated:async()=>{this._logger.debug("[onTerminated]",{data:{deviceId:e.deviceId}});try{await this._safeCancel(e.deviceId)}catch(c){this._logger.error("[onTerminated] Error in termination of device connection",{data:{e:c}})}finally{this._deviceConnectionsById.delete(e.deviceId),this._reconnectionSubscription.ifJust(c=>{c.unsubscribe(),this._reconnectionSubscription=v.zero()}),this._logger.debug("[onTerminated] signaling disconnection",{data:{deviceId:e.deviceId}}),e.onDisconnect(e.deviceId)}}});return await g.setupConnection().catch(c=>{throw this._safeCancel(e.deviceId),a.remove(),c}),this._deviceConnectionsById.set(e.deviceId,l),new I({id:t.id,deviceModel:s,type:"BLE",sendApdu:(...c)=>l.sendApdu(...c),transport:this.identifier})}).run()}async disconnect(e){const n=e.connectedDevice.id,i=this._deviceConnectionsById.get(n);if(!i)throw new U(`No connected device found with id ${n}`);return i.closeConnection(),Promise.resolve(S(void 0))}isSupported(){return["android","ios"].includes(this._platform.OS)}getIdentifier(){return this.identifier}async checkAndRequestPermissions(){return this._logger.debug("[checkAndRequestPermissions] Called"),await this._permissionsService.checkRequiredPermissions()?!0:await this._permissionsService.requestRequiredPermissions()}_handleDeviceDisconnected(e,n){if(this._logger.debug("[_handleDeviceDisconnected]",{data:{error:e,device:n}}),!n){this._logger.debug("[_handleDeviceDisconnected] disconnected handler didn't find device");return}if(!n?.id||!this._deviceConnectionsById.has(n?.id))return;if(e){this._logger.error("device disconnected error",{data:{error:e,device:n}});return}const i=n.id;v.fromNullable(this._deviceConnectionsById.get(i)).map(t=>t.eventDeviceDisconnected())}_listenToDeviceDisconnected(e){const n=this._manager.onDeviceDisconnected(e,(i,t)=>{this._handleDeviceDisconnected(i,t),n.remove()});return n}async tryToReconnect(e){this._logger.debug("[tryToReconnect] Called",{data:{deviceId:e}});let n=0;await this._stopScanning(),await this._safeCancel(e);const i=F(async()=>{let t=null;n++;try{this._logger.debug(`[tryToReconnect](try=${n}) Reconnecting to device`,{data:{id:e}});const o=await this._manager.connectToDevice(e,{requestMTU:B,timeout:2e3});this._logger.debug(`[tryToReconnect](try=${n}) Established connection to device`,{data:{id:e}});const a=await o.discoverAllServicesAndCharacteristics();return this._logger.debug(`[tryToReconnect](try=${n}) Discovered all services and characteristics`,{data:{usableReconnectedDevice:a}}),t=this._listenToDeviceDisconnected(e),await this._handleDeviceReconnected(a),a}catch(o){throw this._logger.warn(`[tryToReconnect](try=${n}) Reconnecting to device failed`,{data:{e:o}}),t?.remove(),await this._stopScanning(),await this._safeCancel(e),o}}).pipe(L(5));this._reconnectionSubscription=v.of(i.subscribe({next:t=>this._logger.debug(`[tryToReconnect](try=${n}) Fully reconnected to device (id=${t.id})`),complete:()=>{this._logger.debug("[tryToReconnect] Completed"),this._reconnectionSubscription=v.zero()},error:t=>{this._logger.error("[tryToReconnect] All reconnection attempts failed",{data:{e:t}}),this._deviceConnectionsById.get(e)?.closeConnection(),this._reconnectionSubscription=v.zero()}}))}async _handleDeviceReconnected(e){const n=v.fromNullable(this._deviceConnectionsById.get(e.id)).toEither(new H);return C(async({liftEither:i,throwE:t})=>{const o=await i(n),a=(await e.services()).map(s=>s.uuid),r=this._mapServicesUUIDsToBluetoothDeviceInfo(a).caseOf({Right:s=>({id:e.id,bleDeviceInfos:s}),Left:s=>(this._logger.error("[_handleDeviceReconnected] Error in mapping services UUIDs to Bluetooth device info",{data:{error:s}}),t(s))});o.setDependencies({device:e,manager:this._manager,internalDevice:r}),await o.setupConnection().catch(s=>{throw this._safeCancel(e.id),s}),o.eventDeviceConnected()}).run()}async _safeCancel(e){if(typeof this._manager.cancelDeviceConnection=="function"){const n=await this._manager.connectedDevices(this._deviceModelDataSource.getBluetoothServices());for(const i of n)if(i.id===e)try{await this._manager.cancelDeviceConnection(e)}catch(t){this._logger.error("[safeCancel] Error in cancelling device connection",{data:{e:t}})}}}}export{te as RNBleTransport,ne as rnBleTransportIdentifier};
|
|
2
2
|
//# sourceMappingURL=RNBleTransport.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/api/transport/RNBleTransport.ts"],
|
|
4
|
-
"sourcesContent": ["import { PermissionsAndroid, Platform } from \"react-native\";\nimport { BleError, BleManager, type Device, State } from \"react-native-ble-plx\";\nimport {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n type BleDeviceInfos,\n type ConnectError,\n DeviceConnectionStateMachine,\n type DeviceConnectionStateMachineParams,\n type DeviceId,\n type DeviceModelDataSource,\n type DisconnectHandler,\n type DmkError,\n type LoggerPublisherService,\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 { Either, EitherAsync, Left, Maybe, Nothing, Right } from \"purify-ts\";\nimport {\n BehaviorSubject,\n filter,\n finalize,\n from,\n map,\n type Observable,\n retry,\n type Subscription,\n switchMap,\n throttleTime,\n throwError,\n} from \"rxjs\";\n\nimport {\n BLE_DISCONNECT_TIMEOUT_ANDROID,\n BLE_DISCONNECT_TIMEOUT_IOS,\n CONNECTION_LOST_DELAY,\n DEFAULT_MTU,\n} from \"@api/model/Const\";\nimport {\n BleNotSupported,\n DeviceConnectionNotFound,\n NoDeviceModelFoundError,\n PeerRemovedPairingError,\n} from \"@api/model/Errors\";\nimport {\n RNBleApduSender,\n type RNBleApduSenderConstructorArgs,\n type RNBleApduSenderDependencies,\n type RNBleInternalDevice,\n} from \"@api/transport/RNBleApduSender\";\n\nexport const rnBleTransportIdentifier = \"RN_BLE\";\n\ntype InternalScannedDevice = {\n device: Device;\n timestamp: number;\n};\n\nexport class RNBleTransport implements Transport {\n private _logger: LoggerPublisherService;\n private _isSupported: Maybe<boolean>;\n private _deviceConnectionsById: Map<\n DeviceId,\n DeviceConnectionStateMachine<RNBleApduSenderDependencies>\n >;\n // private readonly _manager: BleManager;\n private readonly identifier: TransportIdentifier = \"RN_BLE\";\n private _reconnectionSubscription: Maybe<Subscription>;\n private readonly _bleStateSubject: BehaviorSubject<State> =\n new BehaviorSubject<State>(State.Unknown);\n\n constructor(\n private readonly _deviceModelDataSource: DeviceModelDataSource,\n private readonly _loggerServiceFactory: (\n tag: string,\n ) => LoggerPublisherService,\n private readonly _apduSenderFactory: ApduSenderServiceFactory,\n private readonly _apduReceiverFactory: ApduReceiverServiceFactory,\n private readonly _manager: BleManager,\n private readonly _platform: Platform = Platform,\n private readonly _permissionsAndroid: PermissionsAndroid = PermissionsAndroid,\n private readonly _deviceConnectionStateMachineFactory: (\n args: DeviceConnectionStateMachineParams<RNBleApduSenderDependencies>,\n ) => DeviceConnectionStateMachine<RNBleApduSenderDependencies> = (args) =>\n new DeviceConnectionStateMachine(args),\n private readonly _deviceApduSenderFactory: (\n args: RNBleApduSenderConstructorArgs,\n loggerFactory: (tag: string) => LoggerPublisherService,\n ) => RNBleApduSender = (args, loggerFactory) =>\n new RNBleApduSender(args, loggerFactory),\n ) {\n this._logger = _loggerServiceFactory(\"ReactNativeBleTransport\");\n this._isSupported = Maybe.zero();\n this._deviceConnectionsById = new Map();\n this._reconnectionSubscription = Maybe.zero();\n this._manager.onStateChange((state) => {\n this._bleStateSubject.next(state);\n }, true);\n }\n\n /**\n * Not implemented for now as the return signature is not really usable.\n * Use listenToAvailableDevices instead.\n */\n startDiscovering(): Observable<TransportDiscoveredDevice> {\n return from([]);\n }\n\n /**\n * Stops the device scanning operation currently in progress.\n *\n * @return {Promise<void>} A promise that resolves once the device scanning has been successfully stopped.\n */\n async stopDiscovering(): Promise<void> {\n await this._stopScanning();\n }\n\n private _maybeScanningSubject: Maybe<\n BehaviorSubject<InternalScannedDevice[]>\n > = Nothing;\n\n private _scannedDevicesSubject: BehaviorSubject<InternalScannedDevice[]> =\n new BehaviorSubject<InternalScannedDevice[]>([]);\n private _startedScanningSubscriber: Subscription | undefined = undefined;\n\n private _startScanning() {\n if (this._startedScanningSubscriber != undefined) {\n return;\n }\n\n //Reset the scanned devices list as new scan will start\n this._scannedDevicesSubject.next([]);\n\n this._startedScanningSubscriber = from(this._bleStateSubject)\n .pipe(\n filter((state) => state === \"PoweredOn\"),\n switchMap(() => this.requestPermission()),\n switchMap((isSupported) => {\n if (!isSupported) {\n return throwError(() => new BleNotSupported(\"BLE not supported\"));\n }\n\n const subject = new BehaviorSubject<InternalScannedDevice[]>([]);\n this._maybeScanningSubject = Maybe.of(subject);\n const devicesById = new Map<string, InternalScannedDevice>();\n\n this._logger.info(\"[RNBleTransport][startScanning] startDeviceScan\");\n this._manager.startDeviceScan(\n this._deviceModelDataSource.getBluetoothServices(),\n { allowDuplicates: true },\n (error, rnDevice) => {\n if (error || !rnDevice) {\n subject.error(error || new Error(\"scan error\"));\n return;\n }\n devicesById.set(rnDevice.id, {\n device: rnDevice,\n timestamp: Date.now(),\n });\n subject.next(Array.from(devicesById.values()));\n },\n );\n\n /**\n * In case there is no update from startDeviceScan, we still emit the\n * list of devices. This is useful for instance if there is only 1 device\n * in the vicinity and it just got turned off. It will not \"advertise\"\n * anymore so startDeviceScan won't trigger.\n */\n const interval = setInterval(() => {\n subject.next(Array.from(devicesById.values()));\n }, 1000);\n\n return subject.asObservable().pipe(\n finalize(() => {\n this._logger.debug(\"[RNBleTransport][startScanning] finalize\");\n subject.complete();\n clearInterval(interval);\n this._maybeScanningSubject = Nothing;\n this._manager.stopDeviceScan();\n }),\n );\n }),\n throttleTime(1000),\n )\n .subscribe({\n next: (devices) => {\n this._logger.debug(\n \"[RNBleTransport][startScanning] onNext called with devices\",\n { data: { devices } },\n );\n this._scannedDevicesSubject.next(devices);\n },\n error: (error) => {\n this._logger.error(\"Error while scanning\", { data: { error } });\n },\n });\n }\n\n private async _stopScanning(): Promise<void> {\n this._maybeScanningSubject.map((subject) => {\n subject.complete();\n this._maybeScanningSubject = Nothing;\n });\n\n await this._manager.stopDeviceScan();\n //Stop listening the observable from this._startScanning()\n this._startedScanningSubscriber?.unsubscribe();\n this._startedScanningSubscriber = undefined;\n\n return;\n }\n\n /**\n * Listens to known devices and emits updates when new devices are discovered or when properties of existing devices are updated.\n *\n * @return {Observable<TransportDiscoveredDevice[]>} An observable stream of discovered devices, containing device information as an array of TransportDiscoveredDevice objects.\n */\n listenToAvailableDevices(): Observable<TransportDiscoveredDevice[]> {\n this._startScanning();\n\n return this._scannedDevicesSubject.asObservable().pipe(\n map((internalScannedDevices) => {\n const eitherConnectedDevices = Array.from(\n this._deviceConnectionsById.values(),\n ).map((connection) =>\n this._mapDeviceToTransportDiscoveredDevice(\n connection.getDependencies().device,\n [\n connection.getDependencies().internalDevice.bleDeviceInfos\n .serviceUuid,\n ],\n ),\n );\n\n const connectedDevices = Either.rights(eitherConnectedDevices);\n\n const eitherScannedDevices = internalScannedDevices\n .filter(\n ({ timestamp }) => timestamp > Date.now() - CONNECTION_LOST_DELAY,\n )\n .sort(\n (a, b) =>\n (b.device.rssi ?? -Infinity) - (a.device.rssi ?? -Infinity), // RSSI is a negative value and the higher, the stronger the signal\n )\n .map(({ device }) =>\n this._mapDeviceToTransportDiscoveredDevice(\n device,\n device.serviceUUIDs,\n ),\n )\n .filter((d) => !!d);\n\n const scannedDevices = Either.rights(eitherScannedDevices);\n\n return [...connectedDevices, ...scannedDevices];\n }),\n );\n }\n\n private _mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, BleDeviceInfos> {\n for (const serviceUUID of servicesUUIDs || []) {\n const bluetoothServiceInfo =\n this._deviceModelDataSource.getBluetoothServicesInfos()[serviceUUID];\n if (bluetoothServiceInfo) return Right(bluetoothServiceInfo);\n }\n\n return Left(\n new NoDeviceModelFoundError(\n `No device model found for [uuids=${servicesUUIDs}]`,\n ),\n );\n }\n\n private _mapServicesUUIDsToDeviceModel(\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, TransportDeviceModel> {\n const bluetoothServiceInfo =\n this._mapServicesUUIDsToBluetoothDeviceInfo(servicesUUIDs);\n return bluetoothServiceInfo.map((info) => info.deviceModel);\n }\n\n private _mapDeviceToTransportDiscoveredDevice(\n device: Device,\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, TransportDiscoveredDevice> {\n const deviceModel = this._mapServicesUUIDsToDeviceModel(servicesUUIDs);\n return deviceModel.map((model) => ({\n id: device.id,\n name: device.localName || device.name || \"\",\n deviceModel: model,\n transport: this.identifier,\n rssi: device.rssi || undefined,\n }));\n }\n\n /**\n * Establishes a connection to a device and configures the necessary parameters for communication.\n *\n * @param {Object} params - An object containing parameters required for the connection.\n * @param {DeviceId} params.deviceId - The unique identifier of the device to connect to.\n * @param {DisconnectHandler} params.onDisconnect - A callback function to handle device disconnection.\n * @returns {Promise<Either<ConnectError, TransportConnectedDevice>>} A promise resolving to either a connection error or a successfully connected device.\n */\n async connect(params: {\n deviceId: DeviceId;\n onDisconnect: DisconnectHandler;\n }): Promise<Either<ConnectError, TransportConnectedDevice>> {\n const existing = this._deviceConnectionsById.get(params.deviceId);\n if (existing) {\n const deviceModel =\n existing.getDependencies().internalDevice.bleDeviceInfos.deviceModel;\n return Right(\n new TransportConnectedDevice({\n id: params.deviceId,\n deviceModel: deviceModel,\n type: \"BLE\",\n sendApdu: (...a) => existing.sendApdu(...a),\n transport: this.identifier,\n }),\n );\n }\n\n await this._stopScanning();\n await this._safeCancel(params.deviceId);\n\n return EitherAsync<ConnectError, TransportConnectedDevice>(\n async ({ throwE }) => {\n let device: Device;\n let servicesUUIDs: string[] = [];\n try {\n await this._manager.connectToDevice(params.deviceId, {\n requestMTU: DEFAULT_MTU,\n });\n\n device =\n await this._manager.discoverAllServicesAndCharacteristicsForDevice(\n params.deviceId,\n );\n\n servicesUUIDs = (await device.services()).map((s) => s.uuid);\n } catch (error) {\n if (\n error instanceof BleError &&\n (error.iosErrorCode as number) === 14\n ) {\n /**\n * This happens when the Ledger device reset its pairing, but the\n * iOS system still has that device paired.\n */\n return throwE(new PeerRemovedPairingError(error));\n }\n return throwE(new OpeningConnectionError(error));\n }\n\n const disconnectionSubscription = this._manager.onDeviceDisconnected(\n device.id,\n (error, d) => {\n this._handleDeviceDisconnected(error, d);\n },\n );\n\n const bleDeviceInfos = this._mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs,\n ).caseOf({\n Right: (info) => {\n return info;\n },\n Left: (error) => {\n return throwE(new OpeningConnectionError(error));\n },\n });\n\n const deviceModel = bleDeviceInfos.deviceModel;\n\n const internalDevice: RNBleInternalDevice = {\n id: device.id,\n bleDeviceInfos,\n };\n\n const deviceApduSender = this._deviceApduSenderFactory(\n {\n apduSenderFactory: this._apduSenderFactory,\n apduReceiverFactory: this._apduReceiverFactory,\n dependencies: { device, internalDevice, manager: this._manager },\n },\n this._loggerServiceFactory,\n );\n\n const reconnectionTimeout =\n Platform.OS === \"ios\"\n ? BLE_DISCONNECT_TIMEOUT_IOS\n : BLE_DISCONNECT_TIMEOUT_ANDROID;\n\n const deviceConnectionStateMachine =\n this._deviceConnectionStateMachineFactory({\n deviceId: params.deviceId,\n deviceApduSender,\n timeoutDuration: reconnectionTimeout,\n tryToReconnect: () => {\n this.tryToReconnect(params.deviceId);\n },\n onTerminated: () => {\n try {\n this._safeCancel(params.deviceId);\n params.onDisconnect(params.deviceId);\n this._deviceConnectionsById.delete(params.deviceId);\n disconnectionSubscription.remove();\n if (this._reconnectionSubscription.isJust()) {\n this._reconnectionSubscription.map((sub) =>\n sub.unsubscribe(),\n );\n this._reconnectionSubscription = Maybe.zero();\n }\n } catch (e) {\n this._logger.error(\n \"Error in termination of device connection\",\n { data: { e } },\n );\n }\n },\n });\n\n await deviceApduSender.setupConnection().catch((e) => {\n this._safeCancel(params.deviceId);\n disconnectionSubscription.remove();\n throw e;\n });\n\n this._deviceConnectionsById.set(\n params.deviceId,\n deviceConnectionStateMachine,\n );\n\n return new TransportConnectedDevice({\n id: device.id,\n deviceModel: deviceModel,\n type: \"BLE\",\n sendApdu: (...args) => deviceConnectionStateMachine.sendApdu(...args),\n transport: this.identifier,\n });\n },\n ).run();\n }\n\n /**\n * Terminates the connection with the connected device and cleans up related resources.\n *\n * @param {TransportConnectedDevice} params.connectedDevice - The connected device to be disconnected.\n * @return {Promise<Either<DmkError, void>>} A promise resolving to either a success (void) or a failure (DmkError) value.\n */\n async disconnect(params: {\n connectedDevice: TransportConnectedDevice;\n }): Promise<Either<DmkError, void>> {\n const deviceId = params.connectedDevice.id;\n const deviceConnection = this._deviceConnectionsById.get(deviceId);\n if (!deviceConnection) {\n throw new UnknownDeviceError(\n `No connected device found with id ${deviceId}`,\n );\n }\n\n deviceConnection.closeConnection();\n\n return Promise.resolve(Right(undefined));\n }\n\n /**\n * Determines if the feature or permission is supported.\n *\n * This method evaluates the current state of the `_isSupported` property to determine\n * whether the relevant feature is supported or throws an error if its state has\n * not been initialized properly.\n *\n * @return {boolean} Returns `true` if the feature is supported, otherwise `false`.\n * Throws an error if the `_isSupported` property has not been initialized.\n */\n isSupported(): boolean {\n return this._isSupported.caseOf({\n Just: (isSupported) => isSupported,\n Nothing: () => {\n throw new Error(\"Should initialize permission\");\n },\n });\n }\n\n /**\n * Retrieves the transport identifier associated with the object.\n *\n * @return {TransportIdentifier} The transport identifier.\n */\n getIdentifier(): TransportIdentifier {\n return this.identifier;\n }\n\n /**\n * Requests the necessary permissions based on the operating system.\n * For iOS, it automatically sets the permissions as granted.\n * For Android, it checks and requests location, Bluetooth scan, and Bluetooth connect permissions, depending on the API level.\n * If permissions are granted, updates the internal support state and logs the result.\n *\n * @return {Promise<boolean>} A promise that resolves to true if the required permissions are granted, otherwise false.\n */\n async requestPermission(): Promise<boolean> {\n if (this._platform.OS === \"ios\") {\n this._isSupported = Maybe.of(true);\n return true;\n }\n\n if (\n this._platform.OS === \"android\" &&\n this._permissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"]\n ) {\n const apiLevel = parseInt(this._platform.Version.toString(), 10);\n\n if (apiLevel < 31) {\n const granted = await this._permissionsAndroid.request(\n this._permissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"],\n );\n this._isSupported = Maybe.of(\n granted === this._permissionsAndroid.RESULTS[\"GRANTED\"],\n );\n }\n if (\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_SCAN\"] &&\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_CONNECT\"]\n ) {\n const result = await this._permissionsAndroid.requestMultiple([\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_SCAN\"],\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_CONNECT\"],\n this._permissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"],\n ]);\n\n this._isSupported = Maybe.of(\n result[\"android.permission.BLUETOOTH_CONNECT\"] ===\n this._permissionsAndroid.RESULTS[\"GRANTED\"] &&\n result[\"android.permission.BLUETOOTH_SCAN\"] ===\n this._permissionsAndroid.RESULTS[\"GRANTED\"] &&\n result[\"android.permission.ACCESS_FINE_LOCATION\"] ===\n this._permissionsAndroid.RESULTS[\"GRANTED\"],\n );\n\n return true;\n }\n }\n\n this._logger.error(\"Permission have not been granted\", {\n data: { isSupported: this._isSupported.extract() },\n });\n\n this._isSupported = Maybe.of(false);\n return false;\n }\n\n /**\n * Handles the event when a Bluetooth device gets disconnected. This method attempts\n * to reconnect to the device, retries a certain number of times on failure, and\n * invokes a callback if the reconnection does not succeed.\n *\n * @param {BleError | null} error - The error object representing the reason for the disconnection, or null if no error occurred.\n * @param {Device | null} device - The Bluetooth device that was disconnected, or null if no device is provided.\n * @return {void}\n */\n private _handleDeviceDisconnected(\n error: BleError | null,\n device: Device | null,\n ) {\n this._logger.debug(\"[RNBLE][_handleDeviceDisconnected]\", {\n data: { error, device },\n });\n if (!device) {\n this._logger.debug(\n \"[_handleDeviceDisconnected] disconnected handler didn't find device\",\n );\n return;\n }\n if (!device?.id || !this._deviceConnectionsById.has(device?.id)) return;\n if (error) {\n this._logger.error(\"device disconnected error\", {\n data: { error, device },\n });\n return;\n }\n const deviceId = device.id;\n if (this._reconnectionSubscription.isJust()) {\n return;\n }\n\n Maybe.fromNullable(this._deviceConnectionsById.get(deviceId)).map(\n (deviceConnection) => deviceConnection.eventDeviceDisconnected(),\n );\n }\n\n private tryToReconnect(deviceId: DeviceId) {\n const reconnect$ = from([0]).pipe(\n switchMap(async () => {\n await this._stopScanning();\n await this._safeCancel(deviceId);\n }),\n switchMap(async () => {\n this._logger.debug(\n \"[_handleDeviceDisconnected] reconnecting to device\",\n { data: { id: deviceId } },\n );\n const reconnectedDevice = await this._manager.connectToDevice(\n deviceId,\n { requestMTU: DEFAULT_MTU, timeout: 2000 },\n );\n this._logger.debug(\n \"[_handleDeviceDisconnected] reconnected to device\",\n { data: { id: deviceId } },\n );\n const reconnectedDeviceUsable =\n await reconnectedDevice.discoverAllServicesAndCharacteristics();\n this._logger.debug(\n \"[_handleDeviceDisconnected] discovered all services and characteristics\",\n { data: { reconnectedDeviceUsable } },\n );\n await this._handleDeviceReconnected(reconnectedDeviceUsable);\n return reconnectedDeviceUsable;\n }),\n retry(5),\n );\n\n this._reconnectionSubscription = Maybe.of(\n reconnect$.subscribe({\n next: (d) =>\n this._logger.debug(\n \"[_handleDeviceDisconnected] Reconnected to device\",\n { data: { id: d.id } },\n ),\n complete: () => {\n this._reconnectionSubscription = Maybe.zero();\n },\n error: (e) => {\n this._logger.error(\n \"[_handleDeviceDisconnected] All reconnection attempts failed\",\n { data: { e } },\n );\n Maybe.fromNullable(this._deviceConnectionsById.get(deviceId)).map(\n (sm) => sm.closeConnection(),\n );\n this._reconnectionSubscription = Maybe.zero();\n },\n }),\n );\n }\n\n /**\n * Handles the reconnection of a device. Configures the device connection and its corresponding\n * internal device upon reconnection, including updating the connection state, registering\n * callbacks for write and monitor operations, and initiating a reconnect operation.\n *\n * @param {Device} device - The ddevice object that has been reconnected. Contains device details,\n * such as the device ID.\n * @return {Promise<Either<DeviceConnectionNotFound | InternalDeviceNotFound, void>>} A promise that completes when the device reconnection has been fully\n * configured. Resolves with no value or rejects if an error occurs during\n * the reconnection process.\n */\n private async _handleDeviceReconnected(device: Device) {\n const errorOrDeviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(device.id),\n ).toEither(new DeviceConnectionNotFound());\n\n return EitherAsync(async ({ liftEither, throwE }) => {\n const deviceConnectionStateMachine = await liftEither(\n errorOrDeviceConnection,\n );\n\n const servicesUUIDs = (await device.services()).map((s) => s.uuid);\n\n const internalDevice = this._mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs,\n ).caseOf({\n Right: (info) => {\n return {\n id: device.id,\n bleDeviceInfos: info,\n };\n },\n Left: (error) => {\n this._logger.error(\n \"Error in mapping services UUIDs to Bluetooth device info\",\n {\n data: { error },\n },\n );\n\n return throwE(error);\n },\n });\n\n deviceConnectionStateMachine.setDependencies({\n device,\n manager: this._manager,\n internalDevice,\n });\n\n await deviceConnectionStateMachine.setupConnection().catch((e) => {\n this._safeCancel(device.id);\n throw e;\n });\n\n deviceConnectionStateMachine.eventDeviceConnected();\n }).run();\n }\n\n private async _safeCancel(deviceId: DeviceId) {\n // only invoke if the BleManager under test actually has it\n if (typeof this._manager.cancelDeviceConnection === \"function\") {\n const connectedDevices = await this._manager.connectedDevices(\n this._deviceModelDataSource.getBluetoothServices(),\n );\n\n for (const device of connectedDevices) {\n if (device.id === deviceId) {\n await this._manager.cancelDeviceConnection(deviceId);\n }\n }\n }\n }\n}\n\nexport const RNBleTransportFactory: TransportFactory = ({\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n}) =>\n new RNBleTransport(\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n new BleManager(),\n );\n"],
|
|
5
|
-
"mappings": "AAAA,OAAS,sBAAAA,EAAoB,YAAAC,MAAgB,eAC7C,OAAS,YAAAC,EAAU,cAAAC,EAAyB,SAAAC,MAAa,uBACzD,OAKE,gCAAAC,EAOA,0BAAAC,EAEA,4BAAAC,EAKA,sBAAAC,MACK,kCACP,OAAS,UAAAC,EAAQ,eAAAC,EAAa,QAAAC,EAAM,SAAAC,EAAO,WAAAC,EAAS,SAAAC,MAAa,YACjE,OACE,mBAAAC,EACA,UAAAC,EACA,YAAAC,EACA,QAAAC,EACA,OAAAC,EAEA,SAAAC,EAEA,aAAAC,EACA,gBAAAC,EACA,cAAAC,MACK,OAEP,OACE,kCAAAC,EACA,8BAAAC,EACA,yBAAAC,EACA,eAAAC,MACK,mBACP,OACE,mBAAAC,EACA,4BAAAC,EACA,2BAAAC,EACA,2BAAAC,MACK,oBACP,OACE,mBAAAC,MAIK,iCAEA,MAAMC,GAA2B,SAOjC,MAAMC,CAAoC,CAa/C,YACmBC,EACAC,EAGAC,EACAC,EACAC,EACAC,EAAsBvC,EACtBwC,EAA0CzC,EAC1C0C,EAEiDC,GAChE,IAAItC,EAA6BsC,CAAI,EACtBC,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form } from \"react-native\";\nimport {\n BleError,\n BleErrorCode,\n type BleManager,\n type Device,\n State,\n type Subscription as BleSubscription,\n} from \"react-native-ble-plx\";\nimport {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n type BleDeviceInfos,\n type ConnectError,\n DeviceConnectionStateMachine,\n type DeviceConnectionStateMachineParams,\n type DeviceId,\n type DeviceModelDataSource,\n type DisconnectHandler,\n type DmkError,\n type LoggerPublisherService,\n OpeningConnectionError,\n type Transport,\n TransportConnectedDevice,\n type TransportDeviceModel,\n type TransportDiscoveredDevice,\n type TransportIdentifier,\n UnknownDeviceError,\n} from \"@ledgerhq/device-management-kit\";\nimport { Either, EitherAsync, Left, Maybe, Right } from \"purify-ts\";\nimport {\n BehaviorSubject,\n defer,\n finalize,\n first,\n from,\n type Observable,\n retry,\n type Subscription,\n switchMap,\n tap,\n throttleTime,\n} from \"rxjs\";\n\nimport {\n BLE_DISCONNECT_TIMEOUT_ANDROID,\n BLE_DISCONNECT_TIMEOUT_IOS,\n CONNECTION_LOST_DELAY,\n DEFAULT_MTU,\n} from \"@api/model/Const\";\nimport {\n BleNotSupported,\n BlePermissionsNotGranted,\n BlePoweredOff,\n DeviceConnectionNotFound,\n NoDeviceModelFoundError,\n PeerRemovedPairingError,\n} from \"@api/model/Errors\";\nimport { type PermissionsService } from \"@api/permissions/PermissionsService\";\nimport {\n RNBleApduSender,\n type RNBleApduSenderConstructorArgs,\n type RNBleApduSenderDependencies,\n type RNBleInternalDevice,\n} from \"@api/transport/RNBleApduSender\";\n\nexport const rnBleTransportIdentifier = \"RN_BLE\";\n\ntype InternalScannedDevice = {\n device: Device;\n timestamp: number;\n};\n\nexport class RNBleTransport implements Transport {\n private _logger: LoggerPublisherService;\n private _deviceConnectionsById: Map<\n DeviceId,\n DeviceConnectionStateMachine<RNBleApduSenderDependencies>\n >;\n // private readonly _manager: BleManager;\n private readonly identifier: TransportIdentifier = \"RN_BLE\";\n private _reconnectionSubscription: Maybe<Subscription>;\n private readonly _bleStateSubject: BehaviorSubject<State> =\n new BehaviorSubject<State>(State.Unknown);\n\n constructor(\n private readonly _deviceModelDataSource: DeviceModelDataSource,\n private readonly _loggerServiceFactory: (\n tag: string,\n ) => LoggerPublisherService,\n private readonly _apduSenderFactory: ApduSenderServiceFactory,\n private readonly _apduReceiverFactory: ApduReceiverServiceFactory,\n private readonly _manager: BleManager,\n private readonly _platform: Platform,\n private readonly _permissionsService: PermissionsService,\n private readonly _scanThrottleDelayMs: number = 1000,\n private readonly _deviceConnectionStateMachineFactory: (\n args: DeviceConnectionStateMachineParams<RNBleApduSenderDependencies>,\n ) => DeviceConnectionStateMachine<RNBleApduSenderDependencies> = (args) =>\n new DeviceConnectionStateMachine(args),\n private readonly _deviceApduSenderFactory: (\n args: RNBleApduSenderConstructorArgs,\n loggerFactory: (tag: string) => LoggerPublisherService,\n ) => RNBleApduSender = (args, loggerFactory) =>\n new RNBleApduSender(args, loggerFactory),\n ) {\n this._logger = _loggerServiceFactory(\"ReactNativeBleTransport\");\n this._deviceConnectionsById = new Map();\n this._reconnectionSubscription = Maybe.zero();\n // FIXME: we should have a destroy method to unregister the onStateChange listener\n let lastBleStateIsUnknown = false;\n this._manager.onStateChange((state) => {\n this._logger.debug(`[manager.onStateChange] called with state: ${state}`);\n this._bleStateSubject.next(state);\n lastBleStateIsUnknown = state === State.Unknown;\n if (lastBleStateIsUnknown) {\n // There seems to be a bug in the library where the state is not updated after going in an Unknown state...\n this._logger.debug(\n `[manager.onStateChange] forcing state update from \"Unknown\"`,\n );\n this._manager.state().then((s) => {\n if (lastBleStateIsUnknown) {\n this._logger.debug(\n `[manager.onStateChange] forcing state update to: \"${s}\"`,\n );\n this._bleStateSubject.next(s);\n }\n });\n }\n }, true);\n }\n\n /** Exposed for testing purposes */\n observeBleState(): Observable<State> {\n return this._bleStateSubject.asObservable();\n }\n\n /**\n * Not implemented for now as the return signature is not really usable.\n * Use listenToAvailableDevices instead.\n */\n startDiscovering(): Observable<TransportDiscoveredDevice> {\n return from([]);\n }\n\n /**\n * Stops the device scanning operation currently in progress.\n *\n * @return {Promise<void>} A promise that resolves once the device scanning has been successfully stopped.\n */\n async stopDiscovering(): Promise<void> {\n await this._stopScanning();\n }\n\n private _scannedDevicesSubject: BehaviorSubject<InternalScannedDevice[]> =\n new BehaviorSubject<InternalScannedDevice[]>([]);\n private _startedScanningSubscriber: Subscription | undefined = undefined;\n\n /**\n * Returns an observable that emits a value when the prerequisites for scanning are met.\n * The prerequisites are:\n * - BLE should be supported. If not, it will throw an error.\n * - Permissions should be granted. If not, it request them, if it fails, it will throw an error.\n * - BLE state should be PoweredOn.\n * - If BLE state is undetermined (Unknown or Resetting), it will wait for the state to be updated.\n * - For other states, it will throw an error.\n */\n private _waitForScanningPrerequisites() {\n return from([true]).pipe(\n tap(() => {\n if (!this.isSupported()) {\n throw new BleNotSupported(\"BLE not supported\");\n }\n this._logger.debug(\n \"[waitForScanningPrerequisites] Prerequisite: isSupported=true\",\n );\n }),\n switchMap(async () => this.checkAndRequestPermissions()),\n tap((hasPermissions) => {\n this._logger.debug(\n `[_waitForScanningPrerequisites] Prerequisite: hasPermissions=${hasPermissions}`,\n );\n if (!hasPermissions) {\n throw new BlePermissionsNotGranted(\"Permissions not granted\");\n }\n }),\n switchMap(() => this.observeBleState()),\n first((state) => {\n /**\n * We wait for the BLE state to be PoweredOn, in case the current state is one of those:\n * - Unknown: temporary undetermined state which will quickly be updated\n * - Resetting: temporary undetermined state which will quickly be updated\n */\n const canStartScanning = state === State.PoweredOn;\n this._logger.info(\n `[waitForScanningPrerequisites] Prerequisite: BLE state=${state}, canStartScanning=${canStartScanning}`,\n );\n if (state === State.PoweredOff) {\n throw new BlePoweredOff();\n } else if (state === State.Unauthorized) {\n throw new BlePermissionsNotGranted('Ble State is \"Unauthorized\"');\n } else if (state === State.Unsupported) {\n throw new BleNotSupported();\n }\n return canStartScanning;\n }),\n );\n }\n\n private _startScanning() {\n if (this._startedScanningSubscriber != undefined) {\n this._logger.info(\"[startScanning] !! startScanning already started\");\n return;\n }\n\n //Reset the scanned devices list as new scan will start\n this._scannedDevicesSubject.next([]);\n\n this._logger.info(\"[startScanning] startScanning\");\n\n this._startedScanningSubscriber = from([true])\n .pipe(\n switchMap(() => {\n const subject = new BehaviorSubject<InternalScannedDevice[]>([]);\n const devicesById = new Map<string, InternalScannedDevice>();\n\n this._logger.info(\"[startScanning] startDeviceScan\");\n this._manager\n .startDeviceScan(\n this._deviceModelDataSource.getBluetoothServices(),\n { allowDuplicates: true },\n (error, rnDevice) => {\n if (error) {\n this._logger.error(\n \"[startScanning] Error in startDeviceScan callback\",\n {\n data: { error, rnDevice },\n },\n );\n subject.error(error);\n return;\n }\n if (!rnDevice) {\n this._logger.warn(\n \"[startScanning] Null Device in startDeviceScan callback\",\n {\n data: { rnDevice },\n },\n );\n subject.error(\n new Error(\"Null device in startDeviceScan callback\"),\n );\n return;\n }\n devicesById.set(rnDevice.id, {\n device: rnDevice,\n timestamp: Date.now(),\n });\n subject.next(Array.from(devicesById.values()));\n },\n )\n .catch((e) => {\n subject.error(e);\n this._logger.error(\n \"[startScanning] Error while calling startDeviceScan\",\n {\n data: { error: e },\n },\n );\n });\n\n this._logger.debug(\"[startScanning] after startDeviceScan\");\n\n /**\n * In case there is no update from startDeviceScan, we still emit the\n * list of devices. This is useful for instance if there is only 1 device\n * in the vicinity and it just got turned off. It will not \"advertise\"\n * anymore so startDeviceScan won't trigger.\n */\n const interval = setInterval(() => {\n subject.next(Array.from(devicesById.values()));\n }, 1000);\n\n return subject.pipe(\n finalize(() => {\n this._logger.debug(\"[startScanning] finalize\");\n subject.complete();\n clearInterval(interval);\n this._stopScanning();\n }),\n );\n }),\n throttleTime(this._scanThrottleDelayMs),\n )\n .subscribe({\n next: (devices) => {\n this._scannedDevicesSubject.next(devices);\n },\n error: (error) => {\n this._logger.error(\"[startScanning] Error while scanning\", {\n data: { error },\n });\n this._scannedDevicesSubject.error(error);\n },\n });\n }\n\n private async _stopScanning(): Promise<void> {\n this._logger.debug(\"[stopScanning] stopScanning\");\n await this._manager.stopDeviceScan();\n //Stop listening the observable from this._startScanning()\n this._startedScanningSubscriber?.unsubscribe();\n this._startedScanningSubscriber = undefined;\n this._scannedDevicesSubject.complete();\n this._scannedDevicesSubject = new BehaviorSubject<InternalScannedDevice[]>(\n [],\n );\n\n return;\n }\n\n /**\n * Listens to known devices and emits updates when new devices are discovered or when properties of existing devices are updated.\n *\n * @return {Observable<TransportDiscoveredDevice[]>} An observable stream of discovered devices, containing device information as an array of TransportDiscoveredDevice objects.\n */\n listenToAvailableDevices(): Observable<TransportDiscoveredDevice[]> {\n return this._waitForScanningPrerequisites().pipe(\n tap(() => this._startScanning()),\n switchMap(() => this._scannedDevicesSubject),\n switchMap(async (internalScannedDevices) => {\n const eitherScannedDevices = internalScannedDevices\n .filter(\n ({ timestamp }) => timestamp > Date.now() - CONNECTION_LOST_DELAY,\n )\n .sort(\n (a, b) =>\n (b.device.rssi ?? -Infinity) - (a.device.rssi ?? -Infinity), // RSSI is a negative value and the higher, the stronger the signal\n )\n .map(({ device }) =>\n this._mapDeviceToTransportDiscoveredDevice(\n device,\n device.serviceUUIDs,\n ),\n )\n .filter((d) => !!d);\n\n const scannedDevices = Either.rights(eitherScannedDevices);\n\n const rawConnectedDevices = await this._manager\n .connectedDevices(this._deviceModelDataSource.getBluetoothServices())\n .catch((e) => {\n this._logger.error(\n \"[listenToAvailableDevices] Error calling manager.connectedDevices\",\n {\n data: { error: e },\n },\n );\n throw e;\n });\n\n const eitherConnectedDevices = await Promise.all(\n rawConnectedDevices.map(async (device) => {\n try {\n const services = await device.services();\n const servicesUUIDs = services.map((s) => s.uuid);\n return this._mapDeviceToTransportDiscoveredDevice(\n device,\n servicesUUIDs,\n );\n } catch (e) {\n this._logger.error(\n \"[listenToAvailableDevices] Error in mapping device to transport discovered device\",\n {\n data: { e },\n },\n );\n return Left(\n new NoDeviceModelFoundError(\n `Error in mapping device to transport discovered device: ${e}`,\n ),\n );\n }\n }),\n );\n\n const connectedDevices = Either.rights(eitherConnectedDevices);\n\n this._logger.debug(\"[listenToAvailableDevices]\", {\n data: {\n rawConnectedDevices: rawConnectedDevices.map((d) => d.name),\n connectedDevices: connectedDevices.map((d) => d.name),\n scannedDevices: scannedDevices.map((d) => d.name),\n },\n });\n\n /** We return both connected and scanned devices, as scanned devices don't include connected devices */\n return [...connectedDevices, ...scannedDevices];\n }),\n );\n }\n\n private _mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, BleDeviceInfos> {\n for (const serviceUUID of servicesUUIDs || []) {\n const bluetoothServiceInfo =\n this._deviceModelDataSource.getBluetoothServicesInfos()[serviceUUID];\n if (bluetoothServiceInfo) return Right(bluetoothServiceInfo);\n }\n\n return Left(\n new NoDeviceModelFoundError(\n `No device model found for [uuids=${servicesUUIDs}]`,\n ),\n );\n }\n\n private _mapServicesUUIDsToDeviceModel(\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, TransportDeviceModel> {\n const bluetoothServiceInfo =\n this._mapServicesUUIDsToBluetoothDeviceInfo(servicesUUIDs);\n return bluetoothServiceInfo.map((info) => info.deviceModel);\n }\n\n private _mapDeviceToTransportDiscoveredDevice(\n device: Device,\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, TransportDiscoveredDevice> {\n const deviceModel = this._mapServicesUUIDsToDeviceModel(servicesUUIDs);\n return deviceModel.map((model) => ({\n id: device.id,\n name: device.localName || device.name || \"\",\n deviceModel: model,\n transport: this.identifier,\n rssi: device.rssi || undefined,\n }));\n }\n\n /**\n * Establishes a connection to a device and configures the necessary parameters for communication.\n *\n * @param {Object} params - An object containing parameters required for the connection.\n * @param {DeviceId} params.deviceId - The unique identifier of the device to connect to.\n * @param {DisconnectHandler} params.onDisconnect - A callback function to handle device disconnection.\n * @returns {Promise<Either<ConnectError, TransportConnectedDevice>>} A promise resolving to either a connection error or a successfully connected device.\n */\n async connect(params: {\n deviceId: DeviceId;\n onDisconnect: DisconnectHandler;\n }): Promise<Either<ConnectError, TransportConnectedDevice>> {\n this._logger.debug(\"[connect] Called\", {\n data: { deviceId: params.deviceId },\n });\n const existing = this._deviceConnectionsById.get(params.deviceId);\n if (existing) {\n this._logger.debug(\"[connect] Existing device connection found\", {\n data: { deviceId: params.deviceId },\n });\n const deviceModel =\n existing.getDependencies().internalDevice.bleDeviceInfos.deviceModel;\n return Right(\n new TransportConnectedDevice({\n id: params.deviceId,\n deviceModel: deviceModel,\n type: \"BLE\",\n sendApdu: (...a) => existing.sendApdu(...a),\n transport: this.identifier,\n }),\n );\n }\n\n this._logger.debug(\n \"[connect] No existing device connection found, establishing one\",\n {\n data: { deviceId: params.deviceId },\n },\n );\n\n await this._stopScanning();\n await this._safeCancel(params.deviceId);\n\n return EitherAsync<ConnectError, TransportConnectedDevice>(\n async ({ throwE }) => {\n let device: Device;\n let servicesUUIDs: string[] = [];\n try {\n await this._manager.connectToDevice(params.deviceId, {\n requestMTU: DEFAULT_MTU,\n });\n\n device =\n await this._manager.discoverAllServicesAndCharacteristicsForDevice(\n params.deviceId,\n );\n\n servicesUUIDs = (await device.services()).map((s) => s.uuid);\n } catch (error) {\n if (\n error instanceof BleError &&\n (error.iosErrorCode as number) === 14\n ) {\n /**\n * This happens when the Ledger device reset its pairing, but the\n * iOS system still has that device paired.\n */\n return throwE(new PeerRemovedPairingError(error));\n }\n if (\n error instanceof BleError &&\n error.errorCode === BleErrorCode.OperationCancelled &&\n Platform.OS === \"android\"\n ) {\n return throwE(new PeerRemovedPairingError(error));\n }\n return throwE(new OpeningConnectionError(error));\n }\n\n const disconnectionSubscription = this._listenToDeviceDisconnected(\n params.deviceId,\n );\n\n const bleDeviceInfos = this._mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs,\n ).caseOf({\n Right: (info) => {\n return info;\n },\n Left: (error) => {\n return throwE(new OpeningConnectionError(error));\n },\n });\n\n const deviceModel = bleDeviceInfos.deviceModel;\n\n const internalDevice: RNBleInternalDevice = {\n id: device.id,\n bleDeviceInfos,\n };\n\n const deviceApduSender = this._deviceApduSenderFactory(\n {\n apduSenderFactory: this._apduSenderFactory,\n apduReceiverFactory: this._apduReceiverFactory,\n dependencies: { device, internalDevice, manager: this._manager },\n },\n this._loggerServiceFactory,\n );\n\n const reconnectionTimeout =\n Platform.OS === \"ios\"\n ? BLE_DISCONNECT_TIMEOUT_IOS\n : BLE_DISCONNECT_TIMEOUT_ANDROID;\n\n const deviceConnectionStateMachine =\n this._deviceConnectionStateMachineFactory({\n deviceId: params.deviceId,\n deviceApduSender,\n timeoutDuration: reconnectionTimeout,\n tryToReconnect: () => this.tryToReconnect(params.deviceId),\n onTerminated: async () => {\n this._logger.debug(\"[onTerminated]\", {\n data: { deviceId: params.deviceId },\n });\n try {\n await this._safeCancel(params.deviceId);\n } catch (e) {\n this._logger.error(\n \"[onTerminated] Error in termination of device connection\",\n { data: { e } },\n );\n } finally {\n this._deviceConnectionsById.delete(params.deviceId);\n this._reconnectionSubscription.ifJust((sub) => {\n sub.unsubscribe();\n this._reconnectionSubscription = Maybe.zero();\n });\n this._logger.debug(\"[onTerminated] signaling disconnection\", {\n data: { deviceId: params.deviceId },\n });\n params.onDisconnect(params.deviceId);\n }\n },\n });\n\n await deviceApduSender.setupConnection().catch((e) => {\n this._safeCancel(params.deviceId);\n disconnectionSubscription.remove();\n throw e;\n });\n\n this._deviceConnectionsById.set(\n params.deviceId,\n deviceConnectionStateMachine,\n );\n\n return new TransportConnectedDevice({\n id: device.id,\n deviceModel: deviceModel,\n type: \"BLE\",\n sendApdu: (...args) => deviceConnectionStateMachine.sendApdu(...args),\n transport: this.identifier,\n });\n },\n ).run();\n }\n\n /**\n * Terminates the connection with the connected device and cleans up related resources.\n *\n * @param {TransportConnectedDevice} params.connectedDevice - The connected device to be disconnected.\n * @return {Promise<Either<DmkError, void>>} A promise resolving to either a success (void) or a failure (DmkError) value.\n */\n async disconnect(params: {\n connectedDevice: TransportConnectedDevice;\n }): Promise<Either<DmkError, void>> {\n const deviceId = params.connectedDevice.id;\n const deviceConnection = this._deviceConnectionsById.get(deviceId);\n if (!deviceConnection) {\n throw new UnknownDeviceError(\n `No connected device found with id ${deviceId}`,\n );\n }\n\n deviceConnection.closeConnection();\n\n return Promise.resolve(Right(undefined));\n }\n\n /**\n * Determines if the feature or permission is supported.\n *\n * This method evaluates the current state of the `_isSupported` property to determine\n * whether the relevant feature is supported or throws an error if its state has\n * not been initialized properly.\n *\n * @return {boolean} Returns `true` if the feature is supported, otherwise `false`.\n * Throws an error if the `_isSupported` property has not been initialized.\n */\n isSupported(): boolean {\n return [\"android\", \"ios\"].includes(this._platform.OS);\n }\n\n /**\n * Retrieves the transport identifier associated with the object.\n *\n * @return {TransportIdentifier} The transport identifier.\n */\n getIdentifier(): TransportIdentifier {\n return this.identifier;\n }\n\n /**\n * Checks if the necessary permissions are granted and requests them if not.\n */\n async checkAndRequestPermissions(): Promise<boolean> {\n this._logger.debug(\"[checkAndRequestPermissions] Called\");\n\n const checkResult =\n await this._permissionsService.checkRequiredPermissions();\n if (checkResult) return true;\n\n const requestResult =\n await this._permissionsService.requestRequiredPermissions();\n return requestResult;\n }\n\n /**\n * Handles the event when a Bluetooth device gets disconnected. This method attempts\n * to reconnect to the device, retries a certain number of times on failure, and\n * invokes a callback if the reconnection does not succeed.\n *\n * @param {BleError | null} error - The error object representing the reason for the disconnection, or null if no error occurred.\n * @param {Device | null} device - The Bluetooth device that was disconnected, or null if no device is provided.\n * @return {void}\n */\n private _handleDeviceDisconnected(\n error: BleError | null,\n device: Device | null,\n ) {\n this._logger.debug(\"[_handleDeviceDisconnected]\", {\n data: { error, device },\n });\n if (!device) {\n this._logger.debug(\n \"[_handleDeviceDisconnected] disconnected handler didn't find device\",\n );\n return;\n }\n if (!device?.id || !this._deviceConnectionsById.has(device?.id)) return;\n if (error) {\n this._logger.error(\"device disconnected error\", {\n data: { error, device },\n });\n return;\n }\n const deviceId = device.id;\n\n Maybe.fromNullable(this._deviceConnectionsById.get(deviceId)).map(\n (deviceConnection) => deviceConnection.eventDeviceDisconnected(),\n );\n }\n\n private _listenToDeviceDisconnected(deviceId: DeviceId): BleSubscription {\n const disconnectionSubscription = this._manager.onDeviceDisconnected(\n deviceId,\n (error, d) => {\n this._handleDeviceDisconnected(error, d);\n disconnectionSubscription.remove();\n },\n );\n return disconnectionSubscription;\n }\n\n private async tryToReconnect(deviceId: DeviceId) {\n this._logger.debug(\"[tryToReconnect] Called\", {\n data: { deviceId },\n });\n let reconnectionTryCount = 0;\n\n await this._stopScanning();\n await this._safeCancel(deviceId);\n\n const reconnect$ = defer(async () => {\n let disconnectionSubscription: BleSubscription | null = null;\n reconnectionTryCount++;\n try {\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Reconnecting to device`,\n {\n data: { id: deviceId },\n },\n );\n const reconnectedDevice = await this._manager.connectToDevice(\n deviceId,\n { requestMTU: DEFAULT_MTU, timeout: 2000 },\n );\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Established connection to device`,\n {\n data: { id: deviceId },\n },\n );\n const usableReconnectedDevice =\n await reconnectedDevice.discoverAllServicesAndCharacteristics();\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Discovered all services and characteristics`,\n { data: { usableReconnectedDevice } },\n );\n disconnectionSubscription = this._listenToDeviceDisconnected(deviceId);\n await this._handleDeviceReconnected(usableReconnectedDevice);\n return usableReconnectedDevice;\n } catch (e) {\n this._logger.warn(\n `[tryToReconnect](try=${reconnectionTryCount}) Reconnecting to device failed`,\n {\n data: { e },\n },\n );\n disconnectionSubscription?.remove();\n await this._stopScanning();\n await this._safeCancel(deviceId);\n throw e;\n }\n }).pipe(retry(5));\n\n this._reconnectionSubscription = Maybe.of(\n reconnect$.subscribe({\n next: (d) =>\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Fully reconnected to device (id=${d.id})`,\n ),\n complete: () => {\n this._logger.debug(\"[tryToReconnect] Completed\");\n this._reconnectionSubscription = Maybe.zero();\n },\n error: (e) => {\n this._logger.error(\n `[tryToReconnect] All reconnection attempts failed`,\n { data: { e } },\n );\n this._deviceConnectionsById.get(deviceId)?.closeConnection();\n this._reconnectionSubscription = Maybe.zero();\n },\n }),\n );\n }\n\n /**\n * Handles the reconnection of a device. Configures the device connection and its corresponding\n * internal device upon reconnection, including updating the connection state, registering\n * callbacks for write and monitor operations, and initiating a reconnect operation.\n *\n * @param {Device} device - The ddevice object that has been reconnected. Contains device details,\n * such as the device ID.\n * @return {Promise<Either<DeviceConnectionNotFound | InternalDeviceNotFound, void>>} A promise that completes when the device reconnection has been fully\n * configured. Resolves with no value or rejects if an error occurs during\n * the reconnection process.\n */\n private async _handleDeviceReconnected(device: Device) {\n const errorOrDeviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(device.id),\n ).toEither(new DeviceConnectionNotFound());\n\n return EitherAsync(async ({ liftEither, throwE }) => {\n const deviceConnectionStateMachine = await liftEither(\n errorOrDeviceConnection,\n );\n\n const servicesUUIDs = (await device.services()).map((s) => s.uuid);\n\n const internalDevice = this._mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs,\n ).caseOf({\n Right: (info) => {\n return {\n id: device.id,\n bleDeviceInfos: info,\n };\n },\n Left: (error) => {\n this._logger.error(\n \"[_handleDeviceReconnected] Error in mapping services UUIDs to Bluetooth device info\",\n {\n data: { error },\n },\n );\n\n return throwE(error);\n },\n });\n\n deviceConnectionStateMachine.setDependencies({\n device,\n manager: this._manager,\n internalDevice,\n });\n\n await deviceConnectionStateMachine.setupConnection().catch((e) => {\n this._safeCancel(device.id);\n throw e;\n });\n\n deviceConnectionStateMachine.eventDeviceConnected();\n }).run();\n }\n\n private async _safeCancel(deviceId: DeviceId) {\n // only invoke if the BleManager under test actually has it\n if (typeof this._manager.cancelDeviceConnection === \"function\") {\n const connectedDevices = await this._manager.connectedDevices(\n this._deviceModelDataSource.getBluetoothServices(),\n );\n\n for (const device of connectedDevices) {\n if (device.id === deviceId) {\n try {\n await this._manager.cancelDeviceConnection(deviceId);\n } catch (e) {\n this._logger.error(\n \"[safeCancel] Error in cancelling device connection\",\n {\n data: { e },\n },\n );\n }\n }\n }\n }\n }\n}\n"],
|
|
5
|
+
"mappings": "AAAA,OAAS,YAAAA,MAAgB,eACzB,OACE,YAAAC,EACA,gBAAAC,EAGA,SAAAC,MAEK,uBACP,OAKE,gCAAAC,EAOA,0BAAAC,EAEA,4BAAAC,EAIA,sBAAAC,MACK,kCACP,OAAS,UAAAC,EAAQ,eAAAC,EAAa,QAAAC,EAAM,SAAAC,EAAO,SAAAC,MAAa,YACxD,OACE,mBAAAC,EACA,SAAAC,EACA,YAAAC,EACA,SAAAC,EACA,QAAAC,EAEA,SAAAC,EAEA,aAAAC,EACA,OAAAC,EACA,gBAAAC,MACK,OAEP,OACE,kCAAAC,EACA,8BAAAC,EACA,yBAAAC,EACA,eAAAC,MACK,mBACP,OACE,mBAAAC,EACA,4BAAAC,EACA,iBAAAC,EACA,4BAAAC,EACA,2BAAAC,EACA,2BAAAC,MACK,oBAEP,OACE,mBAAAC,MAIK,iCAEA,MAAMC,GAA2B,SAOjC,MAAMC,EAAoC,CAY/C,YACmBC,EACAC,EAGAC,EACAC,EACAC,EACAC,EACAC,EACAC,EAA+B,IAC/BC,EAEiDC,GAChE,IAAIxC,EAA6BwC,CAAI,EACtBC,EAGM,CAACD,EAAME,IAC5B,IAAId,EAAgBY,EAAME,CAAa,EACzC,CAnBiB,4BAAAX,EACA,2BAAAC,EAGA,wBAAAC,EACA,0BAAAC,EACA,cAAAC,EACA,eAAAC,EACA,yBAAAC,EACA,0BAAAC,EACA,0CAAAC,EAIA,8BAAAE,EAMjB,KAAK,QAAUT,EAAsB,yBAAyB,EAC9D,KAAK,uBAAyB,IAAI,IAClC,KAAK,0BAA4BzB,EAAM,KAAK,EAE5C,IAAIoC,EAAwB,GAC5B,KAAK,SAAS,cAAeC,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AuB,qBAAqB,CACnD,EAEA,UAAWN,KAAUM,EACnB,GAAIN,EAAO,KAAOsB,EAChB,GAAI,CACF,MAAM,KAAK,SAAS,uBAAuBA,CAAQ,CACrD,OAAS9B,EAAG,CACV,KAAK,QAAQ,MACX,qDACA,CACE,KAAM,CAAE,EAAAA,CAAE,CACZ,CACF,CACF,CAGN,CACF,CACF",
|
|
6
|
+
"names": ["Platform", "BleError", "BleErrorCode", "State", "DeviceConnectionStateMachine", "OpeningConnectionError", "TransportConnectedDevice", "UnknownDeviceError", "Either", "EitherAsync", "Left", "Maybe", "Right", "BehaviorSubject", "defer", "finalize", "first", "from", "retry", "switchMap", "tap", "throttleTime", "BLE_DISCONNECT_TIMEOUT_ANDROID", "BLE_DISCONNECT_TIMEOUT_IOS", "CONNECTION_LOST_DELAY", "DEFAULT_MTU", "BleNotSupported", "BlePermissionsNotGranted", "BlePoweredOff", "DeviceConnectionNotFound", "NoDeviceModelFoundError", "PeerRemovedPairingError", "RNBleApduSender", "rnBleTransportIdentifier", "RNBleTransport", "_deviceModelDataSource", "_loggerServiceFactory", "_apduSenderFactory", "_apduReceiverFactory", "_manager", "_platform", "_permissionsService", "_scanThrottleDelayMs", "_deviceConnectionStateMachineFactory", "args", "_deviceApduSenderFactory", "loggerFactory", "lastBleStateIsUnknown", "state", "s", "hasPermissions", "canStartScanning", "subject", "devicesById", "error", "rnDevice", "e", "interval", "devices", "internalScannedDevices", "eitherScannedDevices", "timestamp", "a", "b", "device", "d", "scannedDevices", "rawConnectedDevices", "eitherConnectedDevices", "servicesUUIDs", "connectedDevices", "serviceUUID", "bluetoothServiceInfo", "info", "model", "params", "existing", "deviceModel", "throwE", "disconnectionSubscription", "bleDeviceInfos", "internalDevice", "deviceApduSender", "reconnectionTimeout", "deviceConnectionStateMachine", "sub", "deviceId", "deviceConnection", "reconnectionTryCount", "reconnect$", "reconnectedDevice", "usableReconnectedDevice", "errorOrDeviceConnection", "liftEither"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{BleManager as u,State as g}from"react-native-ble-plx";import{BleDeviceInfos as L,DeviceConnectionStateMachine as U,DeviceModelId as _,OpeningConnectionError as B,TransportConnectedDevice as M,TransportDeviceModel as V}from"@ledgerhq/device-management-kit";import{Left as H,Right as E}from"purify-ts";import{lastValueFrom as N,take as T}from"rxjs";import{beforeEach as F,expect as i}from"vitest";import{BleNotSupported as q}from"../model/Errors";import{RNBleTransport as v,RNBleTransportFactory as x}from"./RNBleTransport";const l={error:vi.fn(),info:vi.fn(),warn:vi.fn(),debug:vi.fn()};vi.mock("react-native",()=>({Platform:{},PermissionsAndroid:{}}));vi.mock("react-native-ble-plx",()=>({Device:vi.fn(),State:{PoweredOn:"PoweredOn",Unknown:"Unknown"},BleError:vi.fn(),BleManager:vi.fn().mockReturnValue({onStateChange:vi.fn(),startDeviceScan:vi.fn(),stopDeviceScan:vi.fn(),connectToDevice:vi.fn(),disconnectFromDevice:vi.fn(),cancelDeviceConnection:vi.fn(),connectedDevices:vi.fn(),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),discoverAllServicesAndCharacteristicsForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn()})}));const h=async(r,I)=>{const b={OS:"android",Version:r.version},R={request:vi.fn().mockImplementation(o=>Promise.resolve({ACCESS_FINE_LOCATION:r.accessFineLocationResult}[o])),PERMISSIONS:r.permissions,RESULTS:{GRANTED:"granted"},requestMultiple:vi.fn().mockImplementation(()=>Promise.resolve(r.requestPermissionResult))},m=new v("DeviceModelDataSource",()=>l,()=>{},()=>{},new u,b,R);await m.requestPermission();const O=m.isSupported();I.callRequestPermission&&i(R.request).toHaveBeenCalledWith("ACCESS_FINE_LOCATION"),i(O).toBe(I.isSupported)};describe("RNBleTransportFactory",()=>{it("should return a RNBleTransport",()=>{const I=x({deviceModelDataSource:"DeviceModelDataSource",loggerServiceFactory:()=>l,apduSenderServiceFactory:()=>{},apduReceiverServiceFactory:()=>{},config:{}});i(I).toBeInstanceOf(v)})});describe("RNBleTransport",()=>{const r={OS:"ios"},I=new V({id:_.FLEX,productName:"Ledger Flex",usbProductId:112,bootloaderUsbProductId:7,usbOnly:!1,memorySize:1533*1024,blockSize:32,masks:[858783744]}),b=vi.fn(()=>["ledgerId"]),R=vi.fn(()=>({ledgerId:new L(I,"serviceUuid","notifyUuid","writeCmdUuid","readCmdUuid")})),m={getBluetoothServices:b,getBluetoothServicesInfos:R};let O;F(()=>{vi.clearAllMocks()}),afterEach(()=>{O&&O.unsubscribe()}),describe("getIdentifier",()=>{it("should return rnBleTransportIdentifier",()=>{const o=new u,e=new v("DeviceModelDataSource",()=>l,()=>{},()=>{},o).getIdentifier();i(e).toStrictEqual("RN_BLE")})}),describe("isSupported",()=>{it("should return true if platform is ios",async()=>{const o={OS:"ios"},n=new u,e=new v("DeviceModelDataSource",()=>l,()=>{},()=>{},n,o);await e.requestPermission();const s=e.isSupported();i(s).toBe(!0)}),it("should return true if platform is android and apiLevel < 31 with good permissions",async()=>{await h({version:30,permissions:{ACCESS_FINE_LOCATION:"ACCESS_FINE_LOCATION",BLUETOOTH_SCAN:"BLUETOOTH_SCAN",BLUETOOTH_CONNECT:"BLUETOOTH_CONNECT"},requestPermissionResult:{"android.permission.BLUETOOTH_CONNECT":"granted","android.permission.BLUETOOTH_SCAN":"granted","android.permission.ACCESS_FINE_LOCATION":"granted"}},{isSupported:!0,callRequestPermission:!0})}),it("should return true if platform is android and apiLevel >= 31 with good permissions",async()=>{await h({version:31,permissions:{ACCESS_FINE_LOCATION:"ACCESS_FINE_LOCATION",BLUETOOTH_SCAN:"BLUETOOTH_SCAN",BLUETOOTH_CONNECT:"BLUETOOTH_CONNECT"},requestPermissionResult:{"android.permission.BLUETOOTH_CONNECT":"granted","android.permission.BLUETOOTH_SCAN":"granted","android.permission.ACCESS_FINE_LOCATION":"granted"}},{isSupported:!0,callRequestPermission:!1})}),it("should return false if platform is android with bad permissions",async()=>{await h({version:31,permissions:{ACCESS_FINE_LOCATION:"",BLUETOOTH_SCAN:"",BLUETOOTH_CONNECT:"BLUETOOTH_CONNECT"},requestPermissionResult:{"android.permission.ACCESS_FINE_LOCATION":"denied","android.permission.BLUETOOTH_CONNECT":"granted","android.permission.BLUETOOTH_SCAN":"granted"}},{isSupported:!1,callRequestPermission:!1})}),it("should return false if platform is android and denied permissions",async()=>{await h({version:31,permissions:{ACCESS_FINE_LOCATION:"ACCESS_FINE_LOCATION",BLUETOOTH_SCAN:"BLUETOOTH_SCAN",BLUETOOTH_CONNECT:"BLUETOOTH_CONNECT"},requestPermissionResult:{"android.permission.BLUETOOTH_CONNECT":"denied","android.permission.BLUETOOTH_SCAN":"denied","android.permission.ACCESS_FINE_LOCATION":"denied"}},{isSupported:!1,callRequestPermission:!1})}),it("should return false if platform isn't android nor ios",async()=>{const o=new u,n=new v("DeviceModelDataSource",()=>l,()=>{},()=>{},o,{OS:"windows"});await n.requestPermission();const e=n.isSupported();i(e).toBe(!1)})}),describe("startDiscovering",()=>{it("should throw error if transport is not supported",()=>{const o={OS:"windows"},n=new u,e=new v(m,()=>l,()=>{},()=>{},n,o);try{e.startDiscovering()}catch(s){i(s).toBeInstanceOf(q)}}),it("should emit an empty array",()=>new Promise(o=>{const n=new u;O=new v(m,()=>l,()=>{},()=>{},n,r,{}).startDiscovering().subscribe({next:t=>{i(t).toStrictEqual([]),o(void 0)},error:t=>{throw t},complete:()=>{o(void 0)}})})),it.skip("should emit discovered new device",()=>new Promise(o=>{let n=null;const e=new u,s=vi.fn().mockImplementation((c,k,a)=>(n=setInterval(()=>{a(null,{id:"id",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},500),a(null,{id:"43",localName:"name43",serviceUUIDs:["notLedgerId"],rssi:43}),Promise.resolve())),t=vi.fn().mockImplementation(()=>(n&&(clearInterval(n),n=null),Promise.resolve()));vi.spyOn(e,"connectedDevices").mockResolvedValueOnce([]),vi.spyOn(e,"startDeviceScan").mockImplementation(s),vi.spyOn(e,"stopDeviceScan").mockImplementation(t),O=new v(m,()=>l,()=>{},()=>{},e,r,{}).startDiscovering().subscribe({next:c=>{i(c).toStrictEqual([]),o(void 0)},error:c=>{throw c},complete:()=>{throw new Error("complete should not be called")}})})),it.skip("should emit both known and new device",()=>new Promise(o=>{let n=null;const e=new u,s={readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"knownDeviceId",localName:"knownDeviceName"})})},t=vi.fn().mockImplementation((a,f,D)=>(n=setInterval(()=>{D(null,{id:"newDeviceId",localName:"newDeviceName",serviceUUIDs:["ledgerId"],rssi:42})},500),D(null,{id:"43",localName:"name43",serviceUUIDs:["notLedgerId"],rssi:43}),Promise.resolve())),p=vi.fn().mockImplementation(()=>(n&&(clearInterval(n),n=null),Promise.resolve()));vi.spyOn(e,"connectedDevices").mockResolvedValueOnce([s]),vi.spyOn(e,"startDeviceScan").mockImplementation(t),vi.spyOn(e,"stopDeviceScan").mockImplementation(p),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(vi.fn());const c=new v(m,()=>l,()=>{},()=>{},e,r,{}).startDiscovering(),k={};O=c.subscribe({next:a=>{k[a.id]=a,Object.values(k).length===2&&(i(Object.values(k)).toStrictEqual([{id:"knownDeviceId",name:"knownDeviceName",deviceModel:I,transport:"RN_BLE",rssi:64},{id:"newDeviceId",name:"newDeviceName",deviceModel:I,transport:"RN_BLE",rssi:42}]),o(void 0))}})}))}),describe("stopDiscovering",()=>{it("should call ble manager stop scan on stop discovering",()=>{const o=new u,n=vi.fn();vi.spyOn(o,"connectedDevices").mockResolvedValueOnce([]),vi.spyOn(o,"stopDeviceScan").mockImplementation(n),new v(m,()=>l,()=>{},()=>{},o,r,{}).stopDiscovering(),i(n).toHaveBeenCalled()}),it.skip("should call ble manager stop scan when unsubscribe startDiscovering obs",()=>{let o=null;const n=new u,e=vi.fn().mockImplementation((p,S,c)=>(o=setInterval(()=>{c(null,{id:"id",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},500),c(null,{id:"43",localName:"name43",serviceUUIDs:["notLedgerId"],rssi:43}),Promise.resolve())),s=vi.fn().mockImplementation(()=>(o&&(clearInterval(o),o=null),Promise.resolve()));vi.spyOn(n,"connectedDevices").mockResolvedValueOnce([]),vi.spyOn(n,"startDeviceScan").mockImplementation(e),vi.spyOn(n,"stopDeviceScan").mockImplementation(s),vi.spyOn(n,"onDeviceDisconnected").mockImplementation(vi.fn()),new v(m,()=>l,()=>{},()=>{},n,r,{}).startDiscovering().subscribe().unsubscribe(),i(e).toHaveBeenCalled(),i(s).toHaveBeenCalled()})}),describe("listenToAvailableDevices",()=>{it("should call startScan and connectedDevices from ble manager",()=>new Promise(o=>{let n=null;const e=new u,s={readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"knownDeviceId",localName:"knownDeviceName"})})},t=vi.fn().mockImplementation((c,k,a)=>{n=setInterval(()=>{a(null,{id:"id",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},10),a(null,{id:"43",localName:"name43",serviceUUIDs:["notLedgerId"],rssi:43})}),p=vi.fn().mockImplementation(()=>{n&&(clearInterval(n),n=null)});vi.spyOn(e,"connectedDevices").mockResolvedValueOnce([s]),vi.spyOn(e,"startDeviceScan").mockImplementation(t),vi.spyOn(e,"stopDeviceScan").mockImplementation(p),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(vi.fn()),vi.spyOn(e,"isDeviceConnected").mockImplementation(vi.fn()),vi.spyOn(e,"onStateChange").mockImplementation(c=>(c(g.PoweredOn),{remove:vi.fn()})),O=new v(m,()=>l,()=>{},()=>{},e,r,{}).listenToAvailableDevices().subscribe({next:c=>{c.length===1&&(i(c).toEqual([{id:"id",name:"name",deviceModel:I,transport:"RN_BLE",rssi:42}]),o(void 0))}})}))}),describe("connect",()=>{let o;F(()=>{o=vi.fn().mockResolvedValueOnce([{readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"deviceId",localName:"knownDeviceName"})})}])}),it("should throw an error if device id is unknown",async()=>{const n=new u;vi.spyOn(n,"connectedDevices").mockImplementation(o),vi.spyOn(n,"discoverAllServicesAndCharacteristicsForDevice").mockRejectedValueOnce(new Error("discoverAllServicesAndCharacteristicsForDevice error"));const e=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0)}),t=await new v(m,()=>l,()=>{},()=>{},n,r,{},vi.fn(),e).connect({deviceId:null,onDisconnect:vi.fn()});i(t).toEqual(H(new B("discoverAllServicesAndCharacteristicsForDevice error")))}),it("should connect to a discovered device with correct MTU and discover services and setup apdu sender",async()=>{let n=null;const e=new u,s={readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"knownDeviceId",localName:"knownDeviceName"})}),services:vi.fn().mockResolvedValueOnce([{uuid:"ledgerId"}])},t=vi.fn().mockImplementation((w,C,A)=>{n=setInterval(()=>{A(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},500),A(null,{id:"43",localName:"name43",serviceUUIDs:["notLedgerId"],rssi:43})}),p=vi.fn().mockImplementation(()=>{n&&(clearInterval(n),n=null)});vi.spyOn(e,"connectedDevices").mockImplementation(o),vi.spyOn(e,"startDeviceScan").mockImplementation(t),vi.spyOn(e,"stopDeviceScan").mockImplementation(p),vi.spyOn(e,"connectToDevice").mockResolvedValueOnce(s),vi.spyOn(e,"discoverAllServicesAndCharacteristicsForDevice").mockResolvedValueOnce(s),vi.spyOn(e,"monitorCharacteristicForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"writeCharacteristicWithoutResponseForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(vi.fn()),vi.spyOn(e,"isDeviceConnected").mockImplementation(vi.fn()),vi.spyOn(e,"onStateChange").mockImplementation(w=>(w(g.PoweredOn),{remove:vi.fn()}));const S=vi.fn().mockResolvedValue(void 0),c=vi.fn().mockReturnValue({sendApdu:vi.fn()}),k=vi.fn().mockReturnValue({setupConnection:S}),a=new v(m,()=>l,()=>{},()=>{},e,r,{},c,k),[f]=await N(a.listenToAvailableDevices().pipe(T(3))),D=await a.connect({deviceId:f.id,onDisconnect:vi.fn()});i(D.isRight()).toBe(!0),i(e.connectToDevice).toHaveBeenCalledWith("deviceId",{requestMTU:156}),i(e.discoverAllServicesAndCharacteristicsForDevice).toHaveBeenCalledWith("deviceId"),i(S).toHaveBeenCalled()}),it("should return a connected device which calls state machine sendApdu",async()=>{let n=null;const e=new u,s={id:"deviceId",readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"knownDeviceId",localName:"knownDeviceName"})}),services:vi.fn().mockResolvedValueOnce([{uuid:"ledgerId"}])},t=vi.fn().mockImplementation((C,A,d)=>{n=setInterval(()=>{d(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},100)}),p=vi.fn().mockImplementation(()=>{n&&(clearInterval(n),n=null)});vi.spyOn(e,"connectedDevices").mockImplementation(o),vi.spyOn(e,"startDeviceScan").mockImplementation(t),vi.spyOn(e,"stopDeviceScan").mockImplementation(p),vi.spyOn(e,"connectToDevice").mockResolvedValueOnce(s),vi.spyOn(e,"discoverAllServicesAndCharacteristicsForDevice").mockResolvedValueOnce(s),vi.spyOn(e,"monitorCharacteristicForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"writeCharacteristicWithoutResponseForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(vi.fn()),vi.spyOn(e,"isDeviceConnected").mockImplementation(vi.fn()),vi.spyOn(e,"onStateChange").mockImplementation(C=>(C(g.PoweredOn),{remove:vi.fn()}));const S=vi.fn(),c=vi.fn().mockReturnValue({sendApdu:S}),k=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0)}),a=new v(m,()=>l,()=>{},()=>{},e,r,{},c,k),[f]=await N(a.listenToAvailableDevices().pipe(T(3))),D=await a.connect({deviceId:f.id,onDisconnect:vi.fn()});D.extract().sendApdu(Uint8Array.from([67,50])),i(D).toEqual(E(new M({id:"deviceId",deviceModel:I,type:"BLE",transport:"RN_BLE",sendApdu:i.any(Function)}))),i(S).toHaveBeenCalledWith(Uint8Array.from([67,50]))})}),describe("disconnect",()=>{let o;F(()=>{o=vi.fn().mockResolvedValue([{readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"deviceId",localName:"knownDeviceName"})})}])}),it("should disconnect gracefully",async()=>{let n=null;const e=new u,s={id:"deviceId",readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"knownDeviceId",localName:"knownDeviceName"})}),services:vi.fn().mockResolvedValueOnce([{uuid:"ledgerId"}])},t=vi.fn().mockImplementation((d,y,P)=>{n=setInterval(()=>{P(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},100)}),p=vi.fn().mockImplementation(()=>{n&&(clearInterval(n),n=null)}),S=vi.fn().mockImplementation((d,y)=>(y(null,{deviceId:"deviceId",connect:vi.fn().mockResolvedValue({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"deviceId",localName:"knownDeviceName"}),discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"deviceId",localName:"knownDeviceName"})}),{remove:vi.fn()})),c=vi.fn();vi.spyOn(e,"connectedDevices").mockImplementation(o),vi.spyOn(e,"startDeviceScan").mockImplementation(t),vi.spyOn(e,"stopDeviceScan").mockImplementation(p),vi.spyOn(e,"connectToDevice").mockResolvedValueOnce(s),vi.spyOn(e,"discoverAllServicesAndCharacteristicsForDevice").mockResolvedValueOnce(s),vi.spyOn(e,"monitorCharacteristicForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"writeCharacteristicWithoutResponseForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(vi.fn()),vi.spyOn(e,"isDeviceConnected").mockImplementation(vi.fn()),vi.spyOn(e,"onStateChange").mockImplementation(d=>(d(g.PoweredOn),{remove:vi.fn()})),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(S),vi.spyOn(e,"isDeviceConnected").mockImplementation(vi.fn());const k=d=>new U({deviceId:"deviceId",deviceApduSender:d.deviceApduSender,timeoutDuration:1e3,onTerminated:d.onTerminated,tryToReconnect:d.tryToReconnect}),a=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0),closeConnection:c}),f=new v(m,()=>l,()=>{},()=>{},e,r,{},k,a),D=vi.fn(),[w]=await N(f.listenToAvailableDevices().pipe(T(3))),C=await f.connect({deviceId:w.id,onDisconnect:D}),A=await f.disconnect({connectedDevice:C.extract()});i(A).toEqual(E(void 0)),i(D).toHaveBeenCalled(),i(c).toHaveBeenCalled()}),it("should handle error while disconnecting",async()=>{let n=null;const e=new u,s={id:"deviceId",readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"knownDeviceId",localName:"knownDeviceName"})}),services:vi.fn().mockResolvedValueOnce([{uuid:"ledgerId"}])},t=vi.fn().mockImplementation((d,y,P)=>{n=setInterval(()=>{P(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},100)}),p=vi.fn().mockImplementation(()=>{n&&(clearInterval(n),n=null)}),S=vi.fn().mockImplementation((d,y)=>(y(new Error("yolo"),null),{remove:vi.fn()})),c=vi.fn();vi.spyOn(e,"connectedDevices").mockImplementation(o),vi.spyOn(e,"startDeviceScan").mockImplementation(t),vi.spyOn(e,"stopDeviceScan").mockImplementation(p),vi.spyOn(e,"connectToDevice").mockResolvedValueOnce(s),vi.spyOn(e,"discoverAllServicesAndCharacteristicsForDevice").mockResolvedValueOnce(s),vi.spyOn(e,"monitorCharacteristicForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"writeCharacteristicWithoutResponseForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(vi.fn()),vi.spyOn(e,"isDeviceConnected").mockImplementation(vi.fn()),vi.spyOn(e,"onStateChange").mockImplementation(d=>(d(g.PoweredOn),{remove:vi.fn()})),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(S),vi.spyOn(e,"isDeviceConnected").mockImplementation(vi.fn());const k=d=>new U({deviceId:"deviceId",deviceApduSender:d.deviceApduSender,timeoutDuration:1e3,onTerminated:d.onTerminated,tryToReconnect:d.tryToReconnect}),a=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0),closeConnection:c}),f=new v(m,()=>l,()=>{},()=>{},e,r,{},k,a),D=vi.fn(),[w]=await N(f.listenToAvailableDevices().pipe(T(3))),C=await f.connect({deviceId:w.id,onDisconnect:D}),A=await f.disconnect({connectedDevice:C.extract()});i(A).toEqual(E(void 0)),i(D).toHaveBeenCalled()})})});
|
|
1
|
+
import{BleManager as N,State as d}from"react-native-ble-plx";import{BleDeviceInfos as V,DeviceConnectionStateMachine as R,DeviceModelId as U,OpeningConnectionError as L,TransportConnectedDevice as x,TransportDeviceModel as _}from"@ledgerhq/device-management-kit";import{Left as q,Right as P}from"purify-ts";import{firstValueFrom as f,Subject as F}from"rxjs";import{beforeEach as H,expect as t}from"vitest";import{BleNotSupported as W,BlePermissionsNotGranted as A,BlePoweredOff as z}from"../model/Errors";import{DefaultPermissionsService as j}from"../permissions/DefaultPermissionsService";import{RNBleTransport as T}from"./RNBleTransport";import{RNBleTransportFactory as G}from"./RNBleTransportFactory";const O={error:vi.fn(),info:vi.fn(),warn:vi.fn(),debug:vi.fn(),subscribers:[]},J={error:console.error,info:console.info,warn:console.warn,debug:console.debug,subscribers:[]};vi.mock("react-native",()=>({Platform:{},PermissionsAndroid:{}}));vi.mock("react-native-ble-plx",()=>({Device:vi.fn(),State:{PoweredOn:"PoweredOn",Unknown:"Unknown",PoweredOff:"PoweredOff",Resetting:"Resetting",Unsupported:"Unsupported",Unauthorized:"Unauthorized"},BleError:vi.fn(),BleManager:vi.fn().mockReturnValue({onStateChange:vi.fn(),startDeviceScan:vi.fn(),stopDeviceScan:vi.fn(),connectToDevice:vi.fn(),disconnectFromDevice:vi.fn(),cancelDeviceConnection:vi.fn(),connectedDevices:vi.fn(),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),discoverAllServicesAndCharacteristicsForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn()})}));const M=new _({id:U.FLEX,productName:"Ledger Flex",usbProductId:112,bootloaderUsbProductId:7,usbOnly:!1,memorySize:1533*1024,blockSize:32,masks:[858783744]}),h={OS:"ios"},K={OS:"android"},I={OS:"windows"};class s{deviceModelDataSource=b();loggerServiceFactory=()=>O;apduSenderServiceFactory=()=>{};apduReceiverServiceFactory=()=>{};bleManager=new N;platform=h;permissionsService=new j;deviceConnectionStateMachineFactory;deviceApduSenderFactory;scanThrottleDelayMs=1e3;withDeviceModelDataSource(e){return this.deviceModelDataSource=e,this}withPlatform(e){return this.platform=e,this}withPermissionsService(e){return this.permissionsService=e,this}withBleManager(e){return this.bleManager=e,this}withDeviceConnectionStateMachineFactory(e){return this.deviceConnectionStateMachineFactory=e,this}withDeviceApduSenderFactory(e){return this.deviceApduSenderFactory=e,this}withLogger(e=J){return this.loggerServiceFactory=()=>e,this}withScanThrottleDelayMs(e){return this.scanThrottleDelayMs=e,this}build(){return new T(this.deviceModelDataSource,this.loggerServiceFactory,this.apduSenderServiceFactory,this.apduReceiverServiceFactory,this.bleManager,this.platform,this.permissionsService,this.scanThrottleDelayMs,this.deviceConnectionStateMachineFactory,this.deviceApduSenderFactory)}}function b(){const p=vi.fn(()=>["ledgerId"]),e=vi.fn(()=>({ledgerId:new V(M,"serviceUuid","notifyUuid","writeCmdUuid","readCmdUuid")}));return{getBluetoothServices:p,getBluetoothServicesInfos:e,getAllDeviceModels:vi.fn(),getDeviceModel:vi.fn(),filterDeviceModels:vi.fn()}}function B(p={}){return{id:"deviceId",localName:"deviceName",serviceUUIDs:["ledgerId"],services:vi.fn().mockResolvedValue([{uuid:"ledgerId"}]),...p}}function m(p={},e=d.PoweredOn){return{onStateChange:vi.fn().mockImplementation((o,c)=>(c&&o(e),{remove:vi.fn()})),startDeviceScan:vi.fn(),stopDeviceScan:vi.fn(),connectToDevice:vi.fn(),disconnectFromDevice:vi.fn(),cancelDeviceConnection:vi.fn(),connectedDevices:vi.fn().mockResolvedValue([]),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),discoverAllServicesAndCharacteristicsForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),state:vi.fn(),...p}}describe("RNBleTransportFactory",()=>{it("should return a RNBleTransport",()=>{const p={deviceModelDataSource:b(),loggerServiceFactory:()=>O,apduSenderServiceFactory:()=>{},apduReceiverServiceFactory:()=>{},config:{}},e=G(p);t(e).toBeInstanceOf(T)})});describe("RNBleTransport",()=>{let p;H(()=>{vi.clearAllMocks(),vi.useRealTimers()}),afterEach(()=>{p&&p.unsubscribe()}),describe("BLE state monitoring",()=>{test("the constructor should call BleManager.onStateChange with a parameter requesting the initial state",()=>{const e=vi.fn();new s().withBleManager(m({onStateChange:e})).build(),t(e).toHaveBeenCalledWith(t.any(Function),!0)}),describe("observeBleState",()=>{it("should emit the initial BLE state",async()=>{const e=vi.fn().mockImplementation((i,r)=>(r&&i(d.PoweredOn),{remove:vi.fn()})),o=new s().withBleManager(m({onStateChange:e})).build().observeBleState(),c=await f(o);t(c).toBe(d.PoweredOn)}),it("should emit the new BLE state values",async()=>{const e=new F,o=new s().withBleManager(m({onStateChange:r=>(r(d.PoweredOn),e.subscribe(a=>r(a)),{remove:vi.fn()})})).build().observeBleState();e.next(d.PoweredOff);const c=await f(o);t(c).toBe(d.PoweredOff),e.next(d.Resetting);const i=await f(o);t(i).toBe(d.Resetting)}),it("should recover from an Unknown state by calling BleManager.state() method and emitting the new state",async()=>{vi.useFakeTimers();const e=new F,n=vi.fn().mockImplementation(()=>new Promise(a=>{setTimeout(()=>{a(d.PoweredOn)},10)})),c=new s().withBleManager(m({state:n,onStateChange:a=>(e.subscribe(v=>a(v)),{remove:vi.fn()})})).build().observeBleState();e.next(d.PoweredOff),t(n).not.toHaveBeenCalled(),e.next(d.Unknown);const i=await f(c);t(i).toBe(d.Unknown),t(n).toHaveBeenCalled(),vi.advanceTimersByTime(11),await Promise.resolve();const r=await f(c);t(r).toBe(d.PoweredOn)})})}),describe("getIdentifier",()=>{it("should return rnBleTransportIdentifier",()=>{const n=new s().build().getIdentifier();t(n).toStrictEqual("RN_BLE")})}),describe("isSupported",()=>{it("should return true if platform is ios",()=>{const n=new s().withPlatform(h).build().isSupported();t(n).toBe(!0)}),it("should return true if platform is android",()=>{const n=new s().withPlatform(K).build().isSupported();t(n).toBe(!0)}),it("should return false if platform is not android nor ios",()=>{const n=new s().withPlatform(I).build().isSupported();t(n).toBe(!1)})}),describe("startDiscovering",()=>{it("should emit an empty array",()=>new Promise((e,n)=>{p=new s().withPlatform(h).withDeviceModelDataSource(b()).build().startDiscovering().subscribe({next:i=>{try{t(i).toStrictEqual([])}catch(r){n(r)}},error:i=>{throw n(i),i},complete:()=>{e(void 0)}})}))}),describe("stopDiscovering",()=>{it("should call ble manager stop scan on stop discovering",()=>{const e=vi.fn(),n=m({stopDeviceScan:e,connectedDevices:vi.fn().mockResolvedValueOnce([])});new s().withBleManager(n).withPlatform(h).withDeviceModelDataSource(b()).build().stopDiscovering(),t(e).toHaveBeenCalled()})}),describe("listenToAvailableDevices",()=>{it("should emit an error if platform is not android nor ios",async()=>{const e=new s().withBleManager(m()).withPlatform(I).build();return new Promise((n,o)=>{e.listenToAvailableDevices().subscribe({error:c=>{try{t(c).toBeInstanceOf(W)}catch(i){o(i)}n(void 0)},complete:()=>{o(new Error("Should not complete"))}})})}),it("should emit an error if BLE state is PoweredOff",async()=>{const n=new s().withBleManager(m({},d.PoweredOff)).build().listenToAvailableDevices();let o;await f(n).catch(c=>{o=c}),t(o).toBeInstanceOf(z)}),describe("permissions check",()=>{const e=vi.fn(),n=vi.fn(),o={checkRequiredPermissions:e,requestRequiredPermissions:n},c=vi.fn().mockImplementation(async()=>{}),i=m({startDeviceScan:c,stopDeviceScan:vi.fn(),connectedDevices:vi.fn().mockResolvedValue([]),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:r=>(r(d.PoweredOn),{remove:vi.fn()})});it("should call checkPermissions",async()=>{const a=new s().withBleManager(i).withPlatform(h).withPermissionsService(o).build().listenToAvailableDevices();await f(a).catch(v=>{t(v).toBeInstanceOf(A)}),t(e).toHaveBeenCalled()}),it("should call BleManager.startDeviceScan if checkPermissions resolves to true",async()=>{e.mockResolvedValue(!0);const a=new s().withBleManager(i).withPlatform(h).withPermissionsService(o).build().listenToAvailableDevices();await f(a).catch(v=>{t(v).toBeInstanceOf(A)}),t(c).toHaveBeenCalled()}),it("should call requestPermissions if checkPermissions resolves to false",async()=>{e.mockResolvedValue(!1);const a=new s().withBleManager(i).withPlatform(h).withPermissionsService(o).build().listenToAvailableDevices();await f(a).catch(()=>{}),t(n).toHaveBeenCalled()}),it("should call BleManager.startDeviceScan if requestPermissions resolves to true",async()=>{e.mockResolvedValue(!1),n.mockResolvedValue(!0);const r=new s().withBleManager(i).withPlatform(h).withPermissionsService(o).build(),a=r.listenToAvailableDevices();await f(r.observeBleState()),await f(a),t(c).toHaveBeenCalled()}),it("should emit an error if checkPermissions and requestPermissions resolve to false",async()=>{e.mockResolvedValue(!1),n.mockResolvedValue(!1);const a=new s().withBleManager(i).withPlatform(h).withPermissionsService(o).build().listenToAvailableDevices();return new Promise((v,l)=>{a.subscribe({error:u=>{try{t(u).toBeInstanceOf(A)}catch(S){l(S)}v(void 0)},complete:()=>{l(new Error("Should not complete"))}})})})}),it("should return already connected devices and scanned devices",()=>new Promise((e,n)=>{let o=null;const c=B({id:"aConnectedDeviceId",localName:"aConnectedDeviceName"}),i=vi.fn().mockImplementation(async(u,S,w)=>{o=setInterval(()=>{w(null,{id:"aScannedDeviceId",localName:"aScannedDeviceName",serviceUUIDs:["ledgerId"],rssi:1})},10),w(null,{id:"aNonLedgerScannedDeviceId",localName:"aNonLedgerScannedDeviceName",serviceUUIDs:["notLedgerId"],rssi:2})}),r=vi.fn().mockImplementation(()=>{o&&(clearInterval(o),o=null)}),a=m({connectedDevices:vi.fn().mockResolvedValue([c]),startDeviceScan:i,stopDeviceScan:r,onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:u=>(u(d.PoweredOn),{remove:vi.fn()})}),v=new s().withBleManager(a).withPlatform(h).withDeviceModelDataSource(b()).withScanThrottleDelayMs(1).build(),l=[];p=v.listenToAvailableDevices().subscribe({next:u=>{if(l.push(u),l.length===2)try{t(l).toEqual([[{id:"aConnectedDeviceId",name:"aConnectedDeviceName",deviceModel:M,transport:"RN_BLE",rssi:void 0}],[{id:"aConnectedDeviceId",name:"aConnectedDeviceName",deviceModel:M,transport:"RN_BLE",rssi:void 0},{id:"aScannedDeviceId",name:"aScannedDeviceName",deviceModel:M,transport:"RN_BLE",rssi:1}]]),e(void 0)}catch(S){n(S)}}})})),it("should propagate the error if startDeviceScan throws an error",()=>{const e=new Error("startDeviceScan error"),n=vi.fn().mockRejectedValueOnce(e),c=new s().withBleManager(m({startDeviceScan:n})).build().listenToAvailableDevices();return new Promise((i,r)=>{c.subscribe({error:a=>{try{t(a).toBe(e),i(void 0)}catch(v){r(v)}},complete:()=>r(new Error("Should not complete"))})})}),it("should propagate the error if startDeviceScan emits an error",()=>{const e=new Error("startDeviceScan error"),n=vi.fn().mockImplementation(async(i,r,a)=>{a(e,{})}),c=new s().withBleManager(m({startDeviceScan:n})).build().listenToAvailableDevices();return new Promise((i,r)=>{c.subscribe({error:a=>{try{t(a).toBe(e),i(void 0)}catch(v){r(v)}i(void 0)},complete:()=>r(new Error("Should not complete"))})})}),it("should propagate an error if startDeviceScan emits a null device",()=>{const e=vi.fn().mockImplementation(async(c,i,r)=>{r(null,null)}),o=new s().withBleManager(m({startDeviceScan:e})).build().listenToAvailableDevices();return new Promise((c,i)=>{o.subscribe({error:r=>{try{t(r).toEqual(new Error("Null device in startDeviceScan callback")),c(void 0)}catch(a){i(a)}}})})}),it("should recover from a scanning error, allowing next calls of listenToAvailableDevices to succeed and emit the devices",async()=>{vi.useFakeTimers();const e=new Error("A Scan Error"),n=vi.fn().mockRejectedValueOnce(e),o=new s().withBleManager(m({startDeviceScan:n})).build(),c=o.listenToAvailableDevices();let i;await f(c).catch(v=>{i=v}),t(i).toBe(e),n.mockImplementation(async(v,l,u)=>{u(null,{id:"aScannedDeviceId",localName:"aScannedDeviceName",serviceUUIDs:["ledgerId"],rssi:1})});const r=o.listenToAvailableDevices();vi.advanceTimersByTime(2e3);const a=await f(r).catch(()=>{throw new Error("Caught error in second observable, this should not happen if listenToAvailableDevices recovers from the scanning error")});t(a).toEqual([{id:"aScannedDeviceId",name:"aScannedDeviceName",deviceModel:M,transport:"RN_BLE",rssi:1}])})}),describe("connect",()=>{it("should throw an error if device id is unknown",async()=>{const e=m({connectedDevices:vi.fn().mockResolvedValue([]),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockRejectedValueOnce(new Error("discoverAllServicesAndCharacteristicsForDevice error"))}),n=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0)}),c=await new s().withBleManager(e).withPlatform(h).withDeviceModelDataSource(b()).withDeviceApduSenderFactory(n).build().connect({deviceId:null,onDisconnect:vi.fn()});t(c).toEqual(q(new L("discoverAllServicesAndCharacteristicsForDevice error")))}),it("should connect to a discovered device with correct MTU and discover services and setup apdu sender",async()=>{const e=B({id:"deviceId",localName:"name"}),n=vi.fn().mockImplementation(async(g,k,y)=>{y(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})}),o=vi.fn(),c=m({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:n,stopDeviceScan:o,connectToDevice:vi.fn().mockResolvedValueOnce(e),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(e),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:g=>(g(d.PoweredOn),{remove:vi.fn()})}),i=vi.fn().mockResolvedValue(void 0),r=vi.fn().mockReturnValue({sendApdu:vi.fn()}),a=vi.fn().mockReturnValue({setupConnection:i}),v=new s().withBleManager(c).withPlatform(h).withDeviceModelDataSource(b()).withDeviceConnectionStateMachineFactory(r).withDeviceApduSenderFactory(a).withScanThrottleDelayMs(1).build(),l=v.listenToAvailableDevices(),u=await f(l),[S]=u,w=await v.connect({deviceId:S.id,onDisconnect:vi.fn()});t(w.isRight()).toBe(!0),t(c.connectToDevice).toHaveBeenCalledWith("deviceId",{requestMTU:156}),t(c.discoverAllServicesAndCharacteristicsForDevice).toHaveBeenCalledWith("deviceId"),t(i).toHaveBeenCalled()}),it("should return a connected device which calls state machine sendApdu",async()=>{vi.useFakeTimers();const e=B({id:"deviceId",localName:"name"}),n=vi.fn().mockImplementation(async(k,y,D)=>{D(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})}),o=vi.fn(),c=m({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:n,stopDeviceScan:o,connectToDevice:vi.fn().mockResolvedValueOnce(e),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(e),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:k=>(k(d.PoweredOn),{remove:vi.fn()})}),i=vi.fn(),r=vi.fn().mockReturnValue({sendApdu:i}),a=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0)}),v=new s().withBleManager(c).withPlatform(h).withDeviceModelDataSource(b()).withDeviceConnectionStateMachineFactory(r).withDeviceApduSenderFactory(a).build(),l=v.listenToAvailableDevices();vi.advanceTimersByTime(2e3);const u=await f(l),[S]=u,w=await v.connect({deviceId:S.id,onDisconnect:vi.fn()});w.extract().sendApdu(Uint8Array.from([67,50])),t(w).toEqual(P(new x({id:"deviceId",deviceModel:M,type:"BLE",transport:"RN_BLE",sendApdu:t.any(Function)}))),t(i).toHaveBeenCalledWith(Uint8Array.from([67,50]))})}),describe("disconnect",()=>{it("should disconnect gracefully",async()=>{vi.useFakeTimers();const e=B({id:"deviceId",localName:"name"}),n=vi.fn().mockImplementation(async(D,E,C)=>{C(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})}),o=vi.fn(),c=vi.fn().mockImplementation(()=>({remove:vi.fn()})),i=vi.fn(),r=m({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:n,stopDeviceScan:o,connectToDevice:vi.fn().mockResolvedValueOnce(e),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(e),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onStateChange:D=>(D(d.PoweredOn),{remove:vi.fn()}),onDeviceDisconnected:c,isDeviceConnected:vi.fn()}),a=D=>new R({deviceId:"deviceId",deviceApduSender:D.deviceApduSender,timeoutDuration:1e3,onTerminated:D.onTerminated,tryToReconnect:D.tryToReconnect}),v=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0),closeConnection:i}),l=new s().withBleManager(r).withPlatform(h).withDeviceModelDataSource(b()).withDeviceConnectionStateMachineFactory(a).withDeviceApduSenderFactory(v).build(),u=vi.fn(),S=l.listenToAvailableDevices();vi.advanceTimersByTime(2e3);const w=await f(S),[g]=w,k=await l.connect({deviceId:g.id,onDisconnect:u}),y=await l.disconnect({connectedDevice:k.extract()});t(y).toEqual(P(void 0)),t(u).toHaveBeenCalled(),t(i).toHaveBeenCalled()}),it("should handle error while disconnecting",async()=>{vi.useFakeTimers();const e=B({id:"deviceId",localName:"name"}),n=vi.fn().mockImplementation(async(D,E,C)=>{C(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})}),o=vi.fn(),c=vi.fn().mockImplementation(()=>({remove:vi.fn()})),i=vi.fn(),r=m({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:n,stopDeviceScan:o,connectToDevice:vi.fn().mockResolvedValueOnce(e),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(e),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onDeviceDisconnected:c,isDeviceConnected:vi.fn(),onStateChange:D=>(D(d.PoweredOn),{remove:vi.fn()})}),a=D=>new R({deviceId:"deviceId",deviceApduSender:D.deviceApduSender,timeoutDuration:1e3,onTerminated:D.onTerminated,tryToReconnect:D.tryToReconnect}),v=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0),closeConnection:i}),l=new s().withBleManager(r).withPlatform(h).withDeviceModelDataSource(b()).withDeviceConnectionStateMachineFactory(a).withDeviceApduSenderFactory(v).build(),u=vi.fn(),S=l.listenToAvailableDevices();vi.advanceTimersByTime(2e3);const w=await f(S),[g]=w,k=await l.connect({deviceId:g.id,onDisconnect:u}),y=await l.disconnect({connectedDevice:k.extract()});t(y).toEqual(P(void 0)),t(u).toHaveBeenCalled()})})});
|
|
2
2
|
//# sourceMappingURL=RNBleTransport.test.js.map
|