From c761359b867d6ad7715251e036cf5ce3254231c2 Mon Sep 17 00:00:00 2001 From: Leon Date: Wed, 11 Dec 2024 16:48:38 +0800 Subject: [PATCH] OK-34140: Improve hardware device verification process (#6323) * Update Verification.tsx * Update ConnectYourDevice.tsx * Update Verification.tsx * Update FirmwareVerifyDialog.tsx * Update FirmwareVerifyDialog.tsx * Update FirmwareVerifyDialog.tsx * Update FirmwareVerifyDialog.tsx * Update FirmwareVerifyDialog.tsx * remove features * feat: verify firmware * feat: compare version * refactor: Remove deplicate component * feat: memoizee version info * fix: memoizee * fix: Catch validate failed * fix: compare field * fix: code review issue * i18n * feat: Add verify log * feat: Link to release url * chore: lint * fix: adapter classic1s --------- Co-authored-by: huhuanming Co-authored-by: Franco --- .../ServiceHardware/HardwareVerifyManager.ts | 198 +++++++- .../ServiceHardware/ServiceHardware.ts | 45 ++ .../WalletOptions/Verification.tsx | 18 +- .../ConnectYourDevice.tsx | 1 + .../FirmwareVerifyDialog.tsx | 440 +++++++++++++++++- .../shared/src/locale/enum/translations.ts | 2 + packages/shared/src/locale/json/bn.json | 2 + packages/shared/src/locale/json/de.json | 2 + packages/shared/src/locale/json/en.json | 2 + packages/shared/src/locale/json/en_US.json | 2 + packages/shared/src/locale/json/es.json | 2 + packages/shared/src/locale/json/fr_FR.json | 2 + packages/shared/src/locale/json/hi_IN.json | 2 + packages/shared/src/locale/json/id.json | 2 + packages/shared/src/locale/json/it_IT.json | 2 + packages/shared/src/locale/json/ja_JP.json | 2 + packages/shared/src/locale/json/ko_KR.json | 2 + packages/shared/src/locale/json/pt.json | 2 + packages/shared/src/locale/json/pt_BR.json | 2 + packages/shared/src/locale/json/ru.json | 2 + packages/shared/src/locale/json/th_TH.json | 2 + packages/shared/src/locale/json/uk_UA.json | 2 + packages/shared/src/locale/json/vi.json | 2 + packages/shared/src/locale/json/zh_CN.json | 2 + packages/shared/src/locale/json/zh_HK.json | 2 + packages/shared/src/locale/json/zh_TW.json | 2 + .../src/logger/scopes/hardware/index.ts | 3 + .../logger/scopes/hardware/scenes/verify.ts | 21 + packages/shared/src/utils/deviceUtils.ts | 164 ++++++- packages/shared/types/device.ts | 64 +++ 30 files changed, 955 insertions(+), 41 deletions(-) create mode 100644 packages/shared/src/logger/scopes/hardware/scenes/verify.ts diff --git a/packages/kit-bg/src/services/ServiceHardware/HardwareVerifyManager.ts b/packages/kit-bg/src/services/ServiceHardware/HardwareVerifyManager.ts index dfb10c9cd32..3b84a0f79d9 100644 --- a/packages/kit-bg/src/services/ServiceHardware/HardwareVerifyManager.ts +++ b/packages/kit-bg/src/services/ServiceHardware/HardwareVerifyManager.ts @@ -8,9 +8,18 @@ import { EAppEventBusNames, appEventBus, } from '@onekeyhq/shared/src/eventBus/appEventBus'; -import platformEnv from '@onekeyhq/shared/src/platformEnv'; +import { defaultLogger } from '@onekeyhq/shared/src/logger/logger'; import bufferUtils from '@onekeyhq/shared/src/utils/bufferUtils'; +import { memoizee } from '@onekeyhq/shared/src/utils/cacheUtils'; +import deviceUtils from '@onekeyhq/shared/src/utils/deviceUtils'; import stringUtils from '@onekeyhq/shared/src/utils/stringUtils'; +import timerUtils from '@onekeyhq/shared/src/utils/timerUtils'; +import type { + IDeviceVerifyVersionCompareResult, + IFetchFirmwareVerifyHashParams, + IFirmwareVerifyInfo, + IOneKeyDeviceFeatures, +} from '@onekeyhq/shared/types/device'; import { EServiceEndpointEnum } from '@onekeyhq/shared/types/endpoint'; import localDb from '../../dbs/local/localDb'; @@ -25,6 +34,7 @@ import type { import type { DeviceVerifySignature, IDeviceType, + OnekeyFeatures, SearchDevice, } from '@onekeyfe/hd-core'; @@ -189,4 +199,190 @@ export class HardwareVerifyManager extends ServiceHardwareManagerBase { }, ); } + + @backgroundMethod() + async shouldAuthenticateFirmwareByHash({ + features, + }: { + features: IOneKeyDeviceFeatures | undefined; + }) { + // onekey_firmware_version + // onekey_firmware_hash + // onekey_ble_version + // onekey_ble_hash + // onekey_boot_version + // onekey_boot_hash + if (!features) { + return false; + } + const verifyVersions = + await deviceUtils.getDeviceVerifyVersionsFromFeatures({ + features, + }); + if (!verifyVersions) { + return false; + } + const result = await this.fetchFirmwareVerifyHash(verifyVersions); + // server should return 3 firmware config + if (!result || !Array.isArray(result) || result.length !== 3) { + return false; + } + const isValid = result.every((firmware) => { + if ( + firmware.type === 'system' && + firmware.version !== verifyVersions.firmwareVersion + ) { + console.log('System version mismatch:', { + expected: verifyVersions.firmwareVersion, + actual: firmware.version, + }); + return false; + } + if ( + firmware.type === 'bluetooth' && + firmware.version !== verifyVersions.bluetoothVersion + ) { + console.log('Bluetooth version mismatch:', { + expected: verifyVersions.bluetoothVersion, + actual: firmware.version, + }); + return false; + } + if ( + firmware.type === 'bootloader' && + firmware.version !== verifyVersions.bootloaderVersion + ) { + console.log('Bootloader version mismatch:', { + expected: verifyVersions.bootloaderVersion, + actual: firmware.version, + }); + return false; + } + return true; + }); + + console.log('shouldAuthenticateFirmwareByHash isValid: ', isValid); + return isValid; + } + + @backgroundMethod() + async fetchFirmwareVerifyHash( + params: IFetchFirmwareVerifyHashParams, + ): Promise { + try { + return await this.fetchFirmwareVerifyHashWithCache(params); + } catch { + return []; + } + } + + fetchFirmwareVerifyHashWithCache = memoizee( + async (params: IFetchFirmwareVerifyHashParams) => { + const client = await this.serviceHardware.getClient( + EServiceEndpointEnum.Utility, + ); + const resp = await client.get<{ + data: { + firmwares: IFirmwareVerifyInfo[]; + }; + }>('/utility/v1/firmware/detail', { + params: { + deviceType: params.deviceType, + system: params.firmwareVersion, + bluetooth: params.bluetoothVersion, + bootloader: params.bootloaderVersion, + }, + }); + return resp.data.data.firmwares; + }, + { + promise: true, + maxAge: timerUtils.getTimeDurationMs({ minute: 2 }), + }, + ); + + @backgroundMethod() + async verifyFirmwareHash({ + deviceType, + onekeyFeatures, + }: { + deviceType: IDeviceType; + onekeyFeatures: OnekeyFeatures | undefined; + }): Promise { + const defaultResult = { + certificate: { + isMatch: true, + format: onekeyFeatures?.onekey_serial_no ?? '', + }, + firmware: { isMatch: false, format: '' }, + bluetooth: { isMatch: false, format: '' }, + bootloader: { isMatch: false, format: '' }, + }; + + if (!onekeyFeatures) { + return defaultResult; + } + + const verifyVersions = + await deviceUtils.getDeviceVerifyVersionsFromFeatures({ + features: onekeyFeatures, + deviceType, + }); + if (!verifyVersions) { + return defaultResult; + } + + const result = await this.fetchFirmwareVerifyHash(verifyVersions); + if (!result || !Array.isArray(result)) { + return defaultResult; + } + const serverVerifyInfos = deviceUtils.parseServerVersionInfos({ + serverVerifyInfos: result, + }); + const localVerifyInfos = deviceUtils.parseLocalDeviceVersions({ + onekeyFeatures, + }); + + const firmwareMatch = deviceUtils.compareDeviceVersions({ + local: localVerifyInfos.firmware.raw, + remote: serverVerifyInfos.firmware.raw, + }); + const bluetoothMatch = deviceUtils.compareDeviceVersions({ + local: localVerifyInfos.bluetooth.raw, + remote: serverVerifyInfos.bluetooth.raw, + }); + const bootloaderMatch = deviceUtils.compareDeviceVersions({ + local: localVerifyInfos.bootloader.raw, + remote: serverVerifyInfos.bootloader.raw, + }); + + if (!firmwareMatch || !bluetoothMatch || !bootloaderMatch) { + defaultLogger.hardware.verify.verifyFailed({ + local: localVerifyInfos, + server: serverVerifyInfos, + }); + } + + return { + certificate: { + isMatch: true, + format: onekeyFeatures?.onekey_serial_no ?? '', + }, + firmware: { + isMatch: firmwareMatch, + format: serverVerifyInfos.firmware.formatted, + releaseUrl: serverVerifyInfos.firmware.releaseUrl, + }, + bluetooth: { + isMatch: bluetoothMatch, + format: serverVerifyInfos.bluetooth.formatted, + releaseUrl: serverVerifyInfos.bluetooth.releaseUrl, + }, + bootloader: { + isMatch: bootloaderMatch, + format: serverVerifyInfos.bootloader.formatted, + releaseUrl: serverVerifyInfos.bootloader.releaseUrl, + }, + }; + } } diff --git a/packages/kit-bg/src/services/ServiceHardware/ServiceHardware.ts b/packages/kit-bg/src/services/ServiceHardware/ServiceHardware.ts index c65c6a50126..94cf14636a9 100644 --- a/packages/kit-bg/src/services/ServiceHardware/ServiceHardware.ts +++ b/packages/kit-bg/src/services/ServiceHardware/ServiceHardware.ts @@ -32,6 +32,8 @@ import deviceUtils from '@onekeyhq/shared/src/utils/deviceUtils'; import timerUtils from '@onekeyhq/shared/src/utils/timerUtils'; import type { IBleFirmwareReleasePayload, + IDeviceResponseResult, + IDeviceVerifyVersionCompareResult, IFirmwareReleasePayload, IOneKeyDeviceFeatures, } from '@onekeyhq/shared/types/device'; @@ -75,6 +77,8 @@ import type { Features, IDeviceType, KnownDevice, + OnekeyFeatures, + Response, SearchDevice, UiEvent, } from '@onekeyfe/hd-core'; @@ -891,6 +895,27 @@ class ServiceHardware extends ServiceBase { return this.hardwareVerifyManager.firmwareAuthenticate(p); } + @backgroundMethod() + async shouldAuthenticateFirmwareByHash(params: { + features: IOneKeyDeviceFeatures | undefined; + }) { + return this.hardwareVerifyManager.shouldAuthenticateFirmwareByHash(params); + } + + @backgroundMethod() + async verifyFirmwareHash({ + deviceType, + onekeyFeatures, + }: { + deviceType: IDeviceType; + onekeyFeatures: OnekeyFeatures | undefined; + }): Promise { + return this.hardwareVerifyManager.verifyFirmwareHash({ + deviceType, + onekeyFeatures, + }); + } + @backgroundMethod() async uploadResource(connectId: string, params: DeviceUploadResourceParams) { const hardwareSDK = await this.getSDKInstance(); @@ -911,6 +936,26 @@ class ServiceHardware extends ServiceBase { } return logs; } + + @backgroundMethod() + async getOneKeyFeatures({ + connectId, + deviceType, + }: { + connectId: string; + deviceType: IDeviceType; + }): Promise { + const hardwareSDK = await this.getSDKInstance(); + return convertDeviceResponse(() => { + // classic1s does not support getOnekeyFeatures method + if (deviceType === 'classic1s') { + return hardwareSDK?.getFeatures( + connectId, + ) as unknown as Response; + } + return hardwareSDK?.getOnekeyFeatures(connectId); + }); + } } export default ServiceHardware; diff --git a/packages/kit/src/views/AccountManagerStacks/pages/AccountSelectorStack/WalletDetails/WalletOptions/Verification.tsx b/packages/kit/src/views/AccountManagerStacks/pages/AccountSelectorStack/WalletDetails/WalletOptions/Verification.tsx index 63e78e616be..7a0d5c93798 100644 --- a/packages/kit/src/views/AccountManagerStacks/pages/AccountSelectorStack/WalletDetails/WalletOptions/Verification.tsx +++ b/packages/kit/src/views/AccountManagerStacks/pages/AccountSelectorStack/WalletDetails/WalletOptions/Verification.tsx @@ -1,6 +1,6 @@ import { useIntl } from 'react-intl'; -import type { IIconProps, IKeyOfIcons } from '@onekeyhq/components'; +import { type IIconProps, type IKeyOfIcons } from '@onekeyhq/components'; import { useFirmwareVerifyDialog } from '@onekeyhq/kit/src/views/Onboarding/pages/ConnectHardwareWallet/FirmwareVerifyDialog'; import type { IDBDevice } from '@onekeyhq/kit-bg/src/dbs/local/types'; import { ETranslations } from '@onekeyhq/shared/src/locale'; @@ -9,21 +9,6 @@ import { WalletOptionItem } from './WalletOptionItem'; export function Verification({ device }: { device?: IDBDevice | undefined }) { const intl = useIntl(); - // const returnVerified = () => { - // setVerified(true); - // Toast.success({ - // title: 'Verified', - // message: 'You are good to go', - // }); - // }; - - // const returnUnofficial = () => { - // setUnofficial(true); - // Toast.error({ - // title: 'Unofficial', - // message: 'Please contact support', - // }); - // }; const getIconNameAndIconColor = (): { iconName: IKeyOfIcons; @@ -69,6 +54,7 @@ export function Verification({ device }: { device?: IDBDevice | undefined }) { } await showFirmwareVerifyDialog({ device, + features: device.featuresInfo, onContinue: async ({ checked }) => { console.log(checked); }, diff --git a/packages/kit/src/views/Onboarding/pages/ConnectHardwareWallet/ConnectYourDevice.tsx b/packages/kit/src/views/Onboarding/pages/ConnectHardwareWallet/ConnectYourDevice.tsx index d5784872e1e..be22b8a269c 100644 --- a/packages/kit/src/views/Onboarding/pages/ConnectHardwareWallet/ConnectYourDevice.tsx +++ b/packages/kit/src/views/Onboarding/pages/ConnectHardwareWallet/ConnectYourDevice.tsx @@ -647,6 +647,7 @@ function ConnectByUSBOrBLE({ ) { await showFirmwareVerifyDialog({ device, + features, onContinue: async ({ checked }) => { if (deviceMode === EOneKeyDeviceMode.notInitialized) { handleNotActivatedDevicePress({ deviceType }); diff --git a/packages/kit/src/views/Onboarding/pages/ConnectHardwareWallet/FirmwareVerifyDialog.tsx b/packages/kit/src/views/Onboarding/pages/ConnectHardwareWallet/FirmwareVerifyDialog.tsx index c10194fb3c2..b56344acc35 100644 --- a/packages/kit/src/views/Onboarding/pages/ConnectHardwareWallet/FirmwareVerifyDialog.tsx +++ b/packages/kit/src/views/Onboarding/pages/ConnectHardwareWallet/FirmwareVerifyDialog.tsx @@ -1,16 +1,18 @@ -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { HardwareErrorCode } from '@onekeyfe/hd-shared'; import { useIntl } from 'react-intl'; import { Linking, StyleSheet } from 'react-native'; -import type { IButtonProps } from '@onekeyhq/components'; import { + Anchor, Button, Dialog, + Icon, SizableText, Spinner, Stack, + XStack, YStack, useDialogInstance, } from '@onekeyhq/components'; @@ -18,9 +20,9 @@ import backgroundApiProxy from '@onekeyhq/kit/src/background/instance/background import { useHelpLink } from '@onekeyhq/kit/src/hooks/useHelpLink'; import type { IDBDevice } from '@onekeyhq/kit-bg/src/dbs/local/types'; import { FIRMWARE_CONTACT_US_URL } from '@onekeyhq/shared/src/config/appConfig'; -import type { - OneKeyError, - OneKeyServerApiError, +import { + type OneKeyError, + type OneKeyServerApiError, } from '@onekeyhq/shared/src/errors'; import { EOneKeyErrorClassNames } from '@onekeyhq/shared/src/errors/types/errorTypes'; import { @@ -29,6 +31,10 @@ import { } from '@onekeyhq/shared/src/eventBus/appEventBus'; import { ETranslations } from '@onekeyhq/shared/src/locale'; import platformEnv from '@onekeyhq/shared/src/platformEnv'; +import type { + IDeviceVerifyVersionCompareResult, + IOneKeyDeviceFeatures, +} from '@onekeyhq/shared/types/device'; import type { SearchDevice } from '@onekeyfe/hd-core'; @@ -41,19 +47,23 @@ type IFirmwareAuthenticationState = export enum EFirmwareAuthenticationDialogContentType { default = 'default', verifying = 'verifying', + verification_verify = 'verification_verify', verification_successful = 'verification_successful', network_error = 'network_error', unofficial_device_detected = 'unofficial_device_detected', verification_temporarily_unavailable = 'verification_temporarily_unavailable', error_fallback = 'error_fallback', + unofficial_firmware_detected = 'unofficial_firmware_detected', } function useFirmwareVerifyBase({ device, skipDeviceCancel, + useNewProcess, }: { device: SearchDevice | IDBDevice; skipDeviceCancel?: boolean; + useNewProcess?: boolean; }) { const [result, setResult] = useState('unknown'); // unknown, official, unofficial, error const [errorObj, setErrorObj] = useState<{ code: number; message?: string }>({ @@ -62,6 +72,9 @@ function useFirmwareVerifyBase({ const [contentType, setContentType] = useState( EFirmwareAuthenticationDialogContentType.default, ); + const [versionCompareResult, setVersionCompareResult] = useState< + IDeviceVerifyVersionCompareResult | undefined + >(undefined); const dialogInstance = useDialogInstance(); useEffect(() => { const callback = () => { @@ -88,8 +101,14 @@ function useFirmwareVerifyBase({ console.log('firmwareAuthenticate >>>> ', authResult); if (authResult.verified) { setResult('official'); + // Set certificate to success first + setVersionCompareResult({ + certificate: { isMatch: true, format: authResult.result?.data ?? '' }, + } as unknown as IDeviceVerifyVersionCompareResult); setContentType( - EFirmwareAuthenticationDialogContentType.verification_successful, + useNewProcess + ? EFirmwareAuthenticationDialogContentType.verification_verify + : EFirmwareAuthenticationDialogContentType.verification_successful, ); } else { setResult('unofficial'); @@ -98,6 +117,30 @@ function useFirmwareVerifyBase({ EFirmwareAuthenticationDialogContentType.unofficial_device_detected, ); } + + if (useNewProcess) { + // verify firmware hash + const latestFeatures = + await backgroundApiProxy.serviceHardware.getOneKeyFeatures({ + connectId: device?.connectId ?? '', + deviceType: device.deviceType, + }); + const verifyResult = + await backgroundApiProxy.serviceHardware.verifyFirmwareHash({ + deviceType: device.deviceType, + onekeyFeatures: latestFeatures, + }); + console.log('=====>>>> verifyResult: ', verifyResult); + setVersionCompareResult(verifyResult); + const hasUnverifiedFirmware = Object.entries(verifyResult).some( + ([, value]: [string, { isMatch: boolean }]) => !value.isMatch, + ); + if (hasUnverifiedFirmware) { + setContentType( + EFirmwareAuthenticationDialogContentType.unofficial_firmware_detected, + ); + } + } } catch (error) { setResult('error'); @@ -150,25 +193,254 @@ function useFirmwareVerifyBase({ skipDeviceCancel, }); } - }, [device, dialogInstance, skipDeviceCancel]); + }, [device, dialogInstance, skipDeviceCancel, useNewProcess]); useEffect(() => { setTimeout(async () => { await verify(); }, 50); - // setTimeout(() => { - // setIsConfirmOnDevice(true); - // setTimeout(() => { - // setResult('official'); - // }, 3000); - // }, 3000); }, [verify]); const reset = useCallback(() => { setResult('unknown'); }, []); - return { result, reset, verify, contentType, setContentType, errorObj }; + return { + result, + reset, + verify, + contentType, + setContentType, + errorObj, + versionCompareResult, + }; +} + +export type IHashInfo = { + certificate: string; + firmware: string; + bluetooth: string; + bootloader: string; + securityElement: string; +}; + +type IVerifyHashRowStatus = 'error' | 'success' | 'loading' | 'init'; +function VerifyHashRow({ + title, + status, + result, + releaseUrl, +}: { + title: string; + status: IVerifyHashRowStatus; + result: string; + releaseUrl?: string; +}) { + const intl = useIntl(); + const icon = useMemo(() => { + if (status === 'loading') { + return ( + + + + ); + } + if (status === 'success') { + return ; + } + if (status === 'init') { + return ( + + + + ); + } + return ; + }, [status]); + const resultInfo = useMemo(() => { + if (status === 'loading') { + return ( + + {intl.formatMessage({ + id: ETranslations.device_auth_verifying_component_label, + })} + + ); + } + if (status === 'success') { + if (releaseUrl) { + return ( + + {result} + + ); + } + return ( + + {result} + + ); + } + if (status === 'error') { + return ( + + {intl.formatMessage({ id: ETranslations.global_failed })} + + ); + } + + return null; + }, [intl, result, status, releaseUrl]); + return ( + + + {icon} + {title} + + {resultInfo} + + ); +} + +const keys = ['certificate', 'firmware', 'bluetooth', 'bootloader']; +function VerifyHash({ + certificateResult, + onActionPress, + initStatuses = { + certificate: 'loading', + firmware: 'init', + bluetooth: 'init', + bootloader: 'init', + }, + versionCompareResult, +}: { + certificateResult?: IFirmwareAuthenticationState; + versionCompareResult?: IDeviceVerifyVersionCompareResult; + onActionPress?: () => void; + initStatuses?: { + certificate: IVerifyHashRowStatus; + firmware: IVerifyHashRowStatus; + bluetooth: IVerifyHashRowStatus; + bootloader: IVerifyHashRowStatus; + }; +}) { + const [statues, setStatues] = useState(initStatuses); + const intl = useIntl(); + const verifiedKeys = useRef(new Set()); + + useEffect(() => { + keys.forEach((key) => { + if ( + key !== 'certificate' && + !verifiedKeys.current.has(key) && + versionCompareResult?.[key as keyof IDeviceVerifyVersionCompareResult] + ) { + verifiedKeys.current.add(key); + setStatues((prev) => ({ + ...prev, + [key]: versionCompareResult[ + key as keyof IDeviceVerifyVersionCompareResult + ].isMatch + ? 'success' + : 'error', + })); + } + }); + }, [versionCompareResult]); + + useEffect(() => { + if ( + certificateResult === 'official' || + certificateResult === 'unofficial' + ) { + verifiedKeys.current.add('certificate'); + setStatues((prev) => ({ + ...prev, + certificate: certificateResult === 'official' ? 'success' : 'error', + ...(certificateResult === 'official' ? { firmware: 'loading' } : {}), + })); + } + }, [certificateResult]); + + const titles = useMemo( + () => [ + intl.formatMessage({ id: ETranslations.device_auth_certificate }), + intl.formatMessage({ id: ETranslations.global_firmware }), + intl.formatMessage({ id: ETranslations.global_bluetooth }), + 'Bootloader', + 'Security Element', + ], + [intl], + ); + + const isShowContinue = + Object.values(statues).filter((s) => s !== 'success').length === 0; + + return ( + + {isShowContinue ? ( + + + + {intl.formatMessage({ + id: ETranslations.device_auth_successful_title, + })} + + + {intl.formatMessage({ + id: ETranslations.device_auth_successful_desc, + })} + + + ) : null} + + {keys.map((key, index) => ( + + ))} + + {isShowContinue ? ( + + ) : null} + + ); } export function EnumBasicDialogContentContainer({ @@ -176,6 +448,9 @@ export function EnumBasicDialogContentContainer({ onActionPress, onContinuePress, errorObj, + certificateResult, + versionCompareResult, + useNewProcess, }: { contentType: EFirmwareAuthenticationDialogContentType; errorObj: { @@ -184,6 +459,9 @@ export function EnumBasicDialogContentContainer({ }; onActionPress?: () => void; onContinuePress?: () => void; + certificateResult?: IFirmwareAuthenticationState; + versionCompareResult?: IDeviceVerifyVersionCompareResult; + useNewProcess?: boolean; }) { const intl = useIntl(); @@ -257,10 +535,29 @@ export function EnumBasicDialogContentContainer({ ); case EFirmwareAuthenticationDialogContentType.verifying: + if (useNewProcess) { + return ( + <> + + + + {intl.formatMessage({ + id: ETranslations.device_auth_verifying_title, + })} + + + + + ); + } return ( <> - + {intl.formatMessage({ id: ETranslations.device_auth_verifying_title, @@ -284,6 +581,24 @@ export function EnumBasicDialogContentContainer({ ); + case EFirmwareAuthenticationDialogContentType.verification_verify: + return ( + <> + + + + {intl.formatMessage({ + id: ETranslations.device_auth_verifying_title, + })} + + + + + ); case EFirmwareAuthenticationDialogContentType.verification_successful: return ( <> @@ -386,6 +701,54 @@ export function EnumBasicDialogContentContainer({ ) : null} ); + case EFirmwareAuthenticationDialogContentType.unofficial_firmware_detected: + return ( + <> + + + + {intl.formatMessage({ + id: ETranslations.device_auth_unofficial_device_detected, + })} + + + {intl.formatMessage({ + id: ETranslations.device_auth_unofficial_device_detected_help_text, + })} + + + + + {platformEnv.isDev ? ( + + ) : null} + + ); case EFirmwareAuthenticationDialogContentType.verification_temporarily_unavailable: return ( <> @@ -458,6 +821,9 @@ export function EnumBasicDialogContentContainer({ onActionPress, onContinuePress, renderFooter, + certificateResult, + versionCompareResult, + useNewProcess, ]); return {content}; } @@ -466,16 +832,26 @@ export function FirmwareAuthenticationDialogContent({ onContinue, device, skipDeviceCancel, + useNewProcess, }: { onContinue: (params: { checked: boolean }) => void; device: SearchDevice | IDBDevice; skipDeviceCancel?: boolean; + useNewProcess?: boolean; }) { - const { result, reset, verify, contentType, setContentType, errorObj } = - useFirmwareVerifyBase({ - device, - skipDeviceCancel, - }); + const { + result, + reset, + verify, + contentType, + setContentType, + errorObj, + versionCompareResult, + } = useFirmwareVerifyBase({ + device, + skipDeviceCancel, + useNewProcess, + }); const requestsUrl = useHelpLink({ path: 'requests/new' }); @@ -512,10 +888,13 @@ export function FirmwareAuthenticationDialogContent({ return ( ); }, [ @@ -528,6 +907,8 @@ export function FirmwareAuthenticationDialogContent({ reset, setContentType, verify, + versionCompareResult, + useNewProcess, ]); return {content}; @@ -537,11 +918,25 @@ export function useFirmwareVerifyDialog() { const showFirmwareVerifyDialog = useCallback( async ({ device, + features, onContinue, }: { device: SearchDevice | IDBDevice; + features: IOneKeyDeviceFeatures | undefined; onContinue: (params: { checked: boolean }) => Promise | void; }) => { + console.log('====> features: ', features); + // use old features to quick check if need new version + const shouldUseNewAuthenticateVersion = + await backgroundApiProxy.serviceHardware.shouldAuthenticateFirmwareByHash( + { + features, + }, + ); + console.log( + 'shouldUseNewAuthenticateVersion: ====>>>: ', + shouldUseNewAuthenticateVersion, + ); const firmwareAuthenticationDialog = Dialog.show({ tone: 'success', icon: 'DocumentSearch2Outline', @@ -551,14 +946,13 @@ export function useFirmwareVerifyDialog() { showFooter: false, renderContent: ( { await firmwareAuthenticationDialog.close(); await onContinue({ checked }); }} - {...{ - skipDeviceCancel: true, // FirmwareAuthenticationDialogContent - }} + useNewProcess={shouldUseNewAuthenticateVersion} /> ), async onClose() { diff --git a/packages/shared/src/locale/enum/translations.ts b/packages/shared/src/locale/enum/translations.ts index 563e613f850..a6feacfb6be 100644 --- a/packages/shared/src/locale/enum/translations.ts +++ b/packages/shared/src/locale/enum/translations.ts @@ -302,6 +302,7 @@ date_yesterday = 'date.yesterday', derivation_path = 'derivation_path', description_403 = 'description_403', + device_auth_certificate = 'device_auth.certificate', device_auth_continue_anyway_warning_message = 'device_auth.continue_anyway_warning_message', device_auth_request_desc = 'device_auth.request_desc', device_auth_request_title = 'device_auth.request_title', @@ -311,6 +312,7 @@ device_auth_temporarily_unavailable_help_text = 'device_auth.temporarily_unavailable_help_text', device_auth_unofficial_device_detected = 'device_auth.unofficial_device_detected', device_auth_unofficial_device_detected_help_text = 'device_auth.unofficial_device_detected_help_text', + device_auth_verifying_component_label = 'device_auth.verifying_component_label', device_auth_verifying_desc = 'device_auth.verifying_desc', device_auth_verifying_title = 'device_auth.verifying_title', dont_have_mobile_app_yet = 'dont_have_mobile_app_yet', diff --git a/packages/shared/src/locale/json/bn.json b/packages/shared/src/locale/json/bn.json index a9f4b086275..48d3fe8bb48 100644 --- a/packages/shared/src/locale/json/bn.json +++ b/packages/shared/src/locale/json/bn.json @@ -297,6 +297,7 @@ "date.yesterday": "গতকাল", "derivation_path": "উৎপত্তি পথ", "description_403": "আমাদের সেবাগুলি আপনার অঞ্চলে পাওয়া যায় না।", + "device_auth.certificate": "সার্টিফিকেট", "device_auth.continue_anyway_warning_message": "আমরা বর্তমানে আপনার ডিভাইসটি যাচাই করতে অক্ষম। চালিয়ে যাওয়া নিরাপত্তা ঝুঁকিতে সরবরাহ করতে পারে।", "device_auth.request_desc": "আপনার যন্ত্রের প্রামাণিকতা যাচাই করার জন্য এবং আপনার সংযোগটি নিরাপদ রাখার জন্য নিশ্চিত করুন।", "device_auth.request_title": "ডিভাইস প্রমাণীকরণ", @@ -306,6 +307,7 @@ "device_auth.temporarily_unavailable_help_text": "বর্তমানে, আমরা আপনার ডিভাইসটি সার্ভার সমস্যার কারণে যাচাই করতে অক্ষম। দয়া করে পরে আবার চেষ্টা করুন।", "device_auth.unofficial_device_detected": "অনাধিকৃত ডিভাইস সনাক্ত করা হয়েছে", "device_auth.unofficial_device_detected_help_text": "আপনার ডিভাইসটি অফিসিয়াল হিসেবে যাচাই করা যায়নি। দয়া করে আমাদের সাথে অবিলম্বে যোগাযোগ করুন।", + "device_auth.verifying_component_label": "চলছে", "device_auth.verifying_desc": "অনুগ্রহ করে অপেক্ষা করুন...", "device_auth.verifying_title": "ডিভাইস যাচাই করা হচ্ছে", "dont_have_mobile_app_yet": "মোবাইল অ্যাপটি এখনো নেই?", diff --git a/packages/shared/src/locale/json/de.json b/packages/shared/src/locale/json/de.json index 87dfe183292..966cd276c20 100644 --- a/packages/shared/src/locale/json/de.json +++ b/packages/shared/src/locale/json/de.json @@ -297,6 +297,7 @@ "date.yesterday": "Gestern", "derivation_path": "Ableitungspfad", "description_403": "Unsere Dienstleistungen sind in Ihrer Region nicht verfügbar.", + "device_auth.certificate": "Zertifikat", "device_auth.continue_anyway_warning_message": "Wir können Ihr Gerät derzeit nicht verifizieren. Eine Fortsetzung könnte Sicherheitsrisiken bergen.", "device_auth.request_desc": "Bestätigen Sie auf Ihrem Gerät, um seine Echtheit zu überprüfen und Ihre Verbindung zu sichern.", "device_auth.request_title": "Geräteauthentifizierung", @@ -306,6 +307,7 @@ "device_auth.temporarily_unavailable_help_text": "Derzeit können wir Ihr Gerät aufgrund von Serverproblemen nicht verifizieren. Bitte versuchen Sie es später erneut.", "device_auth.unofficial_device_detected": "Unoffizielles Gerät erkannt", "device_auth.unofficial_device_detected_help_text": "Ihr Gerät konnte nicht als offiziell verifiziert werden. Bitte kontaktieren Sie uns sofort.", + "device_auth.verifying_component_label": "Im Gange", "device_auth.verifying_desc": "Bitte warten...", "device_auth.verifying_title": "Gerät überprüfen", "dont_have_mobile_app_yet": "Haben Sie die mobile App noch nicht?", diff --git a/packages/shared/src/locale/json/en.json b/packages/shared/src/locale/json/en.json index 1cf6492ad9a..61be2516e20 100644 --- a/packages/shared/src/locale/json/en.json +++ b/packages/shared/src/locale/json/en.json @@ -297,6 +297,7 @@ "date.yesterday": "Yesterday", "derivation_path": "Derivation path", "description_403": "Our services are not available in your region.", + "device_auth.certificate": "Certificate", "device_auth.continue_anyway_warning_message": "We're currently unable to verify your device. Continuing may pose security risks.", "device_auth.request_desc": "Confirm on your device to verify its authenticity and secure your connection.", "device_auth.request_title": "Device authentication", @@ -306,6 +307,7 @@ "device_auth.temporarily_unavailable_help_text": "Currently, we're unable to verify your device due to server issues. Please try again later.", "device_auth.unofficial_device_detected": "Unofficial device detected", "device_auth.unofficial_device_detected_help_text": "Your device could not be verified as official. Please contact us immediately.", + "device_auth.verifying_component_label": "In progress", "device_auth.verifying_desc": "Please wait...", "device_auth.verifying_title": "Verifying device", "dont_have_mobile_app_yet": "Don’t have the mobile App yet?", diff --git a/packages/shared/src/locale/json/en_US.json b/packages/shared/src/locale/json/en_US.json index 0d48ebdb1c6..fe0ac3fae9d 100644 --- a/packages/shared/src/locale/json/en_US.json +++ b/packages/shared/src/locale/json/en_US.json @@ -297,6 +297,7 @@ "date.yesterday": "Yesterday", "derivation_path": "Derivation path", "description_403": "Our services are not available in your region.", + "device_auth.certificate": "Certificate", "device_auth.continue_anyway_warning_message": "We're currently unable to verify your device. Continuing may pose security risks.", "device_auth.request_desc": "Confirm on your device to verify its authenticity and secure your connection.", "device_auth.request_title": "Device authentication", @@ -306,6 +307,7 @@ "device_auth.temporarily_unavailable_help_text": "Currently, we're unable to verify your device due to server issues. Please try again later.", "device_auth.unofficial_device_detected": "Unofficial device detected", "device_auth.unofficial_device_detected_help_text": "Your device could not be verified as official. Please contact us immediately.", + "device_auth.verifying_component_label": "In progress", "device_auth.verifying_desc": "Please wait...", "device_auth.verifying_title": "Verifying device", "dont_have_mobile_app_yet": "Don’t have the mobile App yet?", diff --git a/packages/shared/src/locale/json/es.json b/packages/shared/src/locale/json/es.json index b80471f410f..9e63ca4e865 100644 --- a/packages/shared/src/locale/json/es.json +++ b/packages/shared/src/locale/json/es.json @@ -297,6 +297,7 @@ "date.yesterday": "Ayer", "derivation_path": "Ruta de derivación", "description_403": "Nuestros servicios no están disponibles en su región.", + "device_auth.certificate": "Certificado", "device_auth.continue_anyway_warning_message": "Actualmente no podemos verificar tu dispositivo. Continuar puede representar riesgos de seguridad.", "device_auth.request_desc": "Confirma en tu dispositivo para verificar su autenticidad y asegurar tu conexión.", "device_auth.request_title": "Autenticación del dispositivo", @@ -306,6 +307,7 @@ "device_auth.temporarily_unavailable_help_text": "Actualmente, no podemos verificar su dispositivo debido a problemas con el servidor. Por favor, inténtelo de nuevo más tarde.", "device_auth.unofficial_device_detected": "Dispositivo no oficial detectado", "device_auth.unofficial_device_detected_help_text": "Su dispositivo no pudo ser verificado como oficial. Por favor, contáctenos inmediatamente.", + "device_auth.verifying_component_label": "En curso", "device_auth.verifying_desc": "Por favor espera...", "device_auth.verifying_title": "Verificando dispositivo", "dont_have_mobile_app_yet": "¿Aún no tienes la aplicación móvil?", diff --git a/packages/shared/src/locale/json/fr_FR.json b/packages/shared/src/locale/json/fr_FR.json index 32519e8652a..1f19f3dbb40 100644 --- a/packages/shared/src/locale/json/fr_FR.json +++ b/packages/shared/src/locale/json/fr_FR.json @@ -297,6 +297,7 @@ "date.yesterday": "Hier", "derivation_path": "Chemin de dérivation", "description_403": "Nos services ne sont pas disponibles dans votre région.", + "device_auth.certificate": "Certificat", "device_auth.continue_anyway_warning_message": "Nous ne pouvons actuellement pas vérifier votre appareil. Continuer peut présenter des risques de sécurité.", "device_auth.request_desc": "Confirmez sur votre appareil pour vérifier son authenticité et sécuriser votre connexion.", "device_auth.request_title": "Authentification de l'appareil", @@ -306,6 +307,7 @@ "device_auth.temporarily_unavailable_help_text": "Actuellement, nous ne pouvons pas vérifier votre appareil en raison de problèmes de serveur. Veuillez réessayer plus tard.", "device_auth.unofficial_device_detected": "Appareil non officiel détecté", "device_auth.unofficial_device_detected_help_text": "Votre appareil n'a pas pu être vérifié comme officiel. Veuillez nous contacter immédiatement.", + "device_auth.verifying_component_label": "En cours", "device_auth.verifying_desc": "Veuillez patienter...", "device_auth.verifying_title": "Vérification de l'appareil", "dont_have_mobile_app_yet": "Vous n'avez pas encore l'application mobile ?", diff --git a/packages/shared/src/locale/json/hi_IN.json b/packages/shared/src/locale/json/hi_IN.json index b3505bf3ca7..abb0f4bb6ac 100644 --- a/packages/shared/src/locale/json/hi_IN.json +++ b/packages/shared/src/locale/json/hi_IN.json @@ -297,6 +297,7 @@ "date.yesterday": "कल", "derivation_path": "व्युत्पन्न पथ", "description_403": "हमारी सेवाएं आपके क्षेत्र में उपलब्ध नहीं हैं।", + "device_auth.certificate": "प्रमाणपत्र", "device_auth.continue_anyway_warning_message": "हम वर्तमान में आपके उपकरण की पुष्टि करने में असमर्थ हैं। जारी रखना सुरक्षा जोखिम उत्पन्न कर सकता है।", "device_auth.request_desc": "अपनी उपकरण की प्रामाणिकता की पुष्टि करें और अपने कनेक्शन को सुरक्षित करें।", "device_auth.request_title": "उपकरण प्रमाणीकरण", @@ -306,6 +307,7 @@ "device_auth.temporarily_unavailable_help_text": "वर्तमान में, हम आपके उपकरण की पुष्टि नहीं कर पा रहे हैं क्योंकि सर्वर में समस्याएं हैं। कृपया बाद में पुनः प्रयास करें।", "device_auth.unofficial_device_detected": "अनाधिकृत उपकरण पता चला है", "device_auth.unofficial_device_detected_help_text": "आपकी उपकरण को आधिकारिक रूप से सत्यापित नहीं किया जा सका। कृपया तुरंत हमसे संपर्क करें।", + "device_auth.verifying_component_label": "प्रगति पर है", "device_auth.verifying_desc": "कृपया प्रतीक्षा करें...", "device_auth.verifying_title": "उपकरण की पुष्टि कर रहे हैं", "dont_have_mobile_app_yet": "क्या आपके पास मोबाइल ऐप अभी तक नहीं है?", diff --git a/packages/shared/src/locale/json/id.json b/packages/shared/src/locale/json/id.json index bd178afdc31..4638756b6f2 100644 --- a/packages/shared/src/locale/json/id.json +++ b/packages/shared/src/locale/json/id.json @@ -297,6 +297,7 @@ "date.yesterday": "Kemarin", "derivation_path": "Jalur derivasi", "description_403": "Layanan kami tidak tersedia di wilayah Anda.", + "device_auth.certificate": "Sertifikat", "device_auth.continue_anyway_warning_message": "Kami saat ini tidak dapat memverifikasi perangkat Anda. Melanjutkan mungkin menimbulkan risiko keamanan.", "device_auth.request_desc": "Konfirmasi pada perangkat Anda untuk memverifikasi keasliannya dan mengamankan koneksi Anda.", "device_auth.request_title": "Otentikasi perangkat", @@ -306,6 +307,7 @@ "device_auth.temporarily_unavailable_help_text": "Saat ini, kami tidak dapat memverifikasi perangkat Anda karena masalah server. Silakan coba lagi nanti.", "device_auth.unofficial_device_detected": "Perangkat tidak resmi terdeteksi", "device_auth.unofficial_device_detected_help_text": "Perangkat Anda tidak dapat diverifikasi sebagai resmi. Silakan hubungi kami segera.", + "device_auth.verifying_component_label": "Sedang berlangsung", "device_auth.verifying_desc": "Harap tunggu...", "device_auth.verifying_title": "Memverifikasi perangkat", "dont_have_mobile_app_yet": "Belum memiliki aplikasi seluler?", diff --git a/packages/shared/src/locale/json/it_IT.json b/packages/shared/src/locale/json/it_IT.json index c34e0a05a13..5c3396f2814 100644 --- a/packages/shared/src/locale/json/it_IT.json +++ b/packages/shared/src/locale/json/it_IT.json @@ -297,6 +297,7 @@ "date.yesterday": "Ieri", "derivation_path": "Percorso di derivazione", "description_403": "I nostri servizi non sono disponibili nella tua regione.", + "device_auth.certificate": "Certificato", "device_auth.continue_anyway_warning_message": "Non siamo attualmente in grado di verificare il tuo dispositivo. Continuare potrebbe comportare rischi per la sicurezza.", "device_auth.request_desc": "Conferma sul tuo dispositivo per verificarne l'autenticità e proteggere la tua connessione.", "device_auth.request_title": "Autenticazione del dispositivo", @@ -306,6 +307,7 @@ "device_auth.temporarily_unavailable_help_text": "Attualmente, non siamo in grado di verificare il tuo dispositivo a causa di problemi con il server. Si prega di riprovare più tardi.", "device_auth.unofficial_device_detected": "Rilevato dispositivo non ufficiale", "device_auth.unofficial_device_detected_help_text": "Il tuo dispositivo non può essere verificato come ufficiale. Ti preghiamo di contattarci immediatamente.", + "device_auth.verifying_component_label": "In corso", "device_auth.verifying_desc": "Attendere prego...", "device_auth.verifying_title": "Verifica del dispositivo", "dont_have_mobile_app_yet": "Non hai ancora l'app mobile?", diff --git a/packages/shared/src/locale/json/ja_JP.json b/packages/shared/src/locale/json/ja_JP.json index 9715efc1f0e..90a9433bd37 100644 --- a/packages/shared/src/locale/json/ja_JP.json +++ b/packages/shared/src/locale/json/ja_JP.json @@ -297,6 +297,7 @@ "date.yesterday": "昨日", "derivation_path": "導出パス", "description_403": "弊社のサービスはお客様の地域ではご利用いただけません。", + "device_auth.certificate": "証明書", "device_auth.continue_anyway_warning_message": "現在、お使いのデバイスを確認することができません。続行するとセキュリティリスクが生じる可能性があります。", "device_auth.request_desc": "あなたのデバイスで確認して、その真正性を検証し、接続を安全に保つ。", "device_auth.request_title": "デバイス認証", @@ -306,6 +307,7 @@ "device_auth.temporarily_unavailable_help_text": "現在、サーバーの問題により、あなたのデバイスを確認することができません。後ほど再度お試しください。", "device_auth.unofficial_device_detected": "非公式のデバイスが検出されました", "device_auth.unofficial_device_detected_help_text": "あなたのデバイスは公式として認証できませんでした。すぐにご連絡ください。", + "device_auth.verifying_component_label": "進行中", "device_auth.verifying_desc": "お待ちください...", "device_auth.verifying_title": "デバイスの確認", "dont_have_mobile_app_yet": "まだモバイルアプリをお持ちでないですか?", diff --git a/packages/shared/src/locale/json/ko_KR.json b/packages/shared/src/locale/json/ko_KR.json index a5054514742..5a0f48bee07 100644 --- a/packages/shared/src/locale/json/ko_KR.json +++ b/packages/shared/src/locale/json/ko_KR.json @@ -297,6 +297,7 @@ "date.yesterday": "어제", "derivation_path": "유도 경로", "description_403": "귀하의 지역에서는 당사 서비스를 이용할 수 없습니다.", + "device_auth.certificate": "자격증", "device_auth.continue_anyway_warning_message": "현재 귀하의 장치를 확인할 수 없습니다. 계속 진행하면 보안 위험이 발생할 수 있습니다.", "device_auth.request_desc": "장치의 진위를 확인하고 연결을 보호하기 위해 장치에서 확인하십시오.", "device_auth.request_title": "장치 인증", @@ -306,6 +307,7 @@ "device_auth.temporarily_unavailable_help_text": "현재 서버 문제로 인해 귀하의 장치를 검증할 수 없습니다. 나중에 다시 시도해 주세요.", "device_auth.unofficial_device_detected": "비공식 장치 감지됨", "device_auth.unofficial_device_detected_help_text": "당신의 장치가 공식적으로 확인되지 않았습니다. 즉시 저희에게 연락해 주세요.", + "device_auth.verifying_component_label": "진행중", "device_auth.verifying_desc": "잠시 기다려 주세요...", "device_auth.verifying_title": "장치 확인 중", "dont_have_mobile_app_yet": "아직 모바일 앱을 가지고 있지 않으신가요?", diff --git a/packages/shared/src/locale/json/pt.json b/packages/shared/src/locale/json/pt.json index 1cc19b5552c..b1bfb2db7b2 100644 --- a/packages/shared/src/locale/json/pt.json +++ b/packages/shared/src/locale/json/pt.json @@ -297,6 +297,7 @@ "date.yesterday": "Ontem", "derivation_path": "Caminho de derivação", "description_403": "Nossos serviços não estão disponíveis em sua região.", + "device_auth.certificate": "Certificado", "device_auth.continue_anyway_warning_message": "No momento, não conseguimos verificar o seu dispositivo. Continuar pode representar riscos de segurança.", "device_auth.request_desc": "Confirme no seu dispositivo para verificar a sua autenticidade e garantir a segurança da sua conexão.", "device_auth.request_title": "Autenticação do dispositivo", @@ -306,6 +307,7 @@ "device_auth.temporarily_unavailable_help_text": "Atualmente, não conseguimos verificar o seu dispositivo devido a problemas no servidor. Por favor, tente novamente mais tarde.", "device_auth.unofficial_device_detected": "Dispositivo não oficial detectado", "device_auth.unofficial_device_detected_help_text": "O seu dispositivo não pôde ser verificado como oficial. Por favor, entre em contato conosco imediatamente.", + "device_auth.verifying_component_label": "Em andamento", "device_auth.verifying_desc": "Por favor, aguarde...", "device_auth.verifying_title": "Verificando dispositivo", "dont_have_mobile_app_yet": "Ainda não tem o aplicativo móvel?", diff --git a/packages/shared/src/locale/json/pt_BR.json b/packages/shared/src/locale/json/pt_BR.json index e55fbe3be84..cea0bc56cf0 100644 --- a/packages/shared/src/locale/json/pt_BR.json +++ b/packages/shared/src/locale/json/pt_BR.json @@ -297,6 +297,7 @@ "date.yesterday": "Ontem", "derivation_path": "Caminho de derivação", "description_403": "Nossos serviços não estão disponíveis em sua região.", + "device_auth.certificate": "Certificado", "device_auth.continue_anyway_warning_message": "No momento, não conseguimos verificar seu dispositivo. Continuar pode representar riscos de segurança.", "device_auth.request_desc": "Confirme em seu dispositivo para verificar sua autenticidade e garantir sua conexão segura.", "device_auth.request_title": "Autenticação do dispositivo", @@ -306,6 +307,7 @@ "device_auth.temporarily_unavailable_help_text": "No momento, não conseguimos verificar seu dispositivo devido a problemas no servidor. Por favor, tente novamente mais tarde.", "device_auth.unofficial_device_detected": "Dispositivo não oficial detectado", "device_auth.unofficial_device_detected_help_text": "Seu dispositivo não pôde ser verificado como oficial. Por favor, entre em contato conosco imediatamente.", + "device_auth.verifying_component_label": "Em andamento", "device_auth.verifying_desc": "Por favor, aguarde...", "device_auth.verifying_title": "Verificando dispositivo", "dont_have_mobile_app_yet": "Ainda não tem o aplicativo móvel?", diff --git a/packages/shared/src/locale/json/ru.json b/packages/shared/src/locale/json/ru.json index e21c1a305ce..b6a0aa34e10 100644 --- a/packages/shared/src/locale/json/ru.json +++ b/packages/shared/src/locale/json/ru.json @@ -297,6 +297,7 @@ "date.yesterday": "Вчера", "derivation_path": "Путь производного", "description_403": "Наши услуги недоступны в вашем регионе.", + "device_auth.certificate": "Сертификат", "device_auth.continue_anyway_warning_message": "В настоящее время мы не можем проверить ваше устройство. Продолжение может создать угрозы безопасности.", "device_auth.request_desc": "Подтвердите на вашем устройстве, чтобы проверить его подлинность и обеспечить безопасность вашего соединения.", "device_auth.request_title": "Аутентификация устройства", @@ -306,6 +307,7 @@ "device_auth.temporarily_unavailable_help_text": "В настоящее время мы не можем проверить ваше устройство из-за проблем с сервером. Пожалуйста, попробуйте снова позже.", "device_auth.unofficial_device_detected": "Обнаружено неофициальное устройство", "device_auth.unofficial_device_detected_help_text": "Ваше устройство не может быть проверено как официальное. Пожалуйста, немедленно свяжитесь с нами.", + "device_auth.verifying_component_label": "В ходе выполнения", "device_auth.verifying_desc": "Пожалуйста, подождите...", "device_auth.verifying_title": "Проверка устройства", "dont_have_mobile_app_yet": "У вас еще нет мобильного приложения?", diff --git a/packages/shared/src/locale/json/th_TH.json b/packages/shared/src/locale/json/th_TH.json index 42d34cc7a9c..72559ad5c1d 100644 --- a/packages/shared/src/locale/json/th_TH.json +++ b/packages/shared/src/locale/json/th_TH.json @@ -297,6 +297,7 @@ "date.yesterday": "เมื่อวานนี้", "derivation_path": "เส้นทางการสืบทอด", "description_403": "บริการของเราไม่มีให้บริการในภูมิภาคของคุณ", + "device_auth.certificate": "ใบรับรอง", "device_auth.continue_anyway_warning_message": "ขณะนี้เราไม่สามารถยืนยันอุปกรณ์ของคุณได้ การดำเนินการต่ออาจเป็นความเสี่ยงต่อความปลอดภัย", "device_auth.request_desc": "ยืนยันบนอุปกรณ์ของคุณเพื่อตรวจสอบความถูกต้องและรักษาความปลอดภัยของการเชื่อมต่อของคุณ", "device_auth.request_title": "การตรวจสอบความถูกต้องของอุปกรณ์", @@ -306,6 +307,7 @@ "device_auth.temporarily_unavailable_help_text": "ขณะนี้เราไม่สามารถยืนยันอุปกรณ์ของคุณได้เนื่องจากปัญหาเซิร์ฟเวอร์ กรุณาลองใหม่อีกครั้งในภายหลัง", "device_auth.unofficial_device_detected": "ตรวจพบอุปกรณ์ที่ไม่เป็นทางการ", "device_auth.unofficial_device_detected_help_text": "ไม่สามารถยืนยันอุปกรณ์ของคุณว่าเป็นอย่างทางการ กรุณาติดต่อเราทันที", + "device_auth.verifying_component_label": "อยู่ระหว่างดำเนินการ", "device_auth.verifying_desc": "กรุณารอสักครู่...", "device_auth.verifying_title": "กำลังตรวจสอบอุปกรณ์", "dont_have_mobile_app_yet": "ยังไม่มีแอปมือถือหรือ?", diff --git a/packages/shared/src/locale/json/uk_UA.json b/packages/shared/src/locale/json/uk_UA.json index 4de3cc95b57..8cd34197cfc 100644 --- a/packages/shared/src/locale/json/uk_UA.json +++ b/packages/shared/src/locale/json/uk_UA.json @@ -297,6 +297,7 @@ "date.yesterday": "Вчора", "derivation_path": "Шлях похідного", "description_403": "Наші послуги недоступні у вашому регіоні.", + "device_auth.certificate": "Сертифікат", "device_auth.continue_anyway_warning_message": "Наразі ми не можемо перевірити ваш пристрій. Продовження може становити ризик для безпеки.", "device_auth.request_desc": "Підтвердіть на своєму пристрої, щоб перевірити його автентичність та захистити своє з'єднання.", "device_auth.request_title": "Аутентифікація пристрою", @@ -306,6 +307,7 @@ "device_auth.temporarily_unavailable_help_text": "Наразі ми не можемо перевірити ваш пристрій через проблеми з сервером. Будь ласка, спробуйте знову пізніше.", "device_auth.unofficial_device_detected": "Виявлено неофіційний пристрій", "device_auth.unofficial_device_detected_help_text": "Ваш пристрій не може бути перевірений як офіційний. Будь ласка, негайно зв'яжіться з нами.", + "device_auth.verifying_component_label": "В роботі", "device_auth.verifying_desc": "Будь ласка, зачекайте...", "device_auth.verifying_title": "Перевірка пристрою", "dont_have_mobile_app_yet": "Ще не маєте мобільного додатку?", diff --git a/packages/shared/src/locale/json/vi.json b/packages/shared/src/locale/json/vi.json index 3f5209b0fe6..57a3f1b8c8c 100644 --- a/packages/shared/src/locale/json/vi.json +++ b/packages/shared/src/locale/json/vi.json @@ -297,6 +297,7 @@ "date.yesterday": "Hôm qua", "derivation_path": "Đường dẫn xuất phát", "description_403": "Dịch vụ của chúng tôi không có sẵn ở khu vực của bạn.", + "device_auth.certificate": "Giấy chứng nhận", "device_auth.continue_anyway_warning_message": "Chúng tôi hiện không thể xác minh thiết bị của bạn. Việc tiếp tục có thể gây ra rủi ro về an ninh.", "device_auth.request_desc": "Xác nhận trên thiết bị của bạn để xác minh tính xác thực của nó và bảo mật kết nối của bạn.", "device_auth.request_title": "Xác thực thiết bị", @@ -306,6 +307,7 @@ "device_auth.temporarily_unavailable_help_text": "Hiện tại, chúng tôi không thể xác minh thiết bị của bạn do sự cố máy chủ. Vui lòng thử lại sau.", "device_auth.unofficial_device_detected": "Đã phát hiện thiết bị không chính thức", "device_auth.unofficial_device_detected_help_text": "Thiết bị của bạn không thể được xác minh là chính thức. Vui lòng liên hệ với chúng tôi ngay lập tức.", + "device_auth.verifying_component_label": "Đang tiến hành", "device_auth.verifying_desc": "Vui lòng đợi...", "device_auth.verifying_title": "Xác minh thiết bị", "dont_have_mobile_app_yet": "Chưa có ứng dụng di động?", diff --git a/packages/shared/src/locale/json/zh_CN.json b/packages/shared/src/locale/json/zh_CN.json index 29da3416206..0365ba742aa 100644 --- a/packages/shared/src/locale/json/zh_CN.json +++ b/packages/shared/src/locale/json/zh_CN.json @@ -297,6 +297,7 @@ "date.yesterday": "昨天", "derivation_path": "派生路径", "description_403": "我们的服务在您的地区无法使用", + "device_auth.certificate": "证书", "device_auth.continue_anyway_warning_message": "我们目前无法验证您的设备。继续操作可能会带来安全风险。", "device_auth.request_desc": "在您的设备上确认以验证其真实性并保护您的连接。", "device_auth.request_title": "设备验证", @@ -306,6 +307,7 @@ "device_auth.temporarily_unavailable_help_text": "由于服务器问题,我们目前无法验证您的设备,请稍后再试。", "device_auth.unofficial_device_detected": "检测到非官方设备", "device_auth.unofficial_device_detected_help_text": "您的设备无法被验证为官方设备,请立即与我们联系。", + "device_auth.verifying_component_label": "进行中", "device_auth.verifying_desc": "请稍等...", "device_auth.verifying_title": "正在验证设备", "dont_have_mobile_app_yet": "还没有移动端 App 吗?", diff --git a/packages/shared/src/locale/json/zh_HK.json b/packages/shared/src/locale/json/zh_HK.json index 8d817834950..4390b8d0029 100644 --- a/packages/shared/src/locale/json/zh_HK.json +++ b/packages/shared/src/locale/json/zh_HK.json @@ -297,6 +297,7 @@ "date.yesterday": "昨天", "derivation_path": "派生路徑", "description_403": "我們的服務在您的地區並不提供", + "device_auth.certificate": "證書", "device_auth.continue_anyway_warning_message": "我們目前無法驗證您的設備。繼續操作可能會帶來安全風險。", "device_auth.request_desc": "在您的裝置上確認以驗證其真實性並確保您的連線安全。", "device_auth.request_title": "設備驗證", @@ -306,6 +307,7 @@ "device_auth.temporarily_unavailable_help_text": "目前,由於伺服器問題,我們無法驗證您的裝置,請稍後再試。", "device_auth.unofficial_device_detected": "偵測到非官方裝置", "device_auth.unofficial_device_detected_help_text": "您的裝置無法通過官方驗證,請立即與我們聯繫。", + "device_auth.verifying_component_label": "進行中", "device_auth.verifying_desc": "請稍等...", "device_auth.verifying_title": "正在驗證裝置", "dont_have_mobile_app_yet": "還沒有移動端 App 嗎?", diff --git a/packages/shared/src/locale/json/zh_TW.json b/packages/shared/src/locale/json/zh_TW.json index dd53062f989..be998f38af5 100644 --- a/packages/shared/src/locale/json/zh_TW.json +++ b/packages/shared/src/locale/json/zh_TW.json @@ -297,6 +297,7 @@ "date.yesterday": "昨天", "derivation_path": "導出路徑", "description_403": "我們的服務在您的地區無法使用", + "device_auth.certificate": "證書", "device_auth.continue_anyway_warning_message": "我們目前無法驗證您的裝置。繼續操作可能會帶來安全風險。", "device_auth.request_desc": "請在您的裝置上確認以驗證其真實性並保護您的連接安全。", "device_auth.request_title": "裝置驗證", @@ -306,6 +307,7 @@ "device_auth.temporarily_unavailable_help_text": "目前,由於伺服器問題,我們無法驗證您的裝置,請稍後再試。", "device_auth.unofficial_device_detected": "偵測到非官方裝置", "device_auth.unofficial_device_detected_help_text": "您的裝置無法被驗證為官方,請立即與我們聯繫。", + "device_auth.verifying_component_label": "進行中", "device_auth.verifying_desc": "請稍候...", "device_auth.verifying_title": "正在驗證裝置", "dont_have_mobile_app_yet": "還沒有手機 App 嗎?", diff --git a/packages/shared/src/logger/scopes/hardware/index.ts b/packages/shared/src/logger/scopes/hardware/index.ts index d5351948f29..be4c3f51283 100644 --- a/packages/shared/src/logger/scopes/hardware/index.ts +++ b/packages/shared/src/logger/scopes/hardware/index.ts @@ -3,6 +3,7 @@ import { EScopeName } from '../../types'; import { HardwareHomeScreenScene } from './scenes/homescreen'; import { HardwareSDKScene } from './scenes/sdk'; +import { HardwareVerifyScene } from './scenes/verify'; export class HardwareScope extends BaseScope { protected override scopeName = EScopeName.hardware; @@ -10,4 +11,6 @@ export class HardwareScope extends BaseScope { sdkLog = this.createScene('sdkLog', HardwareSDKScene); homescreen = this.createScene('homescreen', HardwareHomeScreenScene); + + verify = this.createScene('verify', HardwareVerifyScene); } diff --git a/packages/shared/src/logger/scopes/hardware/scenes/verify.ts b/packages/shared/src/logger/scopes/hardware/scenes/verify.ts new file mode 100644 index 00000000000..e31fb8318a9 --- /dev/null +++ b/packages/shared/src/logger/scopes/hardware/scenes/verify.ts @@ -0,0 +1,21 @@ +import type { IAllDeviceVerifyVersions } from '@onekeyhq/shared/types/device'; + +import { BaseScene } from '../../../base/baseScene'; +import { LogToLocal } from '../../../base/decorators'; + +export class HardwareVerifyScene extends BaseScene { + @LogToLocal() + public verifyFailed(params: { + local: IAllDeviceVerifyVersions; + server: IAllDeviceVerifyVersions; + }) { + return { + localFirmware: params.local.firmware.raw, + localBluetooth: params.local.bluetooth.raw, + localBootloader: params.local.bootloader.raw, + serverFirmware: params.server.firmware.raw, + serverBluetooth: params.server.bluetooth.raw, + serverBootloader: params.server.bootloader.raw, + }; + } +} diff --git a/packages/shared/src/utils/deviceUtils.ts b/packages/shared/src/utils/deviceUtils.ts index 42e7ad9091b..c3171faf9d6 100644 --- a/packages/shared/src/utils/deviceUtils.ts +++ b/packages/shared/src/utils/deviceUtils.ts @@ -6,6 +6,7 @@ import { EHardwareUiStateAction } from '@onekeyhq/kit-bg/src/states/jotai/atoms' import { EFirmwareUpdateTipMessages, + EFirmwareVerifyType, EOneKeyDeviceMode, } from '../../types/device'; import bleManagerInstance from '../hardware/bleManager'; @@ -15,10 +16,20 @@ import platformEnv from '../platformEnv'; import { DeviceScannerUtils } from './DeviceScannerUtils'; import type { + IAllDeviceVerifyVersions, + IDeviceVerifyRawVersions, + IDeviceVerifyVersions, + IFetchFirmwareVerifyHashParams, + IFirmwareVerifyInfo, IOneKeyDeviceFeatures, IOneKeyDeviceType, } from '../../types/device'; -import type { IDeviceType, KnownDevice, SearchDevice } from '@onekeyfe/hd-core'; +import type { + IDeviceType, + KnownDevice, + OnekeyFeatures, + SearchDevice, +} from '@onekeyfe/hd-core'; type IGetDeviceVersionParams = { device: SearchDevice | undefined; @@ -232,6 +243,152 @@ async function buildDeviceName({ ); } +async function getDeviceVerifyVersionsFromFeatures({ + deviceType, + features, +}: { + deviceType?: IDeviceType; + features: OnekeyFeatures | IOneKeyDeviceFeatures; +}): Promise { + let finalDeviceType = deviceType; + if (!deviceType) { + finalDeviceType = await getDeviceTypeFromFeatures({ + features: features as IOneKeyDeviceFeatures, + }); + } + if (!finalDeviceType || finalDeviceType === 'unknown') { + return null; + } + + const { + onekey_firmware_version: onekeyFirmwareVersion, + onekey_ble_version: onekeyBleVersion, + onekey_boot_version: onekeyBootVersion, + } = features; + if (!onekeyFirmwareVersion || !onekeyBleVersion || !onekeyBootVersion) { + return null; + } + + return { + deviceType: finalDeviceType, + firmwareVersion: onekeyFirmwareVersion, + bluetoothVersion: onekeyBleVersion, + bootloaderVersion: onekeyBootVersion, + }; +} + +function formatVersionWithHash( + rawVersion: IDeviceVerifyRawVersions, +): IDeviceVerifyVersions { + const { version, checksum, commitId, releaseUrl } = rawVersion; + + if (!version) { + return { + raw: { version, checksum, commitId }, + formatted: '', + }; + } + + if (!checksum || !commitId) { + return { + raw: { version, checksum, commitId }, + formatted: '-', + }; + } + + let validatedReleaseUrl: string | undefined; + + try { + if (releaseUrl) { + // eslint-disable-next-line no-new + new URL(releaseUrl); + validatedReleaseUrl = releaseUrl; + } + } catch { + // ignore + } + + return { + raw: { version, checksum, commitId }, + releaseUrl: validatedReleaseUrl, + formatted: `${version} (${commitId}-${checksum.slice(0, 7)})`, + }; +} + +export function parseLocalDeviceVersions({ + onekeyFeatures, +}: { + onekeyFeatures: OnekeyFeatures; +}): IAllDeviceVerifyVersions { + return { + firmware: formatVersionWithHash({ + version: onekeyFeatures.onekey_firmware_version, + checksum: onekeyFeatures.onekey_firmware_hash, + commitId: onekeyFeatures.onekey_firmware_build_id, + }), + bluetooth: formatVersionWithHash({ + version: onekeyFeatures.onekey_ble_version, + checksum: onekeyFeatures.onekey_ble_hash, + commitId: onekeyFeatures.onekey_ble_build_id, + }), + bootloader: formatVersionWithHash({ + version: onekeyFeatures.onekey_boot_version, + checksum: onekeyFeatures.onekey_boot_hash, + commitId: onekeyFeatures.onekey_boot_build_id, + }), + }; +} + +export function parseServerVersionInfos({ + serverVerifyInfos, +}: { + serverVerifyInfos: IFirmwareVerifyInfo[]; +}): IAllDeviceVerifyVersions { + const defaultVersion: IDeviceVerifyVersions = { + raw: { version: '', checksum: '', commitId: '' }, + formatted: '', + }; + + const result: IAllDeviceVerifyVersions = { + firmware: defaultVersion, + bluetooth: defaultVersion, + bootloader: defaultVersion, + }; + + // loop through server verify infos + serverVerifyInfos.forEach((item) => { + switch (item.type) { + case EFirmwareVerifyType.System: + result.firmware = formatVersionWithHash(item); + break; + case EFirmwareVerifyType.Bluetooth: + result.bluetooth = formatVersionWithHash(item); + break; + case EFirmwareVerifyType.Bootloader: + result.bootloader = formatVersionWithHash(item); + break; + default: + break; + } + }); + + return result; +} + +export function compareDeviceVersions({ + local, + remote, +}: { + local: IDeviceVerifyRawVersions; + remote: IDeviceVerifyRawVersions; +}): boolean { + return ( + local.version === remote.version && + local.checksum === remote.checksum && + local.commitId === remote.commitId + ); +} + export default { dbDeviceToSearchDevice, getDeviceVersion, @@ -248,4 +405,9 @@ export default { checkDeviceBonded, buildDeviceLabel, buildDeviceName, + getDeviceVerifyVersionsFromFeatures, + formatVersionWithHash, + parseLocalDeviceVersions, + parseServerVersionInfos, + compareDeviceVersions, }; diff --git a/packages/shared/types/device.ts b/packages/shared/types/device.ts index ab22f84ea89..8c5a1f23b56 100644 --- a/packages/shared/types/device.ts +++ b/packages/shared/types/device.ts @@ -275,3 +275,67 @@ export enum EFirmwareUpdateTipMessages { 11. ConfirmOnDevice 12. InstallingFirmware */ + +export enum EFirmwareVerifyType { + System = 'system', + Bluetooth = 'bluetooth', + Bootloader = 'bootloader', +} + +export interface IFirmwareVerifyInfo { + deviceType: IDeviceType; + type: EFirmwareVerifyType; + version: string; + checksum: string; + commitId: string; + releaseUrl: string; +} + +export interface IFetchFirmwareVerifyHashParams { + deviceType: IDeviceType; + firmwareVersion: string; + bluetoothVersion: string; + bootloaderVersion: string; +} + +export interface IDeviceVerifyRawVersions { + version?: string; + checksum?: string; + commitId?: string; + releaseUrl?: string; +} + +export interface IDeviceVerifyVersions { + raw: IDeviceVerifyRawVersions; + formatted: string; + releaseUrl?: string; +} + +export interface IAllDeviceVerifyVersions { + firmware: IDeviceVerifyVersions; + bluetooth: IDeviceVerifyVersions; + bootloader: IDeviceVerifyVersions; +} + +export interface IDeviceVerifyVersionCompareResult { + certificate: { + isMatch: boolean; + format: string; + releaseUrl?: string; + }; + firmware: { + isMatch: boolean; + format: string; + releaseUrl?: string; + }; + bluetooth: { + isMatch: boolean; + format: string; + releaseUrl?: string; + }; + bootloader: { + isMatch: boolean; + format: string; + releaseUrl?: string; + }; +}