Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: kk desktop migrate #8927

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions react-app-rewired/headers/csps/wallets/keepkey.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import type { Csp } from '../../types'

export const csp: Csp = {
'connect-src': [
process.env.REACT_APP_KEEPKEY_FIRMWARE_RELEASES_URL!,
process.env.REACT_APP_KEEPKEY_GITHUB_RELEASES_API_URL!,
process.env.REACT_APP_KEEPKEY_VERSIONS_URL!,
process.env.REACT_APP_KEEPKEY_DESKTOP_URL!,
],
Expand Down
10 changes: 8 additions & 2 deletions src/components/Layout/Header/NavBar/KeepKey/KeepKeyMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import { SubmenuHeader } from 'components/Layout/Header/NavBar/SubmenuHeader'
import { WalletImage } from 'components/Layout/Header/NavBar/WalletImage'
import { RawText, Text } from 'components/Text'
import { WalletActions } from 'context/WalletProvider/actions'
import { useKeepKeyVersions } from 'context/WalletProvider/KeepKey/hooks/useKeepKeyVersions'
import { useKeepKey } from 'context/WalletProvider/KeepKeyProvider'
import { useModal } from 'hooks/useModal/useModal'
Expand Down Expand Up @@ -50,10 +51,11 @@
const {
state: { deviceTimeout, features },
} = useKeepKey()
const { versions, updaterUrl } = useKeepKeyVersions()

Check failure on line 54 in src/components/Layout/Header/NavBar/KeepKey/KeepKeyMenu.tsx

View workflow job for this annotation

GitHub Actions / Call / Static

'updaterUrl' is assigned a value but never used. Allowed unused vars must match /^_/u
const {
setDeviceState,
state: { isConnected, walletInfo },
dispatch,
} = useWallet()
const keepKeyWipe = useModal('keepKeyWipe')

Expand Down Expand Up @@ -81,6 +83,10 @@
keepKeyWipe.open({})
}

const handleUpdateClick = useCallback(() => {
dispatch({ type: WalletActions.DOWNLOAD_UPDATER, payload: false })
}, [dispatch])

const deviceTimeoutTranslation: string =
typeof deviceTimeout?.label === 'object'
? translate(...deviceTimeout?.label)
Expand Down Expand Up @@ -134,7 +140,7 @@
badgeColor={versions?.bootloader.updateAvailable ? 'yellow' : 'green'}
valueDisposition={versions?.bootloader.updateAvailable ? 'info' : 'neutral'}
isDisabled={!versions?.bootloader.updateAvailable}
externalUrl={updaterUrl}
onClick={handleUpdateClick}
/>
<ExpandedMenuItem
label='walletProvider.keepKey.settings.menuLabels.firmware'
Expand All @@ -143,7 +149,7 @@
badgeColor={versions?.firmware.updateAvailable ? 'yellow' : 'green'}
valueDisposition={versions?.firmware.updateAvailable ? 'info' : 'neutral'}
isDisabled={!versions?.firmware.updateAvailable}
externalUrl={updaterUrl}
onClick={handleUpdateClick}
/>
<MenuDivider />
<ExpandedMenuItem
Expand Down
18 changes: 12 additions & 6 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,15 +108,21 @@ const validators = {
REACT_APP_COWSWAP_BASE_URL: url({
default: 'https://api.cow.fi',
}),
REACT_APP_KEEPKEY_FIRMWARE_RELEASES_URL: url({
default: 'https://raw.githack.com/keepkey/keepkey-desktop/master/firmware/releases.json',
}),
REACT_APP_KEEPKEY_GITHUB_RELEASES_API_URL: url({
default: 'https://api.github.com/repos/keepkey/keepkey-desktop/releases/latest',
}),
REACT_APP_KEEPKEY_RELEASES_PAGE: url({
default: 'https://github.com/keepkey/keepkey-desktop/releases/latest',
}),
REACT_APP_KEEPKEY_DESKTOP_URL: url({
default: 'http://localhost:1646/',
}),
REACT_APP_ONRAMPER_WIDGET_URL: url(),
REACT_APP_ONRAMPER_API_URL: url(),
REACT_APP_ONRAMPER_API_KEY: str(),
REACT_APP_KEEPKEY_UPDATER_RELEASE_PAGE: url({
default: 'https://github.com/keepkey/keepkey-updater/releases/latest',
}),
REACT_APP_KEEPKEY_UPDATER_BASE_URL: url({
default: 'https://github.com/keepkey/keepkey-updater/releases/download/v2.1.4/',
}),
REACT_APP_ETHERSCAN_API_KEY: str({ default: 'XT8BI6VDYUGD9675X861ATHZNK3AN6HRMF' }),
REACT_APP_MIXPANEL_TOKEN: str(),
REACT_APP_SNAPSHOT_BASE_URL: url({
Expand Down
241 changes: 227 additions & 14 deletions src/context/WalletProvider/KeepKey/components/DownloadUpdaterApp.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,128 @@
import { Button, Icon, Link, ModalBody, ModalHeader, Text as CText } from '@chakra-ui/react'
import { useMemo } from 'react'
import { Button, Icon, ModalBody, ModalHeader, Text as CText, Spinner, useToast } from '@chakra-ui/react'

Check failure on line 1 in src/context/WalletProvider/KeepKey/components/DownloadUpdaterApp.tsx

View workflow job for this annotation

GitHub Actions / Call / Static

Run autofix to sort these imports!

Check failure on line 1 in src/context/WalletProvider/KeepKey/components/DownloadUpdaterApp.tsx

View workflow job for this annotation

GitHub Actions / Call / Static

Replace `·Button,·Icon,·ModalBody,·ModalHeader,·Text·as·CText,·Spinner,·useToast·` with `⏎··Button,⏎··Icon,⏎··ModalBody,⏎··ModalHeader,⏎··Text·as·CText,⏎··Spinner,⏎··useToast,⏎`
import axios from 'axios'
import { useEffect, useMemo, useState, useCallback } from 'react'
import { FaApple, FaLinux, FaWindows } from 'react-icons/fa'
import { Text } from 'components/Text'
import type { TextPropTypes } from 'components/Text/Text'
import { getConfig } from 'config'

import { getPlatform, RELEASE_PAGE, UPDATER_BASE_URL } from '../helpers'
const RELEASE_PAGE = getConfig().REACT_APP_KEEPKEY_RELEASES_PAGE
const GITHUB_API_URL = getConfig().REACT_APP_KEEPKEY_GITHUB_RELEASES_API_URL

// Interface for GitHub release assets
interface GithubReleaseAsset {
name: string;

Check failure on line 14 in src/context/WalletProvider/KeepKey/components/DownloadUpdaterApp.tsx

View workflow job for this annotation

GitHub Actions / Call / Static

Delete `;`
browser_download_url: string;

Check failure on line 15 in src/context/WalletProvider/KeepKey/components/DownloadUpdaterApp.tsx

View workflow job for this annotation

GitHub Actions / Call / Static

Delete `;`
}

// Interface for GitHub release response
interface GithubReleaseResponse {
tag_name: string;

Check failure on line 20 in src/context/WalletProvider/KeepKey/components/DownloadUpdaterApp.tsx

View workflow job for this annotation

GitHub Actions / Call / Static

Delete `;`
assets: GithubReleaseAsset[];

Check failure on line 21 in src/context/WalletProvider/KeepKey/components/DownloadUpdaterApp.tsx

View workflow job for this annotation

GitHub Actions / Call / Static

Delete `;`
body: string;

Check failure on line 22 in src/context/WalletProvider/KeepKey/components/DownloadUpdaterApp.tsx

View workflow job for this annotation

GitHub Actions / Call / Static

Delete `;`
}

export const KeepKeyDownloadUpdaterApp = () => {
const toast = useToast()
const platform = useMemo(() => getPlatform(), [])
const [isLoading, setIsLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [version, setVersion] = useState<string>('')

Check failure on line 31 in src/context/WalletProvider/KeepKey/components/DownloadUpdaterApp.tsx

View workflow job for this annotation

GitHub Actions / Call / Static

Delete `··`
// Use separate state variables for each platform URL
const [urlMacOS, setUrlMacOS] = useState('')
const [urlWindows, setUrlWindows] = useState('')
const [urlLinux, setUrlLinux] = useState('')

// Find latest release links directly from the GitHub API
const findLatestReleaseLinks = useCallback(async () => {
setIsLoading(true)
setError(null)

Check failure on line 41 in src/context/WalletProvider/KeepKey/components/DownloadUpdaterApp.tsx

View workflow job for this annotation

GitHub Actions / Call / Static

Delete `····`
try {
// Use the exact API URL
const resp = await axios<GithubReleaseResponse>({
method: 'GET',
url: GITHUB_API_URL,
headers: {
'Accept': 'application/vnd.github.v3+json',
'User-Agent': 'KeepKey-Desktop-App'
}
})

console.log('findLatestReleaseLinks', resp.data)

if (!resp.data || !resp.data.tag_name || !resp.data.assets) {
throw new Error('Invalid response from GitHub API')
}

// Extract version from tag_name
const versionWithV = resp.data.tag_name
const versionNumber = versionWithV.replace('v', '')
setVersion(versionNumber)

// Find the correct assets by examining the assets array
const assets = resp.data.assets

// Find macOS universal DMG
const macAsset = assets.find(asset =>
asset.name.includes('universal.dmg') ||
asset.name.includes('universal-mac')
)

// Find Windows EXE
const windowsAsset = assets.find(asset =>
asset.name.includes('Setup') && asset.name.endsWith('.exe')
)

// Find Linux AppImage
const linuxAsset = assets.find(asset =>
asset.name.endsWith('.AppImage')
)

// Set the URLs from the assets or construct them if not found
setUrlMacOS(macAsset?.browser_download_url ||
`https://github.com/keepkey/keepkey-desktop/releases/download/v${versionNumber}/KeepKey-Desktop-${versionNumber}-universal.dmg`)

setUrlWindows(windowsAsset?.browser_download_url ||
`https://github.com/keepkey/keepkey-desktop/releases/download/v${versionNumber}/KeepKey-Desktop-Setup-${versionNumber}.exe`)

setUrlLinux(linuxAsset?.browser_download_url ||
`https://github.com/keepkey/keepkey-desktop/releases/download/v${versionNumber}/KeepKey-Desktop-${versionNumber}.AppImage`)

console.log('Download URLs:', {
macOS: macAsset?.browser_download_url,
windows: windowsAsset?.browser_download_url,
linux: linuxAsset?.browser_download_url
})

setError(null)
} catch (e) {
console.error('Error fetching latest version:', e)
setError('Failed to fetch the latest version. Please try again or visit the releases page.')
} finally {
setIsLoading(false)
}
}, [])

// Call the function on component mount
useEffect(() => {
findLatestReleaseLinks()
}, [findLatestReleaseLinks])

const platformFilename = useMemo(() => {
if (isLoading) return null
switch (platform) {
case 'Mac OS':
return 'KeepKey-Updater-2.1.4.dmg'
return `KeepKey Desktop ${version} (macOS)`
case 'Windows':
return 'KeepKey-Updater-Setup-2.1.4.exe'
return `KeepKey Desktop ${version} (Windows)`
case 'Linux':
return 'KeepKey-Updater-2.1.4.AppImage'
return `KeepKey Desktop ${version} (Linux)`
default:
return null
return 'Desktop App'
}
}, [platform])
}, [platform, isLoading, version])

const platformIcon = useMemo(() => {
switch (platform) {
Expand All @@ -43,12 +145,56 @@
const downloadUpdaterTranslation: TextPropTypes['translation'] = useMemo(
() => [
'modals.keepKey.downloadUpdater.button',
{ filename: platformFilename || 'Updater App' },
{ filename: platformFilename || 'Desktop App' },
],
[platformFilename],
)

const updaterUrl = platformFilename ? `${UPDATER_BASE_URL}${platformFilename}` : RELEASE_PAGE
const handleDownload = useCallback(() => {
let downloadUrl = RELEASE_PAGE

// Get the appropriate URL based on platform
switch (platform) {
case 'Mac OS':
downloadUrl = urlMacOS || RELEASE_PAGE
break
case 'Windows':
downloadUrl = urlWindows || RELEASE_PAGE
break
case 'Linux':
downloadUrl = urlLinux || RELEASE_PAGE
break
}

if (!downloadUrl || downloadUrl === RELEASE_PAGE) {
// If we don't have a specific URL, open the releases page
window.open(RELEASE_PAGE, '_blank')
return
}

// Create a temporary link element for better download handling
const link = document.createElement('a')
link.href = downloadUrl
link.rel = 'noopener noreferrer'

// Append to body, click, and remove
document.body.appendChild(link)
link.click()
document.body.removeChild(link)

// Show a toast notification
toast({
title: 'Download Started',
description: 'Your download should begin shortly',
status: 'success',
duration: 5000,
isClosable: true,
})
}, [platform, urlMacOS, urlWindows, urlLinux, toast])

const handleRetry = useCallback(() => {
findLatestReleaseLinks()
}, [findLatestReleaseLinks])

return (
<>
Expand All @@ -60,15 +206,82 @@
{platform && (
<>
<CText fontWeight='bold'>{platform}</CText>
<Link isExternal href={RELEASE_PAGE}>
<Text color='text.subtle' translation={wrongPlatformTranslation} mb={2} />
</Link>
<Button variant='link' onClick={() => window.open(RELEASE_PAGE, '_blank')} mb={2}>
<Text color='text.subtle' translation={wrongPlatformTranslation} />
</Button>
</>
)}
<Button as={Link} width='full' isExternal href={updaterUrl} colorScheme='blue' mt={2}>

{!isLoading && !error && version && (
<CText color="green.500" mb={4} fontSize="sm">
Latest version: {version}
</CText>
)}

{error && (
<>
<CText color="red.500" mb={2}>{error}</CText>
<Button
variant='outline'
colorScheme='blue'
size='sm'
onClick={handleRetry}
mb={4}
isDisabled={isLoading}
>
Retry
</Button>
<Button
variant='outline'
colorScheme='blue'
size='sm'
onClick={() => window.open(RELEASE_PAGE, '_blank')}
ml={2}
mb={4}
>
Go to Releases Page
</Button>
</>
)}

<Button
width='full'
onClick={handleDownload}
colorScheme='blue'
mt={2}
isDisabled={isLoading}
>
{isLoading ? (
<Spinner size="sm" mr={2} />
) : null}
<Text translation={downloadUpdaterTranslation} />
</Button>
</ModalBody>
</>
)
}

const getPlatform = () => {
const platform = navigator?.platform
const macosPlatforms = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K']
const windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE']

if (macosPlatforms.includes(platform)) {
return 'Mac OS'
} else if (windowsPlatforms.includes(platform)) {
return 'Windows'
} else if (/Linux/.test(platform)) {
return 'Linux'
}

const userAgent = navigator.userAgent.toLowerCase()
if (userAgent.includes('mac')) {
return 'Mac OS'
} else if (userAgent.includes('win')) {
return 'Windows'
} else if (userAgent.includes('linux')) {
return 'Linux'
}

return null
}
4 changes: 0 additions & 4 deletions src/context/WalletProvider/KeepKey/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
import type { RecoverDevice } from '@shapeshiftoss/hdwallet-core'
import { getConfig } from 'config'
import type { KeyboardEvent } from 'react'
import { VALID_ENTROPY_NUMBERS } from 'context/WalletProvider/KeepKey/components/RecoverySettings'

export const RELEASE_PAGE = getConfig().REACT_APP_KEEPKEY_UPDATER_RELEASE_PAGE
export const UPDATER_BASE_URL = getConfig().REACT_APP_KEEPKEY_UPDATER_BASE_URL

export const isValidInput = (
e: KeyboardEvent,
wordEntropy: number,
Expand Down
Loading