@ledgerhq/device-transport-kit-react-native-ble 0.0.0-rnble-scan-permission-issue-20250929081059 → 0.0.0-speculos-transport-and-device-interactor-20251015100427
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/cjs/api/index.js +1 -1
- package/lib/cjs/api/index.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/{transport → permissions}/PermissionsAndroidNarrowedType.js.map +1 -1
- 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/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/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/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.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 +6 -12
- 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 +6 -6
- package/lib/types/api/transport/PermissionsAndroidNarrowedType.d.ts.map +0 -1
- /package/lib/cjs/api/{transport → permissions}/PermissionsAndroidNarrowedType.js +0 -0
- /package/lib/esm/api/{transport → permissions}/PermissionsAndroidNarrowedType.js +0 -0
- /package/lib/esm/api/{transport → permissions}/PermissionsAndroidNarrowedType.js.map +0 -0
- /package/lib/types/api/{transport → permissions}/PermissionsAndroidNarrowedType.d.ts +0 -0
|
@@ -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,KAAK,cAElB,CAACC,CAAS,EAAIF,EAAY,MAAM,CAAC,EACvC,IAAIG,EAAYF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,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 R,Platform as m}from"react-native";import{BleError as E,BleManager as A,State as M}from"react-native-ble-plx";import{DeviceConnectionStateMachine as N,OpeningConnectionError as y,TransportConnectedDevice as f,UnknownDeviceError as P}from"@ledgerhq/device-management-kit";import{Either as b,EitherAsync as I,Left as T,Maybe as l,Nothing as h,Right as g}from"purify-ts";import{BehaviorSubject as D,defer as O,filter as U,finalize as F,from as C,retry as L,switchMap as S,tap as j,throttleTime as x,throwError as k}from"rxjs";import{BLE_DISCONNECT_TIMEOUT_ANDROID as $,BLE_DISCONNECT_TIMEOUT_IOS as q,CONNECTION_LOST_DELAY as z,DEFAULT_MTU as w}from"../model/Const";import{BleNotSupported as G,BlePermissionsNotGranted as H,DeviceConnectionNotFound as J,NoDeviceModelFoundError as B,PeerRemovedPairingError as V}from"../model/Errors";import{RNBleApduSender as Y}from"../transport/RNBleApduSender";const re="RN_BLE";class K{constructor(e,n,t,i,c,a=m,r=R,s=d=>new N(d),v=(d,u)=>new Y(d,u)){this._deviceModelDataSource=e;this._loggerServiceFactory=n;this._apduSenderFactory=t;this._apduReceiverFactory=i;this._manager=c;this._platform=a;this._permissionsAndroid=r;this._deviceConnectionStateMachineFactory=s;this._deviceApduSenderFactory=v;this._logger=n("ReactNativeBleTransport"),this._deviceConnectionsById=new Map,this._reconnectionSubscription=l.zero(),this._manager.onStateChange(d=>{this._logger.debug("[manager.onStateChange]",{data:{state:d}}),this._bleStateSubject.next(d)},!0)}_logger;_deviceConnectionsById;identifier="RN_BLE";_reconnectionSubscription;_bleStateSubject=new D(M.Unknown);startDiscovering(){return C([])}async stopDiscovering(){await this._stopScanning()}_maybeScanningSubject=h;_scannedDevicesSubject=new D([]);_startedScanningSubscriber=void 0;_startScanning(){this._startedScanningSubscriber==null&&(this._scannedDevicesSubject.next([]),this._startedScanningSubscriber=C(this._bleStateSubject).pipe(j(()=>{if(!this.isSupported())throw new G("BLE not supported")}),U(e=>e==="PoweredOn"),S(async()=>this.checkAndRequestPermissions()),S(e=>{if(!e)return k(()=>new H("Permissions not granted"));const n=new D([]);this._maybeScanningSubject=l.of(n);const t=new Map;this._logger.info("[startScanning] startDeviceScan"),this._manager.startDeviceScan(this._deviceModelDataSource.getBluetoothServices(),{allowDuplicates:!0},(c,a)=>{if(c||!a){n.error(c||new Error("scan error"));return}t.set(a.id,{device:a,timestamp:Date.now()}),n.next(Array.from(t.values()))}),this._logger.debug("[startScanning] after startDeviceScan");const i=setInterval(()=>{n.next(Array.from(t.values()))},1e3);return n.asObservable().pipe(F(()=>{this._logger.debug("[RNBleTransport][startScanning] finalize"),n.complete(),clearInterval(i),this._maybeScanningSubject=h,this._manager.stopDeviceScan()}))}),x(1e3)).subscribe({next:e=>{this._scannedDevicesSubject.next(e)},error:e=>{this._logger.error("Error while scanning",{data:{error:e}}),this._scannedDevicesSubject.error(e)}}))}async _stopScanning(){this._maybeScanningSubject.map(e=>{e.complete(),this._maybeScanningSubject=h}),await this._manager.stopDeviceScan(),this._startedScanningSubscriber?.unsubscribe(),this._startedScanningSubscriber=void 0}listenToAvailableDevices(){return this._startScanning(),this._scannedDevicesSubject.asObservable().pipe(S(async e=>{const n=e.filter(({timestamp:r})=>r>Date.now()-z).sort((r,s)=>(s.device.rssi??-1/0)-(r.device.rssi??-1/0)).map(({device:r})=>this._mapDeviceToTransportDiscoveredDevice(r,r.serviceUUIDs)).filter(r=>!!r),t=b.rights(n),i=await this._manager.connectedDevices(this._deviceModelDataSource.getBluetoothServices()),c=await Promise.all(i.map(async r=>{try{const v=(await r.services()).map(d=>d.uuid);return this._mapDeviceToTransportDiscoveredDevice(r,v)}catch(s){return this._logger.error("[listenToAvailableDevices] Error in mapping device to transport discovered device",{data:{e:s}}),T(new B(`Error in mapping device to transport discovered device: ${s}`))}})),a=b.rights(c);return this._logger.debug("[listenToAvailableDevices]",{data:{rawConnectedDevices:i.map(r=>r.name),connectedDevices:a.map(r=>r.name),scannedDevices:t.map(r=>r.name)}}),[...a,...t]}))}_mapServicesUUIDsToBluetoothDeviceInfo(e){for(const n of e||[]){const t=this._deviceModelDataSource.getBluetoothServicesInfos()[n];if(t)return g(t)}return T(new B(`No device model found for [uuids=${e}]`))}_mapServicesUUIDsToDeviceModel(e){return this._mapServicesUUIDsToBluetoothDeviceInfo(e).map(t=>t.deviceModel)}_mapDeviceToTransportDiscoveredDevice(e,n){return this._mapServicesUUIDsToDeviceModel(n).map(i=>({id:e.id,name:e.localName||e.name||"",deviceModel:i,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 t=n.getDependencies().internalDevice.bleDeviceInfos.deviceModel;return g(new f({id:e.deviceId,deviceModel:t,type:"BLE",sendApdu:(...i)=>n.sendApdu(...i),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),I(async({throwE:t})=>{let i,c=[];try{await this._manager.connectToDevice(e.deviceId,{requestMTU:w}),i=await this._manager.discoverAllServicesAndCharacteristicsForDevice(e.deviceId),c=(await i.services()).map(o=>o.uuid)}catch(o){return o instanceof E&&o.iosErrorCode===14?t(new V(o)):t(new y(o))}const a=this._listenToDeviceDisconnected(e.deviceId),r=this._mapServicesUUIDsToBluetoothDeviceInfo(c).caseOf({Right:o=>o,Left:o=>t(new y(o))}),s=r.deviceModel,v={id:i.id,bleDeviceInfos:r},d=this._deviceApduSenderFactory({apduSenderFactory:this._apduSenderFactory,apduReceiverFactory:this._apduReceiverFactory,dependencies:{device:i,internalDevice:v,manager:this._manager}},this._loggerServiceFactory),u=m.OS==="ios"?q:$,p=this._deviceConnectionStateMachineFactory({deviceId:e.deviceId,deviceApduSender:d,timeoutDuration:u,tryToReconnect:()=>this.tryToReconnect(e.deviceId),onTerminated:async()=>{this._logger.debug("[onTerminated]",{data:{deviceId:e.deviceId}});try{await this._safeCancel(e.deviceId)}catch(o){this._logger.error("[onTerminated] Error in termination of device connection",{data:{e:o}})}finally{this._deviceConnectionsById.delete(e.deviceId),this._reconnectionSubscription.ifJust(o=>{o.unsubscribe(),this._reconnectionSubscription=l.zero()}),this._logger.debug("[onTerminated] signaling disconnection",{data:{deviceId:e.deviceId}}),e.onDisconnect(e.deviceId)}}});return await d.setupConnection().catch(o=>{throw this._safeCancel(e.deviceId),a.remove(),o}),this._deviceConnectionsById.set(e.deviceId,p),new f({id:i.id,deviceModel:s,type:"BLE",sendApdu:(...o)=>p.sendApdu(...o),transport:this.identifier})}).run()}async disconnect(e){const n=e.connectedDevice.id,t=this._deviceConnectionsById.get(n);if(!t)throw new P(`No connected device found with id ${n}`);return t.closeConnection(),Promise.resolve(g(void 0))}isSupported(){return["android","ios"].includes(this._platform.OS)}getIdentifier(){return this.identifier}async checkAndRequestPermissions(){if(this._logger.debug("[checkAndRequestPermissions] Called"),this._platform.OS==="ios")return!0;if(this._platform.OS==="android"){const{PERMISSIONS:e,RESULTS:n,check:t,requestMultiple:i}=this._permissionsAndroid,c=this._platform.Version,a=c<=28?[e.ACCESS_COARSE_LOCATION]:c<=30?[e.ACCESS_FINE_LOCATION]:[],s=[...c<31?[]:[e.BLUETOOTH_SCAN,e.BLUETOOTH_CONNECT],...a];if((await Promise.all(s.map(o=>t(o)))).every(o=>o))return!0;const u=await i(s);return!!Object.values(u).every(o=>o===n.GRANTED)}return!1}_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 t=n.id;l.fromNullable(this._deviceConnectionsById.get(t)).map(i=>i.eventDeviceDisconnected())}_listenToDeviceDisconnected(e){const n=this._manager.onDeviceDisconnected(e,(t,i)=>{this._handleDeviceDisconnected(t,i),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 t=O(async()=>{let i=null;n++;try{this._logger.debug(`[tryToReconnect](try=${n}) Reconnecting to device`,{data:{id:e}});const c=await this._manager.connectToDevice(e,{requestMTU:w,timeout:2e3});this._logger.debug(`[tryToReconnect](try=${n}) Established connection to device`,{data:{id:e}});const a=await c.discoverAllServicesAndCharacteristics();return this._logger.debug(`[tryToReconnect](try=${n}) Discovered all services and characteristics`,{data:{usableReconnectedDevice:a}}),i=this._listenToDeviceDisconnected(e),await this._handleDeviceReconnected(a),a}catch(c){throw this._logger.warn(`[tryToReconnect](try=${n}) Reconnecting to device failed`,{data:{e:c}}),i?.remove(),await this._stopScanning(),await this._safeCancel(e),c}}).pipe(L(5));this._reconnectionSubscription=l.of(t.subscribe({next:i=>this._logger.debug(`[tryToReconnect](try=${n}) Fully reconnected to device (id=${i.id})`),complete:()=>{this._logger.debug("[tryToReconnect] Completed"),this._reconnectionSubscription=l.zero()},error:i=>{this._logger.error("[tryToReconnect] All reconnection attempts failed",{data:{e:i}}),this._deviceConnectionsById.get(e)?.closeConnection(),this._reconnectionSubscription=l.zero()}}))}async _handleDeviceReconnected(e){const n=l.fromNullable(this._deviceConnectionsById.get(e.id)).toEither(new J);return I(async({liftEither:t,throwE:i})=>{const c=await t(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}}),i(s))});c.setDependencies({device:e,manager:this._manager,internalDevice:r}),await c.setupConnection().catch(s=>{throw this._safeCancel(e.id),s}),c.eventDeviceConnected()}).run()}async _safeCancel(e){if(typeof this._manager.cancelDeviceConnection=="function"){const n=await this._manager.connectedDevices(this._deviceModelDataSource.getBluetoothServices());for(const t of n)if(t.id===e)try{await this._manager.cancelDeviceConnection(e)}catch(i){this._logger.error("[safeCancel] Error in cancelling device connection",{data:{e:i}})}}}}const oe=({deviceModelDataSource:_,loggerServiceFactory:e,apduSenderServiceFactory:n,apduReceiverServiceFactory:t})=>new K(_,e,n,t,new A);export{K as RNBleTransport,oe as RNBleTransportFactory,re as rnBleTransportIdentifier};
|
|
1
|
+
import{Platform as w}from"react-native";import{BleError as B,State as R}from"react-native-ble-plx";import{DeviceConnectionStateMachine as M,OpeningConnectionError as _,TransportConnectedDevice as y,UnknownDeviceError as E}from"@ledgerhq/device-management-kit";import{Either as b,EitherAsync as m,Left as f,Maybe as v,Nothing as p,Right as h}from"purify-ts";import{BehaviorSubject as g,defer as A,filter as N,finalize as U,from as I,retry as P,switchMap as D,tap as F,throttleTime as O,throwError as j}from"rxjs";import{BLE_DISCONNECT_TIMEOUT_ANDROID as L,BLE_DISCONNECT_TIMEOUT_IOS as x,CONNECTION_LOST_DELAY as k,DEFAULT_MTU as T}from"../model/Const";import{BleNotSupported as q,BlePermissionsNotGranted as $,DeviceConnectionNotFound as z,NoDeviceModelFoundError as C,PeerRemovedPairingError as H}from"../model/Errors";import{RNBleApduSender as G}from"../transport/RNBleApduSender";const ne="RN_BLE";class te{constructor(e,n,t,i,o,a,r,s=d=>new M(d),l=(d,u)=>new G(d,u)){this._deviceModelDataSource=e;this._loggerServiceFactory=n;this._apduSenderFactory=t;this._apduReceiverFactory=i;this._manager=o;this._platform=a;this._permissionsService=r;this._deviceConnectionStateMachineFactory=s;this._deviceApduSenderFactory=l;this._logger=n("ReactNativeBleTransport"),this._deviceConnectionsById=new Map,this._reconnectionSubscription=v.zero(),this._manager.onStateChange(d=>{this._logger.debug("[manager.onStateChange]",{data:{state:d}}),this._bleStateSubject.next(d)},!0)}_logger;_deviceConnectionsById;identifier="RN_BLE";_reconnectionSubscription;_bleStateSubject=new g(R.Unknown);startDiscovering(){return I([])}async stopDiscovering(){await this._stopScanning()}_maybeScanningSubject=p;_scannedDevicesSubject=new g([]);_startedScanningSubscriber=void 0;_startScanning(){this._startedScanningSubscriber==null&&(this._scannedDevicesSubject.next([]),this._startedScanningSubscriber=I(this._bleStateSubject).pipe(F(()=>{if(!this.isSupported())throw new q("BLE not supported")}),N(e=>e==="PoweredOn"),D(async()=>this.checkAndRequestPermissions()),D(e=>{if(!e)return j(()=>new $("Permissions not granted"));const n=new g([]);this._maybeScanningSubject=v.of(n);const t=new Map;this._logger.info("[startScanning] startDeviceScan"),this._manager.startDeviceScan(this._deviceModelDataSource.getBluetoothServices(),{allowDuplicates:!0},(o,a)=>{if(o||!a){n.error(o||new Error("scan error"));return}t.set(a.id,{device:a,timestamp:Date.now()}),n.next(Array.from(t.values()))}),this._logger.debug("[startScanning] after startDeviceScan");const i=setInterval(()=>{n.next(Array.from(t.values()))},1e3);return n.asObservable().pipe(U(()=>{this._logger.debug("[RNBleTransport][startScanning] finalize"),n.complete(),clearInterval(i),this._maybeScanningSubject=p,this._manager.stopDeviceScan()}))}),O(1e3)).subscribe({next:e=>{this._scannedDevicesSubject.next(e)},error:e=>{this._logger.error("Error while scanning",{data:{error:e}}),this._scannedDevicesSubject.error(e)}}))}async _stopScanning(){this._maybeScanningSubject.map(e=>{e.complete(),this._maybeScanningSubject=p}),await this._manager.stopDeviceScan(),this._startedScanningSubscriber?.unsubscribe(),this._startedScanningSubscriber=void 0}listenToAvailableDevices(){return this._startScanning(),this._scannedDevicesSubject.asObservable().pipe(D(async e=>{const n=e.filter(({timestamp:r})=>r>Date.now()-k).sort((r,s)=>(s.device.rssi??-1/0)-(r.device.rssi??-1/0)).map(({device:r})=>this._mapDeviceToTransportDiscoveredDevice(r,r.serviceUUIDs)).filter(r=>!!r),t=b.rights(n),i=await this._manager.connectedDevices(this._deviceModelDataSource.getBluetoothServices()),o=await Promise.all(i.map(async r=>{try{const l=(await r.services()).map(d=>d.uuid);return this._mapDeviceToTransportDiscoveredDevice(r,l)}catch(s){return this._logger.error("[listenToAvailableDevices] Error in mapping device to transport discovered device",{data:{e:s}}),f(new C(`Error in mapping device to transport discovered device: ${s}`))}})),a=b.rights(o);return this._logger.debug("[listenToAvailableDevices]",{data:{rawConnectedDevices:i.map(r=>r.name),connectedDevices:a.map(r=>r.name),scannedDevices:t.map(r=>r.name)}}),[...a,...t]}))}_mapServicesUUIDsToBluetoothDeviceInfo(e){for(const n of e||[]){const t=this._deviceModelDataSource.getBluetoothServicesInfos()[n];if(t)return h(t)}return f(new C(`No device model found for [uuids=${e}]`))}_mapServicesUUIDsToDeviceModel(e){return this._mapServicesUUIDsToBluetoothDeviceInfo(e).map(t=>t.deviceModel)}_mapDeviceToTransportDiscoveredDevice(e,n){return this._mapServicesUUIDsToDeviceModel(n).map(i=>({id:e.id,name:e.localName||e.name||"",deviceModel:i,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 t=n.getDependencies().internalDevice.bleDeviceInfos.deviceModel;return h(new y({id:e.deviceId,deviceModel:t,type:"BLE",sendApdu:(...i)=>n.sendApdu(...i),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),m(async({throwE:t})=>{let i,o=[];try{await this._manager.connectToDevice(e.deviceId,{requestMTU:T}),i=await this._manager.discoverAllServicesAndCharacteristicsForDevice(e.deviceId),o=(await i.services()).map(c=>c.uuid)}catch(c){return c instanceof B&&c.iosErrorCode===14?t(new H(c)):t(new _(c))}const a=this._listenToDeviceDisconnected(e.deviceId),r=this._mapServicesUUIDsToBluetoothDeviceInfo(o).caseOf({Right:c=>c,Left:c=>t(new _(c))}),s=r.deviceModel,l={id:i.id,bleDeviceInfos:r},d=this._deviceApduSenderFactory({apduSenderFactory:this._apduSenderFactory,apduReceiverFactory:this._apduReceiverFactory,dependencies:{device:i,internalDevice:l,manager:this._manager}},this._loggerServiceFactory),u=w.OS==="ios"?x:L,S=this._deviceConnectionStateMachineFactory({deviceId:e.deviceId,deviceApduSender:d,timeoutDuration:u,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 d.setupConnection().catch(c=>{throw this._safeCancel(e.deviceId),a.remove(),c}),this._deviceConnectionsById.set(e.deviceId,S),new y({id:i.id,deviceModel:s,type:"BLE",sendApdu:(...c)=>S.sendApdu(...c),transport:this.identifier})}).run()}async disconnect(e){const n=e.connectedDevice.id,t=this._deviceConnectionsById.get(n);if(!t)throw new E(`No connected device found with id ${n}`);return t.closeConnection(),Promise.resolve(h(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 t=n.id;v.fromNullable(this._deviceConnectionsById.get(t)).map(i=>i.eventDeviceDisconnected())}_listenToDeviceDisconnected(e){const n=this._manager.onDeviceDisconnected(e,(t,i)=>{this._handleDeviceDisconnected(t,i),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 t=A(async()=>{let i=null;n++;try{this._logger.debug(`[tryToReconnect](try=${n}) Reconnecting to device`,{data:{id:e}});const o=await this._manager.connectToDevice(e,{requestMTU:T,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}}),i=this._listenToDeviceDisconnected(e),await this._handleDeviceReconnected(a),a}catch(o){throw this._logger.warn(`[tryToReconnect](try=${n}) Reconnecting to device failed`,{data:{e:o}}),i?.remove(),await this._stopScanning(),await this._safeCancel(e),o}}).pipe(P(5));this._reconnectionSubscription=v.of(t.subscribe({next:i=>this._logger.debug(`[tryToReconnect](try=${n}) Fully reconnected to device (id=${i.id})`),complete:()=>{this._logger.debug("[tryToReconnect] Completed"),this._reconnectionSubscription=v.zero()},error:i=>{this._logger.error("[tryToReconnect] All reconnection attempts failed",{data:{e:i}}),this._deviceConnectionsById.get(e)?.closeConnection(),this._reconnectionSubscription=v.zero()}}))}async _handleDeviceReconnected(e){const n=v.fromNullable(this._deviceConnectionsById.get(e.id)).toEither(new z);return m(async({liftEither:t,throwE:i})=>{const o=await t(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}}),i(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 t of n)if(t.id===e)try{await this._manager.cancelDeviceConnection(e)}catch(i){this._logger.error("[safeCancel] Error in cancelling device connection",{data:{e:i}})}}}}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 { type Permission, PermissionsAndroid, Platform } from \"react-native\";\nimport {\n BleError,\n 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 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 defer,\n filter,\n finalize,\n from,\n type Observable,\n retry,\n type Subscription,\n switchMap,\n tap,\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 BlePermissionsNotGranted,\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\nimport { type PermissionsAndroidNarrowedType } from \"./PermissionsAndroidNarrowedType\";\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 = Platform,\n // NB: this type assertion is not great but this type is not properly defined in react-native, and this will actually be correct.\n private readonly _permissionsAndroid: PermissionsAndroidNarrowedType = PermissionsAndroid as PermissionsAndroidNarrowedType,\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 this._manager.onStateChange((state) => {\n this._logger.debug(\"[manager.onStateChange]\", { data: { 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 tap(() => {\n if (!this.isSupported()) {\n throw new BleNotSupported(\"BLE not supported\");\n }\n }),\n filter((state) => state === \"PoweredOn\"),\n switchMap(async () => this.checkAndRequestPermissions()),\n switchMap((hasPermissions) => {\n if (!hasPermissions) {\n return throwError(\n () => new BlePermissionsNotGranted(\"Permissions not granted\"),\n );\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(\"[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 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.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._scannedDevicesSubject.next(devices);\n },\n error: (error) => {\n this._logger.error(\"Error while scanning\", { data: { error } });\n this._scannedDevicesSubject.error(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 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.connectedDevices(\n this._deviceModelDataSource.getBluetoothServices(),\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 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 * 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 checkAndRequestPermissions(): Promise<boolean> {\n this._logger.debug(\"[checkAndRequestPermissions] Called\");\n\n if (this._platform.OS === \"ios\") {\n return true;\n }\n\n if (this._platform.OS === \"android\") {\n const { PERMISSIONS, RESULTS, check, requestMultiple } =\n this._permissionsAndroid;\n\n const apiLevel = this._platform.Version;\n\n /**\n * On Android 9 (SDK level 28) and before, the app needs to have the ACCESS_COARSE_LOCATION permission.\n *\n * On Android 10 (SDK level 29) and 11 (SDK level 30), it needs the ACCESS_FINE_LOCATION permission.\n *\n * See https://developer.android.com/guide/topics/connectivity/bluetooth/permissions#declare\n */\n const locationPermissions: Permission[] =\n apiLevel <= 28\n ? [PERMISSIONS.ACCESS_COARSE_LOCATION]\n : apiLevel <= 30\n ? [PERMISSIONS.ACCESS_FINE_LOCATION]\n : [];\n\n // On Android 11 and above, the app needs to have the BLUETOOTH_SCAN and BLUETOOTH_CONNECT permissions.\n const bluetoothPermissions: Permission[] =\n apiLevel < 31\n ? []\n : [PERMISSIONS.BLUETOOTH_SCAN, PERMISSIONS.BLUETOOTH_CONNECT];\n\n const allPermissions: Permission[] = [\n ...bluetoothPermissions,\n ...locationPermissions,\n ];\n\n // First, check if the permissions are already granted\n const allPermissionsCheckResults = await Promise.all(\n allPermissions.map((permission) => check(permission)),\n );\n\n const allPermissionsGranted = allPermissionsCheckResults.every(\n (granted) => granted,\n );\n\n if (allPermissionsGranted) {\n return true;\n }\n\n // If the permissions are not granted, request them\n const allPermissionsRequestResults =\n await requestMultiple(allPermissions);\n\n const allPermissionsGrantedAfterRequest = Object.values(\n allPermissionsRequestResults,\n ).every((requested) => requested === RESULTS.GRANTED);\n\n if (allPermissionsGrantedAfterRequest) {\n return true;\n }\n\n return false;\n }\n\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(\"[_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\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,OAA0B,sBAAAA,EAAoB,YAAAC,MAAgB,eAC9D,OACE,YAAAC,EACA,cAAAC,EAEA,SAAAC,MAEK,uBACP,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,SAAAC,EACA,UAAAC,EACA,YAAAC,EACA,QAAAC,EAEA,SAAAC,EAEA,aAAAC,EACA,OAAAC,EACA,gBAAAC,EACA,cAAAC,MACK,OAEP,OACE,kCAAAC,EACA,8BAAAC,EACA,yBAAAC,EACA,eAAAC,MACK,mBACP,OACE,mBAAAC,EACA,4BAAAC,EACA,4BAAAC,EACA,2BAAAC,EACA,2BAAAC,MACK,oBACP,OACE,mBAAAC,MAIK,iCAIA,MAAMC,GAA2B,SAOjC,MAAMC,CAAoC,CAY/C,YACmBC,EACAC,EAGAC,EACAC,EACAC,EACAC,EAAsBzC,EAEtB0C,EAAsD3C,EACtD4C,EAEiDC,GAChE,IAAIxC,EAA6BwC,CAAI,EACtBC,EAGM,CAACD,EAAME,IAC5B,IAAIb,EAAgBW,EAAME,CAAa,EACzC,CAnBiB,4BAAAV,EACA,2BAAAC,EAGA,wBAAAC,EACA,0BAAAC,EACA,cAAAC,EACA,eAAAC,EAEA,yBAAAC,EACA,0CAAAC,EAIA,8BAAAE,EAMjB,KAAK,QAAUR,EAAsB,yBAAyB,EAC9D,KAAK,uBAAyB,IAAI,IAClC,KAAK,0BAA4B1B,EAAM,KAAK,EAC5C,KAAK,SAAS,cAAeoC,GAAU,CACrC,KAAK,Q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,GAEF,KAAOpB,IACL,KAAK,QAAQ,MACX,sFACA,CACE,KAAM,CAAE,MAAAA,CAAM,CAChB,CACF,EAEOyB,EAAOzB,CAAK,EAEvB,CAAC,EAED+B,EAA6B,gBAAgB,CAC3C,OAAAtB,EACA,QAAS,KAAK,SACd,eAAAmB,CACF,CAAC,EAED,MAAMG,EAA6B,gBAAgB,EAAE,MAAOf,GAAM,CAChE,WAAK,YAAYP,EAAO,EAAE,EACpBO,CACR,CAAC,EAEDe,EAA6B,qBAAqB,CACpD,CAAC,EAAE,IAAI,CACT,CAEA,MAAc,YAAYE,EAAoB,CAE5C,GAAI,OAAO,KAAK,SAAS,wBAA2B,WAAY,CAC9D,MAAMhB,EAAmB,MAAM,KAAK,SAAS,iBAC3C,KAAK,uBAAuB,qBAAqB,CACnD,EAEA,UAAWR,KAAUQ,EACnB,GAAIR,EAAO,KAAOwB,EAChB,GAAI,CACF,MAAM,KAAK,SAAS,uBAAuBA,CAAQ,CACrD,OAASjB,EAAG,CACV,KAAK,QAAQ,MACX,qDACA,CACE,KAAM,CAAE,EAAAA,CAAE,CACZ,CACF,CACF,CAGN,CACF,CACF,CAEO,MAAMoC,GAA0C,CAAC,CACtD,sBAAAC,EACA,qBAAAC,EACA,yBAAAC,EACA,2BAAAC,CACF,IACE,IAAIxE,EACFqE,EACAC,EACAC,EACAC,EACA,IAAIzG,CACN",
|
|
6
|
-
"names": ["
|
|
4
|
+
"sourcesContent": ["import { Platform } from \"react-native\";\nimport {\n BleError,\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, Nothing, Right } from \"purify-ts\";\nimport {\n BehaviorSubject,\n defer,\n filter,\n finalize,\n from,\n type Observable,\n retry,\n type Subscription,\n switchMap,\n tap,\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 BlePermissionsNotGranted,\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 _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 this._manager.onStateChange((state) => {\n this._logger.debug(\"[manager.onStateChange]\", { data: { 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 tap(() => {\n if (!this.isSupported()) {\n throw new BleNotSupported(\"BLE not supported\");\n }\n }),\n filter((state) => state === \"PoweredOn\"),\n switchMap(async () => this.checkAndRequestPermissions()),\n switchMap((hasPermissions) => {\n if (!hasPermissions) {\n return throwError(\n () => new BlePermissionsNotGranted(\"Permissions not granted\"),\n );\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(\"[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 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.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._scannedDevicesSubject.next(devices);\n },\n error: (error) => {\n this._logger.error(\"Error while scanning\", { data: { error } });\n this._scannedDevicesSubject.error(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 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.connectedDevices(\n this._deviceModelDataSource.getBluetoothServices(),\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 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,EAGA,SAAAC,MAEK,uBACP,OAKE,gCAAAC,EAOA,0BAAAC,EAEA,4BAAAC,EAIA,sBAAAC,MACK,kCACP,OAAS,UAAAC,EAAQ,eAAAC,EAAa,QAAAC,EAAM,SAAAC,EAAO,WAAAC,EAAS,SAAAC,MAAa,YACjE,OACE,mBAAAC,EACA,SAAAC,EACA,UAAAC,EACA,YAAAC,EACA,QAAAC,EAEA,SAAAC,EAEA,aAAAC,EACA,OAAAC,EACA,gBAAAC,EACA,cAAAC,MACK,OAEP,OACE,kCAAAC,EACA,8BAAAC,EACA,yBAAAC,EACA,eAAAC,MACK,mBACP,OACE,mBAAAC,EACA,4BAAAC,EACA,4BAAAC,EACA,2BAAAC,EACA,2BAAAC,MACK,oBAEP,OACE,mBAAAC,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EOyB,EAAOzB,CAAK,EAEvB,CAAC,EAED+B,EAA6B,gBAAgB,CAC3C,OAAAtB,EACA,QAAS,KAAK,SACd,eAAAmB,CACF,CAAC,EAED,MAAMG,EAA6B,gBAAgB,EAAE,MAAOf,GAAM,CAChE,WAAK,YAAYP,EAAO,EAAE,EACpBO,CACR,CAAC,EAEDe,EAA6B,qBAAqB,CACpD,CAAC,EAAE,IAAI,CACT,CAEA,MAAc,YAAYE,EAAoB,CAE5C,GAAI,OAAO,KAAK,SAAS,wBAA2B,WAAY,CAC9D,MAAMhB,EAAmB,MAAM,KAAK,SAAS,iBAC3C,KAAK,uBAAuB,qBAAqB,CACnD,EAEA,UAAWR,KAAUQ,EACnB,GAAIR,EAAO,KAAOwB,EAChB,GAAI,CACF,MAAM,KAAK,SAAS,uBAAuBA,CAAQ,CACrD,OAASjB,EAAG,CACV,KAAK,QAAQ,MACX,qDACA,CACE,KAAM,CAAE,EAAAA,CAAE,CACZ,CACF,CACF,CAGN,CACF,CACF",
|
|
6
|
+
"names": ["Platform", "BleError", "State", "DeviceConnectionStateMachine", "OpeningConnectionError", "TransportConnectedDevice", "UnknownDeviceError", "Either", "EitherAsync", "Left", "Maybe", "Nothing", "Right", "BehaviorSubject", "defer", "filter", "finalize", "from", "retry", "switchMap", "tap", "throttleTime", "throwError", "BLE_DISCONNECT_TIMEOUT_ANDROID", "BLE_DISCONNECT_TIMEOUT_IOS", "CONNECTION_LOST_DELAY", "DEFAULT_MTU", "BleNotSupported", "BlePermissionsNotGranted", "DeviceConnectionNotFound", "NoDeviceModelFoundError", "PeerRemovedPairingError", "RNBleApduSender", "rnBleTransportIdentifier", "RNBleTransport", "_deviceModelDataSource", "_loggerServiceFactory", "_apduSenderFactory", "_apduReceiverFactory", "_manager", "_platform", "_permissionsService", "_deviceConnectionStateMachineFactory", "args", "_deviceApduSenderFactory", "loggerFactory", "state", "hasPermissions", "subject", "devicesById", "error", "rnDevice", "interval", "devices", "internalScannedDevices", "eitherScannedDevices", "timestamp", "a", "b", "device", "d", "scannedDevices", "rawConnectedDevices", "eitherConnectedDevices", "servicesUUIDs", "s", "e", "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 E,State as k}from"react-native-ble-plx";import{BleDeviceInfos as b,DeviceConnectionStateMachine as O,DeviceModelId as B,OpeningConnectionError as _,TransportConnectedDevice as L,TransportDeviceModel as q}from"@ledgerhq/device-management-kit";import{Left as U,Right as T}from"purify-ts";import{lastValueFrom as M,take as g}from"rxjs";import{beforeEach as V,expect as i}from"vitest";import{RNBleTransport as N,RNBleTransportFactory as H}from"./RNBleTransport";const F={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 I=new q({id:B.FLEX,productName:"Ledger Flex",usbProductId:112,bootloaderUsbProductId:7,usbOnly:!1,memorySize:1533*1024,blockSize:32,masks:[858783744]}),p={OS:"ios"},x={OS:"android"},W={OS:"windows"};class u{deviceModelDataSource=f();loggerServiceFactory=()=>F;apduSenderServiceFactory=()=>{};apduReceiverServiceFactory=()=>{};bleManager=new E;platform=p;permissionsAndroid={};deviceConnectionStateMachineFactory;deviceApduSenderFactory;withDeviceModelDataSource(e){return this.deviceModelDataSource=e,this}withPlatform(e){return this.platform=e,this}withPermissionsAndroid(e){return this.permissionsAndroid=e,this}withBleManager(e){return this.bleManager=e,this}withDeviceConnectionStateMachineFactory(e){return this.deviceConnectionStateMachineFactory=e,this}withDeviceApduSenderFactory(e){return this.deviceApduSenderFactory=e,this}build(){return new N(this.deviceModelDataSource,this.loggerServiceFactory,this.apduSenderServiceFactory,this.apduReceiverServiceFactory,this.bleManager,this.platform,this.permissionsAndroid,this.deviceConnectionStateMachineFactory,this.deviceApduSenderFactory)}}function f(){const t=vi.fn(()=>["ledgerId"]),e=vi.fn(()=>({ledgerId:new b(I,"serviceUuid","notifyUuid","writeCmdUuid","readCmdUuid")}));return{getBluetoothServices:t,getBluetoothServicesInfos:e,getAllDeviceModels:vi.fn(),getDeviceModel:vi.fn(),filterDeviceModels:vi.fn()}}function R(t={}){return{id:"deviceId",localName:"deviceName",serviceUUIDs:["ledgerId"],services:vi.fn().mockResolvedValue([{uuid:"ledgerId"}]),...t}}function w(t={}){return{onStateChange: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(),...t}}function $(t={}){return{request:vi.fn(),requestMultiple:vi.fn(),check:vi.fn(),PERMISSIONS:{ACCESS_COARSE_LOCATION:"android.permission.ACCESS_COARSE_LOCATION",ACCESS_FINE_LOCATION:"android.permission.ACCESS_FINE_LOCATION",BLUETOOTH_SCAN:"android.permission.BLUETOOTH_SCAN",BLUETOOTH_CONNECT:"android.permission.BLUETOOTH_CONNECT"},RESULTS:{GRANTED:"granted",DENIED:"denied",NEVER_ASK_AGAIN:"never_ask_again"},...t}}async function h(t,e){const n={OS:"android",Version:t.version},o=$({check:vi.fn().mockImplementation(r=>t.mockCheckResults[r]),requestMultiple:vi.fn().mockImplementation(()=>Promise.resolve(t.mockRequestResults))}),c=await new u().withPlatform(n).withPermissionsAndroid(o).build().checkAndRequestPermissions();i(o.requestMultiple).toBeCalledTimes(e.callsRequestMultiple?1:0),i(c).toBe(e.result)}describe("RNBleTransportFactory",()=>{it("should return a RNBleTransport",()=>{const t={deviceModelDataSource:f(),loggerServiceFactory:()=>F,apduSenderServiceFactory:()=>{},apduReceiverServiceFactory:()=>{},config:{}},e=H(t);i(e).toBeInstanceOf(N)})});describe("RNBleTransport",()=>{let t;V(()=>{vi.clearAllMocks()}),afterEach(()=>{t&&t.unsubscribe()}),describe("getIdentifier",()=>{it("should return rnBleTransportIdentifier",()=>{const n=new u().build().getIdentifier();i(n).toStrictEqual("RN_BLE")})}),describe("isSupported",()=>{it("should return true if platform is ios",()=>{const n=new u().withPlatform(p).build().isSupported();i(n).toBe(!0)}),it("should return true if platform is android",()=>{const n=new u().withPlatform(x).build().isSupported();i(n).toBe(!0)}),it("should return false if platform is not android nor ios",()=>{const n=new u().withPlatform(W).build().isSupported();i(n).toBe(!1)})}),describe("checkAndRequestPermissions",()=>{describe("Android <= 9 (API <=28)",()=>{it("should return true if permissions are already granted",async()=>{await h({version:28,mockCheckResults:{"android.permission.ACCESS_COARSE_LOCATION":!0},mockRequestResults:{}},{result:!0,callsRequestMultiple:!1})}),it("should return false if permissions are requested but not granted",async()=>{await h({version:28,mockCheckResults:{"android.permission.ACCESS_COARSE_LOCATION":!1},mockRequestResults:{"android.permission.ACCESS_COARSE_LOCATION":"denied"}},{result:!1,callsRequestMultiple:!0})}),it("should return true if permissions are requested and granted",async()=>{await h({version:28,mockCheckResults:{},mockRequestResults:{"android.permission.ACCESS_COARSE_LOCATION":"granted"}},{result:!0,callsRequestMultiple:!0})})}),describe("Android 10, 11 (API 29, 30)",()=>{[29,30].forEach(e=>{it(`should return true if permissions are already granted for API ${e}`,async()=>{await h({version:e,mockCheckResults:{"android.permission.ACCESS_FINE_LOCATION":!0},mockRequestResults:{}},{result:!0,callsRequestMultiple:!1})}),it(`should return false if permissions are requested but not granted for API ${e}`,async()=>{await h({version:e,mockCheckResults:{"android.permission.ACCESS_FINE_LOCATION":!1},mockRequestResults:{"android.permission.ACCESS_FINE_LOCATION":"denied"}},{result:!1,callsRequestMultiple:!0})}),it(`should return true if permissions are requested and granted for API ${e}`,async()=>{await h({version:e,mockCheckResults:{},mockRequestResults:{"android.permission.ACCESS_FINE_LOCATION":"granted"}},{result:!0,callsRequestMultiple:!0})})})}),describe("Android >=12 (API =>31+)",()=>{[31,32,33].forEach(e=>{it(`should return true if permissions are already granted for API ${e}`,async()=>{await h({version:e,mockCheckResults:{"android.permission.BLUETOOTH_SCAN":!0,"android.permission.BLUETOOTH_CONNECT":!0},mockRequestResults:{}},{result:!0,callsRequestMultiple:!1})}),it(`should return false if permissions are requested but not all granted for API ${e}`,async()=>{await h({version:e,mockCheckResults:{"android.permission.BLUETOOTH_SCAN":!0,"android.permission.BLUETOOTH_CONNECT":!1},mockRequestResults:{"android.permission.BLUETOOTH_SCAN":"granted","android.permission.BLUETOOTH_CONNECT":"denied"}},{result:!1,callsRequestMultiple:!0})}),it(`should return true if permissions are requested and all granted for API ${e}`,async()=>{await h({version:e,mockCheckResults:{"android.permission.BLUETOOTH_SCAN":!1,"android.permission.BLUETOOTH_CONNECT":!1},mockRequestResults:{"android.permission.BLUETOOTH_SCAN":"granted","android.permission.BLUETOOTH_CONNECT":"granted"}},{result:!0,callsRequestMultiple:!0})})})})}),describe("startDiscovering",()=>{it("should emit an empty array",()=>new Promise((e,n)=>{t=new u().withPlatform(p).withDeviceModelDataSource(f()).build().startDiscovering().subscribe({next:c=>{try{i(c).toStrictEqual([])}catch(r){n(r)}},error:c=>{throw n(c),c},complete:()=>{e(void 0)}})}))}),describe("stopDiscovering",()=>{it("should call ble manager stop scan on stop discovering",()=>{const e=vi.fn(),n=w({stopDeviceScan:e,connectedDevices:vi.fn().mockResolvedValueOnce([])});new u().withBleManager(n).withPlatform(p).withDeviceModelDataSource(f()).build().stopDiscovering(),i(e).toHaveBeenCalled()})}),describe("listenToAvailableDevices",()=>{it("should return already connected devices and scanned devices",()=>new Promise((e,n)=>{let o=null;const d=R({id:"aConnectedDeviceId",localName:"aConnectedDeviceName"}),c=vi.fn().mockImplementation((a,v,m)=>{o=setInterval(()=>{m(null,{id:"aScannedDeviceId",localName:"aScannedDeviceName",serviceUUIDs:["ledgerId"],rssi:1})},10),m(null,{id:"aNonLedgerScannedDeviceId",localName:"aNonLedgerScannedDeviceName",serviceUUIDs:["notLedgerId"],rssi:2})}),r=vi.fn().mockImplementation(()=>{o&&(clearInterval(o),o=null)}),D=w({connectedDevices:vi.fn().mockResolvedValue([d]),startDeviceScan:c,stopDeviceScan:r,onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:a=>(a(k.PoweredOn),{remove:vi.fn()})}),S=new u().withBleManager(D).withPlatform(p).withDeviceModelDataSource(f()).build(),l=[];t=S.listenToAvailableDevices().subscribe({next:a=>{if(l.push(a),l.length===2)try{i(l).toEqual([[{id:"aConnectedDeviceId",name:"aConnectedDeviceName",deviceModel:I,transport:"RN_BLE",rssi:void 0}],[{id:"aConnectedDeviceId",name:"aConnectedDeviceName",deviceModel:I,transport:"RN_BLE",rssi:void 0},{id:"aScannedDeviceId",name:"aScannedDeviceName",deviceModel:I,transport:"RN_BLE",rssi:1}]]),e(void 0)}catch(v){n(v)}}})}))}),describe("connect",()=>{it("should throw an error if device id is unknown",async()=>{const e=w({connectedDevices:vi.fn().mockResolvedValue([]),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockRejectedValueOnce(new Error("discoverAllServicesAndCharacteristicsForDevice error"))}),n=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0)}),d=await new u().withBleManager(e).withPlatform(p).withDeviceModelDataSource(f()).withDeviceApduSenderFactory(n).build().connect({deviceId:null,onDisconnect:vi.fn()});i(d).toEqual(U(new _("discoverAllServicesAndCharacteristicsForDevice error")))}),it("should connect to a discovered device with correct MTU and discover services and setup apdu sender",async()=>{let e=null;const n=R({id:"deviceId",localName:"name"}),o=vi.fn().mockImplementation((m,C,A)=>{e=setInterval(()=>{A(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},500),A(null,{id:"43",localName:"name43",serviceUUIDs:["notLedgerId"],rssi:43})}),d=vi.fn().mockImplementation(()=>{e&&(clearInterval(e),e=null)}),c=w({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:o,stopDeviceScan:d,connectToDevice:vi.fn().mockResolvedValueOnce(n),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(n),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:m=>(m(k.PoweredOn),{remove:vi.fn()})}),r=vi.fn().mockResolvedValue(void 0),D=vi.fn().mockReturnValue({sendApdu:vi.fn()}),S=vi.fn().mockReturnValue({setupConnection:r}),l=new u().withBleManager(c).withPlatform(p).withDeviceModelDataSource(f()).withDeviceConnectionStateMachineFactory(D).withDeviceApduSenderFactory(S).build(),[a]=await M(l.listenToAvailableDevices().pipe(g(3))),v=await l.connect({deviceId:a.id,onDisconnect:vi.fn()});i(v.isRight()).toBe(!0),i(c.connectToDevice).toHaveBeenCalledWith("deviceId",{requestMTU:156}),i(c.discoverAllServicesAndCharacteristicsForDevice).toHaveBeenCalledWith("deviceId"),i(r).toHaveBeenCalled()}),it("should return a connected device which calls state machine sendApdu",async()=>{let e=null;const n=R({id:"deviceId",localName:"name"}),o=vi.fn().mockImplementation((C,A,s)=>{e=setInterval(()=>{s(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},100)}),d=vi.fn().mockImplementation(()=>{e&&(clearInterval(e),e=null)}),c=w({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:o,stopDeviceScan:d,connectToDevice:vi.fn().mockResolvedValueOnce(n),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(n),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:C=>(C(k.PoweredOn),{remove:vi.fn()})}),r=vi.fn(),D=vi.fn().mockReturnValue({sendApdu:r}),S=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0)}),l=new u().withBleManager(c).withPlatform(p).withDeviceModelDataSource(f()).withDeviceConnectionStateMachineFactory(D).withDeviceApduSenderFactory(S).build(),[a]=await M(l.listenToAvailableDevices().pipe(g(3))),v=await l.connect({deviceId:a.id,onDisconnect:vi.fn()});v.extract().sendApdu(Uint8Array.from([67,50])),i(v).toEqual(T(new L({id:"deviceId",deviceModel:I,type:"BLE",transport:"RN_BLE",sendApdu:i.any(Function)}))),i(r).toHaveBeenCalledWith(Uint8Array.from([67,50]))})}),describe("disconnect",()=>{it("should disconnect gracefully",async()=>{let e=null;const n=R({id:"deviceId",localName:"name"}),o=vi.fn().mockImplementation((s,P,y)=>{e=setInterval(()=>{y(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},100)}),d=vi.fn().mockImplementation(()=>{e&&(clearInterval(e),e=null)}),c=vi.fn().mockImplementation(()=>({remove:vi.fn()})),r=vi.fn(),D=w({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:o,stopDeviceScan:d,connectToDevice:vi.fn().mockResolvedValueOnce(n),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(n),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onStateChange:s=>(s(k.PoweredOn),{remove:vi.fn()}),onDeviceDisconnected:c,isDeviceConnected:vi.fn()}),S=s=>new O({deviceId:"deviceId",deviceApduSender:s.deviceApduSender,timeoutDuration:1e3,onTerminated:s.onTerminated,tryToReconnect:s.tryToReconnect}),l=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0),closeConnection:r}),a=new u().withBleManager(D).withPlatform(p).withDeviceModelDataSource(f()).withDeviceConnectionStateMachineFactory(S).withDeviceApduSenderFactory(l).build(),v=vi.fn(),[m]=await M(a.listenToAvailableDevices().pipe(g(3))),C=await a.connect({deviceId:m.id,onDisconnect:v}),A=await a.disconnect({connectedDevice:C.extract()});i(A).toEqual(T(void 0)),i(v).toHaveBeenCalled(),i(r).toHaveBeenCalled()}),it("should handle error while disconnecting",async()=>{let e=null;const n=R({id:"deviceId",localName:"name"}),o=vi.fn().mockImplementation((s,P,y)=>{e=setInterval(()=>{y(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},100)}),d=vi.fn().mockImplementation(()=>{e&&(clearInterval(e),e=null)}),c=vi.fn().mockImplementation(()=>({remove:vi.fn()})),r=vi.fn(),D=w({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:o,stopDeviceScan:d,connectToDevice:vi.fn().mockResolvedValueOnce(n),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(n),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onDeviceDisconnected:c,isDeviceConnected:vi.fn(),onStateChange:s=>(s(k.PoweredOn),{remove:vi.fn()})}),S=s=>new O({deviceId:"deviceId",deviceApduSender:s.deviceApduSender,timeoutDuration:1e3,onTerminated:s.onTerminated,tryToReconnect:s.tryToReconnect}),l=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0),closeConnection:r}),a=new u().withBleManager(D).withPlatform(p).withDeviceModelDataSource(f()).withDeviceConnectionStateMachineFactory(S).withDeviceApduSenderFactory(l).build(),v=vi.fn(),[m]=await M(a.listenToAvailableDevices().pipe(g(3))),C=await a.connect({deviceId:m.id,onDisconnect:v}),A=await a.disconnect({connectedDevice:C.extract()});i(A).toEqual(T(void 0)),i(v).toHaveBeenCalled()})})});
|
|
1
|
+
import{BleManager as N,State as M}from"react-native-ble-plx";import{BleDeviceInfos as V,DeviceConnectionStateMachine as A,DeviceModelId as O,OpeningConnectionError as E,TransportConnectedDevice as U,TransportDeviceModel as x}from"@ledgerhq/device-management-kit";import{Left as L,Right as P}from"purify-ts";import{lastValueFrom as b,take as y}from"rxjs";import{beforeEach as _,expect as o}from"vitest";import{BleNotSupported as q,BlePermissionsNotGranted as H}from"../model/Errors";import{DefaultPermissionsService as W}from"../permissions/DefaultPermissionsService";import{RNBleTransport as F}from"./RNBleTransport";import{RNBleTransportFactory as J}from"./RNBleTransportFactory";const B={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 C=new x({id:O.FLEX,productName:"Ledger Flex",usbProductId:112,bootloaderUsbProductId:7,usbOnly:!1,memorySize:1533*1024,blockSize:32,masks:[858783744]}),D={OS:"ios"},z={OS:"android"},R={OS:"windows"};class l{deviceModelDataSource=S();loggerServiceFactory=()=>B;apduSenderServiceFactory=()=>{};apduReceiverServiceFactory=()=>{};bleManager=new N;platform=D;permissionsService=new W;deviceConnectionStateMachineFactory;deviceApduSenderFactory;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}build(){return new F(this.deviceModelDataSource,this.loggerServiceFactory,this.apduSenderServiceFactory,this.apduReceiverServiceFactory,this.bleManager,this.platform,this.permissionsService,this.deviceConnectionStateMachineFactory,this.deviceApduSenderFactory)}}function S(){const f=vi.fn(()=>["ledgerId"]),e=vi.fn(()=>({ledgerId:new V(C,"serviceUuid","notifyUuid","writeCmdUuid","readCmdUuid")}));return{getBluetoothServices:f,getBluetoothServicesInfos:e,getAllDeviceModels:vi.fn(),getDeviceModel:vi.fn(),filterDeviceModels:vi.fn()}}function g(f={}){return{id:"deviceId",localName:"deviceName",serviceUUIDs:["ledgerId"],services:vi.fn().mockResolvedValue([{uuid:"ledgerId"}]),...f}}function h(f={}){return{onStateChange: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(),...f}}describe("RNBleTransportFactory",()=>{it("should return a RNBleTransport",()=>{const f={deviceModelDataSource:S(),loggerServiceFactory:()=>B,apduSenderServiceFactory:()=>{},apduReceiverServiceFactory:()=>{},config:{}},e=J(f);o(e).toBeInstanceOf(F)})});describe("RNBleTransport",()=>{let f;_(()=>{vi.clearAllMocks()}),afterEach(()=>{f&&f.unsubscribe()}),describe("getIdentifier",()=>{it("should return rnBleTransportIdentifier",()=>{const n=new l().build().getIdentifier();o(n).toStrictEqual("RN_BLE")})}),describe("isSupported",()=>{it("should return true if platform is ios",()=>{const n=new l().withPlatform(D).build().isSupported();o(n).toBe(!0)}),it("should return true if platform is android",()=>{const n=new l().withPlatform(z).build().isSupported();o(n).toBe(!0)}),it("should return false if platform is not android nor ios",()=>{const n=new l().withPlatform(R).build().isSupported();o(n).toBe(!1)})}),describe("startDiscovering",()=>{it("should emit an empty array",()=>new Promise((e,n)=>{f=new l().withPlatform(D).withDeviceModelDataSource(S()).build().startDiscovering().subscribe({next:r=>{try{o(r).toStrictEqual([])}catch(a){n(a)}},error:r=>{throw n(r),r},complete:()=>{e(void 0)}})}))}),describe("stopDiscovering",()=>{it("should call ble manager stop scan on stop discovering",()=>{const e=vi.fn(),n=h({stopDeviceScan:e,connectedDevices:vi.fn().mockResolvedValueOnce([])});new l().withBleManager(n).withPlatform(D).withDeviceModelDataSource(S()).build().stopDiscovering(),o(e).toHaveBeenCalled()})}),describe("listenToAvailableDevices",()=>{it("should emit an error if platform is not android nor ios",async()=>{const e=new l().withBleManager(h()).withPlatform(R).build();return new Promise((n,c)=>{e.listenToAvailableDevices().subscribe({next:()=>{c(new Error("Should not emit any value"))},error:v=>{try{o(v).toBeInstanceOf(q)}catch(r){c(r)}n(void 0)},complete:()=>{c(new Error("Should not complete"))}})})}),describe("permissions check",()=>{const e=vi.fn(),n=vi.fn(),c={checkRequiredPermissions:e,requestRequiredPermissions:n},v=vi.fn(),r=h({startDeviceScan:v,stopDeviceScan:vi.fn(),connectedDevices:vi.fn().mockResolvedValue([]),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:a=>(a(M.PoweredOn),{remove:vi.fn()})});it("should call checkPermissions",async()=>{const d=new l().withBleManager(r).withPlatform(D).withPermissionsService(c).build().listenToAvailableDevices();return new Promise((s,i)=>{d.subscribe({next:()=>{try{o(e).toHaveBeenCalled()}catch(t){i(t)}s(void 0)},error:t=>{i(t)}})})}),it("should call BleManager.startDeviceScan if checkPermissions resolves to true",async()=>{e.mockResolvedValue(!0);const d=new l().withBleManager(r).withPlatform(D).withPermissionsService(c).build().listenToAvailableDevices();return new Promise((s,i)=>{d.subscribe({next:()=>{try{o(v).toHaveBeenCalled()}catch(t){i(t)}s(void 0)},error:t=>{i(t)}})})}),it("should call requestPermissions if checkPermissions resolves to false",async()=>{e.mockResolvedValue(!1);const d=new l().withBleManager(r).withPlatform(D).withPermissionsService(c).build().listenToAvailableDevices();return new Promise((s,i)=>{d.subscribe({next:()=>{try{o(n).toHaveBeenCalled()}catch(t){i(t)}s(void 0)},complete:()=>{i(new Error("Should not complete"))},error:t=>{i(t)}})})}),it("should call BleManager.startDeviceScan if requestPermissions resolves to true",async()=>{e.mockResolvedValue(!1),n.mockResolvedValue(!0);const d=new l().withBleManager(r).withPlatform(D).withPermissionsService(c).build().listenToAvailableDevices();let s=0;return new Promise((i,t)=>{d.subscribe({next:()=>{if(s++,s>1){try{o(v).toHaveBeenCalled()}catch(u){t(u)}i(void 0)}}})})}),it("should emit an error if checkPermissions and requestPermissions resolve to false",async()=>{e.mockResolvedValue(!1),n.mockResolvedValue(!1);const d=new l().withBleManager(r).withPlatform(D).withPermissionsService(c).build().listenToAvailableDevices();return new Promise((s,i)=>{d.subscribe({error:t=>{try{o(t).toBeInstanceOf(H)}catch(u){i(u)}s(void 0)},complete:()=>{i(new Error("Should not complete"))}})})})}),it("should return already connected devices and scanned devices",()=>new Promise((e,n)=>{let c=null;const v=g({id:"aConnectedDeviceId",localName:"aConnectedDeviceName"}),r=vi.fn().mockImplementation((t,u,p)=>{c=setInterval(()=>{p(null,{id:"aScannedDeviceId",localName:"aScannedDeviceName",serviceUUIDs:["ledgerId"],rssi:1})},10),p(null,{id:"aNonLedgerScannedDeviceId",localName:"aNonLedgerScannedDeviceName",serviceUUIDs:["notLedgerId"],rssi:2})}),a=vi.fn().mockImplementation(()=>{c&&(clearInterval(c),c=null)}),d=h({connectedDevices:vi.fn().mockResolvedValue([v]),startDeviceScan:r,stopDeviceScan:a,onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:t=>(t(M.PoweredOn),{remove:vi.fn()})}),s=new l().withBleManager(d).withPlatform(D).withDeviceModelDataSource(S()).build(),i=[];f=s.listenToAvailableDevices().subscribe({next:t=>{if(i.push(t),i.length===2)try{o(i).toEqual([[{id:"aConnectedDeviceId",name:"aConnectedDeviceName",deviceModel:C,transport:"RN_BLE",rssi:void 0}],[{id:"aConnectedDeviceId",name:"aConnectedDeviceName",deviceModel:C,transport:"RN_BLE",rssi:void 0},{id:"aScannedDeviceId",name:"aScannedDeviceName",deviceModel:C,transport:"RN_BLE",rssi:1}]]),e(void 0)}catch(u){n(u)}}})}))}),describe("connect",()=>{it("should throw an error if device id is unknown",async()=>{const e=h({connectedDevices:vi.fn().mockResolvedValue([]),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockRejectedValueOnce(new Error("discoverAllServicesAndCharacteristicsForDevice error"))}),n=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0)}),v=await new l().withBleManager(e).withPlatform(D).withDeviceModelDataSource(S()).withDeviceApduSenderFactory(n).build().connect({deviceId:null,onDisconnect:vi.fn()});o(v).toEqual(L(new E("discoverAllServicesAndCharacteristicsForDevice error")))}),it("should connect to a discovered device with correct MTU and discover services and setup apdu sender",async()=>{let e=null;const n=g({id:"deviceId",localName:"name"}),c=vi.fn().mockImplementation((p,w,k)=>{e=setInterval(()=>{k(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},500),k(null,{id:"43",localName:"name43",serviceUUIDs:["notLedgerId"],rssi:43})}),v=vi.fn().mockImplementation(()=>{e&&(clearInterval(e),e=null)}),r=h({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:c,stopDeviceScan:v,connectToDevice:vi.fn().mockResolvedValueOnce(n),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(n),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:p=>(p(M.PoweredOn),{remove:vi.fn()})}),a=vi.fn().mockResolvedValue(void 0),d=vi.fn().mockReturnValue({sendApdu:vi.fn()}),s=vi.fn().mockReturnValue({setupConnection:a}),i=new l().withBleManager(r).withPlatform(D).withDeviceModelDataSource(S()).withDeviceConnectionStateMachineFactory(d).withDeviceApduSenderFactory(s).build(),[t]=await b(i.listenToAvailableDevices().pipe(y(3))),u=await i.connect({deviceId:t.id,onDisconnect:vi.fn()});o(u.isRight()).toBe(!0),o(r.connectToDevice).toHaveBeenCalledWith("deviceId",{requestMTU:156}),o(r.discoverAllServicesAndCharacteristicsForDevice).toHaveBeenCalledWith("deviceId"),o(a).toHaveBeenCalled()}),it("should return a connected device which calls state machine sendApdu",async()=>{let e=null;const n=g({id:"deviceId",localName:"name"}),c=vi.fn().mockImplementation((w,k,m)=>{e=setInterval(()=>{m(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},100)}),v=vi.fn().mockImplementation(()=>{e&&(clearInterval(e),e=null)}),r=h({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:c,stopDeviceScan:v,connectToDevice:vi.fn().mockResolvedValueOnce(n),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(n),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:w=>(w(M.PoweredOn),{remove:vi.fn()})}),a=vi.fn(),d=vi.fn().mockReturnValue({sendApdu:a}),s=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0)}),i=new l().withBleManager(r).withPlatform(D).withDeviceModelDataSource(S()).withDeviceConnectionStateMachineFactory(d).withDeviceApduSenderFactory(s).build(),[t]=await b(i.listenToAvailableDevices().pipe(y(3))),u=await i.connect({deviceId:t.id,onDisconnect:vi.fn()});u.extract().sendApdu(Uint8Array.from([67,50])),o(u).toEqual(P(new U({id:"deviceId",deviceModel:C,type:"BLE",transport:"RN_BLE",sendApdu:o.any(Function)}))),o(a).toHaveBeenCalledWith(Uint8Array.from([67,50]))})}),describe("disconnect",()=>{it("should disconnect gracefully",async()=>{let e=null;const n=g({id:"deviceId",localName:"name"}),c=vi.fn().mockImplementation((m,T,I)=>{e=setInterval(()=>{I(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},100)}),v=vi.fn().mockImplementation(()=>{e&&(clearInterval(e),e=null)}),r=vi.fn().mockImplementation(()=>({remove:vi.fn()})),a=vi.fn(),d=h({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:c,stopDeviceScan:v,connectToDevice:vi.fn().mockResolvedValueOnce(n),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(n),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onStateChange:m=>(m(M.PoweredOn),{remove:vi.fn()}),onDeviceDisconnected:r,isDeviceConnected:vi.fn()}),s=m=>new A({deviceId:"deviceId",deviceApduSender:m.deviceApduSender,timeoutDuration:1e3,onTerminated:m.onTerminated,tryToReconnect:m.tryToReconnect}),i=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0),closeConnection:a}),t=new l().withBleManager(d).withPlatform(D).withDeviceModelDataSource(S()).withDeviceConnectionStateMachineFactory(s).withDeviceApduSenderFactory(i).build(),u=vi.fn(),[p]=await b(t.listenToAvailableDevices().pipe(y(3))),w=await t.connect({deviceId:p.id,onDisconnect:u}),k=await t.disconnect({connectedDevice:w.extract()});o(k).toEqual(P(void 0)),o(u).toHaveBeenCalled(),o(a).toHaveBeenCalled()}),it("should handle error while disconnecting",async()=>{let e=null;const n=g({id:"deviceId",localName:"name"}),c=vi.fn().mockImplementation((m,T,I)=>{e=setInterval(()=>{I(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},100)}),v=vi.fn().mockImplementation(()=>{e&&(clearInterval(e),e=null)}),r=vi.fn().mockImplementation(()=>({remove:vi.fn()})),a=vi.fn(),d=h({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:c,stopDeviceScan:v,connectToDevice:vi.fn().mockResolvedValueOnce(n),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(n),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onDeviceDisconnected:r,isDeviceConnected:vi.fn(),onStateChange:m=>(m(M.PoweredOn),{remove:vi.fn()})}),s=m=>new A({deviceId:"deviceId",deviceApduSender:m.deviceApduSender,timeoutDuration:1e3,onTerminated:m.onTerminated,tryToReconnect:m.tryToReconnect}),i=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0),closeConnection:a}),t=new l().withBleManager(d).withPlatform(D).withDeviceModelDataSource(S()).withDeviceConnectionStateMachineFactory(s).withDeviceApduSenderFactory(i).build(),u=vi.fn(),[p]=await b(t.listenToAvailableDevices().pipe(y(3))),w=await t.connect({deviceId:p.id,onDisconnect:u}),k=await t.disconnect({connectedDevice:w.extract()});o(k).toEqual(P(void 0)),o(u).toHaveBeenCalled()})})});
|
|
2
2
|
//# sourceMappingURL=RNBleTransport.test.js.map
|