@ledgerhq/device-transport-kit-react-native-ble 1.3.0 → 1.3.2
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/transport/RNBleApduSender.js +1 -1
- package/lib/cjs/api/transport/RNBleApduSender.js.map +2 -2
- package/lib/cjs/api/transport/RNBleTransport.test.js +1 -1
- package/lib/cjs/api/transport/RNBleTransport.test.js.map +2 -2
- package/lib/cjs/package.json +44 -40
- package/lib/esm/api/transport/RNBleApduSender.js +1 -1
- package/lib/esm/api/transport/RNBleApduSender.js.map +3 -3
- package/lib/esm/api/transport/RNBleTransport.test.js +1 -1
- package/lib/esm/api/transport/RNBleTransport.test.js.map +2 -2
- package/lib/esm/package.json +44 -40
- package/lib/types/api/transport/RNBleApduSender.d.ts.map +1 -1
- package/lib/types/tsconfig.prod.tsbuildinfo +1 -1
- package/package.json +35 -31
package/lib/cjs/package.json
CHANGED
|
@@ -1,64 +1,68 @@
|
|
|
1
1
|
{
|
|
2
|
-
"
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
2
|
+
"dependencies": {
|
|
3
|
+
"@sentry/minimal": "catalog:",
|
|
4
|
+
"js-base64": "catalog:",
|
|
5
|
+
"purify-ts": "catalog:",
|
|
6
|
+
"uuid": "catalog:"
|
|
7
|
+
},
|
|
8
|
+
"devDependencies": {
|
|
9
|
+
"@ledgerhq/device-management-kit": "workspace:^",
|
|
10
|
+
"@ledgerhq/eslint-config-dsdk": "workspace:^",
|
|
11
|
+
"@ledgerhq/ldmk-tool": "workspace:^",
|
|
12
|
+
"@ledgerhq/prettier-config-dsdk": "workspace:^",
|
|
13
|
+
"@ledgerhq/tsconfig-dsdk": "workspace:^",
|
|
14
|
+
"@ledgerhq/vitest-config-dmk": "workspace:^",
|
|
15
|
+
"@types/uuid": "catalog:",
|
|
16
|
+
"@vitejs/plugin-react": "catalog:",
|
|
17
|
+
"react-native": "catalog:",
|
|
18
|
+
"react-native-ble-plx": "catalog:",
|
|
19
|
+
"rxjs": "catalog:",
|
|
20
|
+
"ts-node": "catalog:",
|
|
21
|
+
"vitest-react-native": "catalog:"
|
|
22
|
+
},
|
|
6
23
|
"exports": {
|
|
7
24
|
".": {
|
|
8
|
-
"types": "./lib/types/index.d.ts",
|
|
9
25
|
"import": "./lib/esm/index.js",
|
|
10
|
-
"require": "./lib/cjs/index.js"
|
|
26
|
+
"require": "./lib/cjs/index.js",
|
|
27
|
+
"types": "./lib/types/index.d.ts"
|
|
11
28
|
},
|
|
12
29
|
"./*": {
|
|
13
|
-
"types": "./lib/types/*",
|
|
14
30
|
"import": "./lib/esm/*",
|
|
15
|
-
"require": "./lib/cjs/*"
|
|
31
|
+
"require": "./lib/cjs/*",
|
|
32
|
+
"types": "./lib/types/*"
|
|
16
33
|
}
|
|
17
34
|
},
|
|
18
35
|
"files": [
|
|
19
36
|
"./lib"
|
|
20
37
|
],
|
|
38
|
+
"license": "Apache-2.0",
|
|
39
|
+
"name": "@ledgerhq/device-transport-kit-react-native-ble",
|
|
40
|
+
"peerDependencies": {
|
|
41
|
+
"@ledgerhq/device-management-kit": "workspace:^",
|
|
42
|
+
"react-native": ">0.74.1",
|
|
43
|
+
"react-native-ble-plx": "3.4.0",
|
|
44
|
+
"rxjs": "catalog:"
|
|
45
|
+
},
|
|
46
|
+
"private": false,
|
|
47
|
+
"repository": {
|
|
48
|
+
"type": "git",
|
|
49
|
+
"url": "https://github.com/LedgerHQ/device-sdk-ts.git"
|
|
50
|
+
},
|
|
21
51
|
"scripts": {
|
|
22
|
-
"prebuild": "rimraf lib",
|
|
23
52
|
"build": "pnpm ldmk-tool build --entryPoints src/index.ts,src/**/*.ts --tsconfig tsconfig.prod.json",
|
|
24
53
|
"dev": "concurrently \"pnpm watch:builds\" \"pnpm watch:types\"",
|
|
25
|
-
"watch:builds": "pnpm ldmk-tool watch --entryPoints src/index.ts,src/**/*.ts --tsconfig tsconfig.prod.json",
|
|
26
|
-
"watch:types": "concurrently \"tsc --watch -p tsconfig.prod.json\" \"tsc-alias --watch -p tsconfig.prod.json\"",
|
|
27
54
|
"lint": "eslint",
|
|
28
55
|
"lint:fix": "pnpm lint --fix",
|
|
29
56
|
"postpack": "find . -name '*.tgz' -exec cp {} ../../../dist/ \\; ",
|
|
57
|
+
"prebuild": "rimraf lib",
|
|
30
58
|
"prettier": "prettier . --check",
|
|
31
59
|
"prettier:fix": "prettier . --write",
|
|
32
|
-
"typecheck": "tsc --noEmit",
|
|
33
60
|
"test": "vitest run",
|
|
61
|
+
"test:coverage": "vitest run --coverage",
|
|
34
62
|
"test:watch": "vitest",
|
|
35
|
-
"
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
"@sentry/minimal": "catalog:",
|
|
39
|
-
"js-base64": "catalog:",
|
|
40
|
-
"purify-ts": "catalog:",
|
|
41
|
-
"uuid": "catalog:"
|
|
42
|
-
},
|
|
43
|
-
"devDependencies": {
|
|
44
|
-
"@ledgerhq/device-management-kit": "workspace:*",
|
|
45
|
-
"@ledgerhq/eslint-config-dsdk": "workspace:*",
|
|
46
|
-
"@ledgerhq/ldmk-tool": "workspace:*",
|
|
47
|
-
"@ledgerhq/prettier-config-dsdk": "workspace:*",
|
|
48
|
-
"@ledgerhq/tsconfig-dsdk": "workspace:*",
|
|
49
|
-
"@ledgerhq/vitest-config-dmk": "workspace:*",
|
|
50
|
-
"@types/uuid": "catalog:",
|
|
51
|
-
"@vitejs/plugin-react": "catalog:",
|
|
52
|
-
"react-native": "catalog:",
|
|
53
|
-
"react-native-ble-plx": "catalog:",
|
|
54
|
-
"rxjs": "catalog:",
|
|
55
|
-
"ts-node": "catalog:",
|
|
56
|
-
"vitest-react-native": "catalog:"
|
|
63
|
+
"typecheck": "tsc --noEmit",
|
|
64
|
+
"watch:builds": "pnpm ldmk-tool watch --entryPoints src/index.ts,src/**/*.ts --tsconfig tsconfig.prod.json",
|
|
65
|
+
"watch:types": "concurrently \"tsc --watch -p tsconfig.prod.json\" \"tsc-alias --watch -p tsconfig.prod.json\""
|
|
57
66
|
},
|
|
58
|
-
"
|
|
59
|
-
"@ledgerhq/device-management-kit": "workspace:*",
|
|
60
|
-
"react-native": ">0.74.1",
|
|
61
|
-
"react-native-ble-plx": "3.4.0",
|
|
62
|
-
"rxjs": "catalog:"
|
|
63
|
-
}
|
|
67
|
+
"version": "1.3.2"
|
|
64
68
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{DeviceNotInitializedError as l,SendApduTimeoutError as
|
|
1
|
+
import{DeviceNotInitializedError as l,formatApduReceivedLog as m,formatApduSentLog as f,SendApduTimeoutError as _}from"@ledgerhq/device-management-kit";import{Base64 as d}from"js-base64";import{Left as a,Maybe as p,Nothing as u,Right as y}from"purify-ts";import{BehaviorSubject as h}from"rxjs";import{PairingRefusedError as v,UnknownBleError as g}from"../model/Errors";const A=3;class C{_dependencies;_isDeviceReady;_logger;_apduSender;_apduSenderFactory;_apduReceiver;_sendApduPromiseResolver;_writeCharacteristic;_characteristicSubscription=void 0;constructor({apduSenderFactory:i,apduReceiverFactory:t,dependencies:n},r){this._dependencies=n,this._isDeviceReady=new h(!1),this._logger=r("RNBleApduSender"),this._apduSenderFactory=i,this._apduSender=u,this._apduReceiver=t(),this._sendApduPromiseResolver=u}onReceiveSetupApduResponse(i){const t=new Uint8Array(i),{device:n}=this._dependencies,[r]=t.slice(5);let e=n.mtu-A;r&&r!==e&&(e=r),this._apduSender=p.of(this._apduSenderFactory({frameSize:e})),this._isDeviceReady.next(!0)}receiveApdu(i){this._apduReceiver.handleFrame(i).map(n=>{n.map(r=>{this._logger.debug(m(r)),this._sendApduPromiseResolver.map(e=>e(y(r)))})}).mapLeft(n=>{this._sendApduPromiseResolver.map(r=>r(a(n)))})}onMonitor(i){if(!i.value)return;const t=d.toUint8Array(i.value);this._isDeviceReady.value?this.receiveApdu(t):this.onReceiveSetupApduResponse(t)}write(i){return this._writeCharacteristic.isWritableWithoutResponse?this._writeCharacteristic.writeWithoutResponse(i):this._writeCharacteristic.writeWithResponse(i)}getDependencies(){return this._dependencies}setDependencies(i){this._dependencies=i,this._isDeviceReady=new h(!1),this._characteristicSubscription&&(this._characteristicSubscription.remove(),this._characteristicSubscription=void 0)}async setupConnection(){this._characteristicSubscription=this._dependencies.device.monitorCharacteristicForService(this._dependencies.internalDevice.bleDeviceInfos.serviceUuid,this._dependencies.internalDevice.bleDeviceInfos.notifyUuid,(e,c)=>{if(e?.message.includes("notify change failed")){this._isDeviceReady.error(new v(e)),this._logger.error("Pairing failed",{data:{error:e}});return}else e&&(this._isDeviceReady.error(new g(e)),this._logger.error("Error monitoring characteristic",{data:{error:e}}));!e&&c&&this.onMonitor(c)});const i=await this._dependencies.manager.characteristicsForDevice(this._dependencies.device.id,this._dependencies.internalDevice.bleDeviceInfos.serviceUuid);let t=i.find(e=>e.uuid===this._dependencies.internalDevice.bleDeviceInfos.writeCmdUuid);if(t)this._writeCharacteristic=t;else if(t=i.find(e=>e.uuid===this._dependencies.internalDevice.bleDeviceInfos.writeUuid),t)this._writeCharacteristic=t;else throw this._logger.error("No write characteristic found"),new Error("No write characteristic found");const n=Uint8Array.from([8,0,0,0,0]);await this.write(d.fromUint8Array(n)).catch(e=>{throw this._logger.error("Pairing failed",{data:{error:e}}),new v(e)});let r;await new Promise((e,c)=>{r&&r.unsubscribe(),r=this._isDeviceReady.subscribe({next:s=>{s&&e()},error:s=>{c(s)}})})}async sendApdu(i,t,n){if(!this._isDeviceReady.value)return Promise.resolve(a(new l("Unknown MTU")));let r;const e=new Promise(s=>{this._sendApduPromiseResolver=p.of((...o)=>(r&&clearTimeout(r),s(...o)))}),c=this._apduSender.caseOf({Just:s=>s.getFrames(i),Nothing:()=>[]});for(const s of c)try{await this.write(d.fromUint8Array(s.getRawData()))}catch(o){this._logger.info("Error sending frame",{data:{error:o}})}return this._logger.debug(f(i)),n&&(r=setTimeout(()=>{this._logger.debug("[sendApdu] Abort timeout triggered"),this._sendApduPromiseResolver.map(s=>s(a(new _("Abort timeout"))))},n)),e}closeConnection(){this._dependencies.device.cancelConnection()}}export{C as RNBleApduSender};
|
|
2
2
|
//# sourceMappingURL=RNBleApduSender.js.map
|
|
@@ -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._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,
|
|
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"]
|
|
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 formatApduReceivedLog,\n formatApduSentLog,\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._logger.debug(formatApduReceivedLog(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 this._logger.debug(formatApduSentLog(apdu));\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": "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",
|
|
6
|
+
"names": ["DeviceNotInitializedError", "formatApduReceivedLog", "formatApduSentLog", "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{BleManager as N,State as d}from"react-native-ble-plx";import{BleDeviceInfos as V,DeviceConnectionStateMachine as R,DeviceModelId as U,OpeningConnectionError as L,TransportConnectedDevice as x,TransportDeviceModel as _}from"@ledgerhq/device-management-kit";import{Left as q,Right as P}from"purify-ts";import{firstValueFrom as f,Subject as F}from"rxjs";import{beforeEach as H,expect as t}from"vitest";import{BleNotSupported as W,BlePermissionsNotGranted as A,BlePoweredOff as z}from"../model/Errors";import{DefaultPermissionsService as j}from"../permissions/DefaultPermissionsService";import{RNBleTransport as T}from"./RNBleTransport";import{RNBleTransportFactory as G}from"./RNBleTransportFactory";const O={error:vi.fn(),info:vi.fn(),warn:vi.fn(),debug:vi.fn(),subscribers:[]},J={error:console.error,info:console.info,warn:console.warn,debug:console.debug,subscribers:[]};vi.mock("react-native",()=>({Platform:{},PermissionsAndroid:{}}));vi.mock("react-native-ble-plx",()=>({Device:vi.fn(),State:{PoweredOn:"PoweredOn",Unknown:"Unknown",PoweredOff:"PoweredOff",Resetting:"Resetting",Unsupported:"Unsupported",Unauthorized:"Unauthorized"},BleError:vi.fn(),BleManager:vi.fn().mockReturnValue({onStateChange:vi.fn(),startDeviceScan:vi.fn(),stopDeviceScan:vi.fn(),connectToDevice:vi.fn(),disconnectFromDevice:vi.fn(),cancelDeviceConnection:vi.fn(),connectedDevices:vi.fn(),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),discoverAllServicesAndCharacteristicsForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn()})}));const M=new _({id:U.FLEX,productName:"Ledger Flex",usbProductId:112,bootloaderUsbProductId:7,usbOnly:!1,memorySize:1533*1024,blockSize:32,masks:[858783744]}),h={OS:"ios"},K={OS:"android"},I={OS:"windows"};class s{deviceModelDataSource=b();loggerServiceFactory=()=>O;apduSenderServiceFactory=()=>{};apduReceiverServiceFactory=()=>{};bleManager=new N;platform=h;permissionsService=new j;deviceConnectionStateMachineFactory;deviceApduSenderFactory;scanThrottleDelayMs=1e3;withDeviceModelDataSource(e){return this.deviceModelDataSource=e,this}withPlatform(e){return this.platform=e,this}withPermissionsService(e){return this.permissionsService=e,this}withBleManager(e){return this.bleManager=e,this}withDeviceConnectionStateMachineFactory(e){return this.deviceConnectionStateMachineFactory=e,this}withDeviceApduSenderFactory(e){return this.deviceApduSenderFactory=e,this}withLogger(e=J){return this.loggerServiceFactory=()=>e,this}withScanThrottleDelayMs(e){return this.scanThrottleDelayMs=e,this}build(){return new T(this.deviceModelDataSource,this.loggerServiceFactory,this.apduSenderServiceFactory,this.apduReceiverServiceFactory,this.bleManager,this.platform,this.permissionsService,this.scanThrottleDelayMs,this.deviceConnectionStateMachineFactory,this.deviceApduSenderFactory)}}function b(){const p=vi.fn(()=>["ledgerId"]),e=vi.fn(()=>({ledgerId:new V(M,"serviceUuid","notifyUuid","writeCmdUuid","readCmdUuid")}));return{getBluetoothServices:p,getBluetoothServicesInfos:e,getAllDeviceModels:vi.fn(),getDeviceModel:vi.fn(),filterDeviceModels:vi.fn()}}function B(p={}){return{id:"deviceId",localName:"deviceName",serviceUUIDs:["ledgerId"],services:vi.fn().mockResolvedValue([{uuid:"ledgerId"}]),...p}}function m(p={},e=d.PoweredOn){return{onStateChange:vi.fn().mockImplementation((o,c)=>(c&&o(e),{remove:vi.fn()})),startDeviceScan:vi.fn(),stopDeviceScan:vi.fn(),connectToDevice:vi.fn(),disconnectFromDevice:vi.fn(),cancelDeviceConnection:vi.fn(),connectedDevices:vi.fn().mockResolvedValue([]),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),discoverAllServicesAndCharacteristicsForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),state:vi.fn(),...p}}describe("RNBleTransportFactory",()=>{it("should return a RNBleTransport",()=>{const p={deviceModelDataSource:b(),loggerServiceFactory:()=>O,apduSenderServiceFactory:()=>{},apduReceiverServiceFactory:()=>{},config:{}},e=G(p);t(e).toBeInstanceOf(T)})});describe("RNBleTransport",()=>{let p;H(()=>{vi.clearAllMocks(),vi.useRealTimers()}),afterEach(()=>{p&&p.unsubscribe()}),describe("BLE state monitoring",()=>{test("the constructor should call BleManager.onStateChange with a parameter requesting the initial state",()=>{const e=vi.fn();new s().withBleManager(m({onStateChange:e})).build(),t(e).toHaveBeenCalledWith(t.any(Function),!0)}),describe("observeBleState",()=>{it("should emit the initial BLE state",async()=>{const e=vi.fn().mockImplementation((i,r)=>(r&&i(d.PoweredOn),{remove:vi.fn()})),o=new s().withBleManager(m({onStateChange:e})).build().observeBleState(),c=await f(o);t(c).toBe(d.PoweredOn)}),it("should emit the new BLE state values",async()=>{const e=new F,o=new s().withBleManager(m({onStateChange:r=>(r(d.PoweredOn),e.subscribe(a=>r(a)),{remove:vi.fn()})})).build().observeBleState();e.next(d.PoweredOff);const c=await f(o);t(c).toBe(d.PoweredOff),e.next(d.Resetting);const i=await f(o);t(i).toBe(d.Resetting)}),it("should recover from an Unknown state by calling BleManager.state() method and emitting the new state",async()=>{vi.useFakeTimers();const e=new F,n=vi.fn().mockImplementation(()=>new Promise(a=>{setTimeout(()=>{a(d.PoweredOn)},10)})),c=new s().withBleManager(m({state:n,onStateChange:a=>(e.subscribe(v=>a(v)),{remove:vi.fn()})})).build().observeBleState();e.next(d.PoweredOff),t(n).not.toHaveBeenCalled(),e.next(d.Unknown);const i=await f(c);t(i).toBe(d.Unknown),t(n).toHaveBeenCalled(),vi.advanceTimersByTime(11),await Promise.resolve();const r=await f(c);t(r).toBe(d.PoweredOn)})})}),describe("getIdentifier",()=>{it("should return rnBleTransportIdentifier",()=>{const n=new s().build().getIdentifier();t(n).toStrictEqual("RN_BLE")})}),describe("isSupported",()=>{it("should return true if platform is ios",()=>{const n=new s().withPlatform(h).build().isSupported();t(n).toBe(!0)}),it("should return true if platform is android",()=>{const n=new s().withPlatform(K).build().isSupported();t(n).toBe(!0)}),it("should return false if platform is not android nor ios",()=>{const n=new s().withPlatform(I).build().isSupported();t(n).toBe(!1)})}),describe("startDiscovering",()=>{it("should emit an empty array",()=>new Promise((e,n)=>{p=new s().withPlatform(h).withDeviceModelDataSource(b()).build().startDiscovering().subscribe({next:i=>{try{t(i).toStrictEqual([])}catch(r){n(r)}},error:i=>{throw n(i),i},complete:()=>{e(void 0)}})}))}),describe("stopDiscovering",()=>{it("should call ble manager stop scan on stop discovering",()=>{const e=vi.fn(),n=m({stopDeviceScan:e,connectedDevices:vi.fn().mockResolvedValueOnce([])});new s().withBleManager(n).withPlatform(h).withDeviceModelDataSource(b()).build().stopDiscovering(),t(e).toHaveBeenCalled()})}),describe("listenToAvailableDevices",()=>{it("should emit an error if platform is not android nor ios",async()=>{const e=new s().withBleManager(m()).withPlatform(I).build();return new Promise((n,o)=>{e.listenToAvailableDevices().subscribe({error:c=>{try{t(c).toBeInstanceOf(W)}catch(i){o(i)}n(void 0)},complete:()=>{o(new Error("Should not complete"))}})})}),it("should emit an error if BLE state is PoweredOff",async()=>{const n=new s().withBleManager(m({},d.PoweredOff)).build().listenToAvailableDevices();let o;await f(n).catch(c=>{o=c}),t(o).toBeInstanceOf(z)}),describe("permissions check",()=>{const e=vi.fn(),n=vi.fn(),o={checkRequiredPermissions:e,requestRequiredPermissions:n},c=vi.fn().mockImplementation(async()=>{}),i=m({startDeviceScan:c,stopDeviceScan:vi.fn(),connectedDevices:vi.fn().mockResolvedValue([]),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:r=>(r(d.PoweredOn),{remove:vi.fn()})});it("should call checkPermissions",async()=>{const a=new s().withBleManager(i).withPlatform(h).withPermissionsService(o).build().listenToAvailableDevices();await f(a).catch(v=>{t(v).toBeInstanceOf(A)}),t(e).toHaveBeenCalled()}),it("should call BleManager.startDeviceScan if checkPermissions resolves to true",async()=>{e.mockResolvedValue(!0);const a=new s().withBleManager(i).withPlatform(h).withPermissionsService(o).build().listenToAvailableDevices();await f(a).catch(v=>{t(v).toBeInstanceOf(A)}),t(c).toHaveBeenCalled()}),it("should call requestPermissions if checkPermissions resolves to false",async()=>{e.mockResolvedValue(!1);const a=new s().withBleManager(i).withPlatform(h).withPermissionsService(o).build().listenToAvailableDevices();await f(a).catch(()=>{}),t(n).toHaveBeenCalled()}),it("should call BleManager.startDeviceScan if requestPermissions resolves to true",async()=>{e.mockResolvedValue(!1),n.mockResolvedValue(!0);const r=new s().withBleManager(i).withPlatform(h).withPermissionsService(o).build(),a=r.listenToAvailableDevices();await f(r.observeBleState()),await f(a),t(c).toHaveBeenCalled()}),it("should emit an error if checkPermissions and requestPermissions resolve to false",async()=>{e.mockResolvedValue(!1),n.mockResolvedValue(!1);const a=new s().withBleManager(i).withPlatform(h).withPermissionsService(o).build().listenToAvailableDevices();return new Promise((v,l)=>{a.subscribe({error:u=>{try{t(u).toBeInstanceOf(A)}catch(S){l(S)}v(void 0)},complete:()=>{l(new Error("Should not complete"))}})})})}),it("should return already connected devices and scanned devices",()=>new Promise((e,n)=>{let o=null;const c=B({id:"aConnectedDeviceId",localName:"aConnectedDeviceName"}),i=vi.fn().mockImplementation(async(u,S,w)=>{o=setInterval(()=>{w(null,{id:"aScannedDeviceId",localName:"aScannedDeviceName",serviceUUIDs:["ledgerId"],rssi:1})},10),w(null,{id:"aNonLedgerScannedDeviceId",localName:"aNonLedgerScannedDeviceName",serviceUUIDs:["notLedgerId"],rssi:2})}),r=vi.fn().mockImplementation(()=>{o&&(clearInterval(o),o=null)}),a=m({connectedDevices:vi.fn().mockResolvedValue([c]),startDeviceScan:i,stopDeviceScan:r,onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:u=>(u(d.PoweredOn),{remove:vi.fn()})}),v=new s().withBleManager(a).withPlatform(h).withDeviceModelDataSource(b()).withScanThrottleDelayMs(1).build(),l=[];p=v.listenToAvailableDevices().subscribe({next:u=>{if(l.push(u),l.length===2)try{t(l).toEqual([[{id:"aConnectedDeviceId",name:"aConnectedDeviceName",deviceModel:M,transport:"RN_BLE",rssi:void 0}],[{id:"aConnectedDeviceId",name:"aConnectedDeviceName",deviceModel:M,transport:"RN_BLE",rssi:void 0},{id:"aScannedDeviceId",name:"aScannedDeviceName",deviceModel:M,transport:"RN_BLE",rssi:1}]]),e(void 0)}catch(S){n(S)}}})})),it("should propagate the error if startDeviceScan throws an error",()=>{const e=new Error("startDeviceScan error"),n=vi.fn().mockRejectedValueOnce(e),c=new s().withBleManager(m({startDeviceScan:n})).build().listenToAvailableDevices();return new Promise((i,r)=>{c.subscribe({error:a=>{try{t(a).toBe(e),i(void 0)}catch(v){r(v)}},complete:()=>r(new Error("Should not complete"))})})}),it("should propagate the error if startDeviceScan emits an error",()=>{const e=new Error("startDeviceScan error"),n=vi.fn().mockImplementation(async(i,r,a)=>{a(e,{})}),c=new s().withBleManager(m({startDeviceScan:n})).build().listenToAvailableDevices();return new Promise((i,r)=>{c.subscribe({error:a=>{try{t(a).toBe(e),i(void 0)}catch(v){r(v)}i(void 0)},complete:()=>r(new Error("Should not complete"))})})}),it("should propagate an error if startDeviceScan emits a null device",()=>{const e=vi.fn().mockImplementation(async(c,i,r)=>{r(null,null)}),o=new s().withBleManager(m({startDeviceScan:e})).build().listenToAvailableDevices();return new Promise((c,i)=>{o.subscribe({error:r=>{try{t(r).toEqual(new Error("Null device in startDeviceScan callback")),c(void 0)}catch(a){i(a)}}})})}),it("should recover from a scanning error, allowing next calls of listenToAvailableDevices to succeed and emit the devices",async()=>{vi.useFakeTimers();const e=new Error("A Scan Error"),n=vi.fn().mockRejectedValueOnce(e),o=new s().withBleManager(m({startDeviceScan:n})).build(),c=o.listenToAvailableDevices();let i;await f(c).catch(v=>{i=v}),t(i).toBe(e),n.mockImplementation(async(v,l,u)=>{u(null,{id:"aScannedDeviceId",localName:"aScannedDeviceName",serviceUUIDs:["ledgerId"],rssi:1})});const r=o.listenToAvailableDevices();vi.advanceTimersByTime(2e3);const a=await f(r).catch(()=>{throw new Error("Caught error in second observable, this should not happen if listenToAvailableDevices recovers from the scanning error")});t(a).toEqual([{id:"aScannedDeviceId",name:"aScannedDeviceName",deviceModel:M,transport:"RN_BLE",rssi:1}])})}),describe("connect",()=>{it("should throw an error if device id is unknown",async()=>{const e=m({connectedDevices:vi.fn().mockResolvedValue([]),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockRejectedValueOnce(new Error("discoverAllServicesAndCharacteristicsForDevice error"))}),n=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0)}),c=await new s().withBleManager(e).withPlatform(h).withDeviceModelDataSource(b()).withDeviceApduSenderFactory(n).build().connect({deviceId:null,onDisconnect:vi.fn()});t(c).toEqual(q(new L("discoverAllServicesAndCharacteristicsForDevice error")))}),it("should connect to a discovered device with correct MTU and discover services and setup apdu sender",async()=>{const e=B({id:"deviceId",localName:"name"}),n=vi.fn().mockImplementation(async(g,k,y)=>{y(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})}),o=vi.fn(),c=m({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:n,stopDeviceScan:o,connectToDevice:vi.fn().mockResolvedValueOnce(e),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(e),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:g=>(g(d.PoweredOn),{remove:vi.fn()})}),i=vi.fn().mockResolvedValue(void 0),r=vi.fn().mockReturnValue({sendApdu:vi.fn()}),a=vi.fn().mockReturnValue({setupConnection:i}),v=new s().withBleManager(c).withPlatform(h).withDeviceModelDataSource(b()).withDeviceConnectionStateMachineFactory(r).withDeviceApduSenderFactory(a).withScanThrottleDelayMs(1).build(),l=v.listenToAvailableDevices(),u=await f(l),[S]=u,w=await v.connect({deviceId:S.id,onDisconnect:vi.fn()});t(w.isRight()).toBe(!0),t(c.connectToDevice).toHaveBeenCalledWith("deviceId",{requestMTU:156}),t(c.discoverAllServicesAndCharacteristicsForDevice).toHaveBeenCalledWith("deviceId"),t(i).toHaveBeenCalled()}),it("should return a connected device which calls state machine sendApdu",async()=>{vi.useFakeTimers();const e=B({id:"deviceId",localName:"name"}),n=vi.fn().mockImplementation(async(k,y,D)=>{D(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})}),o=vi.fn(),c=m({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:n,stopDeviceScan:o,connectToDevice:vi.fn().mockResolvedValueOnce(e),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(e),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:k=>(k(d.PoweredOn),{remove:vi.fn()})}),i=vi.fn(),r=vi.fn().mockReturnValue({sendApdu:i}),a=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0)}),v=new s().withBleManager(c).withPlatform(h).withDeviceModelDataSource(b()).withDeviceConnectionStateMachineFactory(r).withDeviceApduSenderFactory(a).build(),l=v.listenToAvailableDevices();vi.advanceTimersByTime(2e3);const u=await f(l),[S]=u,w=await v.connect({deviceId:S.id,onDisconnect:vi.fn()});w.extract().sendApdu(Uint8Array.from([67,50])),t(w).toEqual(P(new x({id:"deviceId",deviceModel:M,type:"BLE",transport:"RN_BLE",sendApdu:t.any(Function),name:"name"}))),t(i).toHaveBeenCalledWith(Uint8Array.from([67,50]))})}),describe("disconnect",()=>{it("should disconnect gracefully",async()=>{vi.useFakeTimers();const e=B({id:"deviceId",localName:"name"}),n=vi.fn().mockImplementation(async(D,E,C)=>{C(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})}),o=vi.fn(),c=vi.fn().mockImplementation(()=>({remove:vi.fn()})),i=vi.fn(),r=m({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:n,stopDeviceScan:o,connectToDevice:vi.fn().mockResolvedValueOnce(e),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(e),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onStateChange:D=>(D(d.PoweredOn),{remove:vi.fn()}),onDeviceDisconnected:c,isDeviceConnected:vi.fn()}),a=D=>new R({deviceId:"deviceId",deviceApduSender:D.deviceApduSender,timeoutDuration:1e3,onTerminated:D.onTerminated,tryToReconnect:D.tryToReconnect}),v=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0),closeConnection:i}),l=new s().withBleManager(r).withPlatform(h).withDeviceModelDataSource(b()).withDeviceConnectionStateMachineFactory(a).withDeviceApduSenderFactory(v).build(),u=vi.fn(),S=l.listenToAvailableDevices();vi.advanceTimersByTime(2e3);const w=await f(S),[g]=w,k=await l.connect({deviceId:g.id,onDisconnect:u}),y=await l.disconnect({connectedDevice:k.extract()});t(y).toEqual(P(void 0)),t(u).toHaveBeenCalled(),t(i).toHaveBeenCalled()}),it("should handle error while disconnecting",async()=>{vi.useFakeTimers();const e=B({id:"deviceId",localName:"name"}),n=vi.fn().mockImplementation(async(D,E,C)=>{C(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})}),o=vi.fn(),c=vi.fn().mockImplementation(()=>({remove:vi.fn()})),i=vi.fn(),r=m({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:n,stopDeviceScan:o,connectToDevice:vi.fn().mockResolvedValueOnce(e),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(e),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onDeviceDisconnected:c,isDeviceConnected:vi.fn(),onStateChange:D=>(D(d.PoweredOn),{remove:vi.fn()})}),a=D=>new R({deviceId:"deviceId",deviceApduSender:D.deviceApduSender,timeoutDuration:1e3,onTerminated:D.onTerminated,tryToReconnect:D.tryToReconnect}),v=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0),closeConnection:i}),l=new s().withBleManager(r).withPlatform(h).withDeviceModelDataSource(b()).withDeviceConnectionStateMachineFactory(a).withDeviceApduSenderFactory(v).build(),u=vi.fn(),S=l.listenToAvailableDevices();vi.advanceTimersByTime(2e3);const w=await f(S),[g]=w,k=await l.connect({deviceId:g.id,onDisconnect:u}),y=await l.disconnect({connectedDevice:k.extract()});t(y).toEqual(P(void 0)),t(u).toHaveBeenCalled()})})});
|
|
1
|
+
import{BleManager as N,State as d}from"react-native-ble-plx";import{BleDeviceInfos as V,DeviceConnectionStateMachine as R,DeviceModelId as U,OpeningConnectionError as L,TransportConnectedDevice as x,TransportDeviceModel as _}from"@ledgerhq/device-management-kit";import{Left as q,Right as P}from"purify-ts";import{firstValueFrom as f,Subject as F}from"rxjs";import{beforeEach as H,expect as t}from"vitest";import{BleNotSupported as W,BlePermissionsNotGranted as A,BlePoweredOff as z}from"../model/Errors";import{DefaultPermissionsService as j}from"../permissions/DefaultPermissionsService";import{RNBleTransport as T}from"./RNBleTransport";import{RNBleTransportFactory as G}from"./RNBleTransportFactory";const O={error:vi.fn(),info:vi.fn(),warn:vi.fn(),debug:vi.fn(),subscribers:[]},J={error:console.error,info:console.info,warn:console.warn,debug:console.debug,subscribers:[]};vi.mock("react-native",()=>({Platform:{},PermissionsAndroid:{}}));vi.mock("react-native-ble-plx",()=>({Device:vi.fn(),State:{PoweredOn:"PoweredOn",Unknown:"Unknown",PoweredOff:"PoweredOff",Resetting:"Resetting",Unsupported:"Unsupported",Unauthorized:"Unauthorized"},BleError:vi.fn(),BleManager:vi.fn().mockReturnValue({onStateChange:vi.fn(),startDeviceScan:vi.fn(),stopDeviceScan:vi.fn(),connectToDevice:vi.fn(),disconnectFromDevice:vi.fn(),cancelDeviceConnection:vi.fn(),connectedDevices:vi.fn(),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),discoverAllServicesAndCharacteristicsForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn()})}));const M=new _({id:U.FLEX,productName:"Ledger Flex",usbProductId:112,bootloaderUsbProductId:7,usbOnly:!1,memorySize:1533*1024,getBlockSize:()=>32,masks:[858783744]}),h={OS:"ios"},K={OS:"android"},I={OS:"windows"};class s{deviceModelDataSource=b();loggerServiceFactory=()=>O;apduSenderServiceFactory=()=>{};apduReceiverServiceFactory=()=>{};bleManager=new N;platform=h;permissionsService=new j;deviceConnectionStateMachineFactory;deviceApduSenderFactory;scanThrottleDelayMs=1e3;withDeviceModelDataSource(e){return this.deviceModelDataSource=e,this}withPlatform(e){return this.platform=e,this}withPermissionsService(e){return this.permissionsService=e,this}withBleManager(e){return this.bleManager=e,this}withDeviceConnectionStateMachineFactory(e){return this.deviceConnectionStateMachineFactory=e,this}withDeviceApduSenderFactory(e){return this.deviceApduSenderFactory=e,this}withLogger(e=J){return this.loggerServiceFactory=()=>e,this}withScanThrottleDelayMs(e){return this.scanThrottleDelayMs=e,this}build(){return new T(this.deviceModelDataSource,this.loggerServiceFactory,this.apduSenderServiceFactory,this.apduReceiverServiceFactory,this.bleManager,this.platform,this.permissionsService,this.scanThrottleDelayMs,this.deviceConnectionStateMachineFactory,this.deviceApduSenderFactory)}}function b(){const p=vi.fn(()=>["ledgerId"]),e=vi.fn(()=>({ledgerId:new V(M,"serviceUuid","notifyUuid","writeCmdUuid","readCmdUuid")}));return{getBluetoothServices:p,getBluetoothServicesInfos:e,getAllDeviceModels:vi.fn(),getDeviceModel:vi.fn(),filterDeviceModels:vi.fn()}}function B(p={}){return{id:"deviceId",localName:"deviceName",serviceUUIDs:["ledgerId"],services:vi.fn().mockResolvedValue([{uuid:"ledgerId"}]),...p}}function m(p={},e=d.PoweredOn){return{onStateChange:vi.fn().mockImplementation((o,c)=>(c&&o(e),{remove:vi.fn()})),startDeviceScan:vi.fn(),stopDeviceScan:vi.fn(),connectToDevice:vi.fn(),disconnectFromDevice:vi.fn(),cancelDeviceConnection:vi.fn(),connectedDevices:vi.fn().mockResolvedValue([]),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),discoverAllServicesAndCharacteristicsForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),state:vi.fn(),...p}}describe("RNBleTransportFactory",()=>{it("should return a RNBleTransport",()=>{const p={deviceModelDataSource:b(),loggerServiceFactory:()=>O,apduSenderServiceFactory:()=>{},apduReceiverServiceFactory:()=>{},config:{}},e=G(p);t(e).toBeInstanceOf(T)})});describe("RNBleTransport",()=>{let p;H(()=>{vi.clearAllMocks(),vi.useRealTimers()}),afterEach(()=>{p&&p.unsubscribe()}),describe("BLE state monitoring",()=>{test("the constructor should call BleManager.onStateChange with a parameter requesting the initial state",()=>{const e=vi.fn();new s().withBleManager(m({onStateChange:e})).build(),t(e).toHaveBeenCalledWith(t.any(Function),!0)}),describe("observeBleState",()=>{it("should emit the initial BLE state",async()=>{const e=vi.fn().mockImplementation((i,r)=>(r&&i(d.PoweredOn),{remove:vi.fn()})),o=new s().withBleManager(m({onStateChange:e})).build().observeBleState(),c=await f(o);t(c).toBe(d.PoweredOn)}),it("should emit the new BLE state values",async()=>{const e=new F,o=new s().withBleManager(m({onStateChange:r=>(r(d.PoweredOn),e.subscribe(a=>r(a)),{remove:vi.fn()})})).build().observeBleState();e.next(d.PoweredOff);const c=await f(o);t(c).toBe(d.PoweredOff),e.next(d.Resetting);const i=await f(o);t(i).toBe(d.Resetting)}),it("should recover from an Unknown state by calling BleManager.state() method and emitting the new state",async()=>{vi.useFakeTimers();const e=new F,n=vi.fn().mockImplementation(()=>new Promise(a=>{setTimeout(()=>{a(d.PoweredOn)},10)})),c=new s().withBleManager(m({state:n,onStateChange:a=>(e.subscribe(v=>a(v)),{remove:vi.fn()})})).build().observeBleState();e.next(d.PoweredOff),t(n).not.toHaveBeenCalled(),e.next(d.Unknown);const i=await f(c);t(i).toBe(d.Unknown),t(n).toHaveBeenCalled(),vi.advanceTimersByTime(11),await Promise.resolve();const r=await f(c);t(r).toBe(d.PoweredOn)})})}),describe("getIdentifier",()=>{it("should return rnBleTransportIdentifier",()=>{const n=new s().build().getIdentifier();t(n).toStrictEqual("RN_BLE")})}),describe("isSupported",()=>{it("should return true if platform is ios",()=>{const n=new s().withPlatform(h).build().isSupported();t(n).toBe(!0)}),it("should return true if platform is android",()=>{const n=new s().withPlatform(K).build().isSupported();t(n).toBe(!0)}),it("should return false if platform is not android nor ios",()=>{const n=new s().withPlatform(I).build().isSupported();t(n).toBe(!1)})}),describe("startDiscovering",()=>{it("should emit an empty array",()=>new Promise((e,n)=>{p=new s().withPlatform(h).withDeviceModelDataSource(b()).build().startDiscovering().subscribe({next:i=>{try{t(i).toStrictEqual([])}catch(r){n(r)}},error:i=>{throw n(i),i},complete:()=>{e(void 0)}})}))}),describe("stopDiscovering",()=>{it("should call ble manager stop scan on stop discovering",()=>{const e=vi.fn(),n=m({stopDeviceScan:e,connectedDevices:vi.fn().mockResolvedValueOnce([])});new s().withBleManager(n).withPlatform(h).withDeviceModelDataSource(b()).build().stopDiscovering(),t(e).toHaveBeenCalled()})}),describe("listenToAvailableDevices",()=>{it("should emit an error if platform is not android nor ios",async()=>{const e=new s().withBleManager(m()).withPlatform(I).build();return new Promise((n,o)=>{e.listenToAvailableDevices().subscribe({error:c=>{try{t(c).toBeInstanceOf(W)}catch(i){o(i)}n(void 0)},complete:()=>{o(new Error("Should not complete"))}})})}),it("should emit an error if BLE state is PoweredOff",async()=>{const n=new s().withBleManager(m({},d.PoweredOff)).build().listenToAvailableDevices();let o;await f(n).catch(c=>{o=c}),t(o).toBeInstanceOf(z)}),describe("permissions check",()=>{const e=vi.fn(),n=vi.fn(),o={checkRequiredPermissions:e,requestRequiredPermissions:n},c=vi.fn().mockImplementation(async()=>{}),i=m({startDeviceScan:c,stopDeviceScan:vi.fn(),connectedDevices:vi.fn().mockResolvedValue([]),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:r=>(r(d.PoweredOn),{remove:vi.fn()})});it("should call checkPermissions",async()=>{const a=new s().withBleManager(i).withPlatform(h).withPermissionsService(o).build().listenToAvailableDevices();await f(a).catch(v=>{t(v).toBeInstanceOf(A)}),t(e).toHaveBeenCalled()}),it("should call BleManager.startDeviceScan if checkPermissions resolves to true",async()=>{e.mockResolvedValue(!0);const a=new s().withBleManager(i).withPlatform(h).withPermissionsService(o).build().listenToAvailableDevices();await f(a).catch(v=>{t(v).toBeInstanceOf(A)}),t(c).toHaveBeenCalled()}),it("should call requestPermissions if checkPermissions resolves to false",async()=>{e.mockResolvedValue(!1);const a=new s().withBleManager(i).withPlatform(h).withPermissionsService(o).build().listenToAvailableDevices();await f(a).catch(()=>{}),t(n).toHaveBeenCalled()}),it("should call BleManager.startDeviceScan if requestPermissions resolves to true",async()=>{e.mockResolvedValue(!1),n.mockResolvedValue(!0);const r=new s().withBleManager(i).withPlatform(h).withPermissionsService(o).build(),a=r.listenToAvailableDevices();await f(r.observeBleState()),await f(a),t(c).toHaveBeenCalled()}),it("should emit an error if checkPermissions and requestPermissions resolve to false",async()=>{e.mockResolvedValue(!1),n.mockResolvedValue(!1);const a=new s().withBleManager(i).withPlatform(h).withPermissionsService(o).build().listenToAvailableDevices();return new Promise((v,l)=>{a.subscribe({error:u=>{try{t(u).toBeInstanceOf(A)}catch(S){l(S)}v(void 0)},complete:()=>{l(new Error("Should not complete"))}})})})}),it("should return already connected devices and scanned devices",()=>new Promise((e,n)=>{let o=null;const c=B({id:"aConnectedDeviceId",localName:"aConnectedDeviceName"}),i=vi.fn().mockImplementation(async(u,S,w)=>{o=setInterval(()=>{w(null,{id:"aScannedDeviceId",localName:"aScannedDeviceName",serviceUUIDs:["ledgerId"],rssi:1})},10),w(null,{id:"aNonLedgerScannedDeviceId",localName:"aNonLedgerScannedDeviceName",serviceUUIDs:["notLedgerId"],rssi:2})}),r=vi.fn().mockImplementation(()=>{o&&(clearInterval(o),o=null)}),a=m({connectedDevices:vi.fn().mockResolvedValue([c]),startDeviceScan:i,stopDeviceScan:r,onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:u=>(u(d.PoweredOn),{remove:vi.fn()})}),v=new s().withBleManager(a).withPlatform(h).withDeviceModelDataSource(b()).withScanThrottleDelayMs(1).build(),l=[];p=v.listenToAvailableDevices().subscribe({next:u=>{if(l.push(u),l.length===2)try{t(l).toEqual([[{id:"aConnectedDeviceId",name:"aConnectedDeviceName",deviceModel:M,transport:"RN_BLE",rssi:void 0}],[{id:"aConnectedDeviceId",name:"aConnectedDeviceName",deviceModel:M,transport:"RN_BLE",rssi:void 0},{id:"aScannedDeviceId",name:"aScannedDeviceName",deviceModel:M,transport:"RN_BLE",rssi:1}]]),e(void 0)}catch(S){n(S)}}})})),it("should propagate the error if startDeviceScan throws an error",()=>{const e=new Error("startDeviceScan error"),n=vi.fn().mockRejectedValueOnce(e),c=new s().withBleManager(m({startDeviceScan:n})).build().listenToAvailableDevices();return new Promise((i,r)=>{c.subscribe({error:a=>{try{t(a).toBe(e),i(void 0)}catch(v){r(v)}},complete:()=>r(new Error("Should not complete"))})})}),it("should propagate the error if startDeviceScan emits an error",()=>{const e=new Error("startDeviceScan error"),n=vi.fn().mockImplementation(async(i,r,a)=>{a(e,{})}),c=new s().withBleManager(m({startDeviceScan:n})).build().listenToAvailableDevices();return new Promise((i,r)=>{c.subscribe({error:a=>{try{t(a).toBe(e),i(void 0)}catch(v){r(v)}i(void 0)},complete:()=>r(new Error("Should not complete"))})})}),it("should propagate an error if startDeviceScan emits a null device",()=>{const e=vi.fn().mockImplementation(async(c,i,r)=>{r(null,null)}),o=new s().withBleManager(m({startDeviceScan:e})).build().listenToAvailableDevices();return new Promise((c,i)=>{o.subscribe({error:r=>{try{t(r).toEqual(new Error("Null device in startDeviceScan callback")),c(void 0)}catch(a){i(a)}}})})}),it("should recover from a scanning error, allowing next calls of listenToAvailableDevices to succeed and emit the devices",async()=>{vi.useFakeTimers();const e=new Error("A Scan Error"),n=vi.fn().mockRejectedValueOnce(e),o=new s().withBleManager(m({startDeviceScan:n})).build(),c=o.listenToAvailableDevices();let i;await f(c).catch(v=>{i=v}),t(i).toBe(e),n.mockImplementation(async(v,l,u)=>{u(null,{id:"aScannedDeviceId",localName:"aScannedDeviceName",serviceUUIDs:["ledgerId"],rssi:1})});const r=o.listenToAvailableDevices();vi.advanceTimersByTime(2e3);const a=await f(r).catch(()=>{throw new Error("Caught error in second observable, this should not happen if listenToAvailableDevices recovers from the scanning error")});t(a).toEqual([{id:"aScannedDeviceId",name:"aScannedDeviceName",deviceModel:M,transport:"RN_BLE",rssi:1}])})}),describe("connect",()=>{it("should throw an error if device id is unknown",async()=>{const e=m({connectedDevices:vi.fn().mockResolvedValue([]),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockRejectedValueOnce(new Error("discoverAllServicesAndCharacteristicsForDevice error"))}),n=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0)}),c=await new s().withBleManager(e).withPlatform(h).withDeviceModelDataSource(b()).withDeviceApduSenderFactory(n).build().connect({deviceId:null,onDisconnect:vi.fn()});t(c).toEqual(q(new L("discoverAllServicesAndCharacteristicsForDevice error")))}),it("should connect to a discovered device with correct MTU and discover services and setup apdu sender",async()=>{const e=B({id:"deviceId",localName:"name"}),n=vi.fn().mockImplementation(async(g,k,y)=>{y(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})}),o=vi.fn(),c=m({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:n,stopDeviceScan:o,connectToDevice:vi.fn().mockResolvedValueOnce(e),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(e),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:g=>(g(d.PoweredOn),{remove:vi.fn()})}),i=vi.fn().mockResolvedValue(void 0),r=vi.fn().mockReturnValue({sendApdu:vi.fn()}),a=vi.fn().mockReturnValue({setupConnection:i}),v=new s().withBleManager(c).withPlatform(h).withDeviceModelDataSource(b()).withDeviceConnectionStateMachineFactory(r).withDeviceApduSenderFactory(a).withScanThrottleDelayMs(1).build(),l=v.listenToAvailableDevices(),u=await f(l),[S]=u,w=await v.connect({deviceId:S.id,onDisconnect:vi.fn()});t(w.isRight()).toBe(!0),t(c.connectToDevice).toHaveBeenCalledWith("deviceId",{requestMTU:156}),t(c.discoverAllServicesAndCharacteristicsForDevice).toHaveBeenCalledWith("deviceId"),t(i).toHaveBeenCalled()}),it("should return a connected device which calls state machine sendApdu",async()=>{vi.useFakeTimers();const e=B({id:"deviceId",localName:"name"}),n=vi.fn().mockImplementation(async(k,y,D)=>{D(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})}),o=vi.fn(),c=m({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:n,stopDeviceScan:o,connectToDevice:vi.fn().mockResolvedValueOnce(e),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(e),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:k=>(k(d.PoweredOn),{remove:vi.fn()})}),i=vi.fn(),r=vi.fn().mockReturnValue({sendApdu:i}),a=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0)}),v=new s().withBleManager(c).withPlatform(h).withDeviceModelDataSource(b()).withDeviceConnectionStateMachineFactory(r).withDeviceApduSenderFactory(a).build(),l=v.listenToAvailableDevices();vi.advanceTimersByTime(2e3);const u=await f(l),[S]=u,w=await v.connect({deviceId:S.id,onDisconnect:vi.fn()});w.extract().sendApdu(Uint8Array.from([67,50])),t(w).toEqual(P(new x({id:"deviceId",deviceModel:M,type:"BLE",transport:"RN_BLE",sendApdu:t.any(Function),name:"name"}))),t(i).toHaveBeenCalledWith(Uint8Array.from([67,50]))})}),describe("disconnect",()=>{it("should disconnect gracefully",async()=>{vi.useFakeTimers();const e=B({id:"deviceId",localName:"name"}),n=vi.fn().mockImplementation(async(D,E,C)=>{C(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})}),o=vi.fn(),c=vi.fn().mockImplementation(()=>({remove:vi.fn()})),i=vi.fn(),r=m({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:n,stopDeviceScan:o,connectToDevice:vi.fn().mockResolvedValueOnce(e),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(e),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onStateChange:D=>(D(d.PoweredOn),{remove:vi.fn()}),onDeviceDisconnected:c,isDeviceConnected:vi.fn()}),a=D=>new R({deviceId:"deviceId",deviceApduSender:D.deviceApduSender,timeoutDuration:1e3,onTerminated:D.onTerminated,tryToReconnect:D.tryToReconnect}),v=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0),closeConnection:i}),l=new s().withBleManager(r).withPlatform(h).withDeviceModelDataSource(b()).withDeviceConnectionStateMachineFactory(a).withDeviceApduSenderFactory(v).build(),u=vi.fn(),S=l.listenToAvailableDevices();vi.advanceTimersByTime(2e3);const w=await f(S),[g]=w,k=await l.connect({deviceId:g.id,onDisconnect:u}),y=await l.disconnect({connectedDevice:k.extract()});t(y).toEqual(P(void 0)),t(u).toHaveBeenCalled(),t(i).toHaveBeenCalled()}),it("should handle error while disconnecting",async()=>{vi.useFakeTimers();const e=B({id:"deviceId",localName:"name"}),n=vi.fn().mockImplementation(async(D,E,C)=>{C(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})}),o=vi.fn(),c=vi.fn().mockImplementation(()=>({remove:vi.fn()})),i=vi.fn(),r=m({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:n,stopDeviceScan:o,connectToDevice:vi.fn().mockResolvedValueOnce(e),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(e),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onDeviceDisconnected:c,isDeviceConnected:vi.fn(),onStateChange:D=>(D(d.PoweredOn),{remove:vi.fn()})}),a=D=>new R({deviceId:"deviceId",deviceApduSender:D.deviceApduSender,timeoutDuration:1e3,onTerminated:D.onTerminated,tryToReconnect:D.tryToReconnect}),v=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0),closeConnection:i}),l=new s().withBleManager(r).withPlatform(h).withDeviceModelDataSource(b()).withDeviceConnectionStateMachineFactory(a).withDeviceApduSenderFactory(v).build(),u=vi.fn(),S=l.listenToAvailableDevices();vi.advanceTimersByTime(2e3);const w=await f(S),[g]=w,k=await l.connect({deviceId:g.id,onDisconnect:u}),y=await l.disconnect({connectedDevice:k.extract()});t(y).toEqual(P(void 0)),t(u).toHaveBeenCalled()})})});
|
|
2
2
|
//# sourceMappingURL=RNBleTransport.test.js.map
|