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

fix: ct-1036 #912

Merged
merged 6 commits into from
Jul 6, 2023
Merged
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
35 changes: 31 additions & 4 deletions apps/extension/src/core/handlers/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { DEBUG, PORT_EXTENSION } from "@core/constants"
import { PORT_EXTENSION } from "@core/constants"
import { AnyEthRequest } from "@core/injectEth/types"
import { log } from "@core/log"
import { assert } from "@polkadot/util"
Expand All @@ -12,6 +12,22 @@ import Tabs from "./Tabs"
const extension = new Extension(extensionStores)
const tabs = new Tabs(tabStores)

// dev mode logs shouldn't log content for these messages
const OBFUSCATE_LOG_MESSAGES: MessageTypes[] = [
"pri(mnemonic.unlock)",
"pri(app.authenticate)",
"pri(app.checkPassword)",
"pri(app.changePassword)",
"pri(accounts.export)",
"pri(accounts.export.pk)",
"pri(accounts.validateMnemonic)",
"pri(accounts.create.seed)",
"pri(accounts.create.json)",
"pri(accounts.setVerifierCertMnemonic)",
"pri(app.onboard)",
]
const OBFUSCATED_PAYLOAD = "#OBFUSCATED#"

const formatFrom = (source: string) => {
if (["extension", "<unknown>"].includes(source)) return source
if (!source) return source
Expand All @@ -35,9 +51,10 @@ const talismanHandler = <TMessageType extends MessageTypes>(
const source = `${formatFrom(from)}: ${id}: ${
message === "pub(eth.request)" ? `${message} ${(request as AnyEthRequest).method}` : message
}`
const shouldLog = !OBFUSCATE_LOG_MESSAGES.includes(message)

// eslint-disable-next-line no-console
DEBUG && console.debug(`[${port.name} REQ] ${source}`, { request })
log.debug(`[${port.name} REQ] ${source}`, { request: shouldLog ? request : OBFUSCATED_PAYLOAD })

// handle the request and get a promise as a response
const promise = isExtension
Expand All @@ -47,7 +64,10 @@ const talismanHandler = <TMessageType extends MessageTypes>(
// resolve the promise and send back the response
promise
.then((response): void => {
log.debug(`[${port.name} RES] ${source}`, { request, response })
log.debug(`[${port.name} RES] ${source}`, {
request: shouldLog ? request : OBFUSCATED_PAYLOAD,
response: shouldLog ? response : OBFUSCATED_PAYLOAD,
})

// between the start and the end of the promise, the user may have closed
// the tab, in which case port will be undefined
Expand All @@ -63,9 +83,12 @@ const talismanHandler = <TMessageType extends MessageTypes>(
}
throw e
}

// heap cleanup
response = null
})
.catch((error) => {
log.debug(`[err] ${source}:: ${error.message}`, { error })
log.error(`[${port.name} ERR] ${source}:: ${error.message}`, { error })

if (
error instanceof Error &&
Expand Down Expand Up @@ -97,6 +120,10 @@ const talismanHandler = <TMessageType extends MessageTypes>(
}
}
})
.finally(() => {
// heap cleanup
data.request = null
})
}

export default talismanHandler
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { api } from "@ui/api"
import Layout from "@ui/apps/dashboard/layout"
import { MnemonicModal } from "@ui/domains/Settings/MnemonicModal"
import useMnemonicBackup from "@ui/hooks/useMnemonicBackup"
import { useCallback } from "react"
import { useCallback, useEffect, useMemo } from "react"
import { useForm } from "react-hook-form"
import { useTranslation } from "react-i18next"
import { useNavigate } from "react-router-dom"
Expand All @@ -26,22 +26,27 @@ const ChangePassword = () => {
const { isNotConfirmed } = useMnemonicBackup()
const { isOpen, open, close } = useOpenClose()

const schema = yup
.object({
currentPw: yup.string().required(""),
newPw: yup.string().required("").min(6, t("Password must be at least 6 characters long")),
newPwConfirm: yup
.string()
.required("")
.oneOf([yup.ref("newPw")], t("Passwords must match!")),
})
.required()
const schema = useMemo(
() =>
yup
.object({
currentPw: yup.string().required(""),
newPw: yup.string().required("").min(6, t("Password must be at least 6 characters long")),
newPwConfirm: yup
.string()
.required("")
.oneOf([yup.ref("newPw")], t("Passwords must match!")),
})
.required(),
[t]
)

const {
register,
handleSubmit,
formState: { errors, isValid, isSubmitting },
setError,
setValue,
} = useForm<FormData>({
mode: "onChange",
resolver: yupResolver(schema),
Expand Down Expand Up @@ -73,6 +78,14 @@ const ChangePassword = () => {
[navigate, setError, t]
)

useEffect(() => {
return () => {
setValue("currentPw", "")
setValue("newPw", "")
setValue("newPwConfirm", "")
}
}, [setValue])

return (
<>
<Layout withBack centered>
Expand Down
6 changes: 6 additions & 0 deletions apps/extension/src/ui/apps/onboard/context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,12 @@ const useAppOnboardProvider = ({ isResettingWallet = false }: { isResettingWalle
})
}, [data.allowTracking])

useEffect(() => {
return () => {
setData(DEFAULT_DATA)
}
}, [])

return {
onboard,
reset,
Expand Down
9 changes: 8 additions & 1 deletion apps/extension/src/ui/apps/onboard/routes/ImportSeed.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { yupResolver } from "@hookform/resolvers/yup"
import { api } from "@ui/api"
import { AnalyticsPage, sendAnalyticsEvent } from "@ui/api/analytics"
import { useAnalyticsPageView } from "@ui/hooks/useAnalyticsPageView"
import { useCallback, useMemo } from "react"
import { useCallback, useEffect, useMemo } from "react"
import { useForm } from "react-hook-form"
import { Trans, useTranslation } from "react-i18next"
import { useNavigate } from "react-router-dom"
Expand Down Expand Up @@ -61,6 +61,7 @@ export const ImportSeedPage = () => {
const {
register,
handleSubmit,
setValue,
formState: { errors, isValid },
} = useForm<FormData>({
mode: "onChange",
Expand All @@ -85,6 +86,12 @@ export const ImportSeedPage = () => {
[data.importAccountType, data.importMethodType, navigate, updateData]
)

useEffect(() => {
return () => {
setValue("mnemonic", "")
}
}, [setValue])

return (
<Layout withBack analytics={ANALYTICS_PAGE}>
<div className="flex justify-center">
Expand Down
8 changes: 8 additions & 0 deletions apps/extension/src/ui/apps/onboard/routes/Password.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ export const PasswordPage = () => {
handleSubmit,
watch,
trigger,
setValue,
formState: { errors, isValid, isSubmitting },
} = useForm<FormData>({
mode: "all",
Expand Down Expand Up @@ -99,6 +100,13 @@ export const PasswordPage = () => {
]
}, [data, t])

useEffect(() => {
return () => {
setValue("password", "")
setValue("passwordConfirm", "")
}
}, [setValue])

return (
<Layout withBack analytics={ANALYTICS_PAGE}>
<div className="flex justify-center">
Expand Down
6 changes: 6 additions & 0 deletions apps/extension/src/ui/apps/popup/pages/Login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,12 @@ const Login = ({ setShowResetWallet }: { setShowResetWallet: () => void }) => {
}
}, [handleSubmit, setValue, submit])

useEffect(() => {
return () => {
setValue("password", "")
}
}, [setValue])

return (
<Layout className="pt-32">
<Suspense fallback={<SuspenseTracker name="Background" />}>
Expand Down
8 changes: 8 additions & 0 deletions apps/extension/src/ui/domains/Account/AccountExportModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ const ExportAccountForm = ({ onSuccess }: { onSuccess?: () => void }) => {
formState: { errors, isValid, isSubmitting },
watch,
setError,
setValue,
} = useForm<FormData>({
mode: "onChange",
resolver: yupResolver(schema),
Expand All @@ -99,6 +100,13 @@ const ExportAccountForm = ({ onSuccess }: { onSuccess?: () => void }) => {
[exportAccount, setError, onSuccess, password]
)

useEffect(() => {
return () => {
setValue("newPw", "")
setValue("newPwConfirm", "")
}
}, [setValue])

if (!canExportAccount || !password) return null
return (
<div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ import { notify } from "@talisman/components/Notifications"
import { useOpenClose } from "@talisman/hooks/useOpenClose"
import { CopyIcon, LoaderIcon } from "@talisman/theme/icons"
import { provideContext } from "@talisman/util/provideContext"
import { useQuery } from "@tanstack/react-query"
import { api } from "@ui/api"
import { useCallback, useEffect, useMemo } from "react"
import { useSensitiveState } from "@ui/hooks/useSensitiveState"
import { useCallback, useEffect, useMemo, useState } from "react"
import { useTranslation } from "react-i18next"
import { Button } from "talisman-ui"

Expand All @@ -28,7 +28,7 @@ const useAccountExportPrivateKeyModalProvider = () => {
)

const exportAccount = useCallback(
(password: string) => {
async (password: string) => {
if (!account) return
return api.accountExportPrivateKey(account.address, password)
},
Expand All @@ -46,19 +46,10 @@ const ExportPrivateKeyResult = ({ onClose }: { onClose?: () => void }) => {
const { account, exportAccount } = useAccountExportPrivateKeyModal()
const { password } = usePasswordUnlock()

// force password check each time this component is rendered
const {
error,
data: privateKey,
isLoading,
} = useQuery({
queryKey: ["accountExportPrivateKey", !!password],
queryFn: () => (password ? exportAccount(password) : null),
refetchInterval: false,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
refetchOnMount: true,
})
// don't use react-query here as we don't want this to be cached
const [privateKey, setPrivateKey] = useSensitiveState<string>()
const [isLoading, setIsLoading] = useState(false)
const [error, setError] = useState<Error>()

const copyToClipboard = useCallback(async () => {
if (!privateKey) return
Expand Down Expand Up @@ -88,6 +79,24 @@ const ExportPrivateKeyResult = ({ onClose }: { onClose?: () => void }) => {
}
}, [privateKey, t])

useEffect(() => {
if (password) {
setError(undefined)
setIsLoading(true)
exportAccount(password)
.then(setPrivateKey)
.catch(setError)
.finally(() => setIsLoading(false))
}
}, [exportAccount, password, setPrivateKey])

useEffect(() => {
return () => {
setError(undefined)
setIsLoading(false)
}
}, [])

if (!account) return null

return (
Expand Down
9 changes: 5 additions & 4 deletions apps/extension/src/ui/domains/Account/MnemonicForm.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { classNames } from "@talismn/util"
import { api } from "@ui/api"
import useMnemonicBackup from "@ui/hooks/useMnemonicBackup"
import { useEffect, useState } from "react"
import { useSensitiveState } from "@ui/hooks/useSensitiveState"
import { useEffect } from "react"
import { Trans, useTranslation } from "react-i18next"
import styled from "styled-components"
import { Toggle } from "talisman-ui"
Expand Down Expand Up @@ -41,13 +42,13 @@ type MnemonicFormProps = {
const MnemonicForm = ({ className }: MnemonicFormProps) => {
const { t } = useTranslation()
const { isConfirmed, toggleConfirmed } = useMnemonicBackup()
const [mnemonic, setMnemonic] = useState<string>()
const [mnemonic, setMnemonic] = useSensitiveState<string>()
const { password } = usePasswordUnlock()

useEffect(() => {
if (!password) return
api.mnemonicUnlock(password).then((result) => setMnemonic(result))
}, [password])
api.mnemonicUnlock(password).then(setMnemonic)
}, [password, setMnemonic])

return (
<div className={classNames("flex grow flex-col", className)}>
Expand Down
19 changes: 15 additions & 4 deletions apps/extension/src/ui/domains/Account/PasswordUnlock.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import { yupResolver } from "@hookform/resolvers/yup"
import { KeyIcon } from "@talisman/theme/icons"
import { provideContext } from "@talisman/util/provideContext"
import { api } from "@ui/api"
import { ReactNode, useCallback, useState } from "react"
import { useSensitiveState } from "@ui/hooks/useSensitiveState"
import { ReactNode, useCallback, useEffect } from "react"
import { useForm } from "react-hook-form"
import { useTranslation } from "react-i18next"
import { Button, FormFieldContainer, FormFieldInputText } from "talisman-ui"
Expand Down Expand Up @@ -31,7 +32,7 @@ type PasswordUnlockContext = {
}

function usePasswordUnlockContext(): PasswordUnlockContext {
const [password, setPassword] = useState<string>()
const [password, setPassword] = useSensitiveState<string>()

const checkPassword = useCallback(
async (password: string) => {
Expand All @@ -56,6 +57,8 @@ const BasePasswordUnlock = ({ className, children, buttonText, title }: Password
register,
handleSubmit,
setError,
setValue,
setFocus,
formState: { errors, isValid, isSubmitting },
} = useForm<FormData>({
mode: "onChange",
Expand All @@ -77,6 +80,16 @@ const BasePasswordUnlock = ({ className, children, buttonText, title }: Password
[checkPassword, setError]
)

useEffect(() => {
if (!password) setFocus("password")
}, [password, setFocus])

useEffect(() => {
return () => {
setValue("password", "")
}
}, [setValue])

return password ? (
<div className={className}>{children}</div>
) : (
Expand All @@ -92,8 +105,6 @@ const BasePasswordUnlock = ({ className, children, buttonText, title }: Password
placeholder={t("Enter password")}
spellCheck={false}
data-lpignore
// eslint-disable-next-line jsx-a11y/no-autofocus
autoFocus
/>
</FormFieldContainer>
</div>
Expand Down
Loading