@ledgerhq/device-management-kit 0.0.0-rn-hid-improvements-explorations-20250523153215 → 0.0.0-rn-ble-pairing-removed-while-reconnecting-20250731133348
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/src/api/DeviceManagementKit.js +1 -1
- package/lib/cjs/src/api/DeviceManagementKit.js.map +2 -2
- package/lib/cjs/src/api/apdu/utils/ByteArrayBuilder.js +1 -1
- package/lib/cjs/src/api/apdu/utils/ByteArrayBuilder.js.map +3 -3
- package/lib/cjs/src/api/apdu/utils/ByteArrayBuilder.test.js +1 -1
- package/lib/cjs/src/api/apdu/utils/ByteArrayBuilder.test.js.map +2 -2
- package/lib/cjs/src/api/command/utils/CommandUtils.js +1 -1
- package/lib/cjs/src/api/command/utils/CommandUtils.js.map +2 -2
- package/lib/cjs/src/api/command/utils/CommandUtils.test.js +1 -1
- package/lib/cjs/src/api/command/utils/CommandUtils.test.js.map +2 -2
- package/lib/cjs/src/api/command/utils/GlobalCommandError.js +1 -1
- package/lib/cjs/src/api/command/utils/GlobalCommandError.js.map +2 -2
- package/lib/cjs/src/api/device-action/DeviceAction.js +1 -1
- package/lib/cjs/src/api/device-action/DeviceAction.js.map +1 -1
- package/lib/cjs/src/api/device-action/__test-utils__/makeInternalApi.js +1 -1
- package/lib/cjs/src/api/device-action/__test-utils__/makeInternalApi.js.map +2 -2
- package/lib/cjs/src/api/device-action/model/UserInteractionRequired.js +1 -1
- package/lib/cjs/src/api/device-action/model/UserInteractionRequired.js.map +2 -2
- package/lib/cjs/src/api/device-action/os/CallTaskInAppDeviceAction/CallTaskInAppDeviceAction.js +1 -1
- package/lib/cjs/src/api/device-action/os/CallTaskInAppDeviceAction/CallTaskInAppDeviceAction.js.map +2 -2
- package/lib/cjs/src/api/device-action/os/CallTaskInAppDeviceAction/CallTaskInAppDeviceActionTypes.js.map +1 -1
- package/lib/cjs/src/api/device-action/os/Errors.js +1 -1
- package/lib/cjs/src/api/device-action/os/Errors.js.map +3 -3
- package/lib/cjs/src/api/device-action/os/GetDeviceMetadata/GetDeviceMetadataDeviceAction.js +1 -1
- package/lib/cjs/src/api/device-action/os/GetDeviceMetadata/GetDeviceMetadataDeviceAction.js.map +2 -2
- package/lib/cjs/src/api/device-action/os/GetDeviceMetadata/types.js.map +1 -1
- package/lib/cjs/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.js +1 -1
- package/lib/cjs/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.js.map +2 -2
- package/lib/cjs/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.test.js +1 -1
- package/lib/cjs/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.test.js.map +2 -2
- package/lib/cjs/src/api/device-action/os/GoToDashboard/GoToDashboardDeviceAction.js +1 -1
- package/lib/cjs/src/api/device-action/os/GoToDashboard/GoToDashboardDeviceAction.js.map +3 -3
- package/lib/cjs/src/api/device-action/os/InstallOrUpdateApps/InstallOrUpdateAppsDeviceAction.js +1 -1
- package/lib/cjs/src/api/device-action/os/InstallOrUpdateApps/InstallOrUpdateAppsDeviceAction.js.map +2 -2
- package/lib/cjs/src/api/device-action/os/InstallOrUpdateApps/types.js +1 -1
- package/lib/cjs/src/api/device-action/os/InstallOrUpdateApps/types.js.map +1 -1
- package/lib/cjs/src/api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction.js +1 -1
- package/lib/cjs/src/api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction.js.map +3 -3
- package/lib/cjs/src/api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction.test.js +1 -1
- package/lib/cjs/src/api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction.test.js.map +2 -2
- package/lib/cjs/src/api/device-action/os/OpenAppDeviceAction/types.js +1 -1
- package/lib/cjs/src/api/device-action/os/OpenAppDeviceAction/types.js.map +1 -1
- package/lib/cjs/src/api/device-action/os/OpenAppWithDependencies/OpenAppWithDependenciesDeviceAction.js +1 -1
- package/lib/cjs/src/api/device-action/os/OpenAppWithDependencies/OpenAppWithDependenciesDeviceAction.js.map +2 -2
- package/lib/cjs/src/api/device-action/os/OpenAppWithDependencies/types.js.map +1 -1
- package/lib/cjs/src/api/device-action/os/SendCommandInAppDeviceAction/SendCommandInAppDeviceAction.js +1 -1
- package/lib/cjs/src/api/device-action/os/SendCommandInAppDeviceAction/SendCommandInAppDeviceAction.js.map +2 -2
- package/lib/cjs/src/api/device-action/os/SendCommandInAppDeviceAction/SendCommandInAppDeviceActionTypes.js +1 -1
- package/lib/cjs/src/api/device-action/os/SendCommandInAppDeviceAction/SendCommandInAppDeviceActionTypes.js.map +1 -1
- package/lib/cjs/src/api/device-action/task/BuildAppsInstallPlanTask.js +1 -1
- package/lib/cjs/src/api/device-action/task/BuildAppsInstallPlanTask.js.map +2 -2
- package/lib/cjs/src/api/device-action/task/BuildAppsInstallPlanTask.test.js +1 -1
- package/lib/cjs/src/api/device-action/task/BuildAppsInstallPlanTask.test.js.map +2 -2
- package/lib/cjs/src/api/index.js +1 -1
- package/lib/cjs/src/api/index.js.map +2 -2
- package/lib/cjs/src/api/secure-channel/device-action/GenuineCheck/GenuineCheckDeviceAction.js +1 -1
- package/lib/cjs/src/api/secure-channel/device-action/GenuineCheck/GenuineCheckDeviceAction.js.map +2 -2
- package/lib/cjs/src/api/secure-channel/device-action/GenuineCheck/types.js.map +1 -1
- package/lib/cjs/src/api/secure-channel/device-action/InstallApp/InstallAppDeviceAction.js +1 -1
- package/lib/cjs/src/api/secure-channel/device-action/InstallApp/InstallAppDeviceAction.js.map +2 -2
- package/lib/cjs/src/api/secure-channel/device-action/InstallApp/types.js +1 -1
- package/lib/cjs/src/api/secure-channel/device-action/InstallApp/types.js.map +1 -1
- package/lib/cjs/src/api/secure-channel/device-action/ListInstalledApps/ListInstalledAppsDeviceAction.js +1 -1
- package/lib/cjs/src/api/secure-channel/device-action/ListInstalledApps/ListInstalledAppsDeviceAction.js.map +2 -2
- package/lib/cjs/src/api/secure-channel/device-action/ListInstalledApps/types.js +1 -1
- package/lib/cjs/src/api/secure-channel/device-action/ListInstalledApps/types.js.map +2 -2
- package/lib/cjs/src/api/secure-channel/device-action/UninstallApp/UninstallAppDeviceAction.js +1 -1
- package/lib/cjs/src/api/secure-channel/device-action/UninstallApp/UninstallAppDeviceAction.js.map +2 -2
- package/lib/cjs/src/api/secure-channel/device-action/UninstallApp/types.js +1 -1
- package/lib/cjs/src/api/secure-channel/device-action/UninstallApp/types.js.map +1 -1
- package/lib/cjs/src/api/secure-channel/task/ConnectToSecureChannelTask.js +1 -1
- package/lib/cjs/src/api/secure-channel/task/ConnectToSecureChannelTask.js.map +3 -3
- package/lib/cjs/src/api/secure-channel/task/ConnectToSecureChannelTask.test.js +1 -1
- package/lib/cjs/src/api/secure-channel/task/ConnectToSecureChannelTask.test.js.map +3 -3
- package/lib/cjs/src/api/secure-channel/task/types.js +1 -1
- package/lib/cjs/src/api/secure-channel/task/types.js.map +2 -2
- package/lib/cjs/src/api/secure-channel/utils.js +1 -1
- package/lib/cjs/src/api/secure-channel/utils.js.map +3 -3
- package/lib/cjs/src/api/secure-channel/utils.test.js +1 -1
- package/lib/cjs/src/api/secure-channel/utils.test.js.map +3 -3
- package/lib/cjs/src/api/transport/model/DeviceConnection.js +1 -1
- package/lib/cjs/src/api/transport/model/DeviceConnection.js.map +1 -1
- package/lib/cjs/src/api/transport/model/DeviceConnectionStateMachine.js +1 -1
- package/lib/cjs/src/api/transport/model/DeviceConnectionStateMachine.js.map +3 -3
- package/lib/cjs/src/api/transport/model/DeviceConnectionStateMachine.test.js +2 -0
- package/lib/cjs/src/api/transport/model/DeviceConnectionStateMachine.test.js.map +7 -0
- package/lib/cjs/src/api/transport/model/Errors.js +1 -1
- package/lib/cjs/src/api/transport/model/Errors.js.map +3 -3
- package/lib/cjs/src/api/transport/model/TransportConnectedDevice.js +1 -1
- package/lib/cjs/src/api/transport/model/TransportConnectedDevice.js.map +3 -3
- package/lib/cjs/src/api/utils/AppName.js +2 -0
- package/lib/cjs/src/api/utils/AppName.js.map +7 -0
- package/lib/cjs/src/api/utils/AppName.test.js +2 -0
- package/lib/cjs/src/api/utils/AppName.test.js.map +7 -0
- package/lib/cjs/src/internal/device-session/model/DeviceSession.js +1 -1
- package/lib/cjs/src/internal/device-session/model/DeviceSession.js.map +3 -3
- package/lib/cjs/src/internal/secure-channel/model/Errors.js +1 -1
- package/lib/cjs/src/internal/secure-channel/model/Errors.js.map +3 -3
- package/lib/cjs/src/internal/send/di/sendModule.js +1 -1
- package/lib/cjs/src/internal/send/di/sendModule.js.map +3 -3
- package/lib/cjs/src/internal/send/di/sendTypes.js +1 -1
- package/lib/cjs/src/internal/send/di/sendTypes.js.map +2 -2
- package/lib/cjs/src/internal/send/use-case/SendApduUseCase.js +1 -1
- package/lib/cjs/src/internal/send/use-case/SendApduUseCase.js.map +3 -3
- package/lib/esm/src/api/DeviceManagementKit.js +1 -1
- package/lib/esm/src/api/DeviceManagementKit.js.map +2 -2
- package/lib/esm/src/api/apdu/utils/ByteArrayBuilder.js +1 -1
- package/lib/esm/src/api/apdu/utils/ByteArrayBuilder.js.map +3 -3
- package/lib/esm/src/api/apdu/utils/ByteArrayBuilder.test.js +1 -1
- package/lib/esm/src/api/apdu/utils/ByteArrayBuilder.test.js.map +2 -2
- package/lib/esm/src/api/command/utils/CommandUtils.js +1 -1
- package/lib/esm/src/api/command/utils/CommandUtils.js.map +3 -3
- package/lib/esm/src/api/command/utils/CommandUtils.test.js +1 -1
- package/lib/esm/src/api/command/utils/CommandUtils.test.js.map +2 -2
- package/lib/esm/src/api/command/utils/GlobalCommandError.js +1 -1
- package/lib/esm/src/api/command/utils/GlobalCommandError.js.map +2 -2
- package/lib/esm/src/api/device-action/__test-utils__/makeInternalApi.js +1 -1
- package/lib/esm/src/api/device-action/__test-utils__/makeInternalApi.js.map +2 -2
- package/lib/esm/src/api/device-action/model/UserInteractionRequired.js +1 -1
- package/lib/esm/src/api/device-action/model/UserInteractionRequired.js.map +2 -2
- package/lib/esm/src/api/device-action/os/CallTaskInAppDeviceAction/CallTaskInAppDeviceAction.js +1 -1
- package/lib/esm/src/api/device-action/os/CallTaskInAppDeviceAction/CallTaskInAppDeviceAction.js.map +2 -2
- package/lib/esm/src/api/device-action/os/Errors.js +1 -1
- package/lib/esm/src/api/device-action/os/Errors.js.map +3 -3
- package/lib/esm/src/api/device-action/os/GetDeviceMetadata/GetDeviceMetadataDeviceAction.js +1 -1
- package/lib/esm/src/api/device-action/os/GetDeviceMetadata/GetDeviceMetadataDeviceAction.js.map +2 -2
- package/lib/esm/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.js +1 -1
- package/lib/esm/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.js.map +2 -2
- package/lib/esm/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.test.js +1 -1
- package/lib/esm/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.test.js.map +2 -2
- package/lib/esm/src/api/device-action/os/GoToDashboard/GoToDashboardDeviceAction.js +1 -1
- package/lib/esm/src/api/device-action/os/GoToDashboard/GoToDashboardDeviceAction.js.map +3 -3
- package/lib/esm/src/api/device-action/os/InstallOrUpdateApps/InstallOrUpdateAppsDeviceAction.js +1 -1
- package/lib/esm/src/api/device-action/os/InstallOrUpdateApps/InstallOrUpdateAppsDeviceAction.js.map +2 -2
- package/lib/esm/src/api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction.js +1 -1
- package/lib/esm/src/api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction.js.map +3 -3
- package/lib/esm/src/api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction.test.js +1 -1
- package/lib/esm/src/api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction.test.js.map +3 -3
- package/lib/esm/src/api/device-action/os/OpenAppWithDependencies/OpenAppWithDependenciesDeviceAction.js +1 -1
- package/lib/esm/src/api/device-action/os/OpenAppWithDependencies/OpenAppWithDependenciesDeviceAction.js.map +2 -2
- package/lib/esm/src/api/device-action/os/SendCommandInAppDeviceAction/SendCommandInAppDeviceAction.js +1 -1
- package/lib/esm/src/api/device-action/os/SendCommandInAppDeviceAction/SendCommandInAppDeviceAction.js.map +2 -2
- package/lib/esm/src/api/device-action/task/BuildAppsInstallPlanTask.js +1 -1
- package/lib/esm/src/api/device-action/task/BuildAppsInstallPlanTask.js.map +3 -3
- package/lib/esm/src/api/device-action/task/BuildAppsInstallPlanTask.test.js +1 -1
- package/lib/esm/src/api/device-action/task/BuildAppsInstallPlanTask.test.js.map +3 -3
- package/lib/esm/src/api/index.js +1 -1
- package/lib/esm/src/api/index.js.map +3 -3
- package/lib/esm/src/api/secure-channel/device-action/GenuineCheck/GenuineCheckDeviceAction.js +1 -1
- package/lib/esm/src/api/secure-channel/device-action/GenuineCheck/GenuineCheckDeviceAction.js.map +2 -2
- package/lib/esm/src/api/secure-channel/device-action/InstallApp/InstallAppDeviceAction.js +1 -1
- package/lib/esm/src/api/secure-channel/device-action/InstallApp/InstallAppDeviceAction.js.map +2 -2
- package/lib/esm/src/api/secure-channel/device-action/ListInstalledApps/ListInstalledAppsDeviceAction.js +1 -1
- package/lib/esm/src/api/secure-channel/device-action/ListInstalledApps/ListInstalledAppsDeviceAction.js.map +2 -2
- package/lib/esm/src/api/secure-channel/device-action/ListInstalledApps/types.js +1 -1
- package/lib/esm/src/api/secure-channel/device-action/ListInstalledApps/types.js.map +2 -2
- package/lib/esm/src/api/secure-channel/device-action/UninstallApp/UninstallAppDeviceAction.js +1 -1
- package/lib/esm/src/api/secure-channel/device-action/UninstallApp/UninstallAppDeviceAction.js.map +2 -2
- package/lib/esm/src/api/secure-channel/task/ConnectToSecureChannelTask.js +1 -1
- package/lib/esm/src/api/secure-channel/task/ConnectToSecureChannelTask.js.map +3 -3
- package/lib/esm/src/api/secure-channel/task/ConnectToSecureChannelTask.test.js +1 -1
- package/lib/esm/src/api/secure-channel/task/ConnectToSecureChannelTask.test.js.map +3 -3
- package/lib/esm/src/api/secure-channel/task/types.js +1 -1
- package/lib/esm/src/api/secure-channel/task/types.js.map +2 -2
- package/lib/esm/src/api/secure-channel/utils.js +1 -1
- package/lib/esm/src/api/secure-channel/utils.js.map +3 -3
- package/lib/esm/src/api/secure-channel/utils.test.js +1 -1
- package/lib/esm/src/api/secure-channel/utils.test.js.map +3 -3
- package/lib/esm/src/api/transport/model/DeviceConnectionStateMachine.js +1 -1
- package/lib/esm/src/api/transport/model/DeviceConnectionStateMachine.js.map +3 -3
- package/lib/esm/src/api/transport/model/DeviceConnectionStateMachine.test.js +2 -0
- package/lib/esm/src/api/transport/model/DeviceConnectionStateMachine.test.js.map +7 -0
- package/lib/esm/src/api/transport/model/Errors.js +1 -1
- package/lib/esm/src/api/transport/model/Errors.js.map +3 -3
- package/lib/esm/src/api/transport/model/TransportConnectedDevice.js +1 -1
- package/lib/esm/src/api/transport/model/TransportConnectedDevice.js.map +3 -3
- package/lib/esm/src/api/utils/AppName.js +2 -0
- package/lib/esm/src/api/utils/AppName.js.map +7 -0
- package/lib/esm/src/api/utils/AppName.test.js +2 -0
- package/lib/esm/src/api/utils/AppName.test.js.map +7 -0
- package/lib/esm/src/internal/device-session/model/DeviceSession.js +1 -1
- package/lib/esm/src/internal/device-session/model/DeviceSession.js.map +3 -3
- package/lib/esm/src/internal/secure-channel/model/Errors.js +1 -1
- package/lib/esm/src/internal/secure-channel/model/Errors.js.map +3 -3
- package/lib/esm/src/internal/send/di/sendModule.js +1 -1
- package/lib/esm/src/internal/send/di/sendModule.js.map +3 -3
- package/lib/esm/src/internal/send/di/sendTypes.js +1 -1
- package/lib/esm/src/internal/send/di/sendTypes.js.map +2 -2
- package/lib/esm/src/internal/send/use-case/SendApduUseCase.js +1 -1
- package/lib/esm/src/internal/send/use-case/SendApduUseCase.js.map +3 -3
- package/lib/types/src/api/DeviceManagementKit.d.ts +0 -13
- package/lib/types/src/api/DeviceManagementKit.d.ts.map +1 -1
- package/lib/types/src/api/apdu/utils/ByteArrayBuilder.d.ts +28 -0
- package/lib/types/src/api/apdu/utils/ByteArrayBuilder.d.ts.map +1 -1
- package/lib/types/src/api/command/utils/CommandUtils.d.ts +3 -0
- package/lib/types/src/api/command/utils/CommandUtils.d.ts.map +1 -1
- package/lib/types/src/api/command/utils/GlobalCommandError.d.ts +1 -1
- package/lib/types/src/api/command/utils/GlobalCommandError.d.ts.map +1 -1
- package/lib/types/src/api/device-action/DeviceAction.d.ts +0 -5
- package/lib/types/src/api/device-action/DeviceAction.d.ts.map +1 -1
- package/lib/types/src/api/device-action/__test-utils__/makeInternalApi.d.ts.map +1 -1
- package/lib/types/src/api/device-action/model/UserInteractionRequired.d.ts +1 -0
- package/lib/types/src/api/device-action/model/UserInteractionRequired.d.ts.map +1 -1
- package/lib/types/src/api/device-action/os/CallTaskInAppDeviceAction/CallTaskInAppDeviceAction.d.ts.map +1 -1
- package/lib/types/src/api/device-action/os/CallTaskInAppDeviceAction/CallTaskInAppDeviceActionTypes.d.ts +0 -1
- package/lib/types/src/api/device-action/os/CallTaskInAppDeviceAction/CallTaskInAppDeviceActionTypes.d.ts.map +1 -1
- package/lib/types/src/api/device-action/os/Errors.d.ts +10 -0
- package/lib/types/src/api/device-action/os/Errors.d.ts.map +1 -1
- package/lib/types/src/api/device-action/os/GetDeviceMetadata/GetDeviceMetadataDeviceAction.d.ts.map +1 -1
- package/lib/types/src/api/device-action/os/GetDeviceMetadata/types.d.ts +2 -1
- package/lib/types/src/api/device-action/os/GetDeviceMetadata/types.d.ts.map +1 -1
- package/lib/types/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.d.ts.map +1 -1
- package/lib/types/src/api/device-action/os/GoToDashboard/GoToDashboardDeviceAction.d.ts.map +1 -1
- package/lib/types/src/api/device-action/os/InstallOrUpdateApps/InstallOrUpdateAppsDeviceAction.d.ts.map +1 -1
- package/lib/types/src/api/device-action/os/InstallOrUpdateApps/types.d.ts +3 -2
- package/lib/types/src/api/device-action/os/InstallOrUpdateApps/types.d.ts.map +1 -1
- package/lib/types/src/api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction.d.ts.map +1 -1
- package/lib/types/src/api/device-action/os/OpenAppDeviceAction/types.d.ts +0 -1
- package/lib/types/src/api/device-action/os/OpenAppDeviceAction/types.d.ts.map +1 -1
- package/lib/types/src/api/device-action/os/OpenAppWithDependencies/OpenAppWithDependenciesDeviceAction.d.ts.map +1 -1
- package/lib/types/src/api/device-action/os/OpenAppWithDependencies/types.d.ts +0 -1
- package/lib/types/src/api/device-action/os/OpenAppWithDependencies/types.d.ts.map +1 -1
- package/lib/types/src/api/device-action/os/SendCommandInAppDeviceAction/SendCommandInAppDeviceAction.d.ts.map +1 -1
- package/lib/types/src/api/device-action/os/SendCommandInAppDeviceAction/SendCommandInAppDeviceActionTypes.d.ts +0 -1
- package/lib/types/src/api/device-action/os/SendCommandInAppDeviceAction/SendCommandInAppDeviceActionTypes.d.ts.map +1 -1
- package/lib/types/src/api/device-action/task/BuildAppsInstallPlanTask.d.ts +2 -2
- package/lib/types/src/api/device-action/task/BuildAppsInstallPlanTask.d.ts.map +1 -1
- package/lib/types/src/api/index.d.ts +1 -1
- package/lib/types/src/api/index.d.ts.map +1 -1
- package/lib/types/src/api/secure-channel/device-action/GenuineCheck/GenuineCheckDeviceAction.d.ts.map +1 -1
- package/lib/types/src/api/secure-channel/device-action/GenuineCheck/types.d.ts +2 -1
- package/lib/types/src/api/secure-channel/device-action/GenuineCheck/types.d.ts.map +1 -1
- package/lib/types/src/api/secure-channel/device-action/InstallApp/InstallAppDeviceAction.d.ts.map +1 -1
- package/lib/types/src/api/secure-channel/device-action/InstallApp/types.d.ts +2 -1
- package/lib/types/src/api/secure-channel/device-action/InstallApp/types.d.ts.map +1 -1
- package/lib/types/src/api/secure-channel/device-action/ListInstalledApps/ListInstalledAppsDeviceAction.d.ts.map +1 -1
- package/lib/types/src/api/secure-channel/device-action/ListInstalledApps/types.d.ts +2 -1
- package/lib/types/src/api/secure-channel/device-action/ListInstalledApps/types.d.ts.map +1 -1
- package/lib/types/src/api/secure-channel/device-action/UninstallApp/UninstallAppDeviceAction.d.ts.map +1 -1
- package/lib/types/src/api/secure-channel/device-action/UninstallApp/types.d.ts +2 -1
- package/lib/types/src/api/secure-channel/device-action/UninstallApp/types.d.ts.map +1 -1
- package/lib/types/src/api/secure-channel/task/ConnectToSecureChannelTask.d.ts +5 -2
- package/lib/types/src/api/secure-channel/task/ConnectToSecureChannelTask.d.ts.map +1 -1
- package/lib/types/src/api/secure-channel/task/types.d.ts +6 -1
- package/lib/types/src/api/secure-channel/task/types.d.ts.map +1 -1
- package/lib/types/src/api/secure-channel/utils.d.ts +0 -11
- package/lib/types/src/api/secure-channel/utils.d.ts.map +1 -1
- package/lib/types/src/api/transport/model/DeviceConnection.d.ts +0 -6
- package/lib/types/src/api/transport/model/DeviceConnection.d.ts.map +1 -1
- package/lib/types/src/api/transport/model/DeviceConnectionStateMachine.d.ts +8 -7
- package/lib/types/src/api/transport/model/DeviceConnectionStateMachine.d.ts.map +1 -1
- package/lib/types/src/api/transport/model/DeviceConnectionStateMachine.test.d.ts +2 -0
- package/lib/types/src/api/transport/model/DeviceConnectionStateMachine.test.d.ts.map +1 -0
- package/lib/types/src/api/transport/model/Errors.d.ts +0 -5
- package/lib/types/src/api/transport/model/Errors.d.ts.map +1 -1
- package/lib/types/src/api/transport/model/TransportConnectedDevice.d.ts +2 -4
- package/lib/types/src/api/transport/model/TransportConnectedDevice.d.ts.map +1 -1
- package/lib/types/src/api/utils/AppName.d.ts +2 -0
- package/lib/types/src/api/utils/AppName.d.ts.map +1 -0
- package/lib/types/src/api/utils/AppName.test.d.ts +2 -0
- package/lib/types/src/api/utils/AppName.test.d.ts.map +1 -0
- package/lib/types/src/internal/device-session/model/DeviceSession.d.ts +0 -2
- package/lib/types/src/internal/device-session/model/DeviceSession.d.ts.map +1 -1
- package/lib/types/src/internal/secure-channel/model/Errors.d.ts +22 -2
- package/lib/types/src/internal/secure-channel/model/Errors.d.ts.map +1 -1
- package/lib/types/src/internal/send/di/sendModule.d.ts.map +1 -1
- package/lib/types/src/internal/send/di/sendTypes.d.ts +0 -1
- package/lib/types/src/internal/send/di/sendTypes.d.ts.map +1 -1
- package/lib/types/src/internal/send/use-case/SendApduUseCase.d.ts +5 -1
- package/lib/types/src/internal/send/use-case/SendApduUseCase.d.ts.map +1 -1
- package/lib/types/tsconfig.prod.tsbuildinfo +1 -1
- package/package.json +1 -1
- package/lib/cjs/src/internal/send/use-case/ExchangeBulkApdusUseCase.js +0 -2
- package/lib/cjs/src/internal/send/use-case/ExchangeBulkApdusUseCase.js.map +0 -7
- package/lib/esm/src/internal/send/use-case/ExchangeBulkApdusUseCase.js +0 -2
- package/lib/esm/src/internal/send/use-case/ExchangeBulkApdusUseCase.js.map +0 -7
- package/lib/types/src/internal/send/use-case/ExchangeBulkApdusUseCase.d.ts +0 -32
- package/lib/types/src/internal/send/use-case/ExchangeBulkApdusUseCase.d.ts.map +0 -1
@@ -1,7 +1,7 @@
|
|
1
1
|
{
|
2
2
|
"version": 3,
|
3
3
|
"sources": ["../../../../../../src/api/secure-channel/task/ConnectToSecureChannelTask.ts"],
|
4
|
-
"sourcesContent": ["import WebSocket from \"isomorphic-ws\";\nimport { type Either } from \"purify-ts\";\nimport { Observable } from \"rxjs\";\n\nimport { CommandUtils } from \"@api/command/utils/CommandUtils\";\nimport { type InternalApi } from \"@api/device-action/DeviceAction\";\nimport { type ApduResponse } from \"@api/device-session/ApduResponse\";\nimport {\n InMessageQueryEnum,\n type InMessageType,\n OutMessageResponseEnum,\n type OutMessageType,\n type SecureChannelEvent,\n SecureChannelEventType,\n} from \"@api/secure-channel/task/types\";\nimport {\n isRefusedByUser,\n willRequestPermission,\n} from \"@api/secure-channel/utils\";\nimport { bufferToHexaString, hexaStringToBuffer } from \"@api/utils/HexaString\";\nimport {\n SecureChannelError,\n type WebSocketConnectionError,\n} from \"@internal/secure-channel/model/Errors\";\n\nexport type ConnectToSecureChannelTaskArgs = {\n connection: Either<WebSocketConnectionError, WebSocket>;\n};\n\nexport class ConnectToSecureChannelTask {\n private readonly _connection: WebSocket;\n constructor(\n private readonly _api: InternalApi,\n private readonly _args: ConnectToSecureChannelTaskArgs,\n ) {\n if (this._args.connection.isRight()) {\n this._connection = this._args.connection.extract();\n } else {\n throw new SecureChannelError(\n `Invalid WebSocket connection: ${String(this._args.connection.extract())}`,\n );\n }\n }\n\n run(): Observable<SecureChannelEvent> {\n const reenableRefresher = this._api.disableRefresher(\n \"connectToSecureChannel\",\n );\n\n const obs = new Observable<SecureChannelEvent>((subscriber) => {\n let unsubscribed: boolean = false;\n let inBulkMode = false;\n let communicationFinished = false;\n let deviceError: SecureChannelError | null = null;\n let waitingForUserAction = false;\n\n this._connection.onopen = () => {\n subscriber.next({\n type: SecureChannelEventType.Opened,\n });\n };\n\n this._connection.onerror = (error) => {\n // When the bulk sending is in progress, network error is ignored\n if (inBulkMode) {\n return;\n }\n\n subscriber.error(\n new SecureChannelError({\n url: this._connection.url,\n errorMessage: error.message,\n }),\n );\n };\n\n this._connection.onclose = () => {\n // When the bulk sending is in progress, network event is ignored\n if (inBulkMode) {\n return;\n }\n\n if (communicationFinished) {\n subscriber.next({\n type: SecureChannelEventType.Closed,\n });\n subscriber.complete();\n } else {\n subscriber.error(\n new SecureChannelError(\n deviceError ?? {\n url: this._connection.url,\n errorMessage: \"Connection closed unexpectedly\",\n },\n ),\n );\n }\n };\n\n this._connection.onmessage = async (event) => {\n // When unsubscribed, ignore the message\n if (unsubscribed) {\n return;\n }\n deviceError = null;\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const input: InMessageType = JSON.parse(String(event.data));\n\n switch (input.query) {\n case InMessageQueryEnum.EXCHANGE: {\n const { nonce } = input;\n\n if (Array.isArray(input.data)) {\n subscriber.error(\n new SecureChannelError(\n `${InMessageQueryEnum.EXCHANGE} data type should not be Array`,\n ),\n );\n break;\n }\n\n const apdu = hexaStringToBuffer(input.data);\n\n if (apdu === null || apdu.length < 5) {\n subscriber.error(\n new SecureChannelError(\n `Received invalid APDU data: ${input.data}`,\n ),\n );\n break;\n }\n\n subscriber.next({\n type: SecureChannelEventType.PreExchange,\n payload: { nonce, apdu },\n });\n\n if (\n willRequestPermission(apdu) &&\n !this.isSecureConnectionAllowed()\n ) {\n waitingForUserAction = true;\n subscriber.next({\n type: SecureChannelEventType.PermissionRequested,\n });\n }\n\n const response = await this._api.sendApdu(apdu);\n\n if (unsubscribed) {\n return;\n }\n\n response.caseOf({\n Left: (error) => {\n subscriber.error(new SecureChannelError(error));\n },\n Right: (apduResponse: ApduResponse) => {\n let outMessageResponse: OutMessageResponseEnum;\n /**\n * | Status Code | Description | Event Emitted |\n * |-------------|------------------------------------|------------------------------------|\n * | 0x9000 | Success | SecureChannelEventEnum.Exchange |\n * | 0x5515 | Device is locked | Error |\n * | 0x5501 | User refused on the device | Error |\n * | 0x6985 | Condition of use not satisfied | Error |\n */\n // Success response\n if (CommandUtils.isSuccessResponse(apduResponse)) {\n outMessageResponse = OutMessageResponseEnum.SUCCESS;\n // Emit event for the exchange\n subscriber.next({\n type: SecureChannelEventType.Exchange,\n payload: {\n nonce,\n apdu,\n data: apduResponse.data,\n status: apduResponse.statusCode,\n },\n });\n } else {\n outMessageResponse = OutMessageResponseEnum.ERROR;\n\n deviceError = new SecureChannelError({\n url: this._connection.url,\n errorMessage: `Invalid status code: ${bufferToHexaString(\n apduResponse.statusCode,\n )}`,\n });\n\n // Device is locked\n if (CommandUtils.isLockedDeviceResponse(apduResponse)) {\n subscriber.error(\n new SecureChannelError({\n url: this._connection.url,\n errorMessage: `Device is locked`,\n }),\n );\n return;\n }\n\n // User refused the permission\n if (\n isRefusedByUser(apduResponse.statusCode) &&\n waitingForUserAction\n ) {\n subscriber.error(\n new SecureChannelError({\n url: this._connection.url,\n errorMessage: \"User refused on the device\",\n }),\n );\n return;\n }\n }\n\n if (waitingForUserAction) {\n subscriber.next({\n type: SecureChannelEventType.PermissionGranted,\n });\n waitingForUserAction = false;\n }\n\n // Send the message back to the server\n const message: OutMessageType = {\n nonce,\n response: outMessageResponse,\n data: bufferToHexaString(apduResponse.data).slice(2),\n };\n this._connection.send(JSON.stringify(message));\n },\n });\n break;\n }\n case InMessageQueryEnum.BULK: {\n inBulkMode = true;\n this._connection.close();\n\n if (!Array.isArray(input.data) || input.data.length === 0) {\n subscriber.error(\n new SecureChannelError(\"Invalid bulk data received\"),\n );\n break;\n }\n\n const apdus = input.data.reduce(\n (acc: Array<Uint8Array>, cur: string) => {\n const apdu = hexaStringToBuffer(cur);\n return apdu === null ? acc : [...acc, apdu];\n },\n [],\n );\n\n const t1 = performance.now();\n const enableNativeBulk = true;\n console.log(\"PERF: exchangeBulkApdus call at\", t1, {\n enableNativeBulk,\n });\n\n if (enableNativeBulk) {\n this._api.exchangeBulkApdus(apdus).then((observable) => {\n observable.subscribe({\n next: (result) => {\n if (unsubscribed) {\n return;\n }\n if (\"currentIndex\" in result) {\n subscriber.next({\n type: SecureChannelEventType.Progress,\n payload: {\n progress: +Number(\n (result.currentIndex + 1) / apdus.length,\n ).toFixed(2),\n index: result.currentIndex,\n total: apdus.length,\n },\n });\n } else {\n const payload = result.result;\n\n if (payload.isLeft()) {\n subscriber.error(\n new SecureChannelError(payload.extract()),\n );\n } else {\n subscriber.next({\n type: SecureChannelEventType.Result,\n payload: payload.extract(),\n });\n }\n }\n },\n error: (error) => {\n if (unsubscribed) {\n return;\n }\n subscriber.error(new SecureChannelError(error));\n },\n complete: () => {\n if (unsubscribed) {\n return;\n }\n communicationFinished = true;\n subscriber.complete();\n const t2 = performance.now();\n console.log(\n \"PERF: exchangeBulkApdus result from nativeModule duration:\",\n t2 - t1,\n \"ms\",\n );\n },\n });\n });\n } else {\n for (let i = 0, len = apdus.length; i < len; i++) {\n await this._api.sendApdu(apdus[i]!);\n if (unsubscribed) {\n subscriber.error(\n new SecureChannelError(\n \"Bulk sending cancelled by unsubscribing\",\n ),\n );\n break;\n }\n subscriber.next({\n type: SecureChannelEventType.Progress,\n payload: {\n progress: +Number((i + 1) / len).toFixed(2),\n index: i,\n total: len,\n },\n });\n }\n const t2 = performance.now();\n console.log(\n \"PERF: exchangeBulkApdus result from TS implementation duration:\",\n t2 - t1,\n \"ms\",\n );\n communicationFinished = true;\n subscriber.complete();\n }\n break;\n }\n case InMessageQueryEnum.SUCCESS: {\n // Ignore success message when in bulk mode\n if (inBulkMode) {\n break;\n }\n // Emit the result if there is any\n const payload = input.result ?? input.data;\n if (payload) {\n subscriber.next({\n type: SecureChannelEventType.Result,\n payload: payload ?? \"\",\n });\n }\n communicationFinished = true;\n subscriber.complete();\n break;\n }\n case InMessageQueryEnum.WARNING: {\n // Ignore warning message when in bulk mode\n if (inBulkMode) {\n break;\n }\n subscriber.next({\n type: SecureChannelEventType.Warning,\n payload: { message: String(input.data) },\n });\n break;\n }\n case InMessageQueryEnum.ERROR: {\n if (inBulkMode) {\n break;\n }\n subscriber.error(\n new SecureChannelError({\n url: this._connection.url,\n errorMessage: String(input.data),\n }),\n );\n }\n }\n } catch (error) {\n deviceError = new SecureChannelError(error);\n subscriber.error(deviceError);\n }\n };\n\n return () => {\n reenableRefresher();\n unsubscribed = true;\n // Close the connection if it is open when unsubscribing\n if (this._connection.readyState === WebSocket.OPEN) {\n this._connection.close();\n }\n };\n });\n\n return obs;\n }\n\n /**\n * Determines if a secure connection is already allowed based on the current device session state.\n *\n * @returns {boolean} `true` if a secure connection is allowed, otherwise `false`.\n */\n isSecureConnectionAllowed(): boolean {\n const deviceSessionState = this._api.getDeviceSessionState();\n return (\n \"isSecureConnectionAllowed\" in deviceSessionState &&\n deviceSessionState.isSecureConnectionAllowed\n );\n }\n}\n"],
|
5
|
-
"mappings": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,gCAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAsB,4BAEtBC,EAA2B,gBAE3BC,EAA6B,2CAG7BC,EAOO,0CACPC,
|
6
|
-
"names": ["ConnectToSecureChannelTask_exports", "__export", "ConnectToSecureChannelTask", "__toCommonJS", "import_isomorphic_ws", "import_rxjs", "import_CommandUtils", "import_types", "import_utils", "import_HexaString", "import_Errors", "_api", "_args", "reenableRefresher", "subscriber", "unsubscribed", "
|
4
|
+
"sourcesContent": ["import WebSocket from \"isomorphic-ws\";\nimport { type Either } from \"purify-ts\";\nimport { Observable } from \"rxjs\";\n\nimport { CommandUtils } from \"@api/command/utils/CommandUtils\";\nimport { type InternalApi } from \"@api/device-action/DeviceAction\";\nimport { type ApduResponse } from \"@api/device-session/ApduResponse\";\nimport {\n InMessageQueryEnum,\n type InMessageType,\n OutMessageResponseEnum,\n type OutMessageType,\n type SecureChannelEvent,\n SecureChannelEventType,\n} from \"@api/secure-channel/task/types\";\nimport { willRequestPermission } from \"@api/secure-channel/utils\";\nimport { bufferToHexaString, hexaStringToBuffer } from \"@api/utils/HexaString\";\nimport {\n SecureChannelError,\n SecureChannelErrorType,\n type WebSocketConnectionError,\n} from \"@internal/secure-channel/model/Errors\";\n\nexport type ConnectToSecureChannelTaskArgs = {\n connection: Either<WebSocketConnectionError, WebSocket>;\n};\n\nexport class ConnectToSecureChannelTask {\n private readonly _connection: WebSocket;\n constructor(\n private readonly _api: InternalApi,\n private readonly _args: ConnectToSecureChannelTaskArgs,\n ) {\n if (this._args.connection.isRight()) {\n this._connection = this._args.connection.extract();\n } else {\n throw new SecureChannelError(\n `Invalid WebSocket connection: ${String(this._args.connection.extract())}`,\n );\n }\n }\n\n run(): Observable<SecureChannelEvent> {\n const reenableRefresher = this._api.disableRefresher(\n \"connectToSecureChannel\",\n );\n\n const obs = new Observable<SecureChannelEvent>((subscriber) => {\n let unsubscribed: boolean = false;\n let ignoreNetworkEvents = false;\n let communicationFinished = false;\n\n const notifyError = (error: SecureChannelError) => {\n subscriber.next({\n type: SecureChannelEventType.Error,\n error,\n });\n subscriber.complete();\n\n // Netowrks events can be ignored once the obervable has been completed\n ignoreNetworkEvents = true;\n };\n\n this._connection.onopen = () => {\n subscriber.next({\n type: SecureChannelEventType.Opened,\n });\n };\n\n this._connection.onerror = (error) => {\n if (ignoreNetworkEvents) {\n return;\n }\n\n subscriber.next({\n type: SecureChannelEventType.Error,\n error: new SecureChannelError({\n url: this._connection.url,\n errorMessage: error.message,\n }),\n });\n subscriber.complete();\n };\n\n this._connection.onclose = () => {\n if (ignoreNetworkEvents) {\n return;\n }\n\n if (communicationFinished) {\n subscriber.next({\n type: SecureChannelEventType.Closed,\n });\n } else {\n subscriber.next({\n type: SecureChannelEventType.Error,\n error: new SecureChannelError({\n url: this._connection.url,\n errorMessage: \"Connection closed unexpectedly\",\n }),\n });\n }\n subscriber.complete();\n };\n\n this._connection.onmessage = async (event) => {\n // When unsubscribed, ignore the message\n if (unsubscribed) {\n return;\n }\n\n // Parse input message\n let input: InMessageType;\n try {\n const jsonData = JSON.parse(String(event.data));\n if (this.isInMessageType(jsonData)) {\n input = jsonData;\n } else {\n throw new Error(\"Data does not match InMessageType\");\n }\n } catch (_) {\n notifyError(\n new SecureChannelError({\n url: this._connection.url,\n errorMessage: `Invalid message received: ${String(event.data)}`,\n }),\n );\n return;\n }\n\n // Execute message query\n switch (input.query) {\n case InMessageQueryEnum.EXCHANGE: {\n const { nonce, data } = input;\n\n // Exchange query should contain a single APDU\n if (typeof data !== \"string\") {\n notifyError(\n new SecureChannelError(\n `${InMessageQueryEnum.EXCHANGE} data type should be an APDU`,\n ),\n );\n return;\n }\n\n // APDU should be a valid hex string\n const apdu = hexaStringToBuffer(data);\n if (apdu === null || apdu.length < 5) {\n notifyError(\n new SecureChannelError(`Received invalid APDU data: ${data}`),\n );\n return;\n }\n subscriber.next({\n type: SecureChannelEventType.PreExchange,\n payload: { nonce, apdu },\n });\n\n // Notify permission requested\n let permissionRequested = false;\n if (\n willRequestPermission(apdu) &&\n !this.isSecureConnectionAllowed()\n ) {\n permissionRequested = true;\n subscriber.next({\n type: SecureChannelEventType.PermissionRequested,\n });\n }\n\n // Send APDU to the device\n const response = await this._api.sendApdu(apdu);\n if (unsubscribed) {\n return;\n }\n\n // Map device response\n response.caseOf({\n Left: (error) => {\n notifyError(new SecureChannelError(error));\n },\n Right: (apduResponse: ApduResponse) => {\n let outMessageResponse: OutMessageResponseEnum;\n const deviceError = this.mapDeviceError(apduResponse);\n if (deviceError === null) {\n outMessageResponse = OutMessageResponseEnum.SUCCESS;\n\n // Emit event for the exchange\n subscriber.next({\n type: SecureChannelEventType.Exchange,\n payload: {\n nonce,\n apdu,\n data: apduResponse.data,\n status: apduResponse.statusCode,\n },\n });\n\n // If manager consent was requested, notify the \"granted\" event\n if (permissionRequested) {\n subscriber.next({\n type: SecureChannelEventType.PermissionGranted,\n });\n }\n } else {\n outMessageResponse = OutMessageResponseEnum.ERROR;\n notifyError(deviceError);\n }\n\n // Send the message back to the server\n const message: OutMessageType = {\n nonce,\n response: outMessageResponse,\n data: bufferToHexaString(apduResponse.data).slice(2),\n };\n this._connection.send(JSON.stringify(message));\n },\n });\n break;\n }\n case InMessageQueryEnum.BULK: {\n // Network not needed anymore during bulk APDUs sending\n ignoreNetworkEvents = true;\n this._connection.close();\n\n // A valid array of APDUs is required in a bulk query\n if (\n !Array.isArray(input.data) ||\n input.data.length === 0 ||\n !input.data.every((data) => typeof data === \"string\")\n ) {\n notifyError(new SecureChannelError(\"Invalid bulk data received\"));\n return;\n }\n\n for (let i = 0, len = input.data.length; i < len; i++) {\n // APDU should be a valid hex string\n const apdu = hexaStringToBuffer(input.data[i]!);\n if (apdu === null || apdu.length < 5) {\n notifyError(\n new SecureChannelError(\n `Received invalid APDU bulk data: ${input.data[i]}`,\n ),\n );\n return;\n }\n\n // Send APDU to the device\n const response = await this._api.sendApdu(apdu);\n if (unsubscribed) {\n return;\n }\n\n // Map device response\n if (response.isLeft()) {\n notifyError(new SecureChannelError(response.extract()));\n return;\n } else if (response.isRight()) {\n const deviceError = this.mapDeviceError(response.extract());\n if (deviceError === null) {\n // Notify the progress\n subscriber.next({\n type: SecureChannelEventType.Progress,\n payload: {\n progress: +Number((i + 1) / len).toFixed(2),\n index: i,\n total: len,\n },\n });\n } else {\n notifyError(deviceError);\n return;\n }\n }\n }\n communicationFinished = true;\n subscriber.complete();\n break;\n }\n case InMessageQueryEnum.SUCCESS: {\n if (ignoreNetworkEvents) {\n break;\n }\n // Emit the result if there is any\n const payload = input.result ?? input.data;\n if (payload) {\n subscriber.next({\n type: SecureChannelEventType.Result,\n payload: payload ?? \"\",\n });\n }\n communicationFinished = true;\n subscriber.complete();\n break;\n }\n case InMessageQueryEnum.WARNING: {\n if (ignoreNetworkEvents) {\n break;\n }\n subscriber.next({\n type: SecureChannelEventType.Warning,\n payload: { message: String(input.data) },\n });\n break;\n }\n case InMessageQueryEnum.ERROR: {\n if (ignoreNetworkEvents) {\n break;\n }\n notifyError(\n new SecureChannelError({\n url: this._connection.url,\n errorMessage: String(input.data),\n }),\n );\n }\n }\n };\n\n return () => {\n reenableRefresher();\n unsubscribed = true;\n // Close the connection if it is open when unsubscribing\n if (this._connection.readyState === WebSocket.OPEN) {\n this._connection.close();\n }\n };\n });\n\n return obs;\n }\n\n /**\n * Determines if a secure connection is already allowed based on the current device session state.\n *\n * @returns {boolean} `true` if a secure connection is allowed, otherwise `false`.\n */\n isSecureConnectionAllowed(): boolean {\n const deviceSessionState = this._api.getDeviceSessionState();\n return (\n \"isSecureConnectionAllowed\" in deviceSessionState &&\n deviceSessionState.isSecureConnectionAllowed\n );\n }\n\n isInMessageType(data: unknown): data is InMessageType {\n if (typeof data !== \"object\" || !data) {\n return false;\n }\n\n const message = data as InMessageType;\n return (\n typeof message.uuid === \"string\" &&\n typeof message.session === \"string\" &&\n typeof message.query === \"string\" &&\n Object.values(InMessageQueryEnum).includes(message.query) &&\n typeof message.nonce === \"number\"\n );\n }\n\n mapDeviceError(apduResponse: ApduResponse): SecureChannelError | null {\n if (CommandUtils.isSuccessResponse(apduResponse)) {\n return null;\n }\n\n // Device is locked\n if (CommandUtils.isLockedDeviceResponse(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: `Device is locked`,\n },\n SecureChannelErrorType.DeviceLocked,\n );\n }\n\n // User refused the permission\n if (CommandUtils.isRefusedByUser(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: \"User refused on the device\",\n },\n SecureChannelErrorType.RefusedByUser,\n );\n }\n\n // App already installed\n if (CommandUtils.isAppAlreadyInstalled(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: \"App already installed\",\n },\n SecureChannelErrorType.AppAlreadyInstalled,\n );\n }\n\n // Out of memory\n if (CommandUtils.isOutOfMemory(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: \"Out of memory\",\n },\n SecureChannelErrorType.OutOfMemory,\n );\n }\n\n return new SecureChannelError({\n url: this._connection.url,\n errorMessage: `Invalid status code: ${bufferToHexaString(\n apduResponse.statusCode,\n )}`,\n });\n }\n}\n"],
|
5
|
+
"mappings": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,gCAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAsB,4BAEtBC,EAA2B,gBAE3BC,EAA6B,2CAG7BC,EAOO,0CACPC,EAAsC,qCACtCC,EAAuD,iCACvDC,EAIO,iDAMA,MAAMR,CAA2B,CAEtC,YACmBS,EACAC,EACjB,CAFiB,UAAAD,EACA,WAAAC,EAEjB,GAAI,KAAK,MAAM,WAAW,QAAQ,EAChC,KAAK,YAAc,KAAK,MAAM,WAAW,QAAQ,MAEjD,OAAM,IAAI,qBACR,iCAAiC,OAAO,KAAK,MAAM,WAAW,QAAQ,CAAC,CAAC,EAC1E,CAEJ,CAZiB,YAcjB,KAAsC,CACpC,MAAMC,EAAoB,KAAK,KAAK,iBAClC,wBACF,EA4RA,OA1RY,IAAI,aAAgCC,GAAe,CAC7D,IAAIC,EAAwB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H,CAAC,CACH,CACF",
|
6
|
+
"names": ["ConnectToSecureChannelTask_exports", "__export", "ConnectToSecureChannelTask", "__toCommonJS", "import_isomorphic_ws", "import_rxjs", "import_CommandUtils", "import_types", "import_utils", "import_HexaString", "import_Errors", "_api", "_args", "reenableRefresher", "subscriber", "unsubscribed", "ignoreNetworkEvents", "communicationFinished", "notifyError", "error", "event", "input", "jsonData", "nonce", "data", "apdu", "permissionRequested", "response", "apduResponse", "outMessageResponse", "deviceError", "message", "i", "len", "payload", "WebSocket", "deviceSessionState"]
|
7
7
|
}
|
@@ -1,2 +1,2 @@
|
|
1
|
-
"use strict";var
|
1
|
+
"use strict";var S=Object.create;var g=Object.defineProperty;var b=Object.getOwnPropertyDescriptor;var v=Object.getOwnPropertyNames;var w=Object.getPrototypeOf,E=Object.prototype.hasOwnProperty;var C=(e,l,u,c)=>{if(l&&typeof l=="object"||typeof l=="function")for(let i of v(l))!E.call(e,i)&&i!==u&&g(e,i,{get:()=>l[i],enumerable:!(c=b(l,i))||c.enumerable});return e};var f=(e,l,u)=>(u=e!=null?S(w(e)):{},C(l||!e||!e.__esModule?g(u,"default",{value:e,enumerable:!0}):u,e));var x=f(require("isomorphic-ws")),y=require("purify-ts"),n=require("vitest"),r=require("../../secure-channel/task/types"),d=require("../../../internal/secure-channel/model/Errors"),h=require("./ConnectToSecureChannelTask");n.vi.mock("isomorphic-ws",()=>({...n.vi.importActual("isomorphic-ws"),__esModule:!0,default:class{onopen=null;onmessage=null;send=n.vi.fn();close=n.vi.fn();url;constructor(e){this.url=e}}}));const m=5;(0,n.describe)("ConnectToSecureChannelTask",()=>{let e,l,u,c;const i=n.vi.fn(),p={uuid:"5b776c8d-8af2-48c0-8250-04edca2ef5e9",session:"39ce749e-00a4-4c31-a697-1dc1a29e2cab",query:"success",nonce:15};beforeEach(()=>{e=new x.default("wss://test-host.com"),l={sendApdu:i,disableRefresher:t=>n.vi.fn()},u={connection:(0,y.Right)(e)},c=new h.ConnectToSecureChannelTask(l,u)}),afterEach(()=>{n.vi.resetAllMocks()}),(0,n.it)("should emit Opened event on WebSocket open",async()=>{const t=[];c.run().subscribe(s=>t.push(s)),expect(e.onopen).toBeDefined(),e.onopen({type:"open",target:{}}),await new Promise(s=>setTimeout(s,m)),expect(t).toStrictEqual([{type:r.SecureChannelEventType.Opened}])}),(0,n.it)("Error on wrongly formatted message",async()=>{const t=[];c.run().subscribe({next:s=>{t.push(s)}}),expect(e.onmessage).toBeDefined(),e.onmessage({data:"invalidData",type:"",target:{}}),await new Promise(s=>setTimeout(s,m)),expect(t).toStrictEqual([{type:r.SecureChannelEventType.Error,error:new d.SecureChannelError({url:"wss://test-host.com",errorMessage:"Invalid message received: invalidData"})}])}),(0,n.it)("should handle incoming EXCHANGE message including requesting user permission",async()=>{i.mockResolvedValue((0,y.Right)({data:new Uint8Array([144,0]),statusCode:new Uint8Array([144,0])}));const t=n.vi.spyOn(e,"send");n.vi.spyOn(c,"isSecureConnectionAllowed").mockReturnValueOnce(!1);const a=[];c.run().subscribe({next:o=>{a.push(o)}}),expect(e.onmessage).toBeDefined(),e.onmessage({data:JSON.stringify({...p,query:"exchange",nonce:1,data:"e051000000"}),type:"",target:{}}),await new Promise(o=>setTimeout(o,m)),expect(t).toHaveBeenCalledExactlyOnceWith(JSON.stringify({nonce:1,response:"success",data:"9000"})),expect(a).toStrictEqual([{type:r.SecureChannelEventType.PreExchange,payload:{nonce:1,apdu:new Uint8Array([224,81,0,0,0])}},{type:r.SecureChannelEventType.PermissionRequested},{type:r.SecureChannelEventType.Exchange,payload:{nonce:1,apdu:new Uint8Array([224,81,0,0,0]),data:new Uint8Array([144,0]),status:new Uint8Array([144,0])}},{type:r.SecureChannelEventType.PermissionGranted}])}),(0,n.it)("should handle incoming EXCHANGE message with a device error",async()=>{i.mockResolvedValue((0,y.Right)({data:new Uint8Array([]),statusCode:new Uint8Array([85,21])}));const t=n.vi.spyOn(e,"send"),a=[];c.run().subscribe({next:o=>{a.push(o)}}),expect(e.onmessage).toBeDefined(),e.onmessage({data:JSON.stringify({...p,query:"exchange",nonce:1,data:"e053000000"}),type:"",target:{}}),await new Promise(o=>setTimeout(o,m)),expect(t).toHaveBeenCalledExactlyOnceWith(JSON.stringify({nonce:1,response:"error",data:""})),expect(a).toStrictEqual([{type:r.SecureChannelEventType.PreExchange,payload:{nonce:1,apdu:new Uint8Array([224,83,0,0,0])}},{type:r.SecureChannelEventType.Error,error:new d.SecureChannelError({url:"wss://test-host.com",errorMessage:"Device is locked"},d.SecureChannelErrorType.DeviceLocked)}])}),(0,n.it)("should handle incoming BULK message",async()=>{i.mockResolvedValue((0,y.Right)({data:new Uint8Array([144,0]),statusCode:new Uint8Array([144,0])}));const t=n.vi.fn(),a=c.run(),s=[];a.subscribe({next:o=>{s.push(o)},complete:()=>t()}),expect(e.onmessage).toBeDefined(),e.onmessage({data:JSON.stringify({...p,query:"bulk",nonce:1,data:["0000000100","0000000200","0000000300"]}),type:"",target:{}}),await new Promise(o=>setTimeout(o,m)),expect(i).toHaveBeenCalledTimes(3),expect(s).toStrictEqual([{type:r.SecureChannelEventType.Progress,payload:{progress:.33,index:0,total:3}},{type:r.SecureChannelEventType.Progress,payload:{progress:.67,index:1,total:3}},{type:r.SecureChannelEventType.Progress,payload:{progress:1,index:2,total:3}}]),expect(t).toHaveBeenCalledOnce()}),(0,n.it)("should handle incoming BULK message with a device error",async()=>{i.mockResolvedValue((0,y.Right)({data:new Uint8Array([]),statusCode:new Uint8Array([85,1])}));const t=n.vi.fn(),a=c.run(),s=[];a.subscribe({next:o=>{s.push(o)},complete:()=>t()}),expect(e.onmessage).toBeDefined(),e.onmessage({data:JSON.stringify({...p,query:"bulk",nonce:1,data:["0000000100","0000000200","0000000300"]}),type:"",target:{}}),await new Promise(o=>setTimeout(o,m)),expect(i).toHaveBeenCalledTimes(1),expect(s).toStrictEqual([{type:r.SecureChannelEventType.Error,error:new d.SecureChannelError({url:"wss://test-host.com",errorMessage:"User refused on the device"},d.SecureChannelErrorType.RefusedByUser)}]),expect(t).toHaveBeenCalledOnce()}),(0,n.it)("should handle incoming SUCCESS message",()=>{const t=n.vi.fn(),a=[];c.run().subscribe({next:o=>a.push(o),complete:()=>t()}),e.onmessage({data:JSON.stringify({...p,query:"success",nonce:1,result:"success result"}),type:"",target:{}}),expect(a).toStrictEqual([{type:r.SecureChannelEventType.Result,payload:"success result"}]),expect(t).toHaveBeenCalledOnce()}),(0,n.it)("should handle incoming WARNING message",()=>{const t=[];c.run().subscribe({next:s=>t.push(s)}),expect(e.onmessage).toBeDefined(),e.onmessage({data:JSON.stringify({...p,query:"warning",nonce:1,data:"warning message"}),type:"",target:{}}),expect(t).toStrictEqual([{type:r.SecureChannelEventType.Warning,payload:{message:"warning message"}}])}),(0,n.it)("should handle incoming ERROR message",()=>{const t=[];c.run().subscribe({next:s=>t.push(s)}),expect(e.onmessage).toBeDefined(),e.onmessage({data:JSON.stringify({...p,query:"error",data:"My error"}),type:"",target:{}}),expect(t).toStrictEqual([{type:r.SecureChannelEventType.Error,error:new d.SecureChannelError({url:"wss://test-host.com",errorMessage:"My error"})}])})});
|
2
2
|
//# sourceMappingURL=ConnectToSecureChannelTask.test.js.map
|
@@ -1,7 +1,7 @@
|
|
1
1
|
{
|
2
2
|
"version": 3,
|
3
3
|
"sources": ["../../../../../../src/api/secure-channel/task/ConnectToSecureChannelTask.test.ts"],
|
4
|
-
"sourcesContent": ["import WebSocket from \"isomorphic-ws\";\nimport { Right } from \"purify-ts\";\nimport { describe, it, vi } from \"vitest\";\n\nimport { type InternalApi } from \"@api/index\";\nimport {\n type SecureChannelEvent,\n SecureChannelEventType,\n} from \"@api/secure-channel/task/types\";\nimport { SecureChannelError } from \"@internal/secure-channel/model/Errors\";\n\nimport {\n ConnectToSecureChannelTask,\n type ConnectToSecureChannelTaskArgs,\n} from \"./ConnectToSecureChannelTask\";\n\nvi.mock(\"isomorphic-ws\", () => ({\n ...vi.importActual(\"isomorphic-ws\"),\n __esModule: true,\n default: class {\n onopen: (() => void) | null = null;\n onmessage: ((event: { data: string }) => void) | null = null;\n send = vi.fn();\n close = vi.fn();\n url: string;\n constructor(url: string) {\n this.url = url;\n }\n },\n}));\n\nconst TEST_DELAY = 5;\n\ndescribe(\"ConnectToSecureChannelTask\", () => {\n let mockWebSocket: WebSocket;\n let mockInternalApi: InternalApi;\n let taskArgs: ConnectToSecureChannelTaskArgs;\n let task: ConnectToSecureChannelTask;\n const sendApduFn = vi.fn();\n\n beforeEach(() => {\n // vi.useFakeTimers({ shouldAdvanceTime: true });\n\n mockWebSocket = new WebSocket(\"wss://test-host.com\");\n mockInternalApi = {\n sendApdu: sendApduFn,\n disableRefresher: vi.fn(),\n } as unknown as InternalApi;\n taskArgs = { connection: Right(mockWebSocket) };\n task = new ConnectToSecureChannelTask(mockInternalApi, taskArgs);\n });\n\n afterEach(() => {\n vi.resetAllMocks();\n });\n\n it(\"should emit Opened event on WebSocket open\", async () => {\n const events: SecureChannelEvent[] = [];\n const obs = task.run();\n obs.subscribe((e) => events.push(e));\n\n expect(mockWebSocket.onopen).toBeDefined();\n mockWebSocket.onopen!({\n type: \"open\",\n target: {} as WebSocket,\n });\n\n await new Promise((resolve) => setTimeout(resolve, TEST_DELAY));\n\n expect(events).toStrictEqual([{ type: SecureChannelEventType.Opened }]);\n });\n\n it(\"should handle incoming EXCHANGE message including requesting user permission\", async () => {\n sendApduFn.mockResolvedValue(\n Right({\n data: new Uint8Array([0x90, 0x00]),\n statusCode: new Uint8Array([0x90, 0x00]),\n }),\n );\n\n const sendSpy = vi.spyOn(mockWebSocket, \"send\");\n vi.spyOn(task, \"isSecureConnectionAllowed\").mockReturnValueOnce(false);\n\n const events: SecureChannelEvent[] = [];\n const obs = task.run();\n obs.subscribe({\n next: (event) => {\n events.push(event);\n },\n });\n\n expect(mockWebSocket.onmessage).toBeDefined();\n mockWebSocket.onmessage!({\n data: JSON.stringify({\n query: \"exchange\",\n nonce: 1,\n data: \"e051000000\",\n }),\n type: \"\",\n target: {} as WebSocket,\n });\n\n await new Promise((resolve) => setTimeout(resolve, TEST_DELAY));\n\n expect(sendSpy).toHaveBeenCalledExactlyOnceWith(\n JSON.stringify({\n nonce: 1,\n response: \"success\",\n data: \"9000\",\n }),\n );\n expect(events).toStrictEqual([\n {\n type: SecureChannelEventType.PreExchange,\n payload: {\n nonce: 1,\n apdu: new Uint8Array([0xe0, 0x51, 0x00, 0x00, 0x00]),\n },\n },\n {\n type: SecureChannelEventType.PermissionRequested,\n },\n {\n type: SecureChannelEventType.Exchange,\n payload: {\n nonce: 1,\n apdu: new Uint8Array([0xe0, 0x51, 0x00, 0x00, 0x00]),\n data: new Uint8Array([0x90, 0x00]),\n status: new Uint8Array([0x90, 0x00]),\n },\n },\n {\n type: SecureChannelEventType.PermissionGranted,\n },\n ]);\n });\n\n it(\"should handle incoming BULK message\", async () => {\n sendApduFn.mockResolvedValue(\n Right({\n data: new Uint8Array([0x90, 0x00]),\n statusCode: new Uint8Array([0x90, 0x00]),\n }),\n );\n const completeFn: () => void = vi.fn();\n const obs = task.run();\n const events: SecureChannelEvent[] = [];\n obs.subscribe({\n next: (event: SecureChannelEvent) => {\n events.push(event);\n },\n complete: () => completeFn(),\n });\n\n expect(mockWebSocket.onmessage).toBeDefined();\n mockWebSocket.onmessage!({\n data: JSON.stringify({\n query: \"bulk\",\n nonce: 1,\n data: [\"0000000100\", \"0000000200\", \"0000000300\"],\n }),\n type: \"\",\n target: {} as WebSocket,\n });\n\n await new Promise((resolve) => setTimeout(resolve, TEST_DELAY));\n\n expect(sendApduFn).toHaveBeenCalledTimes(3);\n expect(events).toStrictEqual([\n {\n type: SecureChannelEventType.Progress,\n payload: { progress: 0.33, index: 0, total: 3 },\n },\n {\n type: SecureChannelEventType.Progress,\n payload: { progress: 0.67, index: 1, total: 3 },\n },\n {\n type: SecureChannelEventType.Progress,\n payload: { progress: 1.0, index: 2, total: 3 },\n },\n ]);\n expect(completeFn).toHaveBeenCalledOnce();\n });\n\n it(\"should handle incoming SUCCESS message\", () => {\n const completeFn: () => void = vi.fn();\n const events: SecureChannelEvent[] = [];\n const observable = task.run();\n observable.subscribe({\n next: (event: SecureChannelEvent) => events.push(event),\n complete: () => completeFn(),\n });\n\n mockWebSocket.onmessage!({\n data: JSON.stringify({\n query: \"success\",\n nonce: 1,\n result: \"success result\",\n }),\n type: \"\",\n target: {} as WebSocket,\n });\n\n expect(events).toStrictEqual([\n { type: SecureChannelEventType.Result, payload: \"success result\" },\n ]);\n expect(completeFn).toHaveBeenCalledOnce();\n });\n\n it(\"should handle incoming WARNING message\", () => {\n const events: SecureChannelEvent[] = [];\n const observable = task.run();\n observable.subscribe({\n next: (event: SecureChannelEvent) => events.push(event),\n });\n\n expect(mockWebSocket.onmessage).toBeDefined();\n mockWebSocket.onmessage!({\n data: JSON.stringify({\n query: \"warning\",\n nonce: 1,\n data: \"warning message\",\n }),\n type: \"\",\n target: {} as WebSocket,\n });\n\n expect(events).toStrictEqual([\n {\n type: SecureChannelEventType.Warning,\n payload: { message: \"warning message\" },\n },\n ]);\n });\n\n it(\"should handle incoming ERROR message\", () => {\n const errorFn = vi.fn();\n const observable = task.run();\n observable.subscribe({\n error: (err) => {\n expect(err).toBeInstanceOf(SecureChannelError);\n errorFn(err);\n },\n });\n\n expect(mockWebSocket.onmessage).toBeDefined();\n mockWebSocket.onmessage!({\n data: JSON.stringify({\n query: \"error\",\n }),\n type: \"\",\n target: {} as WebSocket,\n });\n\n expect(errorFn).toHaveBeenCalled();\n });\n});\n"],
|
5
|
-
"mappings": "wdAAA,IAAAA,EAAsB,4BACtBC,EAAsB,qBACtBC,EAAiC,kBAGjCC,EAGO,0CACPC,
|
6
|
-
"names": ["import_isomorphic_ws", "import_purify_ts", "import_vitest", "import_types", "import_Errors", "import_ConnectToSecureChannelTask", "url", "TEST_DELAY", "mockWebSocket", "mockInternalApi", "taskArgs", "task", "sendApduFn", "
|
4
|
+
"sourcesContent": ["import WebSocket from \"isomorphic-ws\";\nimport { Right } from \"purify-ts\";\nimport { describe, it, vi } from \"vitest\";\n\nimport { type InternalApi } from \"@api/index\";\nimport {\n type SecureChannelEvent,\n SecureChannelEventType,\n} from \"@api/secure-channel/task/types\";\nimport {\n SecureChannelError,\n SecureChannelErrorType,\n} from \"@internal/secure-channel/model/Errors\";\n\nimport {\n ConnectToSecureChannelTask,\n type ConnectToSecureChannelTaskArgs,\n} from \"./ConnectToSecureChannelTask\";\n\nvi.mock(\"isomorphic-ws\", () => ({\n ...vi.importActual(\"isomorphic-ws\"),\n __esModule: true,\n default: class {\n onopen: (() => void) | null = null;\n onmessage: ((event: { data: string }) => void) | null = null;\n send = vi.fn();\n close = vi.fn();\n url: string;\n constructor(url: string) {\n this.url = url;\n }\n },\n}));\n\nconst TEST_DELAY = 5;\n\ndescribe(\"ConnectToSecureChannelTask\", () => {\n let mockWebSocket: WebSocket;\n let mockInternalApi: InternalApi;\n let taskArgs: ConnectToSecureChannelTaskArgs;\n let task: ConnectToSecureChannelTask;\n const sendApduFn = vi.fn();\n const mockMessage = {\n uuid: \"5b776c8d-8af2-48c0-8250-04edca2ef5e9\",\n session: \"39ce749e-00a4-4c31-a697-1dc1a29e2cab\",\n query: \"success\",\n nonce: 15,\n };\n\n beforeEach(() => {\n // vi.useFakeTimers({ shouldAdvanceTime: true });\n\n mockWebSocket = new WebSocket(\"wss://test-host.com\");\n mockInternalApi = {\n sendApdu: sendApduFn,\n disableRefresher: (_: unknown) => vi.fn(),\n } as unknown as InternalApi;\n taskArgs = { connection: Right(mockWebSocket) };\n task = new ConnectToSecureChannelTask(mockInternalApi, taskArgs);\n });\n\n afterEach(() => {\n vi.resetAllMocks();\n });\n\n it(\"should emit Opened event on WebSocket open\", async () => {\n const events: SecureChannelEvent[] = [];\n const obs = task.run();\n obs.subscribe((e) => events.push(e));\n\n expect(mockWebSocket.onopen).toBeDefined();\n mockWebSocket.onopen!({\n type: \"open\",\n target: {} as WebSocket,\n });\n\n await new Promise((resolve) => setTimeout(resolve, TEST_DELAY));\n\n expect(events).toStrictEqual([{ type: SecureChannelEventType.Opened }]);\n });\n\n it(\"Error on wrongly formatted message\", async () => {\n const events: SecureChannelEvent[] = [];\n const obs = task.run();\n obs.subscribe({\n next: (event) => {\n events.push(event);\n },\n });\n\n expect(mockWebSocket.onmessage).toBeDefined();\n mockWebSocket.onmessage!({\n data: \"invalidData\",\n type: \"\",\n target: {} as WebSocket,\n });\n\n await new Promise((resolve) => setTimeout(resolve, TEST_DELAY));\n\n expect(events).toStrictEqual([\n {\n type: SecureChannelEventType.Error,\n error: new SecureChannelError({\n url: \"wss://test-host.com\",\n errorMessage: \"Invalid message received: invalidData\",\n }),\n },\n ]);\n });\n\n it(\"should handle incoming EXCHANGE message including requesting user permission\", async () => {\n sendApduFn.mockResolvedValue(\n Right({\n data: new Uint8Array([0x90, 0x00]),\n statusCode: new Uint8Array([0x90, 0x00]),\n }),\n );\n\n const sendSpy = vi.spyOn(mockWebSocket, \"send\");\n vi.spyOn(task, \"isSecureConnectionAllowed\").mockReturnValueOnce(false);\n\n const events: SecureChannelEvent[] = [];\n const obs = task.run();\n obs.subscribe({\n next: (event) => {\n events.push(event);\n },\n });\n\n expect(mockWebSocket.onmessage).toBeDefined();\n mockWebSocket.onmessage!({\n data: JSON.stringify({\n ...mockMessage,\n query: \"exchange\",\n nonce: 1,\n data: \"e051000000\",\n }),\n type: \"\",\n target: {} as WebSocket,\n });\n\n await new Promise((resolve) => setTimeout(resolve, TEST_DELAY));\n\n expect(sendSpy).toHaveBeenCalledExactlyOnceWith(\n JSON.stringify({\n nonce: 1,\n response: \"success\",\n data: \"9000\",\n }),\n );\n expect(events).toStrictEqual([\n {\n type: SecureChannelEventType.PreExchange,\n payload: {\n nonce: 1,\n apdu: new Uint8Array([0xe0, 0x51, 0x00, 0x00, 0x00]),\n },\n },\n {\n type: SecureChannelEventType.PermissionRequested,\n },\n {\n type: SecureChannelEventType.Exchange,\n payload: {\n nonce: 1,\n apdu: new Uint8Array([0xe0, 0x51, 0x00, 0x00, 0x00]),\n data: new Uint8Array([0x90, 0x00]),\n status: new Uint8Array([0x90, 0x00]),\n },\n },\n {\n type: SecureChannelEventType.PermissionGranted,\n },\n ]);\n });\n\n it(\"should handle incoming EXCHANGE message with a device error\", async () => {\n sendApduFn.mockResolvedValue(\n Right({\n data: new Uint8Array([]),\n statusCode: new Uint8Array([0x55, 0x15]),\n }),\n );\n\n const sendSpy = vi.spyOn(mockWebSocket, \"send\");\n const events: SecureChannelEvent[] = [];\n const obs = task.run();\n obs.subscribe({\n next: (event) => {\n events.push(event);\n },\n });\n\n expect(mockWebSocket.onmessage).toBeDefined();\n mockWebSocket.onmessage!({\n data: JSON.stringify({\n ...mockMessage,\n query: \"exchange\",\n nonce: 1,\n data: \"e053000000\",\n }),\n type: \"\",\n target: {} as WebSocket,\n });\n\n await new Promise((resolve) => setTimeout(resolve, TEST_DELAY));\n\n expect(sendSpy).toHaveBeenCalledExactlyOnceWith(\n JSON.stringify({\n nonce: 1,\n response: \"error\",\n data: \"\",\n }),\n );\n expect(events).toStrictEqual([\n {\n type: SecureChannelEventType.PreExchange,\n payload: {\n nonce: 1,\n apdu: new Uint8Array([0xe0, 0x53, 0x00, 0x00, 0x00]),\n },\n },\n {\n type: SecureChannelEventType.Error,\n error: new SecureChannelError(\n {\n url: \"wss://test-host.com\",\n errorMessage: \"Device is locked\",\n },\n SecureChannelErrorType.DeviceLocked,\n ),\n },\n ]);\n });\n\n it(\"should handle incoming BULK message\", async () => {\n sendApduFn.mockResolvedValue(\n Right({\n data: new Uint8Array([0x90, 0x00]),\n statusCode: new Uint8Array([0x90, 0x00]),\n }),\n );\n const completeFn: () => void = vi.fn();\n const obs = task.run();\n const events: SecureChannelEvent[] = [];\n obs.subscribe({\n next: (event: SecureChannelEvent) => {\n events.push(event);\n },\n complete: () => completeFn(),\n });\n\n expect(mockWebSocket.onmessage).toBeDefined();\n mockWebSocket.onmessage!({\n data: JSON.stringify({\n ...mockMessage,\n query: \"bulk\",\n nonce: 1,\n data: [\"0000000100\", \"0000000200\", \"0000000300\"],\n }),\n type: \"\",\n target: {} as WebSocket,\n });\n\n await new Promise((resolve) => setTimeout(resolve, TEST_DELAY));\n\n expect(sendApduFn).toHaveBeenCalledTimes(3);\n expect(events).toStrictEqual([\n {\n type: SecureChannelEventType.Progress,\n payload: { progress: 0.33, index: 0, total: 3 },\n },\n {\n type: SecureChannelEventType.Progress,\n payload: { progress: 0.67, index: 1, total: 3 },\n },\n {\n type: SecureChannelEventType.Progress,\n payload: { progress: 1.0, index: 2, total: 3 },\n },\n ]);\n expect(completeFn).toHaveBeenCalledOnce();\n });\n\n it(\"should handle incoming BULK message with a device error\", async () => {\n sendApduFn.mockResolvedValue(\n Right({\n data: new Uint8Array([]),\n statusCode: new Uint8Array([0x55, 0x01]),\n }),\n );\n const completeFn: () => void = vi.fn();\n const obs = task.run();\n const events: SecureChannelEvent[] = [];\n obs.subscribe({\n next: (event: SecureChannelEvent) => {\n events.push(event);\n },\n complete: () => completeFn(),\n });\n\n expect(mockWebSocket.onmessage).toBeDefined();\n mockWebSocket.onmessage!({\n data: JSON.stringify({\n ...mockMessage,\n query: \"bulk\",\n nonce: 1,\n data: [\"0000000100\", \"0000000200\", \"0000000300\"],\n }),\n type: \"\",\n target: {} as WebSocket,\n });\n\n await new Promise((resolve) => setTimeout(resolve, TEST_DELAY));\n\n expect(sendApduFn).toHaveBeenCalledTimes(1);\n expect(events).toStrictEqual([\n {\n type: SecureChannelEventType.Error,\n error: new SecureChannelError(\n {\n url: \"wss://test-host.com\",\n errorMessage: \"User refused on the device\",\n },\n SecureChannelErrorType.RefusedByUser,\n ),\n },\n ]);\n expect(completeFn).toHaveBeenCalledOnce();\n });\n\n it(\"should handle incoming SUCCESS message\", () => {\n const completeFn: () => void = vi.fn();\n const events: SecureChannelEvent[] = [];\n const observable = task.run();\n observable.subscribe({\n next: (event: SecureChannelEvent) => events.push(event),\n complete: () => completeFn(),\n });\n\n mockWebSocket.onmessage!({\n data: JSON.stringify({\n ...mockMessage,\n query: \"success\",\n nonce: 1,\n result: \"success result\",\n }),\n type: \"\",\n target: {} as WebSocket,\n });\n\n expect(events).toStrictEqual([\n { type: SecureChannelEventType.Result, payload: \"success result\" },\n ]);\n expect(completeFn).toHaveBeenCalledOnce();\n });\n\n it(\"should handle incoming WARNING message\", () => {\n const events: SecureChannelEvent[] = [];\n const observable = task.run();\n observable.subscribe({\n next: (event: SecureChannelEvent) => events.push(event),\n });\n\n expect(mockWebSocket.onmessage).toBeDefined();\n mockWebSocket.onmessage!({\n data: JSON.stringify({\n ...mockMessage,\n query: \"warning\",\n nonce: 1,\n data: \"warning message\",\n }),\n type: \"\",\n target: {} as WebSocket,\n });\n\n expect(events).toStrictEqual([\n {\n type: SecureChannelEventType.Warning,\n payload: { message: \"warning message\" },\n },\n ]);\n });\n\n it(\"should handle incoming ERROR message\", () => {\n const events: SecureChannelEvent[] = [];\n const observable = task.run();\n observable.subscribe({\n next: (event: SecureChannelEvent) => events.push(event),\n });\n\n expect(mockWebSocket.onmessage).toBeDefined();\n mockWebSocket.onmessage!({\n data: JSON.stringify({\n ...mockMessage,\n query: \"error\",\n data: \"My error\",\n }),\n type: \"\",\n target: {} as WebSocket,\n });\n\n expect(events).toStrictEqual([\n {\n type: SecureChannelEventType.Error,\n error: new SecureChannelError({\n url: \"wss://test-host.com\",\n errorMessage: \"My error\",\n }),\n },\n ]);\n });\n});\n"],
|
5
|
+
"mappings": "wdAAA,IAAAA,EAAsB,4BACtBC,EAAsB,qBACtBC,EAAiC,kBAGjCC,EAGO,0CACPC,EAGO,iDAEPC,EAGO,wCAEP,KAAG,KAAK,gBAAiB,KAAO,CAC9B,GAAG,KAAG,aAAa,eAAe,EAClC,WAAY,GACZ,QAAS,KAAM,CACb,OAA8B,KAC9B,UAAwD,KACxD,KAAO,KAAG,GAAG,EACb,MAAQ,KAAG,GAAG,EACd,IACA,YAAYC,EAAa,CACvB,KAAK,IAAMA,CACb,CACF,CACF,EAAE,EAEF,MAAMC,EAAa,KAEnB,YAAS,6B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AAOQ,GAA8BH,EAAO,KAAKG,CAAK,CACxD,CAAC,EAED,OAAOX,EAAc,SAAS,EAAE,YAAY,EAC5CA,EAAc,UAAW,CACvB,KAAM,KAAK,UAAU,CACnB,GAAGK,EACH,MAAO,QACP,KAAM,UACR,CAAC,EACD,KAAM,GACN,OAAQ,CAAC,CACX,CAAC,EAED,OAAOG,CAAM,EAAE,cAAc,CAC3B,CACE,KAAM,yBAAuB,MAC7B,MAAO,IAAI,qBAAmB,CAC5B,IAAK,sBACL,aAAc,UAChB,CAAC,CACH,CACF,CAAC,CACH,CAAC,CACH,CAAC",
|
6
|
+
"names": ["import_isomorphic_ws", "import_purify_ts", "import_vitest", "import_types", "import_Errors", "import_ConnectToSecureChannelTask", "url", "TEST_DELAY", "mockWebSocket", "mockInternalApi", "taskArgs", "task", "sendApduFn", "mockMessage", "WebSocket", "_", "events", "e", "resolve", "event", "sendSpy", "completeFn", "obs"]
|
7
7
|
}
|
@@ -1,2 +1,2 @@
|
|
1
|
-
"use strict";var o=Object.defineProperty;var
|
1
|
+
"use strict";var o=Object.defineProperty;var g=Object.getOwnPropertyDescriptor;var u=Object.getOwnPropertyNames;var x=Object.prototype.hasOwnProperty;var P=(n,r)=>{for(var t in r)o(n,t,{get:r[t],enumerable:!0})},h=(n,r,t,l)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of u(r))!x.call(n,s)&&s!==t&&o(n,s,{get:()=>r[s],enumerable:!(l=g(r,s))||l.enumerable});return n};var E=n=>h(o({},"__esModule",{value:!0}),n);var U={};P(U,{InMessageQueryEnum:()=>i,OutMessageResponseEnum:()=>y,SecureChannelEventType:()=>c,SecureChannelOperationEnum:()=>d});module.exports=E(U);var d=(a=>(a.GenuineCheck="GenuineCheck",a.ListInstalledApps="ListInstalledApps",a.UpdateMcu="UpdateMcu",a.UpdateFirmware="UpdateFirmware",a.InstallApp="InstallApp",a.UninstallApp="UninstallApp",a))(d||{}),i=(p=>(p.EXCHANGE="exchange",p.BULK="bulk",p.ERROR="error",p.WARNING="warning",p.SUCCESS="success",p))(i||{}),y=(t=>(t.SUCCESS="success",t.ERROR="error",t))(y||{}),c=(e=>(e.Opened="opened",e.Closed="closed",e.PermissionRequested="permission-requested",e.PermissionGranted="permission-granted",e.PreExchange="pre-exchange",e.Exchange="exchange",e.Progress="progress",e.Warning="warning",e.Error="error",e.Result="result",e))(c||{});0&&(module.exports={InMessageQueryEnum,OutMessageResponseEnum,SecureChannelEventType,SecureChannelOperationEnum});
|
2
2
|
//# sourceMappingURL=types.js.map
|
@@ -1,7 +1,7 @@
|
|
1
1
|
{
|
2
2
|
"version": 3,
|
3
3
|
"sources": ["../../../../../../src/api/secure-channel/task/types.ts"],
|
4
|
-
"sourcesContent": ["
|
5
|
-
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,wBAAAE,EAAA,2BAAAC,EAAA,2BAAAC,EAAA,+BAAAC,IAAA,eAAAC,EAAAN,
|
4
|
+
"sourcesContent": ["import { type SecureChannelError } from \"@internal/secure-channel/model/Errors\";\n\nexport enum SecureChannelOperationEnum {\n GenuineCheck = \"GenuineCheck\",\n ListInstalledApps = \"ListInstalledApps\",\n UpdateMcu = \"UpdateMcu\",\n UpdateFirmware = \"UpdateFirmware\",\n InstallApp = \"InstallApp\",\n UninstallApp = \"UninstallApp\",\n}\n\n/**\n * The message that will be received from the server by the secure channel.\n */\nexport type InMessageType = {\n uuid: string;\n session: string;\n query: InMessageQueryEnum;\n nonce: number;\n data: unknown;\n result?: unknown;\n};\n\nexport enum InMessageQueryEnum {\n EXCHANGE = \"exchange\",\n BULK = \"bulk\",\n ERROR = \"error\",\n WARNING = \"warning\",\n SUCCESS = \"success\",\n}\n\n/**\n * The message that will be sent to the server by the secure channel.\n */\nexport type OutMessageType = {\n nonce: number;\n response: OutMessageResponseEnum;\n data: string;\n};\n\nexport enum OutMessageResponseEnum {\n SUCCESS = \"success\",\n ERROR = \"error\",\n}\n\n/**\n * The all event types that can be emitted to the client by the secure channel.\n *\n */\nexport enum SecureChannelEventType {\n Opened = \"opened\",\n Closed = \"closed\",\n PermissionRequested = \"permission-requested\",\n PermissionGranted = \"permission-granted\",\n PreExchange = \"pre-exchange\",\n Exchange = \"exchange\",\n Progress = \"progress\",\n Warning = \"warning\",\n Error = \"error\",\n Result = \"result\",\n}\n\n/**\n * The possible payload that will be sent to the client when a secure channel event occurs.\n */\nexport type SecureChannelEventPayload = {\n PreExchange: { nonce: number; apdu: Uint8Array };\n Exchange: {\n nonce: number;\n apdu: Uint8Array;\n data: Uint8Array;\n status: Uint8Array;\n };\n Progress: { progress: number; index: number; total: number };\n Warning: { message: string };\n Result: unknown;\n};\n\n/**\n * The event type that will be emitted to the client when a secure channel event occurs.\n */\nexport type SecureChannelEvent =\n | {\n type: SecureChannelEventType.Opened;\n }\n | {\n type: SecureChannelEventType.Closed;\n }\n | {\n type: SecureChannelEventType.PermissionRequested;\n }\n | {\n type: SecureChannelEventType.PermissionGranted;\n }\n | {\n type: SecureChannelEventType.PreExchange;\n payload: SecureChannelEventPayload[\"PreExchange\"];\n }\n | {\n type: SecureChannelEventType.Exchange;\n payload: SecureChannelEventPayload[\"Exchange\"];\n }\n | {\n type: SecureChannelEventType.Progress;\n payload: SecureChannelEventPayload[\"Progress\"];\n }\n | {\n type: SecureChannelEventType.Warning;\n payload: SecureChannelEventPayload[\"Warning\"];\n }\n | {\n type: SecureChannelEventType.Error;\n error: SecureChannelError;\n }\n | {\n type: SecureChannelEventType.Result;\n payload: SecureChannelEventPayload[\"Result\"];\n };\n"],
|
5
|
+
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,wBAAAE,EAAA,2BAAAC,EAAA,2BAAAC,EAAA,+BAAAC,IAAA,eAAAC,EAAAN,GAEO,IAAKK,OACVA,EAAA,aAAe,eACfA,EAAA,kBAAoB,oBACpBA,EAAA,UAAY,YACZA,EAAA,eAAiB,iBACjBA,EAAA,WAAa,aACbA,EAAA,aAAe,eANLA,OAAA,IAqBAH,OACVA,EAAA,SAAW,WACXA,EAAA,KAAO,OACPA,EAAA,MAAQ,QACRA,EAAA,QAAU,UACVA,EAAA,QAAU,UALAA,OAAA,IAiBAC,OACVA,EAAA,QAAU,UACVA,EAAA,MAAQ,QAFEA,OAAA,IASAC,OACVA,EAAA,OAAS,SACTA,EAAA,OAAS,SACTA,EAAA,oBAAsB,uBACtBA,EAAA,kBAAoB,qBACpBA,EAAA,YAAc,eACdA,EAAA,SAAW,WACXA,EAAA,SAAW,WACXA,EAAA,QAAU,UACVA,EAAA,MAAQ,QACRA,EAAA,OAAS,SAVCA,OAAA",
|
6
6
|
"names": ["types_exports", "__export", "InMessageQueryEnum", "OutMessageResponseEnum", "SecureChannelEventType", "SecureChannelOperationEnum", "__toCommonJS"]
|
7
7
|
}
|
@@ -1,2 +1,2 @@
|
|
1
|
-
"use strict";var o=Object.defineProperty;var
|
1
|
+
"use strict";var o=Object.defineProperty;var u=Object.getOwnPropertyDescriptor;var a=Object.getOwnPropertyNames;var E=Object.prototype.hasOwnProperty;var c=(e,n)=>{for(var t in n)o(e,t,{get:n[t],enumerable:!0})},m=(e,n,t,i)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of a(n))!E.call(e,r)&&r!==t&&o(e,r,{get:()=>n[r],enumerable:!(i=u(n,r))||i.enumerable});return e};var s=e=>m(o({},"__esModule",{value:!0}),e);var x={};c(x,{isDeviceGenuine:()=>p,willRequestPermission:()=>f});module.exports=s(x);var l=require("./constants");function f(e){return e[0]===224&&e[1]===81}function p(e){return e===l.GENUINE_DEVICE_RESULT}0&&(module.exports={isDeviceGenuine,willRequestPermission});
|
2
2
|
//# sourceMappingURL=utils.js.map
|
@@ -1,7 +1,7 @@
|
|
1
1
|
{
|
2
2
|
"version": 3,
|
3
3
|
"sources": ["../../../../../src/api/secure-channel/utils.ts"],
|
4
|
-
"sourcesContent": ["import { type SecureChannelEventPayload } from \"./task/types\";\nimport { GENUINE_DEVICE_RESULT } from \"./constants\";\n\n/**\n * Checks if the given APDU command will request permission.\n *\n * This method checks if the first byte of the APDU command is `0xe0` and the second byte is `0x51`.\n *\n * @param apdu - The APDU command as a Uint8Array.\n * @returns `true` if the APDU command will request permission, otherwise `false`.\n */\nexport function willRequestPermission(apdu: Uint8Array): boolean {\n return apdu[0] === 0xe0 && apdu[1] === 0x51;\n}\n\n/**\n * Checks if the
|
5
|
-
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,EAAA,
|
6
|
-
"names": ["utils_exports", "__export", "isDeviceGenuine", "
|
4
|
+
"sourcesContent": ["import { type SecureChannelEventPayload } from \"./task/types\";\nimport { GENUINE_DEVICE_RESULT } from \"./constants\";\n\n/**\n * Checks if the given APDU command will request permission.\n *\n * This method checks if the first byte of the APDU command is `0xe0` and the second byte is `0x51`.\n *\n * @param apdu - The APDU command as a Uint8Array.\n * @returns `true` if the APDU command will request permission, otherwise `false`.\n */\nexport function willRequestPermission(apdu: Uint8Array): boolean {\n return apdu[0] === 0xe0 && apdu[1] === 0x51;\n}\n\n/**\n * Checks if the device is genuine.\n *\n * @param payload - The payload of the result secure channel event.\n * The payload has already been stringified, so that the type check is not necessary.\n * @returns `true` if the device is genuine, otherwise `false`.\n */\nexport function isDeviceGenuine(payload: SecureChannelEventPayload[\"Result\"]) {\n return payload === GENUINE_DEVICE_RESULT;\n}\n"],
|
5
|
+
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,EAAA,0BAAAC,IAAA,eAAAC,EAAAJ,GACA,IAAAK,EAAsC,uBAU/B,SAASF,EAAsBG,EAA2B,CAC/D,OAAOA,EAAK,CAAC,IAAM,KAAQA,EAAK,CAAC,IAAM,EACzC,CASO,SAASJ,EAAgBK,EAA8C,CAC5E,OAAOA,IAAY,uBACrB",
|
6
|
+
"names": ["utils_exports", "__export", "isDeviceGenuine", "willRequestPermission", "__toCommonJS", "import_constants", "apdu", "payload"]
|
7
7
|
}
|
@@ -1,2 +1,2 @@
|
|
1
|
-
"use strict";var
|
1
|
+
"use strict";var e=require("./utils");describe("willRequestPermission",()=>{it("should return true if the APDU is a permission request",()=>{const i=new Uint8Array([224,81,0,0,0]);expect((0,e.willRequestPermission)(i)).toBe(!0)}),it("should return false if the APDU is not a permission request",()=>{const i=new Uint8Array([224,82,0,0,0]);expect((0,e.willRequestPermission)(i)).toBe(!1)})});describe("isDeviceGenuine",()=>{it("should return true if the device is genuine",()=>{expect((0,e.isDeviceGenuine)("0000")).toBe(!0)}),it("should return false if the device is not genuine",()=>{expect((0,e.isDeviceGenuine)("not genuine")).toBe(!1)})});
|
2
2
|
//# sourceMappingURL=utils.test.js.map
|
@@ -1,7 +1,7 @@
|
|
1
1
|
{
|
2
2
|
"version": 3,
|
3
3
|
"sources": ["../../../../../src/api/secure-channel/utils.test.ts"],
|
4
|
-
"sourcesContent": ["import {
|
5
|
-
"mappings": "aAAA,IAAAA,
|
6
|
-
"names": ["import_utils", "apdu"
|
4
|
+
"sourcesContent": ["import { isDeviceGenuine, willRequestPermission } from \"./utils\";\n\ndescribe(\"willRequestPermission\", () => {\n it(\"should return true if the APDU is a permission request\", () => {\n const apdu = new Uint8Array([0xe0, 0x51, 0x00, 0x00, 0x00]);\n expect(willRequestPermission(apdu)).toBe(true);\n });\n it(\"should return false if the APDU is not a permission request\", () => {\n const apdu = new Uint8Array([0xe0, 0x52, 0x00, 0x00, 0x00]);\n expect(willRequestPermission(apdu)).toBe(false);\n });\n});\n\ndescribe(\"isDeviceGenuine\", () => {\n it(\"should return true if the device is genuine\", () => {\n const payload = \"0000\";\n expect(isDeviceGenuine(payload)).toBe(true);\n });\n it(\"should return false if the device is not genuine\", () => {\n const payload = \"not genuine\";\n expect(isDeviceGenuine(payload)).toBe(false);\n });\n});\n"],
|
5
|
+
"mappings": "aAAA,IAAAA,EAAuD,mBAEvD,SAAS,wBAAyB,IAAM,CACtC,GAAG,yDAA0D,IAAM,CACjE,MAAMC,EAAO,IAAI,WAAW,CAAC,IAAM,GAAM,EAAM,EAAM,CAAI,CAAC,EAC1D,UAAO,yBAAsBA,CAAI,CAAC,EAAE,KAAK,EAAI,CAC/C,CAAC,EACD,GAAG,8DAA+D,IAAM,CACtE,MAAMA,EAAO,IAAI,WAAW,CAAC,IAAM,GAAM,EAAM,EAAM,CAAI,CAAC,EAC1D,UAAO,yBAAsBA,CAAI,CAAC,EAAE,KAAK,EAAK,CAChD,CAAC,CACH,CAAC,EAED,SAAS,kBAAmB,IAAM,CAChC,GAAG,8CAA+C,IAAM,CAEtD,UAAO,mBADS,MACc,CAAC,EAAE,KAAK,EAAI,CAC5C,CAAC,EACD,GAAG,mDAAoD,IAAM,CAE3D,UAAO,mBADS,aACc,CAAC,EAAE,KAAK,EAAK,CAC7C,CAAC,CACH,CAAC",
|
6
|
+
"names": ["import_utils", "apdu"]
|
7
7
|
}
|
@@ -1,2 +1,2 @@
|
|
1
|
-
"use strict";var
|
1
|
+
"use strict";var t=Object.defineProperty;var i=Object.getOwnPropertyDescriptor;var d=Object.getOwnPropertyNames;var m=Object.prototype.hasOwnProperty;var u=(r,e,n,p)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of d(e))!m.call(r,o)&&o!==n&&t(r,o,{get:()=>e[o],enumerable:!(p=i(e,o))||p.enumerable});return r};var s=r=>u(t({},"__esModule",{value:!0}),r);var c={};module.exports=s(c);
|
2
2
|
//# sourceMappingURL=DeviceConnection.js.map
|
@@ -1,7 +1,7 @@
|
|
1
1
|
{
|
2
2
|
"version": 3,
|
3
3
|
"sources": ["../../../../../../src/api/transport/model/DeviceConnection.ts"],
|
4
|
-
"sourcesContent": ["import { type Either } from \"purify-ts\";\n\nimport { type DeviceId } from \"@api/device/DeviceModel\";\nimport { type ApduResponse } from \"@api/device-session/ApduResponse\";\nimport { type DmkError } from \"@api/Error\";\
|
4
|
+
"sourcesContent": ["import { type Either } from \"purify-ts\";\n\nimport { type DeviceId } from \"@api/device/DeviceModel\";\nimport { type ApduResponse } from \"@api/device-session/ApduResponse\";\nimport { type DmkError } from \"@api/Error\";\n\nexport type DisconnectHandler = (deviceId: DeviceId) => void;\n\nexport type SendApduResult = Either<DmkError, ApduResponse>;\n\nexport type SendApduFnType = (\n apdu: Uint8Array,\n triggersDisconnection?: boolean,\n abortTimeout?: number,\n) => Promise<SendApduResult>;\n\nexport interface DeviceConnection {\n sendApdu: SendApduFnType;\n}\n"],
|
5
5
|
"mappings": "+WAAA,IAAAA,EAAA,kBAAAC,EAAAD",
|
6
6
|
"names": ["DeviceConnection_exports", "__toCommonJS"]
|
7
7
|
}
|
@@ -1,2 +1,2 @@
|
|
1
|
-
"use strict";var
|
1
|
+
"use strict";var l=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var R=Object.getOwnPropertyNames;var y=Object.prototype.hasOwnProperty;var v=(s,n)=>{for(var i in n)l(s,i,{get:n[i],enumerable:!0})},h=(s,n,i,c)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of R(n))!y.call(s,o)&&o!==i&&l(s,o,{get:()=>n[o],enumerable:!(c=C(n,o))||c.enumerable});return s};var T=s=>h(l({},"__esModule",{value:!0}),s);var E={};v(E,{DeviceConnectionStateMachine:()=>S});module.exports=T(E);var t=require("purify-ts"),r=require("xstate"),g=require("../../command/os/GetAppAndVersionCommand"),m=require("../../command/utils/CommandUtils"),A=require("../../Error"),d=require("./Errors");class S{deviceId;deviceAdpuSender;machineActor;timeoutDuration;timeout=null;startReconnectionTimeout(){this.timeout=setTimeout(()=>{this.machineActor.send({type:"ReconnectionTimedOut"})},this.timeoutDuration)}constructor(n){this.deviceId=n.deviceId,this.deviceAdpuSender=n.deviceApduSender,this.timeoutDuration=n.timeoutDuration,this.machineActor=(0,r.createActor)(b({sendApduFn:(i,c,o)=>this.sendApduToDeviceConnection(i,c,o),startReconnectionTimeout:()=>this.startReconnectionTimeout(),cancelReconnectionTimeout:()=>{this.timeout&&(clearTimeout(this.timeout),this.timeout=null)},tryToReconnect:()=>{n.tryToReconnect(this.timeoutDuration)},onTerminated:n.onTerminated,closeConnection:()=>{this.deviceAdpuSender.closeConnection()}})),this.machineActor.start()}sendApduToDeviceConnection(n,i,c){this.deviceAdpuSender.sendApdu(n,i,c).then(o=>{o.caseOf({Left:a=>{this.machineActor.send({type:"ApduSendingError",error:a})},Right:a=>{this.machineActor.send({type:"ApduResponseReceived",apduResponse:a})}})}).catch(o=>{this.machineActor.send({type:"ApduSendingError",error:new A.UnknownDeviceExchangeError(o)})})}getDependencies(){return this.deviceAdpuSender.getDependencies()}setDependencies(n){this.deviceAdpuSender.setDependencies(n)}getDeviceId(){return this.deviceId}sendApdu(n,i,c){return new Promise(o=>{this.machineActor.send({type:"SendApduCalled",apdu:n,triggersDisconnection:!!i,abortTimeout:c,responseCallback:o})})}async setupConnection(){await this.deviceAdpuSender.setupConnection()}eventDeviceConnected(){this.machineActor.send({type:"DeviceConnected"})}eventDeviceDisconnected(){this.machineActor.send({type:"DeviceDisconnected"})}closeConnection(){this.machineActor.send({type:"CloseConnectionCalled"})}}function b({sendApduFn:s,startReconnectionTimeout:n,cancelReconnectionTimeout:i,tryToReconnect:c,onTerminated:o,closeConnection:a}){return(0,r.setup)({types:{},actions:{startTimer:()=>{n()},cancelTimer:()=>{i()},reconnectionTimeoutEvent:(0,r.emit)({type:"ReconnectionTimedOut"}),sendApdu:({context:e})=>{e.apduInProgress.map(({apdu:p,abortTimeout:u})=>{s(p,!1,u)})},sendApduResponse:({context:e},p)=>{e.apduInProgress.map(({responseCallback:u})=>u(p.response))},sendGetAppAndVersion:()=>{s(new g.GetAppAndVersionCommand().getApdu().getRawApdu(),!1)},tryToReconnect:()=>{c()},clearApduInProgress:(0,r.assign)({apduInProgress:t.Nothing}),clearApduResponse:(0,r.assign)({apduResponse:t.Nothing}),signalTermination:()=>{o()},closeConnection:()=>{a()}},guards:{isApduThatTriggersDisconnection:({context:e,event:p})=>p.type!=="ApduResponseReceived"?!1:e.apduInProgress.caseOf({Just:({triggersDisconnection:u,apdu:D})=>(u||m.CommandUtils.isApduThatTriggersDisconnection(D))&&m.CommandUtils.isSuccessResponse(p.apduResponse),Nothing:()=>!1}),isSendApduBusyError:({event:e})=>e.type!=="ApduResponseReceived"?!1:e.apduResponse.statusCode[0]===102&&e.apduResponse.statusCode[1]===1}}).createMachine({id:"deviceConnection",initial:"Connected",context:{apduInProgress:t.Nothing,apduResponse:t.Nothing},states:{Connected:{on:{DeviceDisconnected:{target:"WaitingForReconnection"},SendApduCalled:{target:"SendingApdu",actions:(0,r.assign)({apduInProgress:({event:e})=>t.Maybe.of({apdu:e.apdu,triggersDisconnection:e.triggersDisconnection,abortTimeout:e.abortTimeout,responseCallback:e.responseCallback})})},CloseConnectionCalled:{target:"Terminated"}}},SendingApdu:{entry:"sendApdu",on:{ApduResponseReceived:[{guard:"isApduThatTriggersDisconnection",target:"WaitingForDisconnection",actions:[(0,r.assign)({apduResponse:({event:e})=>t.Maybe.of(e.apduResponse)})]},{target:"Connected",actions:[{type:"sendApduResponse",params:({event:e})=>({response:(0,t.Right)(e.apduResponse)})},{type:"clearApduInProgress"}]}],ApduSendingError:{target:"Connected",actions:[{type:"sendApduResponse",params:({event:e})=>({response:(0,t.Left)(e.error)})},"clearApduInProgress"]},DeviceDisconnected:{target:"WaitingForReconnection",actions:[{type:"sendApduResponse",params:{response:(0,t.Left)(new d.DeviceDisconnectedWhileSendingError)}},"clearApduInProgress"]},CloseConnectionCalled:{target:"Terminated",actions:[{type:"sendApduResponse",params:{response:(0,t.Left)(new d.DeviceDisconnectedWhileSendingError)}},"clearApduInProgress"]},SendApduCalled:{actions:({event:e})=>{e.responseCallback((0,t.Left)(new d.AlreadySendingApduError))}}}},WaitingForDisconnection:{entry:["sendGetAppAndVersion"],exit:[{type:"sendApduResponse",params:({context:e})=>({response:e.apduResponse.caseOf({Just:p=>(0,t.Right)(p),Nothing:()=>(0,t.Left)(new A.UnknownDeviceExchangeError)})})},{type:"clearApduInProgress"},{type:"clearApduResponse"}],on:{ApduResponseReceived:[{guard:"isSendApduBusyError",actions:["sendGetAppAndVersion"],target:"WaitingForDisconnection"},{target:"Connected"}],ApduSendingError:[{target:"WaitingForReconnection"}],SendApduCalled:{actions:({event:e})=>{e.responseCallback((0,t.Left)(new d.AlreadySendingApduError))}},DeviceDisconnected:{target:"WaitingForReconnection"},CloseConnectionCalled:{target:"Terminated"}}},WaitingForReconnection:{entry:["startTimer","tryToReconnect"],on:{DeviceConnected:{target:"Connected",actions:"cancelTimer"},SendApduCalled:{target:"WaitingForReconnectionWithQueuedSendApdu",actions:(0,r.assign)({apduInProgress:({event:e})=>t.Maybe.of({apdu:e.apdu,triggersDisconnection:e.triggersDisconnection,abortTimeout:e.abortTimeout,responseCallback:e.responseCallback})})},ReconnectionTimedOut:{target:"Terminated"},CloseConnectionCalled:{target:"Terminated"}}},WaitingForReconnectionWithQueuedSendApdu:{on:{DeviceConnected:{target:"SendingApdu",actions:"cancelTimer"},ReconnectionTimedOut:{target:"Terminated",actions:[{type:"sendApduResponse",params:{response:(0,t.Left)(new d.DeviceDisconnectedBeforeSendingApdu)}},{type:"clearApduInProgress"}]},CloseConnectionCalled:{target:"Terminated",actions:[{type:"sendApduResponse",params:{response:(0,t.Left)(new d.DeviceDisconnectedWhileSendingError)}},"clearApduInProgress"]},SendApduCalled:{actions:({event:e})=>{e.responseCallback((0,t.Left)(new d.AlreadySendingApduError))}}}},Terminated:{entry:["signalTermination","closeConnection"],type:"final"}}})}0&&(module.exports={DeviceConnectionStateMachine});
|
2
2
|
//# sourceMappingURL=DeviceConnectionStateMachine.js.map
|
@@ -1,7 +1,7 @@
|
|
1
1
|
{
|
2
2
|
"version": 3,
|
3
3
|
"sources": ["../../../../../../src/api/transport/model/DeviceConnectionStateMachine.ts"],
|
4
|
-
"sourcesContent": ["// import { createBrowserInspector } from \"@statelyai/inspect\";\nimport { type Either, Left, Maybe, Nothing, Right } from \"purify-ts\";\nimport { type Actor, assign, createActor, emit, setup } from \"xstate\";\n\nimport { CommandUtils } from \"@api/command/utils/CommandUtils\";\nimport { type ApduResponse } from \"@api/device-session/ApduResponse\";\nimport { type DmkError, UnknownDeviceExchangeError } from \"@api/Error\";\nimport { type DeviceId } from \"@api/types\";\n\nimport { type DeviceApduSender } from \"./DeviceApduSender\";\nimport {\n AlreadySendingApduError,\n DeviceDisconnectedBeforeSendingApdu,\n DeviceDisconnectedWhileSendingError,\n} from \"./Errors\";\n\n// const { inspect } = createBrowserInspector();\n\ntype DeviceDetachedEvent = {\n type: \"DeviceDetached\";\n};\n\ntype DeviceAttachedEvent = {\n type: \"DeviceAttached\";\n};\n\ntype ApduResponseReceived = {\n type: \"ApduResponseReceived\";\n apduResponse: ApduResponse;\n};\n\ntype ApduSendingError = {\n type: \"ApduSendingError\";\n error: DmkError;\n};\n\ntype SendApduCalled = {\n type: \"SendApduCalled\";\n apdu: Uint8Array;\n triggersDisconnection: boolean;\n abortTimeout?: number;\n responseCallback: (response: Either<DmkError, ApduResponse>) => void;\n};\n\ntype ReconnectionTimedOut = {\n type: \"ReconnectionTimedOut\";\n};\n\ntype CloseConnectionCalled = {\n type: \"CloseConnectionCalled\";\n};\n\nexport type DeviceConnectionEvent =\n | DeviceDetachedEvent\n | DeviceAttachedEvent\n | ApduResponseReceived\n | ApduSendingError\n | SendApduCalled\n | CloseConnectionCalled\n | ReconnectionTimedOut;\n\nexport type DeviceConnectionStateMachineParams<Dependencies> = {\n deviceId: DeviceId;\n deviceApduSender: DeviceApduSender<Dependencies>;\n timeoutDuration: number;\n onTerminated: () => void;\n};\n\nexport class DeviceConnectionStateMachine<Dependencies> {\n private deviceId: DeviceId;\n private deviceAdpuSender: DeviceApduSender<Dependencies>;\n\n private machineActor: Actor<ReturnType<typeof makeStateMachine>>;\n\n private timeoutDuration: number;\n private timeout: ReturnType<typeof setTimeout> | null = null;\n\n startReconnectionTimeout() {\n this.timeout = setTimeout(() => {\n this.machineActor.send({ type: \"ReconnectionTimedOut\" });\n }, this.timeoutDuration);\n }\n\n constructor(params: DeviceConnectionStateMachineParams<Dependencies>) {\n this.deviceId = params.deviceId;\n this.deviceAdpuSender = params.deviceApduSender;\n this.timeoutDuration = params.timeoutDuration;\n this.machineActor = createActor(\n makeStateMachine({\n sendApduFn: (apdu, triggersDisconnection, abortTimeout) =>\n this.sendApduToDeviceConnection(\n apdu,\n triggersDisconnection,\n abortTimeout,\n ),\n startReconnectionTimeout: () => this.startReconnectionTimeout(),\n cancelReconnectionTimeout: () => {\n if (this.timeout) {\n clearTimeout(this.timeout);\n this.timeout = null;\n }\n },\n onTerminated: params.onTerminated,\n closeConnection: () => {\n this.deviceAdpuSender.closeConnection();\n },\n }),\n // {\n // // inspect,\n // },\n );\n this.machineActor.start();\n }\n\n private sendApduToDeviceConnection(\n apdu: Uint8Array,\n triggersDisconnection?: boolean,\n abortTimeout?: number,\n ) {\n this.deviceAdpuSender\n .sendApdu(apdu, triggersDisconnection, abortTimeout)\n .then((response) => {\n response.caseOf({\n Left: (error) => {\n this.machineActor.send({ type: \"ApduSendingError\", error });\n },\n Right: (apduResponse) => {\n this.machineActor.send({\n type: \"ApduResponseReceived\",\n apduResponse,\n });\n },\n });\n })\n .catch((error) => {\n this.machineActor.send({\n type: \"ApduSendingError\",\n error: new UnknownDeviceExchangeError(error),\n });\n });\n }\n\n /**\n * Called by the transport\n */\n\n public getDependencies(): Dependencies {\n return this.deviceAdpuSender.getDependencies();\n }\n\n public setDependencies(dependencies: Dependencies) {\n this.deviceAdpuSender.setDependencies(dependencies);\n }\n\n public getDeviceId() {\n return this.deviceId;\n }\n\n public sendApdu(\n apdu: Uint8Array,\n triggersDisconnection?: boolean,\n abortTimeout?: number,\n ): Promise<Either<DmkError, ApduResponse>> {\n return new Promise((responseCallback) => {\n this.machineActor.send({\n type: \"SendApduCalled\",\n apdu,\n triggersDisconnection: !!triggersDisconnection,\n abortTimeout,\n responseCallback,\n });\n });\n }\n\n public async setupConnection() {\n await this.deviceAdpuSender.setupConnection();\n }\n\n // State Machine Events\n\n public eventDeviceAttached() {\n this.machineActor.send({ type: \"DeviceAttached\" });\n }\n\n public eventDeviceDetached() {\n this.machineActor.send({ type: \"DeviceDetached\" });\n }\n\n public closeConnection() {\n this.machineActor.send({ type: \"CloseConnectionCalled\" });\n }\n}\n\nfunction makeStateMachine({\n sendApduFn,\n startReconnectionTimeout,\n cancelReconnectionTimeout,\n onTerminated,\n closeConnection,\n}: {\n sendApduFn: (\n apdu: Uint8Array,\n triggersDisconnection: boolean,\n abortTimeout?: number,\n ) => void;\n startReconnectionTimeout: () => void;\n cancelReconnectionTimeout: () => void;\n onTerminated: () => void;\n closeConnection: () => void;\n}) {\n return setup({\n types: {} as {\n context: {\n apduInProgress: Maybe<{\n apdu: Uint8Array;\n triggersDisconnection: boolean;\n abortTimeout?: number;\n responseCallback: (response: Either<DmkError, ApduResponse>) => void;\n }>;\n };\n events: DeviceConnectionEvent;\n },\n actions: {\n // event transitions\n startTimer: () => {\n startReconnectionTimeout();\n },\n cancelTimer: () => {\n cancelReconnectionTimeout();\n },\n reconnectionTimeoutEvent: emit({ type: \"ReconnectionTimedOut\" }),\n sendApdu: ({ context }) => {\n context.apduInProgress.map(({ apdu, abortTimeout }) => {\n sendApduFn(apdu, false, abortTimeout);\n });\n },\n sendApduResponse: (\n { context },\n params: { response: Either<DmkError, ApduResponse> },\n ) => {\n context.apduInProgress.map(({ responseCallback }) =>\n responseCallback(params.response),\n );\n },\n cleanupContext: assign({ apduInProgress: Nothing }),\n signalTermination: () => {\n onTerminated();\n },\n closeConnection: () => {\n closeConnection(); // ASK: how do we handle errors ?\n },\n },\n guards: {\n isApduThatTriggersDisconnection: (\n { context },\n params: { apduResponse: ApduResponse },\n ) => {\n return context.apduInProgress.caseOf({\n Just: ({ triggersDisconnection, apdu }) => {\n const res =\n (triggersDisconnection ||\n CommandUtils.isApduThatTriggersDisconnection(apdu)) &&\n CommandUtils.isSuccessResponse(params.apduResponse);\n return res;\n },\n Nothing: () => false,\n });\n },\n },\n }).createMachine({\n /** @xstate-layout N4IgpgJg5mDOIC5QTAN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bOsFLGWzUyzE5bssx8ObAsoSqlpq8r1tILadr2g6ERWksQvCiAopi5i4qbRKjH7Bo4N1dsvFjOxEIeIwUPQ9o9AGSYvG+1bfsW7yVN8+agZB3bIHByUGtk1aWti874s1FGJOHYy6gTLo3lMVN7wPBNVAtbRRg0IEC35NmS0pxTltpwL6e2xn9s0w7mY5hGuaRzrAWZIYBJpc0pd1E18tNMZLOMAwnOCAsCDwFB4CORWms3bnm1AozWSgrHYMsYyEL6FGKXcDleMMO5rXJ5XZ0gP3jZqB4evaLwXEeqwnJNKYDypWlzHePwcIVotyuFT83QldOOpqWNU30A8rEmrMjPcAJk6FP7qch432rY3dxnN1onlaZ9idy5NILuCxl+UEwrH7wiqeqmnarpjatbB3Xcibser3eckfmd3xOkrnpce0DMjHMeoAgLjeqCCsBfVCmFOESE+EqdSfnmNwLJjBPBSs0QwuV3CQWPN3AwT4LTtldoEIAA */\n id: \"deviceConnection\",\n initial: \"Connected\",\n context: {\n apduInProgress: Nothing,\n },\n states: {\n Connected: {\n on: {\n DeviceDetached: {\n target: \"WaitingForReconnection\",\n },\n SendApduCalled: {\n target: \"SendingApdu\",\n actions: assign({\n apduInProgress: ({ event }) => {\n return Maybe.of({\n apdu: event.apdu,\n triggersDisconnection: event.triggersDisconnection,\n abortTimeout: event.abortTimeout,\n responseCallback: event.responseCallback,\n });\n },\n }),\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n },\n },\n },\n SendingApdu: {\n entry: \"sendApdu\",\n on: {\n ApduResponseReceived: [\n {\n guard: {\n type: \"isApduThatTriggersDisconnection\",\n params: ({ event }) => ({ apduResponse: event.apduResponse }),\n },\n target: \"WaitingForReconnection\",\n actions: [\n {\n type: \"sendApduResponse\",\n // https://stately.ai/docs/actions#dynamic-action-parameters\n params: ({ event }) => {\n return {\n response: Right(event.apduResponse),\n };\n },\n },\n { type: \"cleanupContext\" },\n ],\n },\n {\n target: \"Connected\",\n actions: [\n {\n type: \"sendApduResponse\",\n // https://stately.ai/docs/actions#dynamic-action-parameters\n params: ({ event }) => {\n return {\n response: Right(event.apduResponse),\n };\n },\n },\n { type: \"cleanupContext\" },\n ],\n },\n ],\n ApduSendingError: {\n target: \"Connected\",\n actions: [\n {\n type: \"sendApduResponse\",\n // https://stately.ai/docs/actions#dynamic-action-parameters\n params: ({ event }) => {\n return {\n response: Left(event.error),\n };\n },\n },\n \"cleanupContext\",\n ],\n },\n DeviceDetached: {\n target: \"WaitingForReconnection\",\n actions: [\n {\n type: \"sendApduResponse\",\n params: {\n response: Left(new DeviceDisconnectedWhileSendingError()),\n },\n },\n \"cleanupContext\",\n ],\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n actions: [\n {\n type: \"sendApduResponse\",\n params: {\n response: Left(new DeviceDisconnectedWhileSendingError()),\n },\n },\n \"cleanupContext\",\n ],\n },\n SendApduCalled: {\n actions: ({ event }) => {\n event.responseCallback(Left(new AlreadySendingApduError()));\n },\n },\n },\n },\n WaitingForReconnection: {\n entry: \"startTimer\",\n on: {\n DeviceAttached: {\n target: \"Connected\",\n actions: \"cancelTimer\",\n },\n SendApduCalled: {\n target: \"WaitingForReconnectionWithQueuedSendApdu\",\n actions: assign({\n apduInProgress: ({ event }) => {\n return Maybe.of({\n apdu: event.apdu,\n triggersDisconnection: event.triggersDisconnection,\n abortTimeout: event.abortTimeout,\n responseCallback: event.responseCallback,\n });\n },\n }),\n },\n ReconnectionTimedOut: {\n target: \"Terminated\",\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n },\n },\n },\n WaitingForReconnectionWithQueuedSendApdu: {\n on: {\n DeviceAttached: {\n target: \"SendingApdu\",\n actions: \"cancelTimer\",\n },\n ReconnectionTimedOut: {\n target: \"Terminated\",\n actions: [\n {\n type: \"sendApduResponse\",\n params: {\n response: Left(new DeviceDisconnectedBeforeSendingApdu()),\n },\n },\n {\n type: \"cleanupContext\",\n },\n ],\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n actions: [\n {\n type: \"sendApduResponse\",\n params: {\n response: Left(new DeviceDisconnectedWhileSendingError()),\n },\n },\n \"cleanupContext\",\n ],\n },\n SendApduCalled: {\n actions: ({ event }) => {\n event.responseCallback(Left(new AlreadySendingApduError()));\n },\n },\n },\n },\n // TODO: ADD INACTIVE STATE\n Terminated: {\n entry: [\"signalTermination\", \"closeConnection\"],\n type: \"final\",\n },\n },\n });\n}\n"],
|
5
|
-
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kCAAAE,IAAA,eAAAC,EAAAH,GACA,IAAAI,EAAyD,qBACzDC,EAA6D,kBAE7DC,EAA6B,2CAE7BC,EAA0D,sBAI1DC,EAIO,
|
6
|
-
"names": ["DeviceConnectionStateMachine_exports", "__export", "DeviceConnectionStateMachine", "__toCommonJS", "import_purify_ts", "import_xstate", "import_CommandUtils", "import_Error", "import_Errors", "params", "makeStateMachine", "apdu", "triggersDisconnection", "abortTimeout", "response", "error", "apduResponse", "dependencies", "responseCallback", "sendApduFn", "startReconnectionTimeout", "cancelReconnectionTimeout", "onTerminated", "closeConnection", "context", "event"]
|
4
|
+
"sourcesContent": ["// import { createBrowserInspector } from \"@statelyai/inspect\";\nimport { type Either, Left, Maybe, Nothing, Right } from \"purify-ts\";\nimport { type Actor, assign, createActor, emit, setup } from \"xstate\";\n\nimport { GetAppAndVersionCommand } from \"@api/command/os/GetAppAndVersionCommand\";\nimport { CommandUtils } from \"@api/command/utils/CommandUtils\";\nimport { type ApduResponse } from \"@api/device-session/ApduResponse\";\nimport { type DmkError, UnknownDeviceExchangeError } from \"@api/Error\";\nimport { type DeviceId } from \"@api/types\";\n\nimport { type DeviceApduSender } from \"./DeviceApduSender\";\nimport {\n AlreadySendingApduError,\n DeviceDisconnectedBeforeSendingApdu,\n DeviceDisconnectedWhileSendingError,\n} from \"./Errors\";\n\n// const { inspect } = createBrowserInspector();\n\ntype DeviceDisconnectedEvent = {\n type: \"DeviceDisconnected\";\n};\n\ntype DeviceConnectedEvent = {\n type: \"DeviceConnected\";\n};\n\ntype ApduResponseReceived = {\n type: \"ApduResponseReceived\";\n apduResponse: ApduResponse;\n};\n\ntype ApduSendingError = {\n type: \"ApduSendingError\";\n error: DmkError;\n};\n\ntype SendApduCalled = {\n type: \"SendApduCalled\";\n apdu: Uint8Array;\n triggersDisconnection: boolean;\n abortTimeout?: number;\n responseCallback: (response: Either<DmkError, ApduResponse>) => void;\n};\n\ntype ReconnectionTimedOut = {\n type: \"ReconnectionTimedOut\";\n};\n\ntype CloseConnectionCalled = {\n type: \"CloseConnectionCalled\";\n};\n\nexport type Events =\n | DeviceDisconnectedEvent\n | DeviceConnectedEvent\n | ApduResponseReceived\n | ApduSendingError\n | SendApduCalled\n | CloseConnectionCalled\n | ReconnectionTimedOut;\n\nexport type DeviceConnectionStateMachineParams<Dependencies> = {\n deviceId: DeviceId;\n deviceApduSender: DeviceApduSender<Dependencies>;\n timeoutDuration: number;\n tryToReconnect: (timeoutDuration: number) => void;\n onTerminated: () => void;\n};\n\nexport class DeviceConnectionStateMachine<Dependencies> {\n private deviceId: DeviceId;\n private deviceAdpuSender: DeviceApduSender<Dependencies>;\n\n private machineActor: Actor<ReturnType<typeof makeStateMachine>>;\n\n private timeoutDuration: number;\n private timeout: ReturnType<typeof setTimeout> | null = null;\n\n startReconnectionTimeout() {\n this.timeout = setTimeout(() => {\n this.machineActor.send({ type: \"ReconnectionTimedOut\" });\n }, this.timeoutDuration);\n }\n\n constructor(params: DeviceConnectionStateMachineParams<Dependencies>) {\n this.deviceId = params.deviceId;\n this.deviceAdpuSender = params.deviceApduSender;\n this.timeoutDuration = params.timeoutDuration;\n this.machineActor = createActor(\n makeStateMachine({\n sendApduFn: (apdu, triggersDisconnection, abortTimeout) =>\n this.sendApduToDeviceConnection(\n apdu,\n triggersDisconnection,\n abortTimeout,\n ),\n startReconnectionTimeout: () => this.startReconnectionTimeout(),\n cancelReconnectionTimeout: () => {\n if (this.timeout) {\n clearTimeout(this.timeout);\n this.timeout = null;\n }\n },\n tryToReconnect: () => {\n params.tryToReconnect(this.timeoutDuration);\n },\n onTerminated: params.onTerminated,\n closeConnection: () => {\n this.deviceAdpuSender.closeConnection();\n },\n }),\n // {\n // // inspect,\n // },\n );\n this.machineActor.start();\n }\n\n private sendApduToDeviceConnection(\n apdu: Uint8Array,\n triggersDisconnection?: boolean,\n abortTimeout?: number,\n ) {\n this.deviceAdpuSender\n .sendApdu(apdu, triggersDisconnection, abortTimeout)\n .then((response) => {\n response.caseOf({\n Left: (error) => {\n this.machineActor.send({ type: \"ApduSendingError\", error });\n },\n Right: (apduResponse) => {\n this.machineActor.send({\n type: \"ApduResponseReceived\",\n apduResponse,\n });\n },\n });\n })\n .catch((error) => {\n this.machineActor.send({\n type: \"ApduSendingError\",\n error: new UnknownDeviceExchangeError(error),\n });\n });\n }\n\n /**\n * Called by the transport\n */\n\n public getDependencies(): Dependencies {\n return this.deviceAdpuSender.getDependencies();\n }\n\n public setDependencies(dependencies: Dependencies) {\n this.deviceAdpuSender.setDependencies(dependencies);\n }\n\n public getDeviceId() {\n return this.deviceId;\n }\n\n public sendApdu(\n apdu: Uint8Array,\n triggersDisconnection?: boolean,\n abortTimeout?: number,\n ): Promise<Either<DmkError, ApduResponse>> {\n return new Promise((responseCallback) => {\n this.machineActor.send({\n type: \"SendApduCalled\",\n apdu,\n triggersDisconnection: !!triggersDisconnection,\n abortTimeout,\n responseCallback,\n });\n });\n }\n\n public async setupConnection() {\n await this.deviceAdpuSender.setupConnection();\n }\n\n // State Machine Events\n\n public eventDeviceConnected() {\n this.machineActor.send({ type: \"DeviceConnected\" });\n }\n\n public eventDeviceDisconnected() {\n this.machineActor.send({ type: \"DeviceDisconnected\" });\n }\n\n public closeConnection() {\n this.machineActor.send({ type: \"CloseConnectionCalled\" });\n }\n}\n\nfunction makeStateMachine({\n sendApduFn,\n startReconnectionTimeout,\n cancelReconnectionTimeout,\n tryToReconnect,\n onTerminated,\n closeConnection,\n}: {\n sendApduFn: (\n apdu: Uint8Array,\n triggersDisconnection: boolean,\n abortTimeout?: number,\n ) => void;\n startReconnectionTimeout: () => void;\n cancelReconnectionTimeout: () => void;\n tryToReconnect: () => void;\n onTerminated: () => void;\n closeConnection: () => void;\n}) {\n return setup({\n types: {} as {\n context: {\n apduInProgress: Maybe<{\n apdu: Uint8Array;\n triggersDisconnection: boolean;\n abortTimeout?: number;\n responseCallback: (response: Either<DmkError, ApduResponse>) => void;\n }>;\n apduResponse: Maybe<ApduResponse>;\n };\n events: Events;\n },\n actions: {\n // event transitions\n startTimer: () => {\n startReconnectionTimeout();\n },\n cancelTimer: () => {\n cancelReconnectionTimeout();\n },\n reconnectionTimeoutEvent: emit({ type: \"ReconnectionTimedOut\" }),\n sendApdu: ({ context }) => {\n context.apduInProgress.map(({ apdu, abortTimeout }) => {\n sendApduFn(apdu, false, abortTimeout);\n });\n },\n sendApduResponse: (\n { context },\n params: { response: Either<DmkError, ApduResponse> },\n ) => {\n context.apduInProgress.map(({ responseCallback }) =>\n responseCallback(params.response),\n );\n },\n sendGetAppAndVersion: () => {\n sendApduFn(new GetAppAndVersionCommand().getApdu().getRawApdu(), false);\n },\n tryToReconnect: () => {\n tryToReconnect();\n },\n clearApduInProgress: assign({\n apduInProgress: Nothing,\n }),\n clearApduResponse: assign({\n apduResponse: Nothing,\n }),\n signalTermination: () => {\n onTerminated();\n },\n closeConnection: () => {\n closeConnection(); // ASK: how do we handle errors ?\n },\n },\n guards: {\n isApduThatTriggersDisconnection: ({ context, event }) => {\n if (event.type !== \"ApduResponseReceived\") {\n return false;\n }\n return context.apduInProgress.caseOf({\n /**\n * If the apdu is known as one that triggers a disconnection,\n * and if it's a success response,\n * then will trigger a disconnection (on Ledger OS prior to the IO revamp).\n */\n Just: ({ triggersDisconnection, apdu }) =>\n (triggersDisconnection ||\n CommandUtils.isApduThatTriggersDisconnection(apdu)) &&\n CommandUtils.isSuccessResponse(event.apduResponse),\n Nothing: () => false,\n });\n },\n isSendApduBusyError: ({ event }) => {\n if (event.type !== \"ApduResponseReceived\") {\n return false;\n }\n return (\n event.apduResponse.statusCode[0] === 0x66 &&\n event.apduResponse.statusCode[1] === 0x01\n );\n },\n },\n }).createMachine({\n /** @xstate-layout N4IgpgJg5mDOIC5QTANwJYGMwGED2AdgWJgC7qEB0+RJpkAxACJpZgukCGmAFpANoAGALqJQABzyx05QmJAAPRAA4A7AGZKywQEYAnAFYATMoAsBg6fUA2ADQgAnolUnKBjUdXXVpnUb0aAL6B9igY2DTEZBQE1IRR9BAMAMpgBBAAguIQAK44nAA2BQIi8pLSsgTySgjW6oKU6uo61kbWyh06Vsr2TgjqAZR6HUaWXcrqBmrBoawR8XQxcbRkjDgFUrgL0YT5RSWiSCDlMjHVKnrWjaO6ev6qlnp6vYim1qaN9YLqGuPKOjpVDMQGE2JFFlRUul0AQoFlcgx4TkAEpwSQEWBgVHYdCoA5lKSnORHGpNVSUPwGXQDQSmNTDF4IZTWPRDJotUw+HwAnTA0HzFaVShQiAwuHZHKIiWo2DozHYsC4gQ6Q4SQmVc79TxDIzqG6eJq+VSM94NPQ6CYuUzmQGCax8uZbQVLEVipFS3Ku2EAUQATr68L6hKrjuqziTEJNNHrTG1dIIDE8jLTGVTlJQboI2i56QZeSEQY7wTtYl7xQiWOF2GAuLx8UcThqIwh-OmdBZPF0qQCBoydIJlAZKK0jP4bHntBaHVXi0Ky+71ptZzE9sUIMGCRVw6Aau2dJQ6WZlMM-D9+89HIh++mbndVHpdNYLAnp2DtnO0qLYe6RUjV-W1S3Ykd0QABac1KFpbx3kHCxumNS9ak5SDTHNax0NUDRfFMV8BQSJYAHVOFOWEADFA2xd8YmYR0MlIWs+HXUoGzDYDFEQQx90mVozABJ9BAvPo6iuFpRgtQRdDUWNcKdfCqCIkioHI31KOdQgUk-P9CjXDcWKAqpmx0dR-gpCTaXNUxvh7RkvCHWlaWM9RfC6dCZOXeTiPIMiKJIKj1NUuSCAAFXQABbSAAHkclIXTAKJAyQIQLpBHJAEXB8AS1HvdRGT0a0D2ZZpBxjSc3L82IFK8pSfMwcqGEXTF3IIf8mJDRtt3YpLLPJZMWkmTtzJyxD+1UBofifVQOm8YyWjKtSKs8sVlICiECAImQeAARRyMAdogX8JRoqs6IYgDQ30zUjJ8CkWQmYZbOsFLGWzUyzE5bssx8ObAsoSqlpq8r1tILadr2g6ERWksQvCiAopi5i4qbRKjH7Bo4N1dsvFjOxEIeIwUPQ9o9AGSYvG+1bfsW7yVN8+agZB3bIHByUGtk1aWti874s1FGJOHYy6gTLo3lMVN7wPBNVAtbRRg0IEC35NmS0pxTltpwL6e2xn9s0w7mY5hGuaRzrAWZIYBJpc0pd1E18tNMZLOMAwnOCAsCDwFB4CORWms3bnm1AozWSgrHYMsYyEL6FGKXcDleMMO5rXJ5XZ0gP3jZqB4evaLwXEeqwnJNKYDypWlzHePwcIVotyuFT83QldOOpqWNU30A8rEmrMjPcAJk6FP7qch432rY3dxnN1onlaZ9idy5NILuCxl+UEwrH7wiqeqmnarpjatbB3Xcibser3eckfmd3xOkrnpce0DMjHMeoAgLjeqCCsBfVCmFOESE+EqdSfnmNwLJjBPBSs0QwuV3CQWPN3AwT4LTtldoEIAA */\n id: \"deviceConnection\",\n initial: \"Connected\",\n context: {\n apduInProgress: Nothing,\n apduResponse: Nothing,\n },\n states: {\n Connected: {\n on: {\n DeviceDisconnected: {\n target: \"WaitingForReconnection\",\n },\n SendApduCalled: {\n target: \"SendingApdu\",\n actions: assign({\n apduInProgress: ({ event }) => {\n return Maybe.of({\n apdu: event.apdu,\n triggersDisconnection: event.triggersDisconnection,\n abortTimeout: event.abortTimeout,\n responseCallback: event.responseCallback,\n });\n },\n }),\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n },\n },\n },\n SendingApdu: {\n entry: \"sendApdu\",\n on: {\n ApduResponseReceived: [\n {\n guard: \"isApduThatTriggersDisconnection\",\n target: \"WaitingForDisconnection\",\n actions: [\n assign({\n apduResponse: ({ event }) => Maybe.of(event.apduResponse),\n }),\n ],\n },\n {\n target: \"Connected\",\n actions: [\n {\n type: \"sendApduResponse\",\n // https://stately.ai/docs/actions#dynamic-action-parameters\n params: ({ event }) => {\n return {\n response: Right(event.apduResponse),\n };\n },\n },\n { type: \"clearApduInProgress\" },\n ],\n },\n ],\n ApduSendingError: {\n target: \"Connected\",\n actions: [\n {\n type: \"sendApduResponse\",\n // https://stately.ai/docs/actions#dynamic-action-parameters\n params: ({ event }) => {\n return {\n response: Left(event.error),\n };\n },\n },\n \"clearApduInProgress\",\n ],\n },\n DeviceDisconnected: {\n target: \"WaitingForReconnection\",\n actions: [\n {\n type: \"sendApduResponse\",\n params: {\n response: Left(new DeviceDisconnectedWhileSendingError()),\n },\n },\n \"clearApduInProgress\",\n ],\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n actions: [\n {\n type: \"sendApduResponse\",\n params: {\n response: Left(new DeviceDisconnectedWhileSendingError()),\n },\n },\n \"clearApduInProgress\",\n ],\n },\n SendApduCalled: {\n actions: ({ event }) => {\n event.responseCallback(Left(new AlreadySendingApduError()));\n },\n },\n },\n },\n WaitingForDisconnection: {\n entry: [\"sendGetAppAndVersion\"],\n exit: [\n {\n type: \"sendApduResponse\",\n params: ({ context }) => {\n return {\n response: context.apduResponse.caseOf({\n Just: (apduResponse) => Right(apduResponse),\n Nothing: () => Left(new UnknownDeviceExchangeError()),\n }),\n };\n },\n },\n { type: \"clearApduInProgress\" },\n { type: \"clearApduResponse\" },\n ],\n on: {\n ApduResponseReceived: [\n {\n guard: \"isSendApduBusyError\",\n actions: [\"sendGetAppAndVersion\"],\n target: \"WaitingForDisconnection\",\n },\n {\n target: \"Connected\",\n },\n ],\n ApduSendingError: [\n {\n target: \"WaitingForReconnection\",\n },\n ],\n SendApduCalled: {\n actions: ({ event }) => {\n event.responseCallback(Left(new AlreadySendingApduError()));\n },\n },\n DeviceDisconnected: {\n target: \"WaitingForReconnection\",\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n },\n },\n },\n WaitingForReconnection: {\n entry: [\"startTimer\", \"tryToReconnect\"],\n on: {\n DeviceConnected: {\n target: \"Connected\",\n actions: \"cancelTimer\",\n },\n SendApduCalled: {\n target: \"WaitingForReconnectionWithQueuedSendApdu\",\n actions: assign({\n apduInProgress: ({ event }) => {\n return Maybe.of({\n apdu: event.apdu,\n triggersDisconnection: event.triggersDisconnection,\n abortTimeout: event.abortTimeout,\n responseCallback: event.responseCallback,\n });\n },\n }),\n },\n ReconnectionTimedOut: {\n target: \"Terminated\",\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n },\n },\n },\n WaitingForReconnectionWithQueuedSendApdu: {\n on: {\n DeviceConnected: {\n target: \"SendingApdu\",\n actions: \"cancelTimer\",\n },\n ReconnectionTimedOut: {\n target: \"Terminated\",\n actions: [\n {\n type: \"sendApduResponse\",\n params: {\n response: Left(new DeviceDisconnectedBeforeSendingApdu()),\n },\n },\n {\n type: \"clearApduInProgress\",\n },\n ],\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n actions: [\n {\n type: \"sendApduResponse\",\n params: {\n response: Left(new DeviceDisconnectedWhileSendingError()),\n },\n },\n \"clearApduInProgress\",\n ],\n },\n SendApduCalled: {\n actions: ({ event }) => {\n event.responseCallback(Left(new AlreadySendingApduError()));\n },\n },\n },\n },\n // TODO: ADD INACTIVE STATE\n Terminated: {\n entry: [\"signalTermination\", \"closeConnection\"],\n type: \"final\",\n },\n },\n });\n}\n"],
|
5
|
+
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kCAAAE,IAAA,eAAAC,EAAAH,GACA,IAAAI,EAAyD,qBACzDC,EAA6D,kBAE7DC,EAAwC,mDACxCC,EAA6B,2CAE7BC,EAA0D,sBAI1DC,EAIO,oBAuDA,MAAMP,CAA2C,CAC9C,SACA,iBAEA,aAEA,gBACA,QAAgD,KAExD,0BAA2B,CACzB,KAAK,QAAU,WAAW,IAAM,CAC9B,KAAK,aAAa,KAAK,CAAE,KAAM,sBAAuB,CAAC,CACzD,EAAG,KAAK,eAAe,CACzB,CAEA,Y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2CACR,WAAS,UAAO,CACd,eAAgB,CAAC,CAAE,MAAAA,CAAM,IAChB,QAAM,GAAG,CACd,KAAMA,EAAM,KACZ,sBAAuBA,EAAM,sBAC7B,aAAcA,EAAM,aACpB,iBAAkBA,EAAM,gBAC1B,CAAC,CAEL,CAAC,CACH,EACA,qBAAsB,CACpB,OAAQ,YACV,EACA,sBAAuB,CACrB,OAAQ,YACV,CACF,CACF,EACA,yCAA0C,CACxC,GAAI,CACF,gBAAiB,CACf,OAAQ,cACR,QAAS,aACX,EACA,qBAAsB,CACpB,OAAQ,aACR,QAAS,CACP,CACE,KAAM,mBACN,OAAQ,CACN,YAAU,QAAK,IAAI,qCAAqC,CAC1D,CACF,EACA,CACE,KAAM,qBACR,CACF,CACF,EACA,sBAAuB,CACrB,OAAQ,aACR,QAAS,CACP,CACE,KAAM,mBACN,OAAQ,CACN,YAAU,QAAK,IAAI,qCAAqC,CAC1D,CACF,EACA,qBACF,CACF,EACA,eAAgB,CACd,QAAS,CAAC,CAAE,MAAAA,CAAM,IAAM,CACtBA,EAAM,oBAAiB,QAAK,IAAI,yBAAyB,CAAC,CAC5D,CACF,CACF,CACF,EAEA,WAAY,CACV,MAAO,CAAC,oBAAqB,iBAAiB,EAC9C,KAAM,OACR,CACF,CACF,CAAC,CACH",
|
6
|
+
"names": ["DeviceConnectionStateMachine_exports", "__export", "DeviceConnectionStateMachine", "__toCommonJS", "import_purify_ts", "import_xstate", "import_GetAppAndVersionCommand", "import_CommandUtils", "import_Error", "import_Errors", "params", "makeStateMachine", "apdu", "triggersDisconnection", "abortTimeout", "response", "error", "apduResponse", "dependencies", "responseCallback", "sendApduFn", "startReconnectionTimeout", "cancelReconnectionTimeout", "tryToReconnect", "onTerminated", "closeConnection", "context", "event"]
|
7
7
|
}
|
@@ -0,0 +1,2 @@
|
|
1
|
+
"use strict";var n=require("purify-ts/Either"),e=require("vitest"),A=require("../../device-session/ApduResponse"),m=require("./DeviceConnectionStateMachine"),i=require("./Errors");(0,e.describe)("DeviceConnectionStateMachine",()=>{let d;const s={sendApdu:e.vi.fn(),getDependencies:e.vi.fn(),setDependencies:e.vi.fn(),closeConnection:e.vi.fn(),setupConnection:e.vi.fn()},t=new A.ApduResponse({statusCode:Uint8Array.from([144,0]),data:new Uint8Array}),p=new A.ApduResponse({statusCode:Uint8Array.from([102,1]),data:new Uint8Array});(0,e.beforeEach)(()=>{e.vi.useFakeTimers(),d=new m.DeviceConnectionStateMachine({deviceId:"deviceId",deviceApduSender:s,timeoutDuration:1e3,tryToReconnect:e.vi.fn(),onTerminated:e.vi.fn()})}),(0,e.afterEach)(()=>{e.vi.useRealTimers(),e.vi.restoreAllMocks()}),(0,e.describe)("Send APDUs",()=>{(0,e.it)("should send APDU successfully",async()=>{const o=Uint8Array.from([1,2,3,4]);s.sendApdu.mockResolvedValue((0,n.Right)(t));const a=await d.sendApdu(o);(0,e.expect)(s.sendApdu).toHaveBeenCalledTimes(1),(0,e.expect)(a).toStrictEqual((0,n.Right)(t))}),(0,e.it)("should send several APDUs successfully",async()=>{const o=Uint8Array.from([1,2,3,4]),a=Uint8Array.from([9,2,3,4]);s.sendApdu.mockResolvedValue((0,n.Right)(t));const r=await d.sendApdu(o),u=await d.sendApdu(a);(0,e.expect)(s.sendApdu).toHaveBeenCalledTimes(2),(0,e.expect)(r).toStrictEqual((0,n.Right)(t)),(0,e.expect)(u).toStrictEqual((0,n.Right)(t))}),(0,e.it)("should not send several APDUs in parallel",async()=>{const o=Uint8Array.from([1,2,3,4]),a=Uint8Array.from([9,2,3,4]);s.sendApdu.mockResolvedValue((0,n.Right)(t));const r=d.sendApdu(o),u=await d.sendApdu(a),c=await r;(0,e.expect)(s.sendApdu).toHaveBeenCalledTimes(1),(0,e.expect)(c).toStrictEqual((0,n.Right)(t)),(0,e.expect)(u).toStrictEqual((0,n.Left)(new i.AlreadySendingApduError))}),(0,e.it)("Disconnected while sending APDU",async()=>{const o=Uint8Array.from([1,2,3,4]);s.sendApdu.mockResolvedValue((0,n.Right)(t));const a=d.sendApdu(o);d.eventDeviceDisconnected();const r=await a;(0,e.expect)(s.sendApdu).toHaveBeenCalledTimes(1),(0,e.expect)(r).toStrictEqual((0,n.Left)(new i.DeviceDisconnectedWhileSendingError))}),(0,e.it)("Request disconnection while sending APDU",async()=>{const o=Uint8Array.from([1,2,3,4]);s.sendApdu.mockResolvedValue((0,n.Right)(t));const a=d.sendApdu(o);d.closeConnection();const r=await a;(0,e.expect)(s.sendApdu).toHaveBeenCalledTimes(1),(0,e.expect)(r).toStrictEqual((0,n.Left)(new i.DeviceDisconnectedWhileSendingError))})}),(0,e.describe)("Send APDUs triggering disconnection",()=>{(0,e.it)("should send one APDU successfully",async()=>{const o=Uint8Array.from([1,2,3,4]);s.sendApdu.mockResolvedValue((0,n.Right)(t));const a=await d.sendApdu(o,!0);(0,e.expect)(s.sendApdu).toHaveBeenCalledTimes(2),(0,e.expect)(s.sendApdu.mock.calls).toEqual([[o,!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0]]),(0,e.expect)(a).toStrictEqual((0,n.Right)(t))}),(0,e.it)("should send several APDUs successfully",async()=>{const o=Uint8Array.from([1,2,3,4]),a=Uint8Array.from([9,2,3,4]);s.sendApdu.mockResolvedValueOnce((0,n.Right)(t)).mockRejectedValueOnce(new Error("Transport error")).mockResolvedValueOnce((0,n.Right)(t));const r=d.sendApdu(o,!0);await Promise.resolve(),d.eventDeviceDisconnected(),d.eventDeviceConnected();const u=d.sendApdu(a),c=await r,l=await u;(0,e.expect)(s.sendApdu).toHaveBeenCalledTimes(3),(0,e.expect)(s.sendApdu.mock.calls).toEqual([[o,!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0],[a,!1,void 0]]),(0,e.expect)(c).toStrictEqual((0,n.Right)(t)),(0,e.expect)(l).toStrictEqual((0,n.Right)(t))}),(0,e.it)("should send a second APDU after reconnection",async()=>{const o=Uint8Array.from([1,2,3,4]),a=Uint8Array.from([9,2,3,4]);s.sendApdu.mockResolvedValueOnce((0,n.Right)(t)).mockRejectedValueOnce(new Error("Transport error")).mockResolvedValueOnce((0,n.Right)(t));const r=await d.sendApdu(o,!0);d.eventDeviceDisconnected(),d.eventDeviceConnected();const u=await d.sendApdu(a);(0,e.expect)(s.sendApdu).toHaveBeenCalledTimes(3),(0,e.expect)(s.sendApdu.mock.calls).toEqual([[o,!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0],[a,!1,void 0]]),(0,e.expect)(r).toStrictEqual((0,n.Right)(t)),(0,e.expect)(u).toStrictEqual((0,n.Right)(t))}),(0,e.it)("should send a second APDU without reconnection, after GetAppAndVersion response",async()=>{const o=Uint8Array.from([1,2,3,4]),a=Uint8Array.from([9,2,3,4]);s.sendApdu.mockResolvedValueOnce((0,n.Right)(t)).mockResolvedValueOnce((0,n.Right)(t)).mockResolvedValueOnce((0,n.Right)(t));const r=await d.sendApdu(o,!0),u=await d.sendApdu(a);(0,e.expect)(s.sendApdu).toHaveBeenCalledTimes(3),(0,e.expect)(s.sendApdu.mock.calls).toEqual([[o,!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0],[a,!1,void 0]]),(0,e.expect)(r).toStrictEqual((0,n.Right)(t)),(0,e.expect)(u).toStrictEqual((0,n.Right)(t))}),(0,e.it)("should send a second APDU without reconnection, after GetAppAndVersion retries",async()=>{const o=Uint8Array.from([1,2,3,4]),a=Uint8Array.from([9,2,3,4]);s.sendApdu.mockResolvedValueOnce((0,n.Right)(t)).mockResolvedValueOnce((0,n.Right)(p)).mockResolvedValueOnce((0,n.Right)(p)).mockResolvedValueOnce((0,n.Right)(t)).mockResolvedValueOnce((0,n.Right)(t));const r=await d.sendApdu(o,!0),u=await d.sendApdu(a);(0,e.expect)(s.sendApdu).toHaveBeenCalledTimes(5),(0,e.expect)(s.sendApdu.mock.calls).toEqual([[o,!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0],[a,!1,void 0]]),(0,e.expect)(r).toStrictEqual((0,n.Right)(t)),(0,e.expect)(u).toStrictEqual((0,n.Right)(t))}),(0,e.it)("should not send several APDUs in parallel",async()=>{const o=Uint8Array.from([1,2,3,4]),a=Uint8Array.from([9,2,3,4]);s.sendApdu.mockResolvedValue((0,n.Right)(t));const r=d.sendApdu(o,!0),u=await d.sendApdu(a),c=await r;(0,e.expect)(s.sendApdu).toHaveBeenCalledTimes(2),(0,e.expect)(s.sendApdu.mock.calls).toEqual([[o,!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0]]),(0,e.expect)(c).toStrictEqual((0,n.Right)(t)),(0,e.expect)(u).toStrictEqual((0,n.Left)(new i.AlreadySendingApduError))}),(0,e.it)("should send another APDU in promise handler",async()=>{const o=Uint8Array.from([1,2,3,4]),a=Uint8Array.from([9,2,3,4]);s.sendApdu.mockResolvedValue((0,n.Right)(t));let r;const u=await d.sendApdu(o,!0).then(l=>(r=d.sendApdu(a),l));d.eventDeviceDisconnected(),d.eventDeviceConnected();const c=await r;(0,e.expect)(s.sendApdu).toHaveBeenCalledTimes(3),(0,e.expect)(s.sendApdu.mock.calls).toEqual([[o,!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0],[a,!1,void 0]]),(0,e.expect)(u).toStrictEqual((0,n.Right)(t)),(0,e.expect)(c).toStrictEqual((0,n.Right)(t))}),(0,e.it)("send an APDU while device is reconnecting",async()=>{const o=Uint8Array.from([1,2,3,4]);s.sendApdu.mockResolvedValue((0,n.Right)(t)),d.eventDeviceDisconnected();const a=d.sendApdu(o,!0);d.eventDeviceConnected();const r=await a;(0,e.expect)(s.sendApdu).toHaveBeenCalledTimes(2),(0,e.expect)(s.sendApdu.mock.calls).toEqual([[o,!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0]]),(0,e.expect)(r).toStrictEqual((0,n.Right)(t))}),(0,e.it)("Close while an APDU is waiting for reconnection",async()=>{const o=Uint8Array.from([1,2,3,4]),a=Uint8Array.from([9,2,3,4]);s.sendApdu.mockResolvedValue((0,n.Right)(t));let r;const u=d.sendApdu(o,!0);await Promise.resolve(),d.eventDeviceDisconnected();const c=await u;r=d.sendApdu(a),d.closeConnection();const l=await r;(0,e.expect)(s.sendApdu.mock.calls).toEqual([[o,!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0]]),(0,e.expect)(c).toStrictEqual((0,n.Right)(t)),(0,e.expect)(l).toStrictEqual((0,n.Left)(new i.DeviceDisconnectedWhileSendingError))})})});
|
2
|
+
//# sourceMappingURL=DeviceConnectionStateMachine.test.js.map
|