index
int64
0
0
repo_id
stringlengths
16
181
file_path
stringlengths
28
270
content
stringlengths
1
11.6M
__index_level_0__
int64
0
10k
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/gmailSyncModal/GmailSyncModalAnimation.tsx
import { c } from 'ttag'; import { Icon, Logo, useUser } from '@proton/components'; import envelope from '@proton/styles/assets/img/illustrations/envelope.svg'; import gmailLogo from '@proton/styles/assets/img/illustrations/gmail-logo.svg'; import key from '@proton/styles/assets/img/illustrations/key.svg'; import stopSign from '@proton/styles/assets/img/illustrations/stop-hand-sign.svg'; import './GmailSyncModalAnimation.scss'; const GmailSyncModalAnimation = () => { const [user] = useUser(); const { DisplayName, Name } = user; const nameToDisplay = <strong key="dummyKey">{DisplayName || Name}</strong>; return ( <div className="gsma" aria-hidden="true"> <div className="gsma-gmail-username-inbox"> <div className="gsma-gmail-logo"> <img src={gmailLogo} alt="" width={40} height={30} /> </div> <div className="gsma-username"> {/* translator: keep this translation as small as possible since the space is reduced. */} <span className="gsma-username-content">{c('Animation').jt`${nameToDisplay}'s inbox`}</span> </div> </div> <div className="gsma-auto-forward"> <div className="gsma-forwarded"> {c('Animation').t`Auto forwarded`} <Icon className="ml-4 flex-item-noshrink" name="arrow-up-and-right-big" /> </div> <div className="gsma-envelope"> <img src={envelope} alt="" width={55} height={35} /> </div> <div className="gsma-new-email">{c('Animation').t`New email`}</div> </div> <div className="gsma-proton"> <Logo appName="proton-mail" variant="glyph-only" size={48} className="gsma-proton-logo" /> </div> <div className="gsma-received"> <div className="gsma-received-inner ui-prominent"> <div className="gsma-received-inner-content">{c('Animation').t`Email received`}</div> </div> </div> <div className="gsma-trackers"> <div className="gsma-trackers-inner ui-prominent"> <div className="gsma-trackers-inner-content"> <img src={stopSign} alt="" width={35} height={35} /> {c('Animation').t`5 trackers removed`} </div> </div> </div> <div className="gsma-encrypted"> <div className="gsma-encrypted-inner ui-prominent"> <div className="gsma-encrypted-inner-content"> <img src={key} alt="" width={25} height={25} /> {c('Animation').t`Encrypted`} </div> </div> </div> <div className="gsma-arrows"> <div className="gsma-arrows-inner"> <Icon className="gsma-arrows-inner-icon" name="chevron-down" size={28} /> </div> <div className="gsma-arrows-inner"> <Icon className="gsma-arrows-inner-icon" name="chevron-down" size={28} /> </div> <div className="gsma-arrows-inner"> <Icon className="gsma-arrows-inner-icon" name="chevron-down" size={28} /> </div> </div> </div> ); }; export default GmailSyncModalAnimation;
6,300
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/gmailSyncModal/SignInWithGoogle.scss
.google-button { --button-default-background-color: #4285f4; --button-hover-background-color: #3265d2; --button-active-background-color: #2245b0; }
6,301
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/gmailSyncModal/SignInWithGoogle.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import googleLogo from '@proton/styles/assets/img/import/providers/google.svg'; import './SignInWithGoogle.scss'; interface Props { loading: boolean; disabled?: boolean; onClick: () => void; } const SignInWithGoogle = ({ loading, disabled, onClick }: Props) => { return ( <Button fullWidth color="norm" onClick={onClick} loading={loading} disabled={loading || disabled} className="flex flex-align-items-center p-1 rounded google-button" > <span className="bg-norm rounded-sm flex flex-justify-center flex-align-items-center w-custom min-h-custom" style={{ '--w-custom': '2.5rem', '--min-h-custom': '2.5rem' }} > <img src={googleLogo} alt="" width={20} height={20} aria-hidden="true" /> </span> <span className="text-semibold flex-item-fluid text-left pl-4 pr-8">{c('Gmail forwarding') .t`Sign in with Google`}</span> </Button> ); }; export default SignInWithGoogle;
6,302
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/gmailSyncModal/index.ts
export { default as GmailSyncModal } from './GmailSyncModal';
6,303
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/heading/PrivateHeader.tsx
import { ReactNode } from 'react'; import { APP_NAMES } from '@proton/shared/lib/constants'; import clsx from '@proton/utils/clsx'; import { Hamburger } from '../../components'; import Header, { Props as HeaderProps } from '../../components/header/Header'; import { TopNavbar, TopNavbarList, TopNavbarListItem, TopNavbarUpsell } from '../../components/topnavbar'; import { useIsPaidUserCookie, useIsProtonUserCookie } from '../../hooks'; import { useTheme } from '../themes'; interface Props extends HeaderProps { settingsButton?: ReactNode; userDropdown?: ReactNode; contactsButton?: ReactNode; feedbackButton?: ReactNode; floatingButton?: ReactNode; upsellButton?: ReactNode; hideMenuButton?: boolean; hideUpsellButton?: boolean; actionArea?: ReactNode; title: string; expanded: boolean; onToggleExpand?: () => void; isNarrow?: boolean; app?: APP_NAMES; } const PrivateHeader = ({ isNarrow, upsellButton, userDropdown, settingsButton, feedbackButton, actionArea, floatingButton, expanded, onToggleExpand, hideMenuButton = false, hideUpsellButton = false, app, }: Props) => { useIsPaidUserCookie(); useIsProtonUserCookie(); const theme = useTheme(); const isProminent = theme.information.prominentHeader; return ( <Header className={clsx(isProminent && 'ui-prominent')}> {!hideMenuButton && <Hamburger expanded={expanded} onToggle={onToggleExpand} />} {/* Handle actionArea in components itself rather than here */} <div className="flex-item-fluid">{actionArea}</div> <TopNavbar> <TopNavbarList> {upsellButton !== undefined ? upsellButton : !hideUpsellButton && <TopNavbarUpsell app={app} />} {feedbackButton ? <TopNavbarListItem noShrink>{feedbackButton}</TopNavbarListItem> : null} {settingsButton ? ( <TopNavbarListItem noShrink className="hidden md:flex"> {settingsButton} </TopNavbarListItem> ) : null} {userDropdown && !isNarrow ? ( <TopNavbarListItem className="relative hidden md:flex">{userDropdown}</TopNavbarListItem> ) : null} </TopNavbarList> </TopNavbar> {isNarrow && floatingButton ? floatingButton : null} </Header> ); }; export default PrivateHeader;
6,304
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/heading/TopNavbarListItemFeedbackButton.tsx
import { c } from 'ttag'; import Icon from '../../components/icon/Icon'; import TopNavbarListItemButton from '../../components/topnavbar/TopNavbarListItemButton'; interface Props { onClick: () => void; } const TopNavbarListItemFeedbackButton = ({ onClick }: Props) => { return ( <TopNavbarListItemButton as="button" type="button" title={c('Title').t`Send feedback`} onClick={onClick} icon={<Icon name="speech-bubble" />} text={c('Title').t`Feedback`} /> ); }; export default TopNavbarListItemFeedbackButton;
6,305
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/heading/UserDropdown.tsx
import { MouseEvent, useEffect, useMemo, useState } from 'react'; import { useLocation } from 'react-router'; import { addDays, fromUnixTime } from 'date-fns'; import { c } from 'ttag'; import { Button, ButtonLike, NotificationDot } from '@proton/atoms'; import { ThemeColor } from '@proton/colors'; import { ConfirmSignOutModal, Dropdown, DropdownMenu, DropdownSizeUnit, FeatureCode, Logo, ReferralSpotlight, SettingsLink, Tooltip, shouldShowConfirmSignOutModal, useActiveBreakpoint, useAuthentication, useConfig, useFeature, useModalState, useNotifications, useOrganization, usePopperAnchor, useSessionRecoveryState, useSettingsLink, useSpotlightOnFeature, useSpotlightShow, useSubscription, useUser, useUserSettings, } from '@proton/components'; import { getAppHref, getAppShortName } from '@proton/shared/lib/apps/helper'; import { getAppFromPathnameSafe, getSlugFromApp } from '@proton/shared/lib/apps/slugHelper'; import { FORK_TYPE } from '@proton/shared/lib/authentication/ForkInterface'; import { requestFork } from '@proton/shared/lib/authentication/sessionForking'; import { APPS, APPS_CONFIGURATION, APP_NAMES, BRAND_NAME, PLANS, PLAN_NAMES, SSO_PATHS, UPSELL_COMPONENT, isSSOMode, } from '@proton/shared/lib/constants'; import { textToClipboard } from '@proton/shared/lib/helpers/browser'; import { isElectronApp } from '@proton/shared/lib/helpers/desktop'; import { getIsEventModified } from '@proton/shared/lib/helpers/dom'; import { getInitials } from '@proton/shared/lib/helpers/string'; import { getHasLegacyPlans, getPlan, getPrimaryPlan, hasLifetime, isTrial, } from '@proton/shared/lib/helpers/subscription'; import { getUpsellRefFromApp } from '@proton/shared/lib/helpers/upsell'; import { getShopURL, getStaticURL } from '@proton/shared/lib/helpers/url'; import { SessionRecoveryState, Subscription } from '@proton/shared/lib/interfaces'; import { FREE_PLAN } from '@proton/shared/lib/subscription/freePlans'; import clsx from '@proton/utils/clsx'; import ProductLink, { apps } from '../../containers/app/ProductLink'; import { generateUID } from '../../helpers'; import SessionRecoverySignOutConfirmPrompt from '../account/sessionRecovery/SessionRecoverySignOutConfirmPrompt'; import { AuthenticatedBugModal } from '../support'; import UserDropdownButton, { Props as UserDropdownButtonProps } from './UserDropdownButton'; const getPlanTitle = (subscription: Subscription, app: APP_NAMES) => { if (hasLifetime(subscription)) { return 'Lifetime'; } const primaryPlan = getPrimaryPlan(subscription, app); if (getHasLegacyPlans(subscription)) { return primaryPlan?.Name || ''; } return getPlan(subscription)?.Title || PLAN_NAMES[FREE_PLAN.Name as PLANS]; }; interface Props extends Omit<UserDropdownButtonProps, 'user' | 'isOpen' | 'onClick'> { onOpenChat?: () => void; app: APP_NAMES; hasAppLinks?: boolean; } const UserDropdown = ({ onOpenChat, app, hasAppLinks = true, ...rest }: Props) => { const { APP_NAME } = useConfig(); const [organization] = useOrganization(); const { Name: organizationName } = organization || {}; const [user] = useUser(); const location = useLocation(); const [subscription] = useSubscription(); const [userSettings] = useUserSettings(); const authentication = useAuthentication(); const [redDotReferral, setRedDotReferral] = useState(false); const { Email, DisplayName, Name, isMember } = user; const nameToDisplay = DisplayName || Name; // nameToDisplay can be falsy for external account const { logout } = useAuthentication(); const [uid] = useState(generateUID('dropdown')); const { anchorRef, isOpen, toggle, close } = usePopperAnchor<HTMLButtonElement>(); const [bugReportModal, setBugReportModal, renderBugReportModal] = useModalState(); const [confirmSignOutModal, setConfirmSignOutModal, renderConfirmSignOutModal] = useModalState(); const [ sessionRecoverySignOutConfirmPrompt, setSessionRecoverySignOutConfirmPrompt, renderSessionRecoverySignOutConfirmPrompt, ] = useModalState(); const sessionRecoveryState = useSessionRecoveryState(); const sessionRecoveryInitiated = sessionRecoveryState === SessionRecoveryState.GRACE_PERIOD || sessionRecoveryState === SessionRecoveryState.INSECURE; const { feature: referralProgramFeature } = useFeature(FeatureCode.ReferralProgram); const isElectron = isElectronApp(); const subscriptionStartedThirtyDaysAgo = !!subscription?.PeriodStart && new Date() > addDays(fromUnixTime(subscription.PeriodStart), 30); const { show: showSpotlight, onDisplayed: onDisplayedSpotlight, onClose: onCloseSpotlight, } = useSpotlightOnFeature( FeatureCode.ReferralProgramSpotlight, !!referralProgramFeature?.Value && !!userSettings?.Referral?.Eligible && subscriptionStartedThirtyDaysAgo ); const shouldShowSpotlight = useSpotlightShow(showSpotlight); const { createNotification } = useNotifications(); const handleCopyEmail = () => { textToClipboard(Email); createNotification({ type: 'success', text: c('Success').t`Email address copied to clipboard`, }); }; const handleSignOutClick = () => { close(); if (sessionRecoveryInitiated) { setSessionRecoverySignOutConfirmPrompt(true); } else if (shouldShowConfirmSignOutModal({ user, authentication })) { setConfirmSignOutModal(true); } else { logout(); } }; const planName = isMember ? '' : getPlanTitle(subscription, APP_NAME); const handleBugReportClick = () => { setBugReportModal(true); }; const userVoiceLinks: Partial<{ [key in APP_NAMES]: string }> = { [APPS.PROTONMAIL]: 'https://protonmail.uservoice.com/', [APPS.PROTONCALENDAR]: 'https://protonmail.uservoice.com/forums/932842-proton-calendar', [APPS.PROTONDRIVE]: 'https://protonmail.uservoice.com/forums/932839-proton-drive', [APPS.PROTONVPN_SETTINGS]: 'https://protonmail.uservoice.com/forums/932836-protonvpn', }; // Show referral dot if the spotlight has been displayed useEffect(() => { if (shouldShowSpotlight) { setRedDotReferral(true); } }, [shouldShowSpotlight, location]); // Hide red dot referral if user has already seen referral page useEffect(() => { if (location.pathname.includes('/referral')) { setRedDotReferral(false); } }, [location.pathname]); const switchHref = useMemo(() => { const href = getAppHref(SSO_PATHS.SWITCH, APPS.PROTONACCOUNT); const toApp = APP_NAME === APPS.PROTONACCOUNT ? getAppFromPathnameSafe(location.pathname) : APP_NAME; const search = `?product=${getSlugFromApp(toApp || APPS.PROTONMAIL)}`; return `${href}${search}`; }, [location.pathname]); const { isNarrow } = useActiveBreakpoint(); // DisplayName is null for VPN users without any addresses, cast to undefined in case Name would be null too. const initials = getInitials(nameToDisplay || Email || ''); const goToSettings = useSettingsLink(); const path = APPS_CONFIGURATION[APP_NAME].publicPath; const isVPN = APP_NAME === APPS.PROTONVPN_SETTINGS; const upgradePathname = isVPN ? '/dashboard' : '/upgrade'; const upsellRef = getUpsellRefFromApp({ app: APP_NAME, feature: '1', component: UPSELL_COMPONENT.BUTTON, fromApp: app, }); const upgradeUrl = `${upgradePathname}?ref=${upsellRef}`; const displayUpgradeButton = (user.isFree || isTrial(subscription)) && !location.pathname.endsWith(upgradePathname); return ( <> {renderBugReportModal && <AuthenticatedBugModal {...bugReportModal} />} {renderSessionRecoverySignOutConfirmPrompt && ( <SessionRecoverySignOutConfirmPrompt onSignOut={() => logout()} {...sessionRecoverySignOutConfirmPrompt} /> )} {renderConfirmSignOutModal && ( <ConfirmSignOutModal onSignOut={(clearDeviceRecoveryData: boolean) => logout({ clearDeviceRecoveryData })} {...confirmSignOutModal} /> )} <ReferralSpotlight show={shouldShowSpotlight} anchorRef={anchorRef} onDisplayed={onDisplayedSpotlight} onClose={onCloseSpotlight} user={user} > <UserDropdownButton data-testid="heading:userdropdown" {...rest} user={user} ref={anchorRef} isOpen={isOpen} onClick={() => { onCloseSpotlight(); toggle(); }} /> </ReferralSpotlight> <Dropdown id={uid} className="userDropdown" isOpen={isOpen} anchorRef={anchorRef} autoClose={false} onClose={close} originalPlacement="bottom-end" adaptiveForTouchScreens={false} size={{ height: DropdownSizeUnit.Dynamic, maxHeight: DropdownSizeUnit.Viewport, width: '17.25rem', maxWidth: '20rem', }} > <DropdownMenu className="pb-4"> <div className="px-4 py-3 flex flex-nowrap gap-4 flex-justify-space-between text-sm"> {planName ? ( <span className="text-semibold block flex-item-noshrink" data-testid="userdropdown:label:plan-name" > {planName} </span> ) : null} {organizationName ? ( <span className="ml-auto text-ellipsis color-weak block" title={organizationName} data-testid="userdropdown:label:org-name" > {organizationName} </span> ) : null} {displayUpgradeButton ? ( <ButtonLike color="norm" shape="underline" className="text-ellipsis p-0 color-primary interactive-pseudo-protrude interactive--no-background" as={SettingsLink} path={upgradeUrl} title={c('specialoffer: Link').t`Go to subscription plans`} >{c('specialoffer: Link').t`Upgrade`}</ButtonLike> ) : null} </div> {!isNarrow && ( <div className="px-4 pb-4 text-sm flex flex-nowrap flex-align-items-center"> <span className="my-auto text-sm rounded border p-1 inline-block relative flex flex-item-noshrink user-initials" aria-hidden="true" > <span className="m-auto">{initials}</span> </span> <div className="flex-item-fluid ml-2"> {nameToDisplay ? ( <div className="text-ellipsis" title={nameToDisplay} data-testid="userdropdown:label:display-name" > {nameToDisplay} </div> ) : null} {Email ? ( <div className="flex flex-nowrap flex-justify-space-between flex-align-items-center"> <Tooltip title={c('Action').t`Copy address`}> <button type="button" className={clsx([ 'user-select relative interactive-pseudo-protrude interactive--no-background', nameToDisplay || organizationName ? 'color-weak' : 'text-bold', ])} title={Email} data-testid="userdropdown:label:email" onClick={handleCopyEmail} > <span className="text-ellipsis block color-weak on-hover-color-norm"> {Email} </span> </button> </Tooltip> </div> ) : null} </div> </div> )} {isSSOMode && !isElectron ? ( <div className="px-4 pb-2"> <ButtonLike as="a" href={switchHref} target="_self" shape="outline" color="weak" className="w-full" onClick={(event: MouseEvent<HTMLAnchorElement>) => { if ( APP_NAME !== APPS.PROTONACCOUNT && event.button === 0 && !getIsEventModified(event.nativeEvent) ) { event.preventDefault(); return requestFork(APP_NAME, undefined, FORK_TYPE.SWITCH); } }} data-testid="userdropdown:button:switch-account" > {c('Action').t`Switch or add account`} </ButtonLike> </div> ) : null} {APP_NAME !== APPS.PROTONACCOUNT && APP_NAME !== APPS.PROTONVPN_SETTINGS ? ( <div className="px-4 pb-2"> <Button shape="outline" color="weak" className="w-full" onClick={() => goToSettings(path, APP_NAME, false)} data-testid="userdropdown:button:settings" >{c('Action').t`Settings`}</Button> </div> ) : undefined} <div className="px-4 pb-4"> <Button shape="solid" color="norm" className="w-full" onClick={handleSignOutClick} data-testid="userdropdown:button:logout" > {c('Action').t`Sign out`} </Button> </div> {isNarrow && hasAppLinks ? ( <ul className="px-4 pb-4 unstyled text-sm"> {apps(user).map((appToLinkTo) => { const appToLinkToName = getAppShortName(appToLinkTo); const current = app && appToLinkTo === app; return ( <li key={appToLinkTo}> <ProductLink ownerApp={APP_NAME} app={app} appToLinkTo={appToLinkTo} user={user} className="flex flex-nowrap flex-align-items-center color-weak text-no-decoration border-weak border-bottom interactive-pseudo relative py-1" > <Logo appName={appToLinkTo} variant="glyph-only" className="flex-item-noshrink mr-2" /> <span className={clsx(current && 'color-norm text-semibold')} aria-hidden> {appToLinkToName} </span> </ProductLink> </li> ); })} </ul> ) : null} <div className="text-sm text-center flex flex-column gap-2"> {APP_NAME !== APPS.PROTONVPN_SETTINGS && referralProgramFeature?.Value && userSettings?.Referral?.Eligible && ( <div className="block"> <SettingsLink className="mx-auto w-full px-2 link link-focus color-weak text-no-decoration on-hover-color-norm" path="/referral" onClick={close} data-testid="userdropdown:button:referral" > {c('Action').t`Refer a friend`} {redDotReferral ? <NotificationDot color={ThemeColor.Danger} /> : <span />} </SettingsLink> </div> )} <div className="block"> <a className="mx-auto w-full px-2 link link-focus color-weak text-no-decoration on-hover-color-norm" href={getShopURL()} target="_blank" data-testid="userdropdown:help:link:request-feature" > {c('Action').t`${BRAND_NAME} shop`} </a> </div> <div className="block"> <a className="mx-auto w-full px-2 link link-focus color-weak text-no-decoration on-hover-color-norm" href={userVoiceLinks[APP_NAME] || userVoiceLinks[APPS.PROTONMAIL]} target="_blank" data-testid="userdropdown:help:link:request-feature" > {c('Action').t`Request a feature`} </a> </div> {onOpenChat && ( <div className="block"> <button type="button" className="mx-auto w-full px-2 link link-focus color-weak text-no-decoration on-hover-color-norm" onClick={() => { close(); onOpenChat(); }} data-testid="userdropdown:help:button:bugreport" > {c('Action').t`Chat with us`} </button> </div> )} <div className="flex flex-nowrap mx-auto flex-justify-center"> <a className="px-1 link link-focus color-weak text-no-decoration on-hover-color-norm" href={ APP_NAME === APPS.PROTONVPN_SETTINGS ? 'https://protonvpn.com/support/' : getStaticURL('/support') } target="_blank" data-testid="userdropdown:help:link:question" > {c('Action').t`Help`} </a> <span className="flex-align-self-center color-weak" aria-hidden="true"> • </span> <button type="button" className="px-1 link link-focus color-weak text-no-decoration on-hover-color-norm" onClick={handleBugReportClick} data-testid="userdropdown:help:button:bugreport" > {c('Action').t`Report a problem`} </button> </div> </div> </DropdownMenu> </Dropdown> </> ); }; export default UserDropdown;
6,306
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/heading/UserDropdownButton.tsx
import { ButtonHTMLAttributes, DetailedHTMLProps, Ref, forwardRef } from 'react'; import { c } from 'ttag'; import { NotificationDot } from '@proton/atoms'; import { ThemeColor } from '@proton/colors'; import { getInitials } from '@proton/shared/lib/helpers/string'; import { UserModel } from '@proton/shared/lib/interfaces'; import { DropdownCaret } from '../..'; export interface Props extends DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement> { user: UserModel; className?: string; isOpen?: boolean; notification?: ThemeColor; } const UserDropdownButton = ({ user, isOpen, notification, ...rest }: Props, ref: Ref<HTMLButtonElement>) => { const { Email, DisplayName, Name } = user; const nameToDisplay = DisplayName || Name; // nameToDisplay can be falsy for external account // DisplayName is null for VPN users without any addresses, cast to undefined in case Name would be null too. const initials = getInitials(nameToDisplay || Email || ''); return ( <button type="button" aria-expanded={isOpen} ref={ref} {...rest} className="max-w-full flex flex-align-items-center flex-nowrap gap-3 user-dropdown-button relative interactive-pseudo-protrude rounded interactive--no-background" title={`${nameToDisplay} <${Email}>`} > <DropdownCaret className="md:hidden ml-1 color-weak" isOpen={isOpen} /> {nameToDisplay ? ( <span className="flex-item-fluid lh130 user-dropdown-text"> <span className="block text-ellipsis text-sm user-dropdown-displayName">{nameToDisplay}</span> {Email ? ( <span className="block text-ellipsis color-weak text-sm m-0 lh-rg user-dropdown-email"> {Email} </span> ) : null} </span> ) : ( <span className="lh130 user-dropdown-text"> <span className="block text-ellipsis user-dropdown-displayName">{Email}</span> </span> )} <span className="my-auto text-sm rounded border p-1 inline-block relative flex flex-item-noshrink user-initials" aria-hidden="true" > <span className="m-auto">{initials}</span> </span> {notification && ( <NotificationDot color={notification} className="absolute top right notification-dot--top-right" alt={c('Info').t`Attention required`} /> )} </button> ); }; export default forwardRef<HTMLButtonElement, Props>(UserDropdownButton);
6,307
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/heading/index.ts
export { default as UserDropdown } from './UserDropdown'; export { default as PrivateHeader } from './PrivateHeader'; export { default as Header } from '../../components/header/Header'; export { default as TopNavbarListItemFeedbackButton } from './TopNavbarListItemFeedbackButton';
6,308
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/illustration/IllustrationPlaceholder.tsx
import { ReactNode } from 'react'; import clsx from '@proton/utils/clsx'; interface Props { className?: string; illustrationClassName?: string; title?: string; url: string; uppercase?: boolean; children?: ReactNode; titleSize?: 'regular' | 'big'; } const IllustrationPlaceholder = ({ className, illustrationClassName, title, url, uppercase, children, titleSize = 'big', }: Props) => { return ( <div className={clsx('flex-no-min-children flex-column flex-nowrap flex-align-items-center w-full', className)}> <img src={url} alt={title} className={clsx('p-1 mb-4', illustrationClassName)} /> {!!title && ( <h1 className={clsx( 'text-bold text-rg mb-1', titleSize === 'regular' && 'text-rg', titleSize === 'big' && 'text-4xl', uppercase && 'text-uppercase' )} > {title} </h1> )} {children} </div> ); }; export default IllustrationPlaceholder;
6,309
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/illustration/index.ts
export { default as IllustrationPlaceholder } from './IllustrationPlaceholder';
6,310
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/importExportApp/ImportExportAppSection.tsx
import { c } from 'ttag'; import { ButtonLike, Href } from '@proton/atoms'; import { getImportExportAppUrl } from '@proton/shared/lib/helpers/url'; import { SettingsParagraph, SettingsSection } from '../account'; const ImportExportAppSection = () => { return ( <SettingsSection> <SettingsParagraph> {c('Info') .t`The Import-Export app allows you to export messages for local backups and to restore previous backups to your account.`} <br /> {c('Info').t`Available on macOS, Windows, and Linux.`} </SettingsParagraph> <ButtonLike color="norm" as={Href} href={getImportExportAppUrl()}> {c('Action').t`Download the Import-Export app`} </ButtonLike> </SettingsSection> ); }; export default ImportExportAppSection;
6,311
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/importExportApp/index.ts
export { default as ImportExportAppSection } from './ImportExportAppSection';
6,312
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/invoices/InvoiceActions.tsx
import { c } from 'ttag'; import { useLoading } from '@proton/hooks'; import { queryPaymentMethodStatus } from '@proton/shared/lib/api/payments'; import { INVOICE_STATE } from '@proton/shared/lib/constants'; import isTruthy from '@proton/utils/isTruthy'; import { DropdownActions } from '../../components'; import { useApi, useModals, useNotifications } from '../../hooks'; import PayInvoiceModal from './PayInvoiceModal'; import { Invoice } from './interface'; interface Props { invoice: Invoice; fetchInvoices: () => void; onPreview?: (invoice: Invoice) => void; onDownload: (invoice: Invoice) => void; } const InvoiceActions = ({ invoice, fetchInvoices, onPreview, onDownload }: Props) => { const { createModal } = useModals(); const { createNotification } = useNotifications(); const api = useApi(); const [downloadLoading, withDownloadLoading] = useLoading(); const [viewLoading, withViewLoading] = useLoading(); const list = [ invoice.State === INVOICE_STATE.UNPAID && { text: c('Action').t`Pay`, 'data-testid': 'payInvoice', async onClick() { const { Card, Paypal } = await api(queryPaymentMethodStatus()); const canPay = Card || Paypal; if (!canPay) { createNotification({ type: 'error', text: c('Error').t`Payments are currently not available, please try again later`, }); return; } createModal(<PayInvoiceModal invoice={invoice} fetchInvoices={fetchInvoices} />); }, }, { text: c('Action').t`View`, 'data-testid': 'viewInvoice', onClick: async () => { const handler = async () => { onPreview?.(invoice); }; await withViewLoading(handler()); }, loading: viewLoading, }, { text: c('Action').t`Download`, 'data-testid': 'downloadInvoice', onClick: async () => { const handler = async () => { onDownload(invoice); }; await withDownloadLoading(handler()); }, loading: downloadLoading, }, ].filter(isTruthy); return <DropdownActions loading={Boolean(downloadLoading || viewLoading)} list={list} size="small" />; }; export default InvoiceActions;
6,313
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/invoices/InvoiceAmount.tsx
import { INVOICE_STATE } from '@proton/shared/lib/constants'; import { Price } from '../../components'; import { Invoice } from './interface'; interface Props { invoice: Invoice; } const format = ({ State, AmountCharged = 0, AmountDue = 0 }: Invoice) => { return State === INVOICE_STATE.UNPAID ? AmountDue : AmountCharged; }; const InvoiceAmount = ({ invoice }: Props) => { return ( <Price currency={invoice.Currency} data-testid="invoice-amount"> {format(invoice)} </Price> ); }; export default InvoiceAmount;
6,314
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/invoices/InvoiceState.tsx
import { c } from 'ttag'; import { INVOICE_STATE } from '@proton/shared/lib/constants'; import { Badge } from '../../components'; import { Invoice } from './interface'; const TYPES = { [INVOICE_STATE.UNPAID]: 'error', [INVOICE_STATE.PAID]: 'success', [INVOICE_STATE.VOID]: 'default', [INVOICE_STATE.BILLED]: 'default', [INVOICE_STATE.WRITEOFF]: 'default', } as const; const getStatesI18N = (invoiceState: INVOICE_STATE) => { switch (invoiceState) { case INVOICE_STATE.UNPAID: return c('Invoice state display as badge').t`Unpaid`; case INVOICE_STATE.PAID: return c('Invoice state display as badge').t`Paid`; case INVOICE_STATE.VOID: return c('Invoice state display as badge').t`Void`; case INVOICE_STATE.BILLED: return c('Invoice state display as badge').t`Billed`; case INVOICE_STATE.WRITEOFF: return c('Invoice state display as badge').t`Gifted`; default: return ''; } }; interface Props { invoice: Invoice; } const InvoiceState = ({ invoice }: Props) => { return ( <Badge type={TYPES[invoice.State] || 'default'} data-testid="invoice-state"> {getStatesI18N(invoice.State)} </Badge> ); }; export default InvoiceState;
6,315
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/invoices/InvoiceTextModal.tsx
import { useState } from 'react'; import PropTypes from 'prop-types'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { updateInvoiceText } from '@proton/shared/lib/api/settings'; import { Form, InputFieldTwo, ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, PrimaryButton, TextAreaTwo, } from '../../components'; import { useApiWithoutResult, useEventManager, useNotifications, useUserSettings } from '../../hooks'; export interface Props { onClose?: () => void; } const InvoiceTextModal = (props: ModalProps) => { const [{ InvoiceText }] = useUserSettings(); const { createNotification } = useNotifications(); const { call } = useEventManager(); const [invoiceText, setInvoiceText] = useState(InvoiceText); const { request, loading } = useApiWithoutResult(() => updateInvoiceText(invoiceText)); const handleSubmit = async () => { await request(); await call(); props.onClose?.(); createNotification({ text: c('Success').t`Invoice customized` }); }; return ( <ModalTwo as={Form} onSubmit={handleSubmit} {...props}> <ModalTwoHeader title={c('Title').t`Edit invoice details`} /> <ModalTwoContent> <div className="mb-4"> {c('Info message for custom invoice modal') .t`Enter a name and address for yourself or your organization. These details will be added to both personal and organizational invoices.`} </div> <InputFieldTwo as={TextAreaTwo} rows={3} autoFocus value={invoiceText} onValue={setInvoiceText} label={c('Label').t`Name and address`} /> </ModalTwoContent> <ModalTwoFooter> <Button onClick={props.onClose}>{c('Action').t`Cancel`}</Button> <PrimaryButton onClick={handleSubmit} loading={loading}>{c('Action').t`Save`}</PrimaryButton> </ModalTwoFooter> </ModalTwo> ); }; InvoiceTextModal.propTypes = { onClose: PropTypes.func, }; export default InvoiceTextModal;
6,316
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/invoices/InvoiceType.tsx
import { c } from 'ttag'; import { INVOICE_TYPE } from '@proton/shared/lib/constants'; import { Invoice } from './interface'; const getType = (type: INVOICE_TYPE) => { switch (type) { case INVOICE_TYPE.OTHER: return c('Invoice type display as badge').t`Other`; case INVOICE_TYPE.SUBSCRIPTION: return c('Invoice type display as badge').t`Subscription`; case INVOICE_TYPE.CANCELLATION: return c('Invoice type display as badge').t`Cancellation`; case INVOICE_TYPE.CREDIT: return c('Invoice type display as badge').t`Credit`; case INVOICE_TYPE.DONATION: return c('Invoice type display as badge').t`Donation`; case INVOICE_TYPE.CHARGEBACK: return c('Invoice type display as badge').t`Chargeback`; case INVOICE_TYPE.RENEWAL: return c('Invoice type display as badge').t`Renewal`; case INVOICE_TYPE.REFUND: return c('Invoice type display as badge').t`Refund`; case INVOICE_TYPE.MODIFICATION: return c('Invoice type display as badge').t`Modification`; case INVOICE_TYPE.ADDITION: return c('Invoice type display as badge').t`Addition`; default: return ''; } }; interface Props { invoice: Invoice; } const InvoiceType = ({ invoice }: Props) => { return <>{getType(invoice.Type)}</>; }; export default InvoiceType;
6,317
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/invoices/InvoicesPreview.tsx
import { Ref, forwardRef, useImperativeHandle, useRef, useState } from 'react'; import { getInvoice } from '@proton/shared/lib/api/payments'; import { useApi } from '../../hooks'; import { FilePreview, NavigationControl } from '../filePreview'; import { Invoice } from './interface'; export interface InvoicesPreviewControls { preview: (invoice: Invoice) => void; } interface Preview { invoice: Invoice; contents?: Uint8Array[]; } interface Props { invoices: Invoice[]; onDownload: (invoice: Invoice) => void; getFilename: (invoice: Invoice) => string; } const InvoicesPreview = ( { invoices, onDownload, getFilename }: Props, ref: Ref<InvoicesPreviewControls | undefined> ) => { const api = useApi(); const [previewing, setPreviewing] = useState<Preview>(); const rootRef = useRef<HTMLDivElement>(null); const handlePreview = async (invoice: Invoice) => { setPreviewing({ invoice }); const buffer = await api<Uint8Array>(getInvoice(invoice.ID)); setPreviewing((previewing) => { // Preview can be closed or changed during download; if (previewing === undefined || previewing.invoice !== invoice) { return previewing; } return { ...previewing, contents: [buffer], }; }); }; useImperativeHandle(ref, () => ({ preview: handlePreview, })); if (!previewing) { return null; } const current = invoices.findIndex((invoice) => invoice === previewing.invoice) + 1; const total = invoices.length; const handleNext = () => handlePreview(invoices[current]); const handlePrevious = () => handlePreview(invoices[current - 2]); const handleClose = () => setPreviewing(undefined); const handleDownload = () => { if (!previewing.invoice) { return; } onDownload(previewing.invoice); }; const filename = () => { if (!previewing.invoice) { return; } return getFilename(previewing.invoice); }; return ( <FilePreview isLoading={!previewing.contents} contents={previewing.contents} fileName={filename()} fileSize={previewing.contents?.length} mimeType="application/pdf" onClose={handleClose} onDownload={handleDownload} ref={rootRef} navigationControls={ <NavigationControl current={current} total={total} rootRef={rootRef} onNext={handleNext} onPrev={handlePrevious} /> } /> ); }; export default forwardRef(InvoicesPreview);
6,318
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/invoices/InvoicesSection.test.tsx
import { render } from '@testing-library/react'; import { useSubscribeEventManager } from '../../hooks'; import InvoicesSection from './InvoicesSection'; jest.mock('../../hooks/useHandler', () => { return { __esModule: true, ...jest.requireActual('../../hooks/useHandler'), useSubscribeEventManager: jest.fn(), }; }); let requestMock: jest.Mock; jest.mock('../../hooks/useApiResult', () => { let request = jest.fn(); requestMock = request; return { __esModule: true, ...jest.requireActual('../../hooks/useApiResult'), default: jest.fn().mockReturnValue({ request, }), }; }); jest.mock('../../hooks/useUser', () => { return { __esModule: true, default: jest.fn().mockReturnValue([ { isPaid: false, }, ]), }; }); jest.mock('../../hooks/useSubscription', () => { return { __esModule: true, default: jest.fn().mockReturnValue([]), }; }); jest.mock('../../hooks/useModals', () => { return { __esModule: true, default: jest.fn().mockReturnValue({ createModal: jest.fn(), }), }; }); describe('InvoicesSection', () => { let useSubscribeEventManagerMock: jest.Mock; beforeAll(() => { useSubscribeEventManagerMock = useSubscribeEventManager as jest.Mock; }); beforeEach(() => { requestMock.mockReset(); useSubscribeEventManagerMock.mockReset(); }); it('should request the list of invoices again when there is an Invoices event', () => { render(<InvoicesSection />); expect(useSubscribeEventManagerMock).toHaveBeenCalledTimes(1); let [callback] = useSubscribeEventManagerMock.mock.lastCall; callback({ Invoices: [{ ID: '123' }], }); expect(requestMock).toHaveBeenCalledTimes(1); }); it('should not request invoices if the Invoices array is empty', () => { render(<InvoicesSection />); expect(useSubscribeEventManagerMock).toHaveBeenCalledTimes(1); let [callback] = useSubscribeEventManagerMock.mock.lastCall; callback({ Invoices: [], }); expect(requestMock).toHaveBeenCalledTimes(0); }); it('should not request invoices if the Invoices are not there ', () => { render(<InvoicesSection />); let useSubscribeEventManagerMock = useSubscribeEventManager as jest.Mock; expect(useSubscribeEventManagerMock).toHaveBeenCalledTimes(1); let [callback] = useSubscribeEventManagerMock.mock.lastCall; callback({}); expect(requestMock).toHaveBeenCalledTimes(0); }); it('should not request invoices if the callback does not have an argument', () => { render(<InvoicesSection />); let useSubscribeEventManagerMock = useSubscribeEventManager as jest.Mock; expect(useSubscribeEventManagerMock).toHaveBeenCalledTimes(1); let [callback] = useSubscribeEventManagerMock.mock.lastCall; callback(); expect(requestMock).toHaveBeenCalledTimes(0); }); });
6,319
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/invoices/InvoicesSection.tsx
import { useRef, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { getInvoice, queryInvoices } from '@proton/shared/lib/api/payments'; import { ELEMENTS_PER_PAGE, INVOICE_OWNER, INVOICE_STATE, MAIL_APP_NAME } from '@proton/shared/lib/constants'; import downloadFile from '@proton/shared/lib/helpers/downloadFile'; import { Alert, Block, ButtonGroup, Pagination, Table, TableBody, TableCell, TableHeader, TableRow, Time, useModalState, usePaginationAsync, } from '../../components'; import { useApi, useApiResult, useSubscribeEventManager, useSubscription, useUser } from '../../hooks'; import { SettingsParagraph, SettingsSectionWide } from '../account'; import MozillaInfoPanel from '../account/MozillaInfoPanel'; import InvoiceActions from './InvoiceActions'; import InvoiceAmount from './InvoiceAmount'; import InvoiceState from './InvoiceState'; import InvoiceTextModal from './InvoiceTextModal'; import InvoiceType from './InvoiceType'; import InvoicesPreview, { InvoicesPreviewControls } from './InvoicesPreview'; import { Invoice, InvoiceResponse } from './interface'; const InvoicesSection = () => { const previewRef = useRef<InvoicesPreviewControls | undefined>(); const api = useApi(); const [user] = useUser(); const { ORGANIZATION, USER } = INVOICE_OWNER; const [owner, setOwner] = useState(USER); const [{ isManagedByMozilla } = { isManagedByMozilla: false }] = useSubscription(); const [invoiceModalProps, setInvoiceModalOpen, renderInvoiceModal] = useModalState(); const { page, onNext, onPrevious, onSelect } = usePaginationAsync(1); const handleOwner = (own = USER) => () => { setOwner(own); onSelect(1); }; const query = () => queryInvoices({ Page: page - 1, PageSize: ELEMENTS_PER_PAGE, Owner: owner, }); const { result = { Invoices: [] as Invoice[], Total: 0, }, loading, request: requestInvoices, } = useApiResult<InvoiceResponse, typeof query>(query, [page, owner]); const { Invoices: invoices, Total: total } = result; const hasUnpaid = invoices.find(({ State }) => State === INVOICE_STATE.UNPAID); useSubscribeEventManager(({ Invoices } = {}) => { if (Invoices && Invoices.length > 0) { requestInvoices(); } }); if (isManagedByMozilla) { return <MozillaInfoPanel />; } const getFilename = (invoice: Invoice) => `${c('Title for PDF file').t`${MAIL_APP_NAME} invoice`} ${invoice.ID}.pdf`; const handleDownload = async (invoice: Invoice) => { const buffer = await api(getInvoice(invoice.ID)); const blob = new Blob([buffer], { type: 'application/pdf' }); downloadFile(blob, getFilename(invoice)); }; const isEmpty = page === 1 && !loading && invoices.length === 0; return ( <> <SettingsSectionWide> <SettingsParagraph>{c('Info').t`View, download, and manage your invoices.`}</SettingsParagraph> {hasUnpaid ? ( <Alert className="mb-4" type="error" data-testid="overdue-alert"> {c('Error') .t`Your account or organization has an overdue invoice. Please pay all unpaid invoices.`} </Alert> ) : null} <Block className="flex flex-justify-space-between"> <div className="flex flex-align-items-center"> {user.isPaid ? ( <ButtonGroup className="mr-4"> <Button className={owner === USER ? 'is-selected' : ''} onClick={handleOwner(USER)}> {c('Action').t`User`} </Button> {user.isAdmin && ( <Button className={owner === ORGANIZATION ? 'is-selected' : ''} onClick={handleOwner(ORGANIZATION)} > {c('Action').t`Organization`} </Button> )} </ButtonGroup> ) : null} {invoices.length > 0 && ( <Button onClick={() => setInvoiceModalOpen(true)}>{c('Action') .t`Edit invoice details`}</Button> )} </div> <Pagination page={page} total={total} limit={ELEMENTS_PER_PAGE} onNext={onNext} onPrevious={onPrevious} onSelect={onSelect} /> </Block> {isEmpty ? ( c('Error').t`You have no invoices.` ) : ( <div style={{ overflow: 'auto' }}> <Table hasActions responsive="cards"> <TableHeader> <TableRow> <TableCell type="header">ID</TableCell> <TableCell type="header">{c('Title').t`Amount`}</TableCell> <TableCell type="header">{c('Title').t`Type`}</TableCell> <TableCell type="header">{c('Title').t`Status`}</TableCell> <TableCell type="header">{c('Title').t`Date`}</TableCell> <TableCell type="header">{c('Title').t`Action`}</TableCell> </TableRow> </TableHeader> <TableBody loading={loading} colSpan={6}> {invoices.map((invoice, index) => { const key = index.toString(); return ( <TableRow key={key} labels={[ 'ID', c('Title').t`Amount`, c('Title').t`Type`, c('Title').t`Status`, c('Title').t`Date`, '', ]} cells={[ invoice.ID, <InvoiceAmount key={key} invoice={invoice} />, <InvoiceType key={key} invoice={invoice} />, <InvoiceState key={key} invoice={invoice} />, <Time key={key}>{invoice.CreateTime}</Time>, <InvoiceActions key={key} invoice={invoice} fetchInvoices={requestInvoices} onPreview={previewRef.current?.preview} onDownload={handleDownload} />, ]} /> ); })} </TableBody> </Table> </div> )} </SettingsSectionWide> <InvoicesPreview ref={previewRef} invoices={invoices} onDownload={handleDownload} getFilename={getFilename} /> {renderInvoiceModal && <InvoiceTextModal {...invoiceModalProps} />} </> ); }; export default InvoicesSection;
6,320
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/invoices/PayInvoiceModal.tsx
import { c } from 'ttag'; import { usePaymentFacade } from '@proton/components/payments/client-extensions'; import { PAYMENT_METHOD_TYPES } from '@proton/components/payments/core'; import { PaymentProcessorHook } from '@proton/components/payments/react-extensions/interface'; import { useLoading } from '@proton/hooks'; import { checkInvoice } from '@proton/shared/lib/api/payments'; import { captureMessage } from '@proton/shared/lib/helpers/sentry'; import { toPrice } from '@proton/shared/lib/helpers/string'; import { Currency } from '@proton/shared/lib/interfaces'; import { getSentryError } from '@proton/shared/lib/keys'; import { EllipsisLoader, Field, FormModal, Input, Label, Price, PrimaryButton, Row } from '../../components'; import { useApiResult, useEventManager, useNotifications } from '../../hooks'; import PaymentWrapper from '../payments/PaymentWrapper'; import StyledPayPalButton from '../payments/StyledPayPalButton'; import { Invoice } from './interface'; interface CheckInvoiceResponse { Code: number; Currency: Currency; Amount: number; Gift: number; Credit: number; AmountDue: number; } export interface Props { invoice: Invoice; fetchInvoices: () => void; onClose?: () => void; } const PayInvoiceModal = ({ invoice, fetchInvoices, ...rest }: Props) => { const { createNotification } = useNotifications(); const [loading, withLoading] = useLoading(); const { call } = useEventManager(); const { result, loading: amountLoading } = useApiResult<CheckInvoiceResponse, typeof checkInvoice>( () => checkInvoice(invoice.ID), [] ); const { AmountDue, Amount, Currency, Credit } = result ?? {}; const amount = AmountDue ?? 0; const currency = Currency as Currency; const paymentFacade = usePaymentFacade({ amount, currency, onChargeable: (operations) => { return withLoading(async () => { await operations.payInvoice(); await Promise.all([ call(), // Update user.Delinquent to hide TopBanner fetchInvoices(), ]); rest.onClose?.(); createNotification({ text: c('Success').t`Invoice paid` }); }); }, flow: 'invoice', }); const process = async (processor?: PaymentProcessorHook) => withLoading(async () => { if (!processor) { return; } try { paymentFacade.paymentContext.setInvoiceData({ invoiceId: invoice.ID, }); await processor.processPaymentToken(); } catch (e) { const error = getSentryError(e); if (error) { const context = { invoiceId: invoice.ID, currency, amount, processorType: paymentFacade.selectedProcessor?.meta.type, paymentMethod: paymentFacade.selectedMethodType, paymentMethodValue: paymentFacade.selectedMethodValue, }; captureMessage('Payments: failed to pay invoice', { level: 'error', extra: { error, context }, }); } } }); const submit = paymentFacade.selectedMethodValue === PAYMENT_METHOD_TYPES.PAYPAL ? ( <StyledPayPalButton type="submit" paypal={paymentFacade.paypal} amount={amount} currency={paymentFacade.currency} loading={loading} data-testid="paypal-button" /> ) : ( <PrimaryButton loading={loading} disabled={paymentFacade.methods.loading || !paymentFacade.userCanTriggerSelected} type="submit" data-testid="pay-invoice-button" > {c('Action').t`Pay`} </PrimaryButton> ); return ( <FormModal onSubmit={() => process(paymentFacade.selectedProcessor)} loading={loading} close={c('Action').t`Close`} submit={submit} title={c('Title').t`Pay invoice`} data-testid="pay-invoice-modal" {...rest} > {amountLoading ? ( <EllipsisLoader /> ) : ( <> {!!Credit && ( <> <Row> <Label>{c('Label').t`Amount`}</Label> <Field className="text-right"> <Price className="label" currency={currency}> {Amount ?? 0} </Price> </Field> </Row> <Row> <Label>{c('Label').t`Credits used`}</Label> <Field className="text-right"> <Price className="label" currency={currency}> {Credit} </Price> </Field> </Row> </> )} <Row> <Label>{c('Label').t`Amount due`}</Label> <Field> <Input className="field--highlight no-pointer-events text-strong text-right" readOnly value={toPrice(amount, currency)} /> </Field> </Row> {amount > 0 ? ( <PaymentWrapper {...paymentFacade} onPaypalCreditClick={() => process(paymentFacade.paypalCredit)} noMaxWidth /> ) : null} </> )} </FormModal> ); }; export default PayInvoiceModal;
6,321
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/invoices/index.ts
export { default as PayInvoiceModal } from './PayInvoiceModal'; export { default as InvoiceState } from './InvoiceState'; export { default as InvoiceType } from './InvoiceType'; export { default as InvoiceAmount } from './InvoiceAmount'; export { default as InvoiceTextModal } from './InvoiceTextModal'; export { default as InvoicesSection } from './InvoicesSection'; export { default as InvoiceActions } from './InvoiceActions';
6,322
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/invoices/interface.ts
import { INVOICE_STATE } from '@proton/shared/lib/constants'; import { Currency } from '@proton/shared/lib/interfaces'; export interface Invoice { ID: string; Type: number; State: INVOICE_STATE; Currency: Currency; AmountDue: number; AmountCharged: number; CreateTime: number; ModifyTime: number; AttemptTime: number; Attempts: number; } export interface InvoiceResponse { Code: number; Invoices: Invoice[]; Total: number; }
6,323
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/items/ItemCheckbox.tsx
import { ChangeEvent, FocusEventHandler, MouseEventHandler } from 'react'; import { DENSITY } from '@proton/shared/lib/constants'; import clsx from '@proton/utils/clsx'; import { Checkbox, Icon, IconName } from '../../components'; import { useUserSettings } from '../../hooks'; import { ContactImage } from '../contacts'; interface Props { ID?: string; name?: string; email?: string; iconName?: IconName; color?: string; compactClassName?: string; normalClassName?: string; bimiSelector?: string; displaySenderImage?: boolean; checked: boolean; onChange: (event: ChangeEvent<HTMLInputElement>) => void; } const ItemCheckbox = ({ ID = '', name = '', email = '', iconName, color, compactClassName, normalClassName, checked, bimiSelector, displaySenderImage, onChange, }: Props) => { const [userSettings] = useUserSettings(); const isCompactView = userSettings.Density === DENSITY.COMPACT; /** * Due to the way we handle focus of parent elements * we need to stop propagation of click and focus * on checkbox label. */ const handleClick: MouseEventHandler<HTMLLabelElement> = (event) => event.stopPropagation(); const handleFocus: FocusEventHandler<HTMLLabelElement> = (event) => event.stopPropagation(); return isCompactView ? ( <Checkbox className={clsx(['item-icon-compact', compactClassName])} checked={checked} onChange={onChange} labelOnClick={handleClick} data-item-id={ID} aria-describedby={ID} data-testid="item-checkbox" /> ) : ( <label className={clsx(['item-checkbox-label relative', normalClassName])} onClick={handleClick} onFocus={handleFocus} > <input type="checkbox" className="item-checkbox inner-ratio-container cursor-pointer m-0" checked={checked} onChange={onChange} data-item-id={ID} data-testid="item-checkbox" /> <span className="item-icon flex-item-noshrink relative rounded inline-flex" style={{ backgroundColor: color ?? '', }} data-testid="element-list:message-checkbox" aria-hidden="true" > <span className="m-auto item-abbr rounded no-scroll" aria-hidden="true"> {iconName ? ( <Icon name={iconName} color="white" /> ) : ( <ContactImage email={email} name={name} bimiSelector={bimiSelector} displaySenderImage={displaySenderImage} className="rounded relative" /> )} </span> <span className="item-icon-fakecheck m-auto"> <Icon color={color ? 'white' : undefined} name="checkmark" className="item-icon-fakecheck-icon" /> </span> </span> </label> ); }; export default ItemCheckbox;
6,324
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/items/constants.ts
/** * ID used in the drag DataTransfer object to store items ids currently dragged */ export const DRAG_ITEM_KEY = 'drag-item'; /** * ID used in the drag DataTransfer object to store the HTML id of the dragged element */ export const DRAG_ITEM_ID_KEY = 'drag-item-id';
6,325
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/items/index.ts
export { default as useItemsSelection } from './useItemsSelection'; export { default as useItemsDraggable } from './useItemsDraggable'; export { default as useItemsDroppable } from './useItemsDroppable'; export { default as ItemCheckbox } from './ItemCheckbox';
6,326
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/items/items.scss
.drag-element { position: absolute; background-color: white; color: black; font-weight: var(--font-weight-bold); z-index: -1; inset-block-start: 0; inset-inline-start: 0; } .item-dragging { opacity: 0.5; } .navigation__dragover { background: var(--interaction-default-hover); }
6,327
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/items/useItemsDraggable.ts
import { DragEvent, useCallback, useEffect, useState } from 'react'; import { generateUID } from '../../helpers'; import useHandler from '../../hooks/useHandler'; import { DRAG_ITEM_ID_KEY, DRAG_ITEM_KEY } from './constants'; import './items.scss'; type AbstractItem = { ID?: string }; /** * Implement the draggable logic for an item * Linked to the selection logic to drag the currently selected elements * or to restore the selection after the drag * Also take care of rendering the drag element and including the needed data in the transfer * Items can be any object containing an ID * @param items List of all items in the list * @param checkedIDs List of the currently checked IDs * @param onCheck Check handler to update selection * @param getDragHtml Callback to return HTML content of the drag element * @returns Currently dragged ids and drag handler to pass to items */ const useItemsDraggable = <Item extends AbstractItem>( items: Item[], checkedIDs: string[], onCheck: (IDs: string[], checked: boolean, replace: boolean) => void, getDragHtml: (draggedIDs: string[]) => string ) => { // HTML reference to the drag element const [dragElement, setDragElement] = useState<HTMLDivElement>(); // List of currently dragged item ids const [draggedIDs, setDraggedIDs] = useState<string[]>([]); // Saved selection when dragging an item not selected const [savedCheck, setSavedCheck] = useState<string[]>(); useEffect(() => { setDraggedIDs([]); }, [items]); const clearDragElement = useCallback(() => { if (dragElement) { document.body.removeChild(dragElement); setDragElement(undefined); } }, [setDragElement]); const handleDragCanceled = useHandler(() => { setDraggedIDs([]); if (savedCheck) { onCheck(savedCheck, true, true); setSavedCheck(undefined); } }); /** * Drag end handler to use on the draggable element */ const handleDragEnd = useCallback( (event: DragEvent) => { // Always clear the drag element no matter why the drag has ended clearDragElement(); // We discover that Chrome initialize the dropEffect to 'copy' and only set it to 'none' just after // We don't use 'copy' at all so both 'none' and 'copy' effects can be considered as canceled drags if (event.dataTransfer.dropEffect === 'none' || event.dataTransfer.dropEffect === 'copy') { return handleDragCanceled(); } }, [clearDragElement, handleDragCanceled] ); const handleDragSucceed = useHandler((action: string | undefined) => { clearDragElement(); setDraggedIDs([]); if (savedCheck) { if (action === 'link') { // Labels onCheck(savedCheck, true, true); } setSavedCheck(undefined); } }); /** * Drag start handler to use on the draggable element */ const handleDragStart = useCallback( (event: DragEvent, item: Item) => { clearDragElement(); const ID = item.ID || ''; const dragInSelection = checkedIDs.includes(ID); const selection = dragInSelection ? checkedIDs : [ID]; setDraggedIDs(selection); setSavedCheck(checkedIDs); if (!dragInSelection) { onCheck([], true, true); } const dragElement = document.createElement('div'); dragElement.innerHTML = getDragHtml(selection); dragElement.className = 'drag-element p-4 border rounded'; dragElement.id = generateUID(DRAG_ITEM_ID_KEY); // Wiring the dragend event on the drag element because the one from drag start is not reliable dragElement.addEventListener('dragend', (event) => handleDragSucceed(event.dataTransfer?.dropEffect)); document.body.appendChild(dragElement); event.dataTransfer.setDragImage(dragElement, 0, 0); event.dataTransfer.setData(DRAG_ITEM_KEY, JSON.stringify(selection)); event.dataTransfer.setData(DRAG_ITEM_ID_KEY, dragElement.id); setDragElement(dragElement); }, [checkedIDs, onCheck] ); return { draggedIDs, handleDragStart, handleDragEnd }; }; export default useItemsDraggable;
6,328
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/items/useItemsDroppable.ts
import { DragEvent } from 'react'; import { useDragOver } from '../../hooks'; import { DRAG_ITEM_ID_KEY, DRAG_ITEM_KEY } from './constants'; /** * Implement the logic of receiving the drop of items from the item list * Prepare all drag handlers for receiving zones and parse events to get items ids * @param dragFilter Filter to accept or not drop on this zone * @param dropEffect Drop effect type to use * @param dropCallback Drop callback to run when a drop event occurs with parsed items ids * @returns All drag handler to use */ const useItemsDroppable = ( dragFilter: (event: DragEvent) => boolean, dropEffect: 'none' | 'copy' | 'link' | 'move' = 'move', dropCallback: (itemIDs: string[]) => void | Promise<void> ) => { const [dragOver, dragProps] = useDragOver( (event: DragEvent) => event.dataTransfer.types.includes(DRAG_ITEM_KEY) && dragFilter(event), dropEffect ); const handleDrop = async (event: DragEvent) => { dragProps.onDrop(event); const data = event.dataTransfer.getData(DRAG_ITEM_KEY); // If no data dont handle drop if (data) { // Manual trigger of the dragend event on the drag element because native event is not reliable const dragElement = document.getElementById(event.dataTransfer.getData(DRAG_ITEM_ID_KEY)); const dragendEvent = new Event('dragend') as any; dragendEvent.dataTransfer = event.dataTransfer; dragendEvent.dataTransfer.dropEffect = dropEffect; // Chrome is losing the original dropEffect dragElement?.dispatchEvent(dragendEvent); const itemIDs = JSON.parse(data) as string[]; void dropCallback(itemIDs); } }; return { dragOver, dragProps, handleDrop }; }; export default useItemsDroppable;
6,329
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/items/useItemsSelection.ts
import { ChangeEvent, DependencyList, useEffect, useMemo, useState } from 'react'; import useHandler from '../../hooks/useHandler'; /** * Implement the selection logic shared between mail and contacts * You have an active id which represents the selection if there is no checked items * As soon as you have checked items, it replaces the active item * Items can be any object, we only deal with IDs * @param activeID The current active item * @param allIDs The complete list of ids in the list * @param resetDependencies React dependencies to reset selection if there is a change * @returns all helpers usefull to check one, a range or all items */ const useItemsSelection = (activeID: string | undefined, allIDs: string[], resetDependencies: DependencyList) => { // We are managing checked IDs through a Map and not an array for performance issues. const [checkedMap, setCheckedMap] = useState<{ [ID: string]: boolean }>({}); // Last item check to deal with range selection const [lastChecked, setLastChecked] = useState<string>(''); const isChecked = (ID: string) => !!checkedMap[ID]; useEffect(() => setCheckedMap({}), resetDependencies); const checkedIDs = useMemo(() => { return Object.entries(checkedMap).reduce<string[]>((acc, [ID, isChecked]) => { if (!isChecked) { return acc; } acc.push(ID); return acc; }, []); }, [checkedMap]); const selectedIDs = useMemo(() => { if (checkedIDs.length) { return checkedIDs; } if (activeID) { return [activeID]; } return []; }, [checkedIDs, activeID]); /** * Put *IDs* to *checked* state * Uncheck others if *replace* is true */ const handleCheck = useHandler((IDs: string[], checked: boolean, replace: boolean) => { setCheckedMap( allIDs.reduce<{ [ID: string]: boolean }>((acc, ID) => { const wasChecked = isChecked(ID); const toCheck = IDs.includes(ID); let value: boolean; if (toCheck) { value = checked; } else if (replace) { value = !checked; } else { value = wasChecked; } acc[ID] = value; return acc; }, {}) ); setLastChecked(''); }); /** * Check or uncheck all items */ const handleCheckAll = useHandler((check: boolean) => check ? handleCheck(allIDs, true, true) : handleCheck([], true, true) ); /** * Just check the given id, nothing more */ const handleCheckOnlyOne = useHandler((id: string) => { handleCheck([id], !isChecked(id), false); setLastChecked(id); }); /** * Check all items from the last checked to the given id */ const handleCheckRange = useHandler((id: string) => { const ids = [id]; if (lastChecked) { const start = allIDs.findIndex((ID) => ID === id); const end = allIDs.findIndex((ID) => ID === lastChecked); ids.push(...allIDs.slice(Math.min(start, end), Math.max(start, end) + 1)); } handleCheck(ids, !isChecked(id), false); setLastChecked(id); }); /** * Check only one or check range depending on the shift key value in the event */ const handleCheckOne = useHandler((event: ChangeEvent, id: string) => { const { shiftKey } = event.nativeEvent as any; if (shiftKey) { handleCheckRange(id); } else { handleCheckOnlyOne(id); } }); // Automatically uncheck an id which is not anymore in the list (Happens frequently when using search) useEffect(() => { const filteredCheckedIDs = checkedIDs.filter((id) => allIDs.includes(id)); if (filteredCheckedIDs.length !== checkedIDs.length) { handleCheck(filteredCheckedIDs, true, true); } }, [allIDs]); return { checkedIDs, selectedIDs, handleCheck, handleCheckAll, handleCheckOne, handleCheckOnlyOne, handleCheckRange, }; }; export default useItemsSelection;
6,330
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/keyTransparency/KeyTransparencyManager.tsx
import { ReactNode, useEffect, useState } from 'react'; import useApiStatus from '@proton/components/hooks/useApiStatus'; import { ktSentryReportError } from '@proton/key-transparency/lib'; import { APP_NAMES, SECOND } from '@proton/shared/lib/constants'; import { KeyTransparencyActivation, KeyTransparencyState } from '@proton/shared/lib/interfaces'; import { useOnline } from '../../hooks'; import { KTContext } from './ktContext'; import useKTActivation from './useKTActivation'; import { KeyTransparencyContext } from './useKeyTransparencyContext'; import useRunSelfAudit from './useRunSelfAudit'; import useVerifyOutboundPublicKeys from './useVerifyOutboundPublicKeys'; interface Props { children: ReactNode; appName: APP_NAMES; } const KeyTransparencyManager = ({ children }: Props) => { const ktActivation = useKTActivation(); const [ktState, setKTState] = useState<KeyTransparencyState>({ selfAuditResult: undefined, }); const [selfAuditPending, setSelfAuditPending] = useState(false); const verifyOutboundPublicKeys = useVerifyOutboundPublicKeys(); const runSelfAudit = useRunSelfAudit(); const { offline } = useApiStatus(); const onlineStatus = useOnline(); const safeIsOnline = onlineStatus && !offline; useEffect(() => { const run = async () => { try { const { selfAuditResult } = await runSelfAudit(); setKTState({ selfAuditResult }); } catch (error) { ktSentryReportError(error, { context: 'runSelfAuditPeriodically' }); } }; if (selfAuditPending && ktActivation !== KeyTransparencyActivation.DISABLED && safeIsOnline) { setSelfAuditPending(false); run(); } }, [selfAuditPending, ktActivation, safeIsOnline]); useEffect(() => { const startDelay = 10 * SECOND; const delay = ktState?.selfAuditResult ? ktState.selfAuditResult.nextAuditTime - ktState.selfAuditResult.auditTime : startDelay; const timeoutID = setTimeout(() => setSelfAuditPending(true), delay); return () => clearTimeout(timeoutID); }, [ktState]); const ktFunctions: KTContext = { ktState, ktActivation, verifyOutboundPublicKeys, }; return <KeyTransparencyContext.Provider value={ktFunctions}>{children}</KeyTransparencyContext.Provider>; }; export default KeyTransparencyManager;
6,331
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/keyTransparency/createKeyMigrationKTVerifier.ts
import { KeyTransparencyError, fetchLatestEpoch, ktSentryReport, ktSentryReportError, verifyAddressIsAbsent, verifyAddressIsObsolete, } from '@proton/key-transparency/lib'; import { Api, FetchedSignedKeyList, KeyMigrationKTVerifier, KeyTransparencyActivation, } from '@proton/shared/lib/interfaces'; const createKeyMigrationKTVerifier = (ktActivation: KeyTransparencyActivation, api: Api): KeyMigrationKTVerifier => { return async (email: string, signedKeyList: Partial<FetchedSignedKeyList> | null | undefined) => { if (ktActivation === KeyTransparencyActivation.DISABLED) { return; } try { const epoch = await fetchLatestEpoch(api); if (signedKeyList?.ObsolescenceToken) { await verifyAddressIsObsolete(epoch, email, signedKeyList, api); } else { await verifyAddressIsAbsent(epoch, email, api); } } catch (error: any) { if (error instanceof KeyTransparencyError) { ktSentryReport('KT error during key migration', { error: error.message }); } else { ktSentryReportError(error, { context: 'KeyMigrationKTVerifier' }); } } }; }; export default createKeyMigrationKTVerifier;
6,332
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/keyTransparency/createPreAuthKTVerifier.ts
import { serverTime } from '@proton/crypto'; import { commitSKLToLS, fetchSignedKeyLists, ktSentryReport, ktSentryReportError } from '@proton/key-transparency'; import { Address, Api, DecryptedKey, KeyTransparencyActivation, PreAuthKTVerifier, PreAuthKTVerify, SignedKeyList, } from '@proton/shared/lib/interfaces'; import { getDefaultKTLS } from '@proton/shared/lib/keyTransparency'; /** * Return a KT verifier for when getSignedKeyList is called before apps are properly mounted, * e.g. signup or login, such that self audit couldn't have run and user keys are not directly accessible */ const createPreAuthKTVerifier = (ktActivation: KeyTransparencyActivation, api: Api): PreAuthKTVerifier => { interface CreatedSKL { address: Address; revision?: number; userKeys: DecryptedKey[]; signedKeyList: SignedKeyList; creationTimestamp: number; } var createdSKLs: CreatedSKL[] = []; const ktLSAPI = getDefaultKTLS(); const preAuthKTVerify: PreAuthKTVerify = (userKeys: DecryptedKey[]) => async (address, signedKeyList) => { if (ktActivation === KeyTransparencyActivation.DISABLED) { return; } createdSKLs.push({ address, revision: address.SignedKeyList?.Revision, userKeys, signedKeyList, creationTimestamp: +serverTime(), }); }; const preAuthKTCommit = async (userID: string) => { try { if (ktActivation === KeyTransparencyActivation.DISABLED) { return; } if (!createdSKLs.length) { return; } for (const savedSKL of createdSKLs) { const allSKLs = await fetchSignedKeyLists(api, savedSKL.revision ?? 0, savedSKL.address.Email); const correspondingSKL = allSKLs.find((skl) => savedSKL.signedKeyList.Data == skl.Data); if (!correspondingSKL || !correspondingSKL.Revision || !correspondingSKL.ExpectedMinEpochID) { ktSentryReport('Could not find new SKL revision and expectedMinEpochID', { email: savedSKL.address.Email, }); return; } const privateKeys = savedSKL.userKeys.map(({ privateKey }) => privateKey); const ktBlob = { creationTimestamp: savedSKL.creationTimestamp, expectedMinEpochID: correspondingSKL.ExpectedMinEpochID, revision: correspondingSKL.Revision, email: savedSKL.address.Email, data: savedSKL.signedKeyList.Data, }; await commitSKLToLS(ktBlob, privateKeys, ktLSAPI, userID, savedSKL.address.ID); } createdSKLs = []; } catch (error: any) { ktSentryReportError(error, { context: 'preAuthKTCommit' }); } }; return { preAuthKTVerify, preAuthKTCommit, }; }; export default createPreAuthKTVerifier;
6,333
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/keyTransparency/index.ts
export { default as KeyTransparencyManager } from './KeyTransparencyManager'; export { default as createPreAuthKTVerifier } from './createPreAuthKTVerifier'; export { default as useKTVerifier } from './useKTVerifier'; export { default as useKeyMigrationKTVerifier } from './useKeyMigrationKTVerifier'; export { default as createKeyMigrationKTVerifier } from './createKeyMigrationKTVerifier'; export * from './useKeyTransparencyContext'; export { default as useResetSelfAudit } from './useResetSelfAudit';
6,334
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/keyTransparency/ktContext.ts
import { KeyTransparencyActivation, KeyTransparencyState, VerifyOutboundPublicKeys, } from '@proton/shared/lib/interfaces'; import { defaultKeyTransparencyState } from '@proton/shared/lib/keyTransparency'; export interface KTContext { verifyOutboundPublicKeys: VerifyOutboundPublicKeys; ktActivation: KeyTransparencyActivation; ktState: KeyTransparencyState; } export const defaultKTContext: KTContext = { verifyOutboundPublicKeys: async () => { return {}; }, ktActivation: KeyTransparencyActivation.DISABLED, ktState: defaultKeyTransparencyState, };
6,335
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/keyTransparency/ktStatus.ts
import { KT_DOMAINS, getBaseDomain } from '@proton/key-transparency'; import { isIos11, isSafari11 } from '@proton/shared/lib/helpers/browser'; export enum KtFeatureEnum { DISABLE, ENABLE_CORE, ENABLE_UI, } export type KT_FF = KtFeatureEnum | undefined; export const isKTActive = (feature: KT_FF) => { // Do not activate KT if // - feature flag is off; // - the api is not prod's or proton.black's // - safari 11 or ios 11 is used due to issues with the CryptoProxy // - BigInt is not supported (it is needed for VRF verification); if (feature === undefined || feature === KtFeatureEnum.DISABLE) { return false; } const domain = getBaseDomain(false); if (domain === KT_DOMAINS.UNKNOWN) { return false; } if (isSafari11() || isIos11()) { return false; } return typeof BigInt !== 'undefined'; };
6,336
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/keyTransparency/useGetLatestEpoch.ts
import { useCallback } from 'react'; import { getPromiseValue } from '@proton/components/hooks/useCachedModelResult'; import { fetchLatestEpoch } from '@proton/key-transparency/lib'; import { getSilentApi } from '@proton/shared/lib/api/helpers/customConfig'; import { HOUR } from '@proton/shared/lib/constants'; import { GetLatestEpoch } from '@proton/shared/lib/interfaces'; import { useApi, useCache } from '../../hooks'; export const CACHE_KEY = 'KEY_TRANSPARENCY_EPOCH'; const DEFAULT_LIFETIME = 2 * HOUR; const useGetLatestEpoch = (): GetLatestEpoch => { const cache = useCache(); const normalApi = useApi(); const silentApi = getSilentApi(normalApi); const miss = useCallback(() => fetchLatestEpoch(silentApi), [silentApi]); return useCallback( (forceRefresh?: boolean) => { if (forceRefresh) { cache.delete(CACHE_KEY); } return getPromiseValue(cache, CACHE_KEY, miss, DEFAULT_LIFETIME); }, [cache, miss] ); }; export default useGetLatestEpoch;
6,337
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/keyTransparency/useKTActivation.ts
import { useEffect, useState } from 'react'; import { APPS, APP_NAMES } from '@proton/shared/lib/constants'; import { KeyTransparencyActivation, MailSettings } from '@proton/shared/lib/interfaces'; import { KEY_TRANSPARENCY_SETTING } from '@proton/shared/lib/mail/mailSettings'; import { useAuthentication, useConfig, useFeature, useGetMailSettings } from '../../hooks'; import { FeatureCode } from '../features'; import { KT_FF, KtFeatureEnum, isKTActive } from './ktStatus'; const getKTActivation = ( featureFlag: KT_FF, appName: APP_NAMES, mailSettings?: MailSettings ): KeyTransparencyActivation => { if (!featureFlag) { return KeyTransparencyActivation.DISABLED; } if (!isKTActive(featureFlag)) { return KeyTransparencyActivation.DISABLED; } if (featureFlag == KtFeatureEnum.ENABLE_CORE) { return KeyTransparencyActivation.LOG_ONLY; } if (featureFlag == KtFeatureEnum.ENABLE_UI) { if (appName === APPS.PROTONMAIL) { if (mailSettings?.KT === KEY_TRANSPARENCY_SETTING.ENABLED) { return KeyTransparencyActivation.SHOW_UI; } else { return KeyTransparencyActivation.LOG_ONLY; } } return KeyTransparencyActivation.SHOW_UI; } return KeyTransparencyActivation.DISABLED; }; const getKTFeatureCode = (appName: APP_NAMES): FeatureCode | undefined => { switch (appName) { case APPS.PROTONMAIL: return FeatureCode.KeyTransparencyMail; case APPS.PROTONACCOUNT: return FeatureCode.KeyTransparencyAccount; case APPS.PROTONCALENDAR: return FeatureCode.KeyTransparencyCalendar; case APPS.PROTONDRIVE: return FeatureCode.KeyTransparencyDrive; } }; const useKTActivation = (): KeyTransparencyActivation => { const { APP_NAME: appName } = useConfig(); const { UID } = useAuthentication(); const isAuthenticated = !!UID; const featureCode = getKTFeatureCode(appName); const { feature } = useFeature<KT_FF>(featureCode ?? FeatureCode.KeyTransparencyAccount); const featureFlag = featureCode ? feature?.Value : undefined; const [ktActivation, setKTActivation] = useState(KeyTransparencyActivation.DISABLED); const getMailSettings = useGetMailSettings(); useEffect(() => { const run = async () => { const mailSettings = isAuthenticated ? await getMailSettings() : undefined; const ktActivation = getKTActivation(featureFlag, appName, mailSettings); setKTActivation(ktActivation); }; void run(); }, [featureFlag, appName, isAuthenticated, getMailSettings]); return ktActivation; }; export default useKTActivation;
6,338
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/keyTransparency/useKTVerifier.ts
import { useRef } from 'react'; import { serverTime } from '@proton/crypto'; import { commitSKLToLS, fetchSignedKeyLists, getKTLocalStorage, ktSentryReport, ktSentryReportError, } from '@proton/key-transparency'; import { Address, Api, DecryptedKey, KeyTransparencyActivation, KeyTransparencyCommit, KeyTransparencyVerify, SignedKeyList, UserModel, } from '@proton/shared/lib/interfaces'; import { useConfig } from '../../hooks'; import useKTActivation from './useKTActivation'; /** * Return a KT verifier for when the state exists, i.e. we are inside the apps * and therefore self audit could run and the normal flow of verification can be performed */ const useKTVerifier = (api: Api, getUser: () => Promise<UserModel>) => { const { APP_NAME } = useConfig(); const ktLSAPIPromise = getKTLocalStorage(APP_NAME); const ktActivation = useKTActivation(); interface CreatedSKL { address: Address; revision?: number; signedKeyList: SignedKeyList; creationTimestamp: number; } const createdSKLs = useRef<CreatedSKL[]>([]); const keyTransparencyVerify: KeyTransparencyVerify = async (address: Address, signedKeyList: SignedKeyList) => { if (ktActivation === KeyTransparencyActivation.DISABLED) { return; } createdSKLs.current.push({ address, revision: address.SignedKeyList?.Revision, signedKeyList, creationTimestamp: +serverTime(), }); }; const keyTransparencyCommit: KeyTransparencyCommit = async (userKeys: DecryptedKey[]) => { try { if (ktActivation === KeyTransparencyActivation.DISABLED) { return; } if (!createdSKLs.current.length) { return; } const user = await getUser(); const privateKeys = userKeys.map(({ privateKey }) => privateKey); const ktLSAPI = await ktLSAPIPromise; for (const savedSKL of createdSKLs.current) { const allSKLs = await fetchSignedKeyLists(api, savedSKL?.revision ?? 0, savedSKL.address.Email); const correspondingSKL = allSKLs.find((skl) => savedSKL.signedKeyList.Data == skl.Data); if (!correspondingSKL || !correspondingSKL.Revision || !correspondingSKL.ExpectedMinEpochID) { ktSentryReport('Could not find new SKL revision and expectedMinEpochID', { email: savedSKL.address.Email, }); return; } const ktBlob = { creationTimestamp: savedSKL.creationTimestamp, expectedMinEpochID: correspondingSKL.ExpectedMinEpochID, revision: correspondingSKL.Revision, email: savedSKL.address.Email, data: savedSKL.signedKeyList.Data, }; await commitSKLToLS(ktBlob, privateKeys, ktLSAPI, user.ID, savedSKL.address.ID); } createdSKLs.current = []; } catch (error: any) { ktSentryReportError(error, { context: 'KeyTransparencyCommit' }); } }; return { keyTransparencyVerify, keyTransparencyCommit, }; }; export default useKTVerifier;
6,339
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/keyTransparency/useKeyMigrationKTVerifier.ts
import { KeyMigrationKTVerifier } from '@proton/shared/lib/interfaces'; import useApi from '../../hooks/useApi'; import createKeyMigrationKTVerifier from './createKeyMigrationKTVerifier'; import useKTActivation from './useKTActivation'; const useKeyMigrationKTVerifier = () => { const ktActivation = useKTActivation(); const api = useApi(); const keyMigrationKTVerifier: KeyMigrationKTVerifier = createKeyMigrationKTVerifier(ktActivation, api); return { keyMigrationKTVerifier, }; }; export default useKeyMigrationKTVerifier;
6,340
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/keyTransparency/useKeyTransparencyContext.ts
import { createContext, useContext } from 'react'; import { KTContext, defaultKTContext } from './ktContext'; export const KeyTransparencyContext = createContext<KTContext>(defaultKTContext); export const useKeyTransparencyContext = () => useContext(KeyTransparencyContext);
6,341
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/keyTransparency/useReportSelfAuditErrors.ts
import { useCallback } from 'react'; import { AddressAuditStatus, SelfAuditResult, ktSentryReport } from '@proton/key-transparency/lib'; import { getSilentApi } from '@proton/shared/lib/api/helpers/customConfig'; import { TelemetryKeyTransparencyErrorEvents, TelemetryMeasurementGroups, TelemetryReport, } from '@proton/shared/lib/api/telemetry'; import { sendMultipleTelemetryReports } from '@proton/shared/lib/helpers/metrics'; import { KeyTransparencyActivation, SimpleMap } from '@proton/shared/lib/interfaces'; import { getWarningReason } from '@proton/shared/lib/keyTransparency/telemetry'; import { useApi } from '../../hooks'; import useKTActivation from './useKTActivation'; const useReportSelfAuditErrors = () => { const api = getSilentApi(useApi()); const ktActivation = useKTActivation(); const reportSelfAuditErrors = useCallback( async (selfAuditResult: SelfAuditResult) => { const failedAddressAuditsResults = selfAuditResult.addressAuditResults.filter( ({ status }) => status !== AddressAuditStatus.Success ); const failedLocalStorageAuditsOwn = selfAuditResult.localStorageAuditResultsOwnAddress.filter( ({ success }) => !success ); const failedLocalStorageAuditsOther = selfAuditResult.localStorageAuditResultsOtherAddress.filter( ({ success }) => !success ); const failedAddressAudits = failedAddressAuditsResults.map(({ email, status, warningDetails }) => ({ email, status, warningDetails, })); const failedLSAuditsOwn = failedLocalStorageAuditsOwn.map(({ email }) => email); const failedLSAuditsOther = failedLocalStorageAuditsOther.map(({ email }) => email); const tooManyRetries = selfAuditResult.error?.tooManyRetries; if ( failedAddressAudits.filter(({ status }) => status === AddressAuditStatus.Failure).length || failedLSAuditsOwn.length || failedLSAuditsOther.length || tooManyRetries ) { ktSentryReport('Self audit would display an error', { failedAddressAudits, failedLSAuditsOwn, failedLSAuditsOther, tooManyRetries: selfAuditResult.error?.tooManyRetries, }); } if ( failedAddressAudits.length || failedLSAuditsOwn.length || failedLSAuditsOther.length || tooManyRetries ) { const reports: TelemetryReport[] = []; const group = { measurementGroup: TelemetryMeasurementGroups.keyTransparency, event: TelemetryKeyTransparencyErrorEvents.self_audit_error, }; const visibility = ktActivation === KeyTransparencyActivation.SHOW_UI ? 'visible' : 'hidden'; if (tooManyRetries) { const dimensions: SimpleMap<string> = { type: 'too_many_retries', result: 'warning', reason: 'too_many_retries', visibility: visibility, }; reports.push({ ...group, dimensions, }); } failedAddressAuditsResults.forEach(({ status, warningDetails }) => { const dimensions: SimpleMap<string> = { type: 'address', result: status === AddressAuditStatus.Warning ? 'warning' : 'failure', reason: getWarningReason(warningDetails), visibility: visibility, }; reports.push({ ...group, dimensions, }); }); failedLocalStorageAuditsOwn.forEach(() => { const dimensions: SimpleMap<string> = { type: 'local_storage_own_keys', result: 'failure', reason: 'local_key_changes_not_applied', visibility: visibility, }; reports.push({ ...group, dimensions, }); }); failedLocalStorageAuditsOther.forEach(() => { const dimensions: SimpleMap<string> = { type: 'local_storage_other_keys', result: 'failure', reason: 'past_keys_not_authentic', visibility: visibility, }; reports.push({ ...group, dimensions, }); }); void sendMultipleTelemetryReports({ api: api, reports, }); } }, [api, ktActivation] ); return reportSelfAuditErrors; }; export default useReportSelfAuditErrors;
6,342
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/keyTransparency/useResetSelfAudit.ts
import { VerifiedEpoch, fetchLatestEpoch, ktSentryReportError, uploadVerifiedEpoch, } from '@proton/key-transparency/lib'; import { getSilentApi } from '@proton/shared/lib/api/helpers/customConfig'; import { getIsAddressDisabled } from '@proton/shared/lib/helpers/address'; import { Address, KeyTransparencyActivation, ResetSelfAudit, User } from '@proton/shared/lib/interfaces'; import { getDecryptedUserKeysHelper } from '@proton/shared/lib/keys'; import { useApi } from '../../hooks'; import useKTActivation from './useKTActivation'; /** * * Upload a fresh verified epoch to avoid failing self audit * after a password reset. */ const useResetSelfAudit = () => { const api = getSilentApi(useApi()); const ktActivation = useKTActivation(); const resetSelfAudit: ResetSelfAudit = async (user: User, keyPassword: string, addressesBeforeReset: Address[]) => { if (ktActivation === KeyTransparencyActivation.DISABLED) { return; } try { const [userKeys, { EpochID }] = await Promise.all([ getDecryptedUserKeysHelper(user, keyPassword), fetchLatestEpoch(api), ]); if (!userKeys.length) { return; } await Promise.all( addressesBeforeReset .filter((address) => !getIsAddressDisabled(address)) .map(async (address) => { if (!address.SignedKeyList) { return; } const { Revision } = address.SignedKeyList; if (!Revision) { return; } const newVerifiedEpoch: VerifiedEpoch = { EpochID, Revision: Revision, SKLCreationTime: 0, }; await uploadVerifiedEpoch(newVerifiedEpoch, address.ID, userKeys[0].privateKey, api); }) ); } catch (error: any) { ktSentryReportError(error, { context: 'resetSelfAudit' }); } }; return resetSelfAudit; }; export default useResetSelfAudit;
6,343
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/keyTransparency/useResignSKLWithPrimaryKey.ts
import { fetchSignedKeyLists, fetchVerifiedEpoch, ktSentryReportError, updateSignedKeyListSignature, verifySKLSignature, } from '@proton/key-transparency/lib'; import { getSilentApi } from '@proton/shared/lib/api/helpers/customConfig'; import { KeyTransparencyActivation, ResignSKLWithPrimaryKey, ResignSKLWithPrimaryKeyArguments, } from '@proton/shared/lib/interfaces'; import { getSignedKeyListSignature } from '@proton/shared/lib/keys'; import { useApi } from '../../hooks'; import useKTActivation from './useKTActivation'; const useResignSKLWithPrimaryKey = (): ResignSKLWithPrimaryKey => { const api = getSilentApi(useApi()); const ktActivation = useKTActivation(); const resignSKLWithPrimaryKey = async ({ address, newPrimaryKey, formerPrimaryKey, userKeys, }: ResignSKLWithPrimaryKeyArguments) => { try { if (ktActivation === KeyTransparencyActivation.DISABLED) { return; } const userVerificationKeys = userKeys.map((key) => key.publicKey); const verifiedEpoch = await fetchVerifiedEpoch(address, api, userVerificationKeys); const skls = await fetchSignedKeyLists(api, verifiedEpoch?.Revision ?? 0, address.Email); await Promise.all( skls.map(async (skl) => { if (skl.Data && skl.Signature) { const timestamp = await verifySKLSignature([formerPrimaryKey], skl.Data, skl.Signature); if (!timestamp) { return; } const newSignature = await getSignedKeyListSignature(skl.Data, newPrimaryKey, timestamp); await updateSignedKeyListSignature(address.ID, skl.Revision, newSignature, api); } }) ); } catch (error: any) { ktSentryReportError(error, { context: 'resignSKLWithPrimaryKey' }); } }; return resignSKLWithPrimaryKey; }; export default useResignSKLWithPrimaryKey;
6,344
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/keyTransparency/useRunSelfAudit.ts
import { useCallback } from 'react'; import { CryptoProxy, serverTime } from '@proton/crypto'; import { SelfAuditResult, StaleEpochError, getAuditResult, getKTLocalStorage, getSelfAuditInterval, ktSentryReportError, selfAudit, storeAuditResult, } from '@proton/key-transparency/lib'; import { getSilentApi } from '@proton/shared/lib/api/helpers/customConfig'; import { INTERVAL_EVENT_TIMER, MINUTE } from '@proton/shared/lib/constants'; import { KEY_TRANSPARENCY_REMINDER_UPDATE } from '@proton/shared/lib/drawer/interfaces'; import { wait } from '@proton/shared/lib/helpers/promise'; import { DecryptedAddressKey, KeyPair, SelfAuditState } from '@proton/shared/lib/interfaces'; import { getPrimaryKey } from '@proton/shared/lib/keys'; import { AddressesModel } from '@proton/shared/lib/models'; import { useApi, useConfig, useEventManager, useGetAddressKeys, useGetAddresses, useGetUserKeys, useUser, } from '../../hooks'; import useGetLatestEpoch from './useGetLatestEpoch'; import useReportSelfAuditErrors from './useReportSelfAuditErrors'; import useSaveSKLToLS from './useSaveSKLToLS'; import useUploadMissingSKL from './useUploadMissingSKL'; const SELF_AUDIT_MAX_TRIALS = 6; const useRunSelfAudit = () => { const getAddresses = useGetAddresses(); const getUserKeys = useGetUserKeys(); const getLatestEpoch = useGetLatestEpoch(); const [{ ID: userID }] = useUser(); const api = getSilentApi(useApi()); const { APP_NAME: appName } = useConfig(); const ktLSAPIPromise = getKTLocalStorage(appName); const uploadMissingSKL = useUploadMissingSKL(); const saveSKLToLS = useSaveSKLToLS(); const reportSelfAuditErrors = useReportSelfAuditErrors(); const getAddressKeys = useGetAddressKeys(); const selfAuditBaseInterval = getSelfAuditInterval(); const { subscribe } = useEventManager(); /* * Wait for the event loop to return an event with no address change * At this point self audit can be sure to have the latest version of addresses. */ const waitForAddressUpdates = async () => { let resolve: () => void; const eventPromise = new Promise<void>((_resolve) => (resolve = _resolve)); const unsubscribe = subscribe((data) => { if (!data[AddressesModel.key]) { resolve(); } }); await Promise.any([eventPromise, wait(5 * INTERVAL_EVENT_TIMER)]); unsubscribe(); }; const ignoreError = (error: any): boolean => { return error instanceof StaleEpochError; }; const reportError = (error: any, tooManyRetries: boolean) => { if (tooManyRetries || !ignoreError(error)) { ktSentryReportError(error, { context: 'runSelfAudit' }); } }; const createSelfAuditStateUserKeys = useCallback(async (): Promise<KeyPair[]> => { const userKeys = await getUserKeys(); const exportedUserKeys = await Promise.all( userKeys.map((key) => CryptoProxy.exportPrivateKey({ privateKey: key.privateKey, passphrase: null, format: 'binary', }) ) ); try { const selfAuditKeyReferences = await Promise.all( exportedUserKeys.map(async (key) => { const privateKey = await CryptoProxy.importPrivateKey({ binaryKey: key, passphrase: null, }); return { privateKey: privateKey, publicKey: privateKey, }; }) ); return selfAuditKeyReferences; } finally { exportedUserKeys.forEach((privateKey) => privateKey.fill(0)); } }, [getUserKeys]); const createSelfAuditStateAddressKeys = useCallback(async () => { const epoch = await getLatestEpoch(true); await waitForAddressUpdates(); const addressesWithoutKeys = await getAddresses(); const addressesKeys = await Promise.all(addressesWithoutKeys.map((address) => getAddressKeys(address.ID))); const exportedAddressesKeys = await Promise.all( addressesKeys.map(async (keys) => Promise.all( keys.map(async (key) => { const privateKey = await CryptoProxy.exportPrivateKey({ privateKey: key.privateKey, passphrase: null, format: 'binary', }); return { ID: key.ID, Flags: key.Flags, Primary: key.Primary, privateKey, }; }) ) ) ); try { const selfAuditAddressesKeys = await Promise.all<Promise<DecryptedAddressKey[]>>( exportedAddressesKeys.map(async (keys) => Promise.all( keys.map(async (key) => { const privateKey = await CryptoProxy.importPrivateKey({ binaryKey: key.privateKey, passphrase: null, }); return { ID: key.ID, Flags: key.Flags, Primary: key.Primary, privateKey: privateKey, publicKey: privateKey, }; }) ) ) ); const addresses = addressesWithoutKeys.map((address, index) => { return { address: address, addressKeys: selfAuditAddressesKeys[index], }; }); return { epoch, addresses }; } finally { exportedAddressesKeys.forEach((keys) => keys.forEach(({ privateKey }) => privateKey.fill(0))); } }, [getLatestEpoch, getAddresses, getAddressKeys]); const createSelfAuditState = async (): Promise<SelfAuditState> => { const [userKeys, addressKeys] = await Promise.all([ createSelfAuditStateUserKeys(), createSelfAuditStateAddressKeys(), ]); return { userKeys, ...addressKeys, }; }; const clearSelfAuditState = useCallback(async (state: SelfAuditState) => { const clearUserKeysPromise = Promise.all( state.userKeys.map(async ({ privateKey }) => CryptoProxy.clearKey({ key: privateKey })) ); const clearAddressKeysPromise = Promise.all( state.addresses.map(async ({ addressKeys }) => { await Promise.all(addressKeys.map(async ({ privateKey }) => CryptoProxy.clearKey({ key: privateKey }))); }) ); await Promise.all([clearUserKeysPromise, clearAddressKeysPromise]); }, []); const runSelfAuditWithState = async (state: SelfAuditState) => { const userPrivateKeys = state.userKeys.map(({ privateKey }) => privateKey); const { publicKey: userPrimaryPublicKey } = getPrimaryKey(state.userKeys) || {}; const ktLSAPI = await ktLSAPIPromise; if (!userPrimaryPublicKey) { throw new Error('User has no user keys'); } const lastSelfAudit = await getAuditResult(userID, userPrivateKeys, ktLSAPI); const now = +serverTime(); if (lastSelfAudit && lastSelfAudit.nextAuditTime > now) { return { selfAuditResult: lastSelfAudit, nextSelfAuditInterval: lastSelfAudit.nextAuditTime - now }; } try { const selfAuditResult = await selfAudit(userID, state, api, ktLSAPI, saveSKLToLS, uploadMissingSKL); // Update local storage value document.dispatchEvent( new CustomEvent(KEY_TRANSPARENCY_REMINDER_UPDATE, { detail: { value: false, }, }) ); await reportSelfAuditErrors(selfAuditResult); await storeAuditResult(userID, selfAuditResult, userPrimaryPublicKey, ktLSAPI); return { selfAuditResult, nextSelfAuditInterval: selfAuditBaseInterval }; } catch (error: any) { const failedTrials = (lastSelfAudit?.error?.failedTrials ?? 0) + 1; const tooManyRetries = failedTrials >= SELF_AUDIT_MAX_TRIALS; const currentTime = +serverTime(); const nextSelfAuditInterval = tooManyRetries ? selfAuditBaseInterval : Math.min(Math.pow(2, failedTrials) * MINUTE, selfAuditBaseInterval); const selfAuditResult: SelfAuditResult = { auditTime: currentTime, nextAuditTime: currentTime + nextSelfAuditInterval, addressAuditResults: [], localStorageAuditResultsOtherAddress: [], localStorageAuditResultsOwnAddress: [], error: { failedTrials: tooManyRetries ? 0 : failedTrials, tooManyRetries }, }; reportError(error, tooManyRetries); await reportSelfAuditErrors(selfAuditResult); await storeAuditResult(userID, selfAuditResult, userPrimaryPublicKey, ktLSAPI); return { selfAuditResult, nextSelfAuditInterval }; } }; const runSelfAudit = async () => { const state = await createSelfAuditState(); try { return await runSelfAuditWithState(state); } finally { await clearSelfAuditState(state); } }; return runSelfAudit; }; export default useRunSelfAudit;
6,345
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/keyTransparency/useSaveSKLToLS.ts
import { CryptoProxy, serverTime } from '@proton/crypto'; import { KTBlobContent, commitSKLToLS, getKTLocalStorage } from '@proton/key-transparency/lib'; import { encodeBase64URL, stringToUint8Array, uint8ArrayToString } from '@proton/shared/lib/helpers/encoding'; import { SaveSKLToLS } from '@proton/shared/lib/interfaces'; import { useConfig, useGetUserKeys, useUser } from '../../hooks'; /** * Generate a unique fake ID from an email address */ const generateID = async (userID: string, email: string) => { const digest = await CryptoProxy.computeHash({ algorithm: 'SHA256', data: stringToUint8Array(`${userID}${email}`), }); return encodeBase64URL(uint8ArrayToString(digest.slice(0, 64))); }; const useSaveSKLToLS = () => { const [{ ID: userID }] = useUser(); const { APP_NAME: appName } = useConfig(); const ktLSAPIPromise = getKTLocalStorage(appName); const getUserKeys = useGetUserKeys(); const saveSKLToLS: SaveSKLToLS = async ( email: string, data: string, revision: number, expectedMinEpochID: number, addressID?: string, isCatchall?: boolean ) => { // The fake address is generated just for matching purposes inside the stashedKeys // structure and to avoid writing the email in plaintext in localStorage const storedAddressID = addressID ?? (await generateID(userID, email)); const ktLSAPI = await ktLSAPIPromise; const ktBlobContent: KTBlobContent = { creationTimestamp: +serverTime(), email, data, revision, expectedMinEpochID, isCatchall, }; const userKeys = await getUserKeys(); await commitSKLToLS( ktBlobContent, userKeys.map(({ privateKey }) => privateKey), ktLSAPI, userID, storedAddressID ); }; return saveSKLToLS; }; export default useSaveSKLToLS;
6,346
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/keyTransparency/useUploadMissingSKL.ts
import { Epoch, fetchProof, throwKTError, updateSignedKeyList, verifyProofOfAbsenceForAllRevision, } from '@proton/key-transparency/lib'; import { getSilentApi } from '@proton/shared/lib/api/helpers/customConfig'; import { Address, SaveSKLToLS, UploadMissingSKL } from '@proton/shared/lib/interfaces'; import { getSignedKeyList } from '@proton/shared/lib/keys'; import { getActiveKeys, getNormalizedActiveKeys } from '@proton/shared/lib/keys/getActiveKeys'; import { useApi, useGetAddressKeys } from '../../hooks'; const useUploadMissingSKL = (): UploadMissingSKL => { const api = getSilentApi(useApi()); const getAddressKeys = useGetAddressKeys(); const uploadMissingSKL: UploadMissingSKL = async (address: Address, epoch: Epoch, saveSKLToLS: SaveSKLToLS) => { const proof = await fetchProof(epoch.EpochID, address.Email, 1, api); verifyProofOfAbsenceForAllRevision(proof, address.Email, epoch.TreeHash); const decryptedKeys = await getAddressKeys(address.ID); const activeKeys = getNormalizedActiveKeys( address, await getActiveKeys(address, null, address.Keys, decryptedKeys) ); const skl = await getSignedKeyList(activeKeys, address, async () => {}); const { Revision, ExpectedMinEpochID } = await updateSignedKeyList(api, address.ID, skl); if (!ExpectedMinEpochID) { return throwKTError('Returned SKL has no ExpectedMinEpochID', { addressID: address.ID }); } saveSKLToLS(address.Email, skl.Data, Revision, ExpectedMinEpochID, address.ID, false); }; return uploadMissingSKL; }; export default useUploadMissingSKL;
6,347
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/keyTransparency/useVerifyOutboundPublicKeys.ts
import { ktSentryReportError, verifyPublicKeysAddressAndCatchall } from '@proton/key-transparency/lib'; import { getSilentApi } from '@proton/shared/lib/api/helpers/customConfig'; import { FetchedSignedKeyList, KeyTransparencyActivation, KeyTransparencyVerificationResult, ProcessedApiAddressKey, VerifyOutboundPublicKeys, } from '@proton/shared/lib/interfaces'; import { useApi } from '../../hooks'; import useGetLatestEpoch from './useGetLatestEpoch'; import useKTActivation from './useKTActivation'; import useSaveSKLToLS from './useSaveSKLToLS'; const useVerifyOutboundPublicKeys = () => { const ktActivation = useKTActivation(); const saveSKLToLS = useSaveSKLToLS(); const api = getSilentApi(useApi()); const getLatestEpoch = useGetLatestEpoch(); const verifyOutboundPublicKeys: VerifyOutboundPublicKeys = async ( email: string, skipVerificationOfExternalDomains: boolean, address: { keyList: ProcessedApiAddressKey[]; signedKeyList: FetchedSignedKeyList | null; }, catchAll?: { keyList: ProcessedApiAddressKey[]; signedKeyList: FetchedSignedKeyList | null; } ): Promise<{ addressKTResult?: KeyTransparencyVerificationResult; catchAllKTResult?: KeyTransparencyVerificationResult; }> => { if (ktActivation === KeyTransparencyActivation.DISABLED) { return {}; } return verifyPublicKeysAddressAndCatchall( api, saveSKLToLS, getLatestEpoch, email, skipVerificationOfExternalDomains, address, catchAll ).catch((error) => { ktSentryReportError(error, { context: 'VerifyOutboundPublicKeys' }); return {}; }); }; return verifyOutboundPublicKeys; }; export default useVerifyOutboundPublicKeys;
6,348
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys/AddressKeysHeaderActions.tsx
import { ChangeEvent } from 'react'; import { c } from 'ttag'; import { Address } from '@proton/shared/lib/interfaces'; import isTruthy from '@proton/utils/isTruthy'; import { DropdownActions, Select } from '../../components'; interface Props { addresses: Address[]; addressIndex: number; onAddKey?: () => void; onImportKey?: () => void; onChangeAddress: (event: ChangeEvent<HTMLSelectElement>) => void; } const AddressKeysHeaderActions = ({ addresses, addressIndex, onAddKey, onImportKey, onChangeAddress }: Props) => { const createActions = [ onAddKey && { text: c('Action').t`Generate key`, onClick: onAddKey, }, onImportKey && { text: c('Action').t`Import key`, onClick: onImportKey, }, ].filter(isTruthy); if (!createActions.length && addresses.length <= 1) { return null; } return ( <div className="mb-4 flex flex-align-items-start"> {addresses.length > 1 && ( <div className="mr-4 mb-2"> <Select value={addressIndex} options={addresses.map(({ Email }, i) => ({ text: Email, value: i }))} onChange={onChangeAddress} /> </div> )} {createActions.length ? ( <span className="inline-flex mr-4 mb-2"> <DropdownActions list={createActions} /> </span> ) : null} </div> ); }; export default AddressKeysHeaderActions;
6,349
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys/AddressKeysSection.tsx
import { ChangeEvent, useEffect, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { AlgorithmInfo } from '@proton/crypto'; import { EncryptionConfig } from '@proton/shared/lib/interfaces'; import { OnKeyImportCallback, addAddressKeysProcess, deleteAddressKey, importKeysProcess, reactivateKeysProcess, setAddressKeyFlags, setPrimaryAddressKey, } from '@proton/shared/lib/keys'; import noop from '@proton/utils/noop'; import { Loader, useModalState } from '../../components'; import { useAddresses, useAddressesKeys, useApi, useAuthentication, useEventManager, useModals, useUser, useUserKeys, } from '../../hooks'; import { SettingsParagraph, SettingsSectionWide } from '../account'; import { useKTVerifier } from '../keyTransparency'; import useResignSKLWithPrimaryKey from '../keyTransparency/useResignSKLWithPrimaryKey'; import AddressKeysHeaderActions from './AddressKeysHeaderActions'; import KeysTable from './KeysTable'; import AddKeyModal from './addKey/AddKeyModal'; import DeleteKeyModal from './deleteKey/DeleteKeyModal'; import ExportPrivateKeyModal from './exportKey/ExportPrivateKeyModal'; import ExportPublicKeyModal from './exportKey/ExportPublicKeyModal'; import ImportKeyModal from './importKeys/ImportKeyModal'; import { ImportKey } from './importKeys/interface'; import ReactivateKeysModal from './reactivateKeys/ReactivateKeysModal'; import { getAllKeysReactivationRequests } from './reactivateKeys/getAllKeysToReactive'; import { getNewKeyFlags } from './shared/flags'; import { getKeyByID } from './shared/helper'; import { FlagAction } from './shared/interface'; import useDisplayKeys from './shared/useDisplayKeys'; const AddressKeysSection = () => { const { createModal } = useModals(); const { call } = useEventManager(); const authentication = useAuthentication(); const api = useApi(); const [User] = useUser(); const [Addresses, loadingAddresses] = useAddresses(); const [userKeys] = useUserKeys(); const [addressesKeys, loadingAddressesKeys] = useAddressesKeys(); const [loadingKeyID, setLoadingKeyID] = useState<string>(''); const [addressIndex, setAddressIndex] = useState(() => (Array.isArray(Addresses) ? 0 : -1)); const { keyTransparencyVerify, keyTransparencyCommit } = useKTVerifier(api, async () => User); const resignSKLWithPrimaryKey = useResignSKLWithPrimaryKey(); const Address = Addresses ? Addresses[addressIndex] : undefined; const { ID: addressID = '', Email: addressEmail = '' } = Address || {}; const addressWithKeys = addressesKeys?.find(({ address }) => address.ID === addressID); const addressKeys = addressWithKeys?.keys; const addressKeysDisplay = useDisplayKeys({ keys: addressKeys, Address, User, loadingKeyID, }); const existingAlgorithms = addressKeysDisplay.reduce<AlgorithmInfo[]>( (acc, { algorithmInfos }) => acc.concat(algorithmInfos), [] ); const [addKeyProps, setAddKeyModalOpen, renderAddKey] = useModalState(); const [importKeyProps, setImportKeyModalOpen, renderImportKey] = useModalState(); const [reactivateKeyProps, setReactivateKeyModalOpen, renderReactivateKey] = useModalState(); useEffect(() => { if (addressIndex === -1 && Array.isArray(Addresses)) { setAddressIndex(0); } }, [addressIndex, Addresses]); const isLoadingKey = loadingKeyID !== ''; const handleSetPrimaryKey = async (ID: string) => { if (isLoadingKey || !addressKeys) { return; } const addressKey = getKeyByID(addressKeys, ID); if (!addressKey || !Address) { throw new Error('Key not found'); } try { setLoadingKeyID(ID); const [newPrimaryKey] = await setPrimaryAddressKey(api, Address, addressKeys, ID, keyTransparencyVerify); await Promise.all([ resignSKLWithPrimaryKey({ address: Address, newPrimaryKey: newPrimaryKey.privateKey, formerPrimaryKey: addressKeys[0].publicKey, userKeys, }), keyTransparencyCommit(userKeys), ]); await call(); } finally { setLoadingKeyID(''); } }; const handleSetFlag = async (ID: string, flagAction: FlagAction) => { if (isLoadingKey || !addressKeys) { return; } const addressDisplayKey = getKeyByID(addressKeysDisplay, ID); if (!addressDisplayKey || !Address) { throw new Error('Key not found'); } try { setLoadingKeyID(ID); await setAddressKeyFlags( api, Address, addressKeys, ID, getNewKeyFlags(addressDisplayKey.flags, flagAction), keyTransparencyVerify ); await keyTransparencyCommit(userKeys); await call(); } finally { setLoadingKeyID(''); } }; const handleSetObsolete = (ID: string) => handleSetFlag(ID, FlagAction.MARK_OBSOLETE); const handleSetNotObsolete = (ID: string) => handleSetFlag(ID, FlagAction.MARK_NOT_OBSOLETE); const handleSetCompromised = (ID: string) => handleSetFlag(ID, FlagAction.MARK_COMPROMISED); const handleSetNotCompromised = (ID: string) => handleSetFlag(ID, FlagAction.MARK_NOT_COMPROMISED); const handleDeleteKey = (ID: string) => { if (isLoadingKey || !addressKeys) { return; } const addressKey = getKeyByID(addressKeys, ID); const addressDisplayKey = getKeyByID(addressKeysDisplay, ID); if (!addressDisplayKey || !Address) { throw new Error('Key not found'); } const { fingerprint } = addressDisplayKey; const privateKey = addressKey?.privateKey; const onDelete = async (): Promise<void> => { await deleteAddressKey(api, Address, addressKeys, ID, keyTransparencyVerify); await keyTransparencyCommit(userKeys); await call(); }; const onExport = (): Promise<void> => { return new Promise((resolve, reject) => { if (!privateKey) { return reject(new Error('Private key is not decrypted')); } createModal( <ExportPrivateKeyModal onClose={reject} onSuccess={resolve} name={addressEmail} privateKey={privateKey} /> ); }); }; createModal( <DeleteKeyModal onDelete={onDelete} onExport={privateKey ? onExport : undefined} fingerprint={fingerprint} /> ); }; const handleAddKey = () => { if (isLoadingKey || !addressKeys || !userKeys) { return; } if (!Address) { throw new Error('Keys not found'); } setAddKeyModalOpen(true); }; const onAdd = async (encryptionConfig: EncryptionConfig) => { if (!Address || !addressKeys) { throw new Error('Missing address or address keys'); } const [newKey] = await addAddressKeysProcess({ api, userKeys, encryptionConfig, addresses: Addresses, address: Address, addressKeys: addressKeys, keyPassword: authentication.getPassword(), keyTransparencyVerify, }); await Promise.all([ resignSKLWithPrimaryKey({ address: Address, newPrimaryKey: newKey.privateKey, formerPrimaryKey: addressKeys[0].publicKey, userKeys, }), keyTransparencyCommit(userKeys), ]); await call(); return newKey.fingerprint; }; const handleImportKey = () => { if (isLoadingKey || !addressKeys || !userKeys) { return; } if (!Address) { throw new Error('Keys not found'); } setImportKeyModalOpen(true); }; const onProcessImport = async (keyImportRecords: ImportKey[], cb: OnKeyImportCallback) => { if (!Address || !addressKeys) { throw new Error('Missing address or address keys'); } await importKeysProcess({ api, address: Address, addressKeys: addressKeys, addresses: Addresses, userKeys, keyImportRecords, keyPassword: authentication.getPassword(), onImport: cb, keyTransparencyVerify, }); await keyTransparencyCommit(userKeys); return call(); }; const handleExportPrivate = (ID: string) => { if (isLoadingKey || !addressKeys) { return; } const decryptedAddressKey = getKeyByID(addressKeys, ID); if (!decryptedAddressKey) { throw new Error('Key not found'); } createModal(<ExportPrivateKeyModal name={addressEmail} privateKey={decryptedAddressKey.privateKey} />); }; const handleExportPublic = (ID: string) => { if (isLoadingKey || !addressKeys) { return; } const decryptedAddressKey = getKeyByID(addressKeys, ID); const Key = getKeyByID(Address?.Keys || [], ID); if (!Key) { throw new Error('Key not found'); } createModal( <ExportPublicKeyModal name={addressEmail} fallbackPrivateKey={Key.PrivateKey} publicKey={decryptedAddressKey?.publicKey} /> ); }; const { isSubUser, isPrivate } = User; const hasDecryptedUserKeys = userKeys?.length > 0; const canAdd = !isSubUser && isPrivate && hasDecryptedUserKeys; const canImport = canAdd; const allKeysToReactivate = getAllKeysReactivationRequests(addressesKeys, User, userKeys); const children = (() => { if (addressIndex === -1 || loadingAddresses) { return ( <SettingsSectionWide> <Loader /> </SettingsSectionWide> ); } if (!Array.isArray(Addresses) || !Addresses.length) { return ( <SettingsSectionWide> <SettingsParagraph>{c('Info').t`No addresses exist`}</SettingsParagraph> </SettingsSectionWide> ); } if (loadingAddressesKeys && !Array.isArray(addressKeys)) { return ( <SettingsSectionWide> <Loader /> </SettingsSectionWide> ); } return ( <SettingsSectionWide> <SettingsParagraph> {c('Info').t`Download your PGP keys for use with other PGP-compatible services.`} </SettingsParagraph> {!!allKeysToReactivate.length && ( <div className="mb-4"> <Button disabled={isLoadingKey} color="norm" onClick={() => setReactivateKeyModalOpen(true)}> {c('Action').t`Reactivate keys`} </Button> </div> )} <AddressKeysHeaderActions addresses={Addresses} addressIndex={addressIndex} onAddKey={canAdd ? handleAddKey : undefined} onImportKey={canImport ? handleImportKey : undefined} onChangeAddress={({ target: { value } }: ChangeEvent<HTMLSelectElement>) => { if (isLoadingKey) { return; } setAddressIndex(+value); }} /> <KeysTable keys={addressKeysDisplay} onExportPrivateKey={handleExportPrivate} onExportPublicKey={handleExportPublic} onDeleteKey={handleDeleteKey} onSetPrimary={handleSetPrimaryKey} onSetCompromised={handleSetCompromised} onSetNotCompromised={handleSetNotCompromised} onSetObsolete={handleSetObsolete} onSetNotObsolete={handleSetNotObsolete} /> </SettingsSectionWide> ); })(); return ( <> {renderAddKey && ( <AddKeyModal type="address" existingAlgorithms={existingAlgorithms} onAdd={onAdd} {...addKeyProps} /> )} {renderImportKey && <ImportKeyModal onProcess={onProcessImport} {...importKeyProps} />} {renderReactivateKey && ( <ReactivateKeysModal userKeys={userKeys} keyReactivationRequests={allKeysToReactivate} onProcess={async (keyReactivationRecords, onReactivation) => { await reactivateKeysProcess({ api, user: User, userKeys, addresses: Addresses, keyReactivationRecords, keyPassword: authentication.getPassword(), onReactivation, keyTransparencyVerify, }); await keyTransparencyCommit(userKeys).catch(noop); return call(); }} {...reactivateKeyProps} /> )} {children} </> ); }; export default AddressKeysSection;
6,350
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys/KeysActions.tsx
import { c } from 'ttag'; import isTruthy from '@proton/utils/isTruthy'; import { DropdownActions } from '../../components'; import { KeyActions } from './shared/interface'; interface Props extends Partial<KeyActions> { isLoading: boolean; ID: string; } const KeysActions = ({ isLoading, ID, onExportPublicKey, onExportPrivateKey, onSetPrimary, onDeleteKey, onSetCompromised, onSetNotCompromised, onSetObsolete, onSetNotObsolete, }: Props) => { const list = [ onExportPublicKey && { text: c('Keys actions').t`Export public key`, onClick: () => onExportPublicKey(ID), }, onExportPrivateKey && { text: c('Keys actions').t`Export private key`, onClick: () => onExportPrivateKey(ID), }, onSetPrimary && { text: c('Keys actions').t`Make primary`, onClick: () => onSetPrimary(ID), }, onSetObsolete && { text: c('Keys actions').t`Mark obsolete`, tooltip: c('Keys actions').t`Disables encryption with this key`, onClick: () => onSetObsolete(ID), }, onSetNotObsolete && { text: c('Keys actions').t`Mark not obsolete`, tooltip: c('Keys actions').t`Enable encryption with this key`, onClick: () => onSetNotObsolete(ID), }, onSetCompromised && { text: c('Keys actions').t`Mark compromised`, tooltip: c('Keys actions').t`Disables signature verification and encryption with this key`, onClick: () => onSetCompromised(ID), }, onSetNotCompromised && { text: c('Keys actions').t`Mark not compromised`, tooltip: c('Keys actions').t`Enable signature verification and encryption with this key`, onClick: () => onSetNotCompromised(ID), }, onDeleteKey && ({ text: c('Keys actions').t`Delete`, actionType: 'delete', onClick: () => onDeleteKey(ID), } as const), ].filter(isTruthy); return <DropdownActions size="small" loading={isLoading} list={list} />; }; export default KeysActions;
6,351
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys/KeysStatus.tsx
import { c } from 'ttag'; import { MAIL_APP_NAME } from '@proton/shared/lib/constants'; import isTruthy from '@proton/utils/isTruthy'; import { Badge } from '../../components'; import { KeyStatus, KeyType } from './shared/interface'; const KeysStatus = ({ type, isPrimary, isDecrypted, isCompromised, isObsolete, isAddressDisabled, isForwarding, }: Partial<KeyStatus> & { type: KeyType }) => { const list = [ isPrimary && ({ tooltip: type === KeyType.User ? c('Tooltip').t`This key is used by ${MAIL_APP_NAME} to encrypt your contact's data` : c('Tooltip').t`${MAIL_APP_NAME} users will use this key by default for sending`, title: c('Key state badge').t`Primary`, type: 'primary', } as const), isDecrypted ? ({ tooltip: c('Tooltip').t`You have locally decrypted this key`, title: c('Key state badge').t`Active`, type: 'success', } as const) : ({ tooltip: c('Tooltip').t`This key is encrypted with an old password`, title: c('Key state badge').t`Inactive`, type: 'error', } as const), isCompromised && ({ tooltip: c('Tooltip') .t`Signatures produced by this key are treated as invalid and this key cannot be used for encryption`, title: c('Key state badge').t`Compromised`, type: 'warning', } as const), isObsolete && !isCompromised && ({ tooltip: c('Tooltip').t`This key cannot be used for encryption`, title: c('Key state badge').t`Obsolete`, type: 'warning', } as const), isAddressDisabled && ({ tooltip: c('Tooltip').t`This address has been disabled`, title: c('Key state badge').t`Disabled`, type: 'warning', } as const), isForwarding && ({ tooltip: c('Tooltip').t`This key is used for email forwarding`, title: c('Key state badge').t`Forwarding`, type: 'info', } as const), ] .filter(isTruthy) .map(({ tooltip, title, type }) => { return ( <Badge className="m-0" key={title} tooltip={tooltip} type={type}> {title} </Badge> ); }); return <div className="flex gap-1">{list}</div>; }; export default KeysStatus;
6,352
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys/KeysTable.tsx
import { c } from 'ttag'; import Copy from '../../components/button/Copy'; import PersonalKeyWarningIcon from '../../components/icon/PersonalKeyWarningIcon'; import { Table, TableBody, TableCell, TableRow } from '../../components/table'; import KeysActions from './KeysActions'; import KeysStatus from './KeysStatus'; import { KeyActions, KeyDisplay } from './shared/interface'; interface Props extends Partial<KeyActions> { keys: KeyDisplay[]; } const KeysTable = ({ keys = [], onDeleteKey, onSetPrimary, onExportPrivateKey, onExportPublicKey, onSetCompromised, onSetNotCompromised, onSetObsolete, onSetNotObsolete, }: Props) => { const headerCells = [ { node: c('Title header for keys table').t`Fingerprint`, className: 'text-ellipsis' }, { node: c('Title header for keys table').t`Key type`, className: 'w-1/6' }, { node: c('Title header for keys table').t`Status`, className: 'w-custom', style: { '--w-custom': '8em' } }, { node: c('Title header for keys table').t`Actions`, className: 'w-custom', style: { '--w-custom': '13em' } }, ].map(({ node, className = '' }) => { return ( <TableCell key={node} className={className} type="header"> {node} </TableCell> ); }); return ( <Table hasActions responsive="cards"> <thead> <tr>{headerCells}</tr> </thead> <TableBody colSpan={4}> {keys.map(({ ID, type, fingerprint, algorithm, status, permissions }) => { return ( <TableRow key={ID} labels={[ c('Title header for keys table').t`Fingerprint`, c('Title header for keys table').t`Key type`, '', '', ]} cells={[ <div key={1} className="flex flex-row flex-nowrap flex-align-items-center"> <Copy size="small" value={fingerprint} className="flex-item-noshrink mr-2 md:mr-4" /> <code className="max-w-full inline-block text-ellipsis" data-testid="fingerprint" title={fingerprint} > {fingerprint} </code> {status.isWeak && ( <PersonalKeyWarningIcon className="ml-auto hidden md:flex flex-item-noshrink" /> )} </div>, algorithm, <KeysStatus key={2} type={type} {...status} />, <KeysActions key={3} isLoading={status.isLoading} ID={ID} onDeleteKey={permissions.canDelete ? onDeleteKey : undefined} onExportPublicKey={permissions.canExportPublicKey ? onExportPublicKey : undefined} onExportPrivateKey={ permissions.canExportPrivateKey ? onExportPrivateKey : undefined } onSetPrimary={permissions.canSetPrimary ? onSetPrimary : undefined} onSetCompromised={permissions.canSetCompromised ? onSetCompromised : undefined} onSetNotCompromised={ permissions.canSetNotCompromised ? onSetNotCompromised : undefined } onSetObsolete={permissions.canSetObsolete ? onSetObsolete : undefined} onSetNotObsolete={permissions.canSetNotObsolete ? onSetNotObsolete : undefined} />, ]} className="xon-mobile-hide-td2 xon-tiny-mobile-hide-td3" /> ); })} </TableBody> </Table> ); }; export default KeysTable;
6,353
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys/UserKeysSection.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { AlgorithmInfo } from '@proton/crypto'; import { EncryptionConfig } from '@proton/shared/lib/interfaces'; import { addUserKeysProcess } from '@proton/shared/lib/keys'; import { Loader, useModalState } from '../../components'; import { useApi, useAuthentication, useEventManager, useGetAddresses, useIsDeviceRecoveryAvailable, useIsDeviceRecoveryEnabled, useModals, useUser, useUserKeys, } from '../../hooks'; import { SettingsParagraph, SettingsSectionWide } from '../account'; import KeysTable from './KeysTable'; import AddKeyModal from './addKey/AddKeyModal'; import ExportPrivateKeyModal from './exportKey/ExportPrivateKeyModal'; import { getKeyByID } from './shared/helper'; import useDisplayKeys from './shared/useDisplayKeys'; const UserKeysSections = () => { const { createModal } = useModals(); const [User] = useUser(); const api = useApi(); const { call } = useEventManager(); const authentication = useAuthentication(); const [userKeys, loadingUserKeys] = useUserKeys(); const userKeysDisplay = useDisplayKeys({ keys: userKeys, User }); const [isDeviceRecoveryAvailable, loadingDeviceRecovery] = useIsDeviceRecoveryAvailable(); const isDeviceRecoveryEnabled = useIsDeviceRecoveryEnabled(); const getAddresses = useGetAddresses(); const existingAlgorithms = userKeysDisplay.reduce<AlgorithmInfo[]>( (acc, { algorithmInfos }) => acc.concat(algorithmInfos), [] ); const [addKeyProps, setAddKeyModalOpen, renderAddKey] = useModalState(); const { Name: userName } = User; const handleExportPrivate = (ID: string) => { const userKey = getKeyByID(userKeys, ID); if (!userKey?.privateKey) { throw new Error('Could not find key'); } createModal(<ExportPrivateKeyModal name={userName} privateKey={userKey.privateKey} />); }; const handleAddKey = () => { if (!userKeys) { return; } setAddKeyModalOpen(true); }; const onAdd = async (encryptionConfig: EncryptionConfig) => { const addresses = await getAddresses(); const newKey = await addUserKeysProcess({ api, user: User, isDeviceRecoveryAvailable, isDeviceRecoveryEnabled, call, encryptionConfig, userKeys, addresses, passphrase: authentication.getPassword(), }); return newKey.getFingerprint(); }; const canGenerateUserKey = !User.isSubUser && User.isPrivate && userKeysDisplay.length < 20; const children = (() => { if (loadingDeviceRecovery || (loadingUserKeys && !Array.isArray(userKeys))) { return ( <SettingsSectionWide> <Loader /> </SettingsSectionWide> ); } // E.g. vpn user if (!userKeysDisplay.length) { return ( <SettingsSectionWide> <SettingsParagraph>{c('Info').t`No account keys exist`}</SettingsParagraph> </SettingsSectionWide> ); } return ( <SettingsSectionWide> {canGenerateUserKey && ( <div className="mb-4"> <Button shape="outline" onClick={handleAddKey} data-testid="generateUserKey"> {c('Action').t`Generate key`} </Button> </div> )} <KeysTable keys={userKeysDisplay} onExportPrivateKey={handleExportPrivate} /> </SettingsSectionWide> ); })(); return ( <> {renderAddKey && ( <AddKeyModal type="user" existingAlgorithms={existingAlgorithms} onAdd={onAdd} {...addKeyProps} /> )} {children} </> ); }; export default UserKeysSections;
6,354
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys/index.ts
export { default as AddressKeysSection } from './AddressKeysSection'; export { default as UserKeysSection } from './UserKeysSection'; export { default as SelectKeyFiles } from './shared/SelectKeyFiles';
6,355
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys/addKey/AddKeyModal.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { AlgorithmInfo } from '@proton/crypto'; import { DEFAULT_ENCRYPTION_CONFIG, ENCRYPTION_CONFIGS, ENCRYPTION_TYPES } from '@proton/shared/lib/constants'; import { EncryptionConfig } from '@proton/shared/lib/interfaces'; import { getAlgorithmExists } from '@proton/shared/lib/keys'; import { Alert, Form, ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, } from '../../../components'; import SelectEncryption from './SelectEncryption'; enum STEPS { SELECT_ENCRYPTION = 1, WARNING = 2, GENERATE_KEY = 3, SUCCESS = 4, } interface Props extends ModalProps { type: 'user' | 'address'; existingAlgorithms: AlgorithmInfo[]; onAdd: (config: EncryptionConfig) => Promise<string>; } const AddKeyModal = ({ existingAlgorithms, type, onAdd, ...rest }: Props) => { const [step, setStep] = useState(STEPS.SELECT_ENCRYPTION); const [encryptionType, setEncryptionType] = useState<ENCRYPTION_TYPES>(DEFAULT_ENCRYPTION_CONFIG); const [newKeyFingerprint, setNewKeyFingerprint] = useState<string>(); const handleProcess = async () => { try { const fingerprint = await onAdd(ENCRYPTION_CONFIGS[encryptionType]); setNewKeyFingerprint(fingerprint); setStep(STEPS.SUCCESS); } catch (error) { rest.onClose?.(); } }; const { children, onSubmit, submit, close, loading } = (() => { if (step === STEPS.SELECT_ENCRYPTION) { return { onSubmit: () => { const encryptionConfig = ENCRYPTION_CONFIGS[encryptionType]; const algorithmExists = getAlgorithmExists(existingAlgorithms, encryptionConfig); const nextStep = algorithmExists ? STEPS.WARNING : STEPS.GENERATE_KEY; setStep(nextStep); if (nextStep === STEPS.GENERATE_KEY) { void handleProcess(); } }, submit: c('Action').t`Continue`, close: undefined, loading: false, children: ( <> <Alert className="mb-4"> {c('Key generation') .t`You can generate a new encryption key if you think your previous key has been compromised.`} </Alert> <SelectEncryption encryptionType={encryptionType} setEncryptionType={setEncryptionType} /> </> ), }; } if (step === STEPS.WARNING) { return { onSubmit: () => { setStep(STEPS.GENERATE_KEY); void handleProcess(); }, close: c('Action').t`No`, submit: c('Action').t`Continue`, loading: false, children: ( <Alert className="mb-4" type="warning"> {type === 'user' ? c('Key generation') .t`A key with the same encryption algorithm already exists. Generating another key will cause slower account loading. Are you sure you want to continue?` : c('Key generation') .t`A key with the same encryption algorithm is already active for this address. Generating another key will cause slower account loading and deletion of this key can cause issues. If you are generating a new key because your old key is compromised, please mark that key as compromised. Are you sure you want to continue?`} </Alert> ), }; } if (step === STEPS.GENERATE_KEY) { return { onSubmit: undefined, loading: true, submit: c('Action').t`Continue`, close: undefined, children: ( <Alert className="mb-4"> {type === 'user' ? // Translator: encryption keys are referred to as "account keys" c('Key generation') .t`The encryption keys are being generated. This may take several minutes and temporarily freeze your browser.` : c('Key generation') .t`The encryption keys for your address are being generated. This may take several minutes and temporarily freeze your browser.`} </Alert> ), }; } if (step === STEPS.SUCCESS) { const fp = <code key="0">{newKeyFingerprint}</code>; return { onSubmit: undefined, close: c('Action').t`Close`, submit: null, loading: false, children: ( <Alert className="mb-4">{c('Key generation') .jt`Key with fingerprint ${fp} successfully created.`}</Alert> ), }; } throw new Error('Unsupported step'); })(); return ( <ModalTwo as={Form} onSubmit={onSubmit} size="large" {...rest}> <ModalTwoHeader title={c('Key generation').t`Generate key`} /> <ModalTwoContent>{children}</ModalTwoContent> <ModalTwoFooter> <Button onClick={rest.onClose} className={submit === null ? 'ml-auto' : undefined}> {close || c('Action').t`Cancel`} </Button> {submit !== null && ( <Button color="norm" type="submit" loading={loading}> {submit || c('Action').t`Save`} </Button> )} </ModalTwoFooter> </ModalTwo> ); }; export default AddKeyModal;
6,356
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys/addKey/SelectEncryption.tsx
import { Dispatch, SetStateAction } from 'react'; import { c } from 'ttag'; import { ENCRYPTION_TYPES } from '@proton/shared/lib/constants'; import { Radio, Row } from '../../../components'; const { RSA4096, CURVE25519 } = ENCRYPTION_TYPES; interface Props { encryptionType: string; setEncryptionType: Dispatch<SetStateAction<ENCRYPTION_TYPES>>; } const SelectEncryption = ({ encryptionType, setEncryptionType }: Props) => { // translator: this bold text is used to make a remark about one of the encryption key options offered to the user. // The full text will be '<bold>State of the art</bold> <Key type>' const stateOfTheArt = <strong key="CURVE25519">{c('Remark about a key type option').t`State of the art`}</strong>; // translator: this bold text is used to make a remark about one of the encryption key options offered to the user. // The full text will be '<bold>Compatibility</bold> <Key type>' const compatibility = <strong key="RSA4096">{c('Remark about a key type option').t`Compatibility`}</strong>; const radios = [ { label: c('Key type option').jt`${stateOfTheArt} ECC Curve25519 (Fastest, most modern)`, value: CURVE25519, }, { label: c('Key type option') .jt`${compatibility} RSA 4096-bit (Slower, but increased compatibility with legacy software)`, value: RSA4096, }, ]; return ( <> {radios.map(({ label, value }, i) => { const id = i.toString(); return ( <Row key={i}> <Radio id={`encryptionChoice${id}`} data-testid={value} name="encryptionType" checked={value === encryptionType} onChange={() => setEncryptionType(value)} > <span className="flex-item-fluid"> <span className="sr-only">{c('Label').t`Key strength`}</span> {label} </span> </Radio> </Row> ); })} </> ); }; export default SelectEncryption;
6,357
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys/deleteKey/DeleteKeyModal.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { BRAND_NAME } from '@proton/shared/lib/constants'; import noop from '@proton/utils/noop'; import { Prompt, PromptProps } from '../../../components'; import { useNotifications } from '../../../hooks'; enum STEPS { EXPORT_KEY, DELETE_KEY, } interface Props extends Omit<PromptProps, 'title' | 'buttons' | 'children'> { fingerprint: string; onDelete: () => Promise<void>; onExport?: () => Promise<void>; } const DeleteKeyModal = ({ onClose, fingerprint, onDelete, onExport, ...rest }: Props) => { const [step, setStep] = useState(onExport ? STEPS.EXPORT_KEY : STEPS.DELETE_KEY); const [loading, withLoading] = useLoading(); const { createNotification } = useNotifications(); const handleClose = loading ? noop : onClose; const deleteKey = async () => { try { await onDelete(); const fp = <code key="0">{fingerprint}</code>; createNotification({ text: <span>{c('Notification').jt`Key with fingerprint ${fp} has been deleted.`}</span>, }); } finally { onClose?.(); } }; const stepProps: { children: PromptProps['children']; buttons: PromptProps['buttons']; title: PromptProps['title']; } = (() => { if (step === STEPS.EXPORT_KEY) { return { title: c('Action').t`Export key before deleting`, children: ( <> <div className="mb-4">{c('Info').t`Key deletion is irreversible!`}</div> <div> {c('Info') .t`You should export a backup of this key in case you need to restore data it encrypted.`} </div> </> ), buttons: [ <Button color="norm" loading={loading} onClick={async () => { await withLoading( (async () => { await onExport?.(); await setStep(STEPS.DELETE_KEY); })() ); }} > {c('Action').t`Export key`} </Button>, <Button onClick={() => setStep(STEPS.DELETE_KEY)} disabled={loading}> {c('Action').t`Delete without exporting`} </Button>, <Button onClick={handleClose} disabled={loading}>{c('Action').t`Cancel`}</Button>, ], }; } if (step === STEPS.DELETE_KEY) { return { title: c('Title').t`Delete key permanently?`, children: ( <> <div className="mb-4"> {c('Info') .t`You will NOT be able to decrypt any messages, files, and other data encrypted with this key. All data signed with this key will no longer be verified by ${BRAND_NAME} applications.`} </div> <div> {c('Info') .t`To avoid data loss, only delete it if you know what you’re doing or have exported a copy.`} </div> </> ), buttons: [ <Button color="danger" loading={loading} onClick={async () => { await withLoading(deleteKey()); }} > {c('Action').t`Delete permanently`} </Button>, <Button onClick={handleClose} disabled={loading}>{c('Action').t`Cancel`}</Button>, ], }; } throw new Error('Unsupported step'); })(); return <Prompt {...rest} {...stepProps} />; }; export default DeleteKeyModal;
6,358
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys/exportKey/ExportPrivateKeyModal.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { CryptoProxy, PrivateKeyReference } from '@proton/crypto'; import { useLoading } from '@proton/hooks'; import { KEY_FILE_EXTENSION } from '@proton/shared/lib/constants'; import downloadFile from '@proton/shared/lib/helpers/downloadFile'; import { passwordLengthValidator } from '@proton/shared/lib/helpers/formValidators'; import noop from '@proton/utils/noop'; import { Form, InputFieldTwo, ModalTwo as Modal, ModalTwoContent as ModalContent, ModalTwoFooter as ModalFooter, ModalTwoHeader as ModalHeader, ModalProps, PasswordInputTwo, useFormErrors, } from '../../../components'; import { generateUID } from '../../../helpers'; import { useModals } from '../../../hooks'; import UnlockModal from '../../login/UnlockModal'; const handleExport = async (name: string, privateKey: PrivateKeyReference, password: string) => { const fingerprint = privateKey.getFingerprint(); const filename = ['privatekey.', name, '-', fingerprint, KEY_FILE_EXTENSION].join(''); const armoredEncryptedKey = await CryptoProxy.exportPrivateKey({ privateKey: privateKey, passphrase: password }); const blob = new Blob([armoredEncryptedKey], { type: 'text/plain' }); downloadFile(blob, filename); }; interface Props extends ModalProps { name: string; privateKey: PrivateKeyReference; onSuccess?: () => void; } const ExportPrivateKeyModal = ({ name, privateKey, onSuccess, onClose, ...rest }: Props) => { const { createModal } = useModals(); const [loading, withLoading] = useLoading(); const { validator, onFormSubmit } = useFormErrors(); const [id] = useState(() => generateUID('exportKey')); const [password, setPassword] = useState(''); const handleSubmit = async () => { // Force a login since the private key is sensitive await new Promise<string>((resolve, reject) => { createModal(<UnlockModal onClose={() => reject()} onSuccess={resolve} />); }); await handleExport(name, privateKey, password); onSuccess?.(); onClose?.(); }; const handleClose = loading ? noop : onClose; return ( <Modal as={Form} onSubmit={() => { if (!onFormSubmit()) { return; } void withLoading(handleSubmit()); }} onClose={handleClose} {...rest} > <ModalHeader title={c('Title').t`Export private key`} /> <ModalContent> <div className="mb-4"> {c('Info') .t`This will download a file containing your private key. Protect this file by encrypting it with a password.`} </div> <InputFieldTwo id={id} as={PasswordInputTwo} label={c('Label').t`Create password`} placeholder={c('Placeholder').t`Password`} value={password} onValue={setPassword} error={validator([passwordLengthValidator(password)])} autoFocus /> <div> {c('Info') .t`Store this password and file in a safe place. You’ll need them again to import your key.`} </div> </ModalContent> <ModalFooter> <Button onClick={handleClose} disabled={loading}> {c('Action').t`Cancel`} </Button> <Button loading={loading} type="submit" color="norm"> {c('Action').t`Encrypt and export`} </Button> </ModalFooter> </Modal> ); }; export default ExportPrivateKeyModal;
6,359
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys/exportKey/ExportPublicKeyModal.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { CryptoProxy, PublicKeyReference } from '@proton/crypto'; import { useLoading } from '@proton/hooks'; import { KEY_FILE_EXTENSION } from '@proton/shared/lib/constants'; import downloadFile from '@proton/shared/lib/helpers/downloadFile'; import noop from '@proton/utils/noop'; import { Form, ModalTwo as Modal, ModalTwoContent as ModalContent, ModalTwoFooter as ModalFooter, ModalTwoHeader as ModalHeader, ModalProps, } from '../../../components'; const handleExport = async (name: string, publicKey: PublicKeyReference) => { const fingerprint = publicKey.getFingerprint(); const filename = ['publickey.', name, '-', fingerprint, KEY_FILE_EXTENSION].join(''); const armoredPublicKey = await CryptoProxy.exportPublicKey({ key: publicKey }); const blob = new Blob([armoredPublicKey], { type: 'text/plain' }); downloadFile(blob, filename); }; interface Props extends ModalProps { name: string; fallbackPrivateKey: string; publicKey?: PublicKeyReference; onSuccess?: () => void; } const ExportPublicKeyModal = ({ name, fallbackPrivateKey, publicKey, onClose, ...rest }: Props) => { const [loading, withLoading] = useLoading(); const handleSubmit = async () => { if (publicKey) { await handleExport(name, publicKey); } else { // If there is no publicKey, it means the private key couldn't be decrypted, so just use whatever was received from the server const fallbackPublicKey = await CryptoProxy.importPublicKey({ armoredKey: fallbackPrivateKey }); await handleExport(name, fallbackPublicKey); } onClose?.(); }; const handleClose = loading ? noop : onClose; return ( <Modal as={Form} onSubmit={() => { void withLoading(handleSubmit()); }} onClose={handleClose} {...rest} > <ModalHeader title={c('Title').t`Export public key`} /> <ModalContent> <div> {c('Info') .t`Give your public key to your friends, or publish it online, so that everyone can send you end-to-end encrypted email!`} </div> </ModalContent> <ModalFooter> <Button onClick={handleClose} disabled={loading}> {c('Action').t`Cancel`} </Button> <Button loading={loading} type="submit" color="norm"> {c('Action').t`Export`} </Button> </ModalFooter> </Modal> ); }; export default ExportPublicKeyModal;
6,360
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys/importKeys/ImportKeyModal.tsx
import { useRef, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { CryptoProxy, PrivateKeyReference } from '@proton/crypto'; import { ArmoredKeyWithInfo } from '@proton/shared/lib/keys'; import { OnKeyImportCallback } from '@proton/shared/lib/keys'; import getRandomString from '@proton/utils/getRandomString'; import { Alert, ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader } from '../../../components'; import { useModals, useNotifications } from '../../../hooks'; import GenericError from '../../error/GenericError'; import DecryptFileKeyModal from '../shared/DecryptFileKeyModal'; import SelectKeyFiles from '../shared/SelectKeyFiles'; import ImportKeysList from './ImportKeysList'; import { ImportKey, Status } from './interface'; import { updateKey } from './state'; const getNewKey = (privateKey: PrivateKeyReference): ImportKey => { return { id: getRandomString(12), privateKey, fingerprint: privateKey.getFingerprint(), status: Status.LOADING, result: undefined, }; }; enum STEPS { WARNING = 1, SELECT_FILES = 2, PROCESS = 3, DONE = 4, FAILURE = 5, } interface Props extends ModalProps { onProcess: (keys: ImportKey[], cb: OnKeyImportCallback) => Promise<void>; } const ImportKeyModal = ({ onProcess, ...rest }: Props) => { const { createNotification } = useNotifications(); const { createModal } = useModals(); const selectRef = useRef<HTMLInputElement>(null); const [step, setStep] = useState<STEPS>(STEPS.WARNING); const [state, setState] = useState<ImportKey[]>([]); const handleSubmit = (promise: Promise<void>) => { setStep(STEPS.PROCESS); promise .then(() => { setStep(STEPS.DONE); }) .catch(() => { setStep(STEPS.FAILURE); }); }; const handleUpload = (privateKeyInfos: ArmoredKeyWithInfo[], acc: ImportKey[]) => { const [first, ...rest] = privateKeyInfos; if (privateKeyInfos.length === 0) { handleSubmit( onProcess(acc, (id: string, result) => { setState((oldKeys) => { return updateKey(oldKeys, id, { status: result === 'ok' ? Status.SUCCESS : Status.ERROR, result, }); }); }) ); return; } const handleAddKey = (decryptedPrivateKey: PrivateKeyReference) => { const newList = [...acc, getNewKey(decryptedPrivateKey)]; setState(newList); handleUpload(rest, newList); }; if (first.keyIsDecrypted) { CryptoProxy.importPrivateKey({ armoredKey: first.armoredKey, passphrase: null }) .then(handleAddKey) .catch((e: Error) => { createNotification({ type: 'error', text: e.message, }); }); return; } createModal( <DecryptFileKeyModal privateKeyInfo={first} onSuccess={(decryptedPrivateKey) => { handleAddKey(decryptedPrivateKey); }} /> ); }; const handleUploadKeys = (keys: ArmoredKeyWithInfo[]) => { const privateKeyInfos = keys.filter(({ keyIsPrivate }) => keyIsPrivate); if (privateKeyInfos.length === 0) { return createNotification({ type: 'error', text: c('Error').t`Invalid private key file`, }); } handleUpload(privateKeyInfos, []); }; const { children, submit, onNext, loading } = (() => { if (step === STEPS.WARNING) { return { submit: c('Action').t`Import`, loading: false, onNext: () => { setStep(STEPS.SELECT_FILES); }, children: ( <Alert className="text-pre-wrap"> {c('Import key') .t`Are you sure you want to import a private key? Importing an insecurely generated or leaked private key can harm the security of your emails. Please also note that the public key corresponding to this private key will be publicly available from our key server. If the key contains personal details (such as your full name) which you do not want to publish, please edit the key before importing it.`} </Alert> ), }; } if (step === STEPS.SELECT_FILES) { return { submit: c('Action').t`Select files`, loading: false, onNext: () => selectRef.current?.click(), children: ( <> <Alert className="mb-4">{c('Label').t`Please select files to upload`}</Alert> <SelectKeyFiles ref={selectRef} onUpload={handleUploadKeys} multiple className="hidden" autoClick /> </> ), }; } if (step === STEPS.PROCESS) { return { submit: c('Action').t`Select files`, onNext: undefined, loading: true, children: <ImportKeysList keys={state} />, }; } if (step === STEPS.DONE) { return { submit: null, onNext: undefined, loading: false, children: <ImportKeysList keys={state} />, }; } if (step === STEPS.FAILURE) { return { submit: null, onNext: undefined, loading: false, children: <GenericError />, }; } throw new Error('Unsupported step'); })(); return ( <ModalTwo size="large" {...rest}> <ModalTwoHeader title={c('Title').t`Import key`} /> <ModalTwoContent>{children}</ModalTwoContent> <ModalTwoFooter> <Button onClick={rest.onClose} className={submit === null ? 'ml-auto' : undefined}> {submit === null ? c('Action').t`Close` : c('Action').t`Cancel`} </Button> {submit !== null && ( <Button color="norm" onClick={onNext} loading={loading}> {submit || c('Action').t`Save`} </Button> )} </ModalTwoFooter> </ModalTwo> ); }; export default ImportKeyModal;
6,361
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys/importKeys/ImportKeysList.tsx
import { c } from 'ttag'; import { Badge, LoaderIcon, Table, TableBody, TableHeader, TableRow } from '../../../components'; import { ImportKey, Status } from './interface'; interface Props { keys: ImportKey[]; } const ImportKeysList = ({ keys }: Props) => { const list = keys.map(({ status, fingerprint, result }, i) => { const keyStatus = (() => { if (status === Status.ERROR) { return ( <Badge type="error" tooltip={result === 'ok' ? '' : result?.message}>{c('Title').t`Error`}</Badge> ); } if (status === Status.SUCCESS) { return <Badge type="success">{c('Title').t`Success`}</Badge>; } return <LoaderIcon />; })(); return ( <TableRow key={i} cells={[ <span key={0} className="max-w-full inline-block text-ellipsis"> {fingerprint} </span>, keyStatus, ]} /> ); }); return ( <Table> <TableHeader cells={[c('Title header for keys table').t`Fingerprint`, c('Title header for keys table').t`Status`]} /> <TableBody>{list}</TableBody> </Table> ); }; export default ImportKeysList;
6,362
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys/importKeys/interface.ts
import { PrivateKeyReference } from '@proton/crypto'; export enum Status { SUCCESS = 1, LOADING = 2, ERROR = 3, } export interface ImportKey { id: string; fingerprint: string; privateKey: PrivateKeyReference; status: Status; result?: 'ok' | Error; }
6,363
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys/importKeys/state.ts
import { ImportKey } from './interface'; export const updateKey = (oldKeys: ImportKey[], id: string, newKey: Partial<ImportKey>): ImportKey[] => { return oldKeys.map((oldKey) => { if (oldKey.id !== id) { return oldKey; } return { ...oldKey, ...newKey }; }); };
6,364
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys/reactivateKeys/KeyUploadContent.tsx
import { ComponentType, Dispatch, ReactNode, SetStateAction, useRef } from 'react'; import { c } from 'ttag'; import { Button, ButtonProps } from '@proton/atoms'; import { CryptoProxy, PrivateKeyReference } from '@proton/crypto'; import { ArmoredKeyWithInfo } from '@proton/shared/lib/keys'; import removeItem from '@proton/utils/removeIndex'; import uniqueBy from '@proton/utils/uniqueBy'; import { Icon, InputFieldTwo, Table, TableBody, TableRow } from '../../../components'; import { useModals, useNotifications } from '../../../hooks'; import DecryptFileKeyModal from '../shared/DecryptFileKeyModal'; interface FileInputProps { multiple?: boolean; onUpload: (keys: ArmoredKeyWithInfo[]) => void; disabled?: boolean; shape?: ButtonProps['shape']; color?: ButtonProps['color']; children: ReactNode; } interface Props { uploadedKeys: PrivateKeyReference[]; setUploadedKeys: Dispatch<SetStateAction<PrivateKeyReference[]>>; disabled?: boolean; error?: string; id: string; label: string; placeholder?: string; assistiveText: string; selectFilesComponent: ComponentType<FileInputProps>; } const KeyUploadContent = ({ uploadedKeys, setUploadedKeys, disabled, error, id, label, placeholder, assistiveText, selectFilesComponent: SelectFilesComponent, }: Props) => { const { createNotification } = useNotifications(); const { createModal } = useModals(); const duplicateBackupKeysRef = useRef<PrivateKeyReference[]>([]); const handleDuplicatedKeysOnUpload = (duplicatedKeys: PrivateKeyReference[]) => { const [first, second, third] = duplicatedKeys; const createAlreadyUploadedNotification = (key: PrivateKeyReference) => { const fingerprint = key.getFingerprint(); createNotification({ type: 'info', text: c('info').t`Key ${fingerprint} has already been uploaded`, }); }; if (first) { createAlreadyUploadedNotification(first); } if (second) { createAlreadyUploadedNotification(second); } if (third) { createNotification({ type: 'info', text: c('info').t`Additional duplicate keys detected. Please upload individually for more information.`, }); } }; const handleUpload = (keysToUpload: ArmoredKeyWithInfo[], acc: PrivateKeyReference[]) => { const [currentKey, ...rest] = keysToUpload; if (keysToUpload.length === 0) { setUploadedKeys((keys) => [...keys, ...acc]); const duplicatedKeys = uniqueBy(duplicateBackupKeysRef.current, (key) => key.getFingerprint()); handleDuplicatedKeysOnUpload(duplicatedKeys); duplicateBackupKeysRef.current = []; return; } const keyAlreadyAdded = acc.find((key) => key.getFingerprint() === currentKey.fingerprint); if (keyAlreadyAdded) { handleUpload(rest, acc); return; } const keyAlreadyInList = uploadedKeys.find((key) => key.getFingerprint() === currentKey.fingerprint); if (keyAlreadyInList) { duplicateBackupKeysRef.current.push(keyAlreadyInList); handleUpload(rest, acc); return; } const handleAddKey = (decryptedPrivateKey: PrivateKeyReference) => { const newList = [...acc, decryptedPrivateKey]; handleUpload(rest, newList); }; if (currentKey.keyIsDecrypted) { CryptoProxy.importPrivateKey({ armoredKey: currentKey.armoredKey, passphrase: null }) .then(handleAddKey) .catch((e: Error) => { createNotification({ type: 'error', text: e.message, }); }); return; } return createModal( <DecryptFileKeyModal privateKeyInfo={currentKey} onSuccess={(decryptedPrivateKey) => { handleAddKey(decryptedPrivateKey); }} /> ); }; const handleUploadKeys = (keys: ArmoredKeyWithInfo[]) => { handleUpload(keys, []); }; const removeUploadedKey = (keyToRemove: PrivateKeyReference) => { const index = uploadedKeys.indexOf(keyToRemove); void CryptoProxy.clearKey({ key: keyToRemove }); // erase private key material if (index === -1) { return; } setUploadedKeys((keys) => removeItem(keys, index)); }; const SelectFiles = (props: Omit<FileInputProps, 'multiple' | 'onUpload' | 'disabled'>) => ( <SelectFilesComponent {...props} multiple onUpload={handleUploadKeys} disabled={disabled} /> ); if (uploadedKeys.length) { return ( <> <Table hasActions> <TableBody> {uploadedKeys.map((key) => { const fingerprint = key.getFingerprint(); return ( <TableRow key={fingerprint} cells={[ <div key={1} className="flex flex-row flex-nowrap flex-align-items-center flex-justify-space-between" > <code className="max-w-full inline-block text-ellipsis" title={fingerprint}> {fingerprint} </code> <Button className="ml-2" icon color="weak" shape="outline" onClick={() => removeUploadedKey(key)} disabled={disabled} > <Icon name="trash" alt={c('Label').t`Delete`} /> </Button> </div>, ]} className="on-mobile-hide-td2 on-tiny-mobile-hide-td3" /> ); })} </TableBody> </Table> <SelectFiles shape="underline" color="norm"> {c('Select files').t`Upload additional files`} </SelectFiles> </> ); } return ( <div className="flex flex-wrap on-mobile-flex-column flex-align-items-center"> <div className="mr-0 md:mr-4 flex-item-fluid min-w-custom" style={{ '--min-w-custom': '14em' }}> <InputFieldTwo id={id} label={label} placeholder={placeholder} assistiveText={assistiveText} error={error} readOnly /> </div> <div className="mt-1"> <SelectFiles>{c('Select files').t`Browse`}</SelectFiles> </div> </div> ); }; export default KeyUploadContent;
6,365
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys/reactivateKeys/ReactivateKeysModal.tsx
import { useEffect, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { CryptoProxy, PrivateKeyReference } from '@proton/crypto'; import { useLoading } from '@proton/hooks'; import { getKeySalts } from '@proton/shared/lib/api/keys'; import { MnemonicKeyResponse, getMnemonicUserKeys } from '@proton/shared/lib/api/settingsMnemonic'; import { lockSensitiveSettings, unlockPasswordChanges } from '@proton/shared/lib/api/user'; import { requiredValidator } from '@proton/shared/lib/helpers/formValidators'; import { DecryptedKey, KeySalt, MNEMONIC_STATUS } from '@proton/shared/lib/interfaces'; import { KeyReactivationRecord, OnKeyReactivationCallback } from '@proton/shared/lib/keys'; import { mnemonicToBase64RandomBytes } from '@proton/shared/lib/mnemonic'; import { computeKeyPassword } from '@proton/srp'; import isTruthy from '@proton/utils/isTruthy'; import { Form, InputFieldTwo, Loader, ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, PasswordInputTwo, Tabs, useFormErrors, } from '../../../components'; import { useApi, useIsMnemonicAvailable, useModals, useNotifications, useRecoverySecrets, useUser, } from '../../../hooks'; import MnemonicInputField, { useMnemonicInputValidation } from '../../mnemonic/MnemonicInputField'; import { AuthModal } from '../../password'; import RecoveryFileTabContent from './RecoveryFileTabContent'; import { KeyReactivationRequest, KeyReactivationRequestState, KeyReactivationRequestStateData } from './interface'; import { getReactivatedKeys } from './reactivateHelper'; import { getInitialStates } from './state'; interface ReactivatedKeysState { numberOfSuccessfullyReactivatedKeys: number; numberOfFailedReactivatedKeys: number; } interface Props extends ModalProps { userKeys: DecryptedKey[]; keyReactivationRequests: KeyReactivationRequest[]; onProcess: (keysToReactivate: KeyReactivationRecord[], onReactivation: OnKeyReactivationCallback) => Promise<void>; } type TabId = 'phrase' | 'password' | 'file'; const ReactivateKeysModal = ({ userKeys, keyReactivationRequests, onProcess, ...rest }: Props) => { const api = useApi(); const [user] = useUser(); const { validator, onFormSubmit } = useFormErrors(); const { createNotification } = useNotifications(); const { createModal } = useModals(); const [loading, withLoading] = useLoading(true); const [isSubmitting, withIsSubmitting] = useLoading(false); const [states, setStates] = useState<KeyReactivationRequestState[]>([]); const [mnemonic, setMnemonic] = useState(''); const mnemonicValidation = useMnemonicInputValidation(mnemonic); const [password, setPassword] = useState(''); const [uploadedFileKeys, setUploadedFileKeys] = useState<PrivateKeyReference[]>([]); const recoverySecrets = useRecoverySecrets(); const recoveryFileAvailable = !!recoverySecrets.length; const fileDescription = recoveryFileAvailable ? c('Info').t`This is a recovery file or encryption key you may have previously saved.` : c('Info').t`This is an encryption key you may have previously saved.`; const [isMnemonicAvailable] = useIsMnemonicAvailable(); const showMnemonicTab = isMnemonicAvailable && (user.MnemonicStatus === MNEMONIC_STATUS.SET || user.MnemonicStatus === MNEMONIC_STATUS.OUTDATED); const tabs: TabId[] = ([showMnemonicTab ? 'phrase' : undefined, 'password', 'file'] as const).filter(isTruthy); const [tab, setTab] = useState(0); useEffect(() => { const run = async () => { const initialStates = await getInitialStates(keyReactivationRequests); setStates(initialStates); }; void withLoading(run()); }, []); const proxiedOnProcess = async ( keysToReactivate: KeyReactivationRecord[], onReactivation?: OnKeyReactivationCallback ): Promise<ReactivatedKeysState> => { let numberOfSuccessfullyReactivatedKeys = 0; let numberOfFailedReactivatedKeys = 0; const proxiedOnReactivation: typeof onReactivation = (...args) => { onReactivation?.(...args); const [, result] = args; if (result === 'ok') { numberOfSuccessfullyReactivatedKeys++; } else { numberOfFailedReactivatedKeys++; } }; await onProcess(keysToReactivate, proxiedOnReactivation); return { numberOfSuccessfullyReactivatedKeys, numberOfFailedReactivatedKeys }; }; const createKeyReactivationNotification = ({ numberOfFailedReactivatedKeys, numberOfSuccessfullyReactivatedKeys, }: ReactivatedKeysState) => { if (!numberOfFailedReactivatedKeys && numberOfSuccessfullyReactivatedKeys) { createNotification({ type: 'success', text: c('Info').t`All keys successfully reactivated` }); return; } if (numberOfFailedReactivatedKeys && numberOfSuccessfullyReactivatedKeys) { createNotification({ type: 'success', text: c('Info').t`Some keys successfully reactivated` }); return; } createNotification({ type: 'error', text: c('Error').t`Zero keys reactivated` }); }; const handleRecoveryPhraseUserKeysReactivation = async ( userKeys: { ID: string; privateKey: PrivateKeyReference }[] ) => { const records = states .filter((state) => !!state.user) .map((keyReactivationRecordState) => { const keysToReactivate = keyReactivationRecordState.keysToReactivate .map(({ id, Key }) => { const decryptedUserKey = userKeys.find(({ ID }) => ID === Key.ID); if (!decryptedUserKey) { return; } return { id, Key, privateKey: decryptedUserKey.privateKey, }; }) .filter(isTruthy); if (!keysToReactivate.length) { return; } return { ...keyReactivationRecordState, keysToReactivate, }; }) .filter(isTruthy); const reactivatedKeysState = await proxiedOnProcess(records); createKeyReactivationNotification(reactivatedKeysState); }; const onRecoveryPhraseSubmit = async () => { await new Promise((resolve, reject) => { createModal(<AuthModal onCancel={reject} onSuccess={resolve} config={unlockPasswordChanges()} />); }); const { MnemonicUserKeys } = await api<{ MnemonicUserKeys: MnemonicKeyResponse[] }>(getMnemonicUserKeys()); const randomBytes = await mnemonicToBase64RandomBytes(mnemonic); const decryptedMnemonicUserKeys = ( await Promise.all( MnemonicUserKeys.map(async ({ ID, PrivateKey, Salt }) => { try { const hashedPassphrase = await computeKeyPassword(randomBytes, Salt); const decryptedPrivateKey = await CryptoProxy.importPrivateKey({ armoredKey: PrivateKey, passphrase: hashedPassphrase, }); return { ID, privateKey: decryptedPrivateKey, }; } catch (e: any) { return undefined; } }) ) ).filter(isTruthy); const newlyDecryptedMnemonicUserKeys = decryptedMnemonicUserKeys.filter(({ ID }) => { return userKeys.find((userKey) => userKey.ID !== ID); }); if (newlyDecryptedMnemonicUserKeys.length) { await handleRecoveryPhraseUserKeysReactivation(newlyDecryptedMnemonicUserKeys); await api(lockSensitiveSettings()); return; } await api(lockSensitiveSettings()); if (!newlyDecryptedMnemonicUserKeys.length && decryptedMnemonicUserKeys.length) { createNotification({ type: 'info', text: c('Info').t`Recovery phrase is not associated with any outdated keys.`, }); return; } createNotification({ type: 'info', text: c('Info').t`Recovery phrase is not associated with any keys.`, }); }; const onPasswordSubmit = async () => { const keySalts = await api<{ KeySalts: KeySalt[] }>(getKeySalts()) .then(({ KeySalts }) => KeySalts) .catch(() => []); let numberOfErrors = 0; const records = ( await Promise.all( states.map(async (keyReactivationRecordState) => { const { process, errors } = await getReactivatedKeys( keyReactivationRecordState.keysToReactivate, password, keySalts ); numberOfErrors += errors.length; if (!process.length) { return; } return { ...keyReactivationRecordState, keysToReactivate: process, }; }) ) ).filter(isTruthy); const { numberOfSuccessfullyReactivatedKeys, numberOfFailedReactivatedKeys } = await proxiedOnProcess(records); createKeyReactivationNotification({ numberOfSuccessfullyReactivatedKeys, numberOfFailedReactivatedKeys: numberOfFailedReactivatedKeys + numberOfErrors, }); }; const onFileSubmit = async () => { const mapToUploadedPrivateKey = ({ id, Key, fingerprint }: KeyReactivationRequestStateData) => { const uploadedPrivateKey = uploadedFileKeys.find((decryptedBackupKey) => { return fingerprint === decryptedBackupKey.getFingerprint(); }); if (!uploadedPrivateKey) { return; } return { id, Key, privateKey: uploadedPrivateKey, }; }; const records = states .map((keyReactivationRecordState) => { const uploadedKeysToReactivate = keyReactivationRecordState.keysToReactivate .map(mapToUploadedPrivateKey) .filter(isTruthy); if (!uploadedKeysToReactivate.length) { return; } return { ...keyReactivationRecordState, keysToReactivate: uploadedKeysToReactivate, }; }) .filter(isTruthy); const reactivatedKeysState = await proxiedOnProcess(records); createKeyReactivationNotification(reactivatedKeysState); }; const onSubmit = async () => { if (!onFormSubmit()) { return; } const submit = async () => { if (tab === tabs.indexOf('phrase')) { await onRecoveryPhraseSubmit(); } else if (tab === tabs.indexOf('password')) { await onPasswordSubmit(); } else if (tab === tabs.indexOf('file')) { await onFileSubmit(); } }; await withIsSubmitting(submit()); rest.onClose?.(); }; return ( <ModalTwo as={Form} onSubmit={onSubmit} size="medium" {...rest}> <ModalTwoHeader title={c('Title').t`Recover data`} /> <ModalTwoContent> <p className="mt-0">{c('Info') .t`To decrypt and view your locked data after a password reset, select a recovery method.`}</p> {loading ? ( <Loader /> ) : ( <> <Tabs value={tab} tabs={[ showMnemonicTab ? { // translator: 'Phrase' here refers to the 'Recovery phrase' title: c('Label').t`Phrase`, content: ( <> <div className="mb-4">{c('Info') .t`This is a 12-word phrase that you were prompted to set.`}</div> <MnemonicInputField disableChange={isSubmitting} value={mnemonic} onValue={setMnemonic} autoFocus error={validator( tab === tabs.indexOf('phrase') ? [requiredValidator(mnemonic), ...mnemonicValidation] : [] )} /> </> ), } : undefined, { title: c('Label').t`Password`, content: ( <> <div className="mb-4">{c('Info') .t`This is the password you used before the password reset.`}</div> <InputFieldTwo id="password" label={c('Label').t`Previous password`} as={PasswordInputTwo} error={validator( tab === tabs.indexOf('password') ? [requiredValidator(password)] : [] )} value={password} onValue={setPassword} autoFocus disabled={isSubmitting} /> </> ), }, { title: c('Label').t`File`, content: ( <> <div className="mb-4">{fileDescription}</div> <RecoveryFileTabContent recoverySecrets={recoverySecrets} uploadedKeys={uploadedFileKeys} setUploadedKeys={setUploadedFileKeys} disabled={isSubmitting} error={validator( tab === tabs.indexOf('file') ? [ requiredValidator( uploadedFileKeys .map((key) => key.getFingerprint()) .join() ), ] : [] )} /> </> ), }, ].filter(isTruthy)} onChange={setTab} /> </> )} </ModalTwoContent> <ModalTwoFooter> <Button onClick={rest.onClose} disabled={isSubmitting}>{c('Action').t`Cancel`}</Button> <Button type="submit" color="norm" loading={isSubmitting} disabled={loading}>{c('Action') .t`Recover data`}</Button> </ModalTwoFooter> </ModalTwo> ); }; export default ReactivateKeysModal;
6,366
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys/reactivateKeys/RecoveryFileTabContent.tsx
import { Dispatch, SetStateAction } from 'react'; import { c } from 'ttag'; import { PrivateKeyReference } from '@proton/crypto'; import { KeyWithRecoverySecret } from '@proton/shared/lib/interfaces'; import KeyUploadContent from './KeyUploadContent'; import SelectRecoveryFiles, { Props as SelectRecoveryFilesProps } from './SelectRecoveryFiles'; interface Props { recoverySecrets: KeyWithRecoverySecret[]; uploadedKeys: PrivateKeyReference[]; setUploadedKeys: Dispatch<SetStateAction<PrivateKeyReference[]>>; disabled?: boolean; error?: string; } const RecoveryFileTabContent = ({ recoverySecrets, ...rest }: Props) => { const SelectFilesComponent = (props: Omit<SelectRecoveryFilesProps, 'recoverySecrets'>) => ( <SelectRecoveryFiles recoverySecrets={recoverySecrets} {...props} /> ); const recoveryFileAvailable = !!recoverySecrets.length; const assistiveText = recoveryFileAvailable ? c('Label').t`Upload 1 or more recovery files or encryption keys` : c('Label').t`Upload 1 or more encryption keys`; return ( <KeyUploadContent id="recovery-file" label={c('Label').t`Recovery file`} assistiveText={assistiveText} selectFilesComponent={SelectFilesComponent} {...rest} /> ); }; export default RecoveryFileTabContent;
6,367
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys/reactivateKeys/SelectRecoveryFiles.tsx
import { ReactNode, Ref, forwardRef, useEffect, useRef } from 'react'; import { c, msgid } from 'ttag'; import { ButtonProps } from '@proton/atoms'; import { useCombinedRefs } from '@proton/hooks'; import { KEY_FILE_EXTENSION } from '@proton/shared/lib/constants'; import { readFileAsString } from '@proton/shared/lib/helpers/file'; import { KeyWithRecoverySecret } from '@proton/shared/lib/interfaces'; import { ArmoredKeyWithInfo, parseKeys } from '@proton/shared/lib/keys'; import { parseRecoveryFiles } from '@proton/shared/lib/recoveryFile/recoveryFile'; import FileInput from '../../../components/input/FileInput'; import { useNotifications } from '../../../hooks'; const RECOVERY_FILE_EXPR = /-----BEGIN PGP MESSAGE-----(?:(?!-----)[\s\S])*-----END PGP MESSAGE-----/g; const BACKUP_PRIVATE_KEY_EXPR = /-----BEGIN PGP PRIVATE KEY BLOCK-----(?:(?!-----)[\s\S])*-----END PGP PRIVATE KEY BLOCK-----/g; export interface Props { recoverySecrets: KeyWithRecoverySecret[]; onUpload: (keys: ArmoredKeyWithInfo[]) => void; autoClick?: boolean; multiple?: boolean; className?: string; children?: ReactNode; disabled?: boolean; shape?: ButtonProps['shape']; color?: ButtonProps['color']; } const SelectRecoveryFiles = ( { recoverySecrets, onUpload, autoClick = false, multiple = false, className = '', children = c('Select files').t`Upload`, disabled, shape, color, }: Props, ref: Ref<HTMLInputElement> ) => { const fileRef = useRef<HTMLInputElement>(null); const { createNotification } = useNotifications(); useEffect(() => { if (autoClick) { fileRef.current?.click(); } }, [autoClick]); const displayRecoveryFileNotifications = (keys: ArmoredKeyWithInfo[], numberOfFilesUploaded: number) => { if (numberOfFilesUploaded === 0) { return; } if (keys.length === 0) { createNotification({ type: 'error', text: numberOfFilesUploaded === 1 ? c('Error').t`The keys in your recovery file can't be validated. Please contact support.` : c('Error') .t`The keys in your recovery files can't be validated. Please upload individually for more information.`, }); } }; const displayBackupKeyNotifications = (keys: ArmoredKeyWithInfo[], numberOfFilesUploaded: number) => { if (numberOfFilesUploaded === 0) { return; } const privateKeys = keys.filter(({ keyIsPrivate }) => keyIsPrivate); if (privateKeys.length === 0) { createNotification({ type: 'error', text: keys.length === 1 ? c('Error').t`Uploaded file is not a valid private key. Please verify and try again.` : c('Error').t`Uploaded files are not valid private keys. Please verify and try again.`, }); return; } const numberOfNonPrivateKeys = numberOfFilesUploaded - privateKeys.length; if (numberOfNonPrivateKeys > 0) { createNotification({ type: 'info', text: numberOfNonPrivateKeys === 1 ? c('Info').t`Uploaded file is not a valid private key. Please verify and try again.` : // translator: the singular version won't be used, it's the string "Uploaded file is not a valid private key. Please verify and try again." that will be used. c('Info').ngettext( msgid`${numberOfNonPrivateKeys} uploaded file is not a valid private key. Please verify and try again.`, `${numberOfNonPrivateKeys} uploaded files are not valid private keys. Please verify and try again.`, numberOfNonPrivateKeys ), }); } }; return ( <FileInput accept={KEY_FILE_EXTENSION} ref={useCombinedRefs(fileRef, ref)} className={className} multiple={multiple} onChange={async ({ target }) => { const files = Array.from(target.files as FileList); const filesAsStrings = await Promise.all(files.map((file) => readFileAsString(file))).catch(() => []); const concatenatedFilesAsString = filesAsStrings.join('\n'); const recoveryFilesAsStrings = concatenatedFilesAsString.match(RECOVERY_FILE_EXPR) || []; const backupKeysAsStrings = concatenatedFilesAsString.match(BACKUP_PRIVATE_KEY_EXPR) || []; const [recoveryFileKeys, backupKeyFileKeys] = await Promise.all([ parseRecoveryFiles(recoveryFilesAsStrings, recoverySecrets), parseKeys(backupKeysAsStrings), ]); displayRecoveryFileNotifications(recoveryFileKeys, recoveryFilesAsStrings.length); displayBackupKeyNotifications(backupKeyFileKeys, backupKeysAsStrings.length); onUpload([...recoveryFileKeys, ...backupKeyFileKeys]); }} disabled={disabled} shape={shape} color={color} > {children} </FileInput> ); }; export default forwardRef<HTMLInputElement, Props>(SelectRecoveryFiles);
6,368
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys/reactivateKeys/getAllKeysToReactive.ts
import { Address, DecryptedKey, Key, User } from '@proton/shared/lib/interfaces'; import isTruthy from '@proton/utils/isTruthy'; import { KeyReactivationRequest } from './interface'; const getKeysToReactivate = (Keys: Key[] = [], keys: DecryptedKey[] = []) => { const set = new Set(keys.map(({ ID }) => ID)); return Keys.filter((Key) => { return !set.has(Key.ID); }); }; export const getKeysToReactivateCount = (inactiveKeys: KeyReactivationRequest[]) => { return inactiveKeys.reduce((acc, { keysToReactivate }) => acc + keysToReactivate.length, 0); }; export const getAllKeysReactivationRequests = ( addressesKeys: { address: Address; keys: DecryptedKey[] }[] | undefined, User: User | undefined, userKeys: DecryptedKey[] | undefined ): KeyReactivationRequest[] => { const allAddressesKeys = (addressesKeys || []).map(({ address, keys }) => { const inactiveAddressKeys = getKeysToReactivate(address.Keys, keys); if (!inactiveAddressKeys.length) { return; } return { address, keys, keysToReactivate: inactiveAddressKeys, }; }); const inactiveUserKeys = getKeysToReactivate(User?.Keys, userKeys); const userKeysReactivation = User && userKeys && inactiveUserKeys.length ? { user: User, keys: userKeys, keysToReactivate: inactiveUserKeys, } : undefined; return [userKeysReactivation, ...allAddressesKeys].filter(isTruthy); };
6,369
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys/reactivateKeys/getLikelyHasKeysToReactivate.ts
import { Address, User } from '@proton/shared/lib/interfaces'; const getLikelyHasKeysToReactivate = (user: User, addresses: Address[]) => { return ( user?.Keys?.some((Key) => !Key.Active) || addresses?.some((address) => address.Keys?.some((Key) => !Key.Active)) ); }; export default getLikelyHasKeysToReactivate;
6,370
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys/reactivateKeys/interface.ts
import { Address, DecryptedKey, Key, User } from '@proton/shared/lib/interfaces'; export interface KeyReactivationRequestStateData { id: string; Key: Key; fingerprint: string; result?: 'ok' | Error; } export type KeyReactivationRequestState = | { user: User; address: undefined; keys: DecryptedKey[]; keysToReactivate: KeyReactivationRequestStateData[]; } | { user: undefined; address: Address; keys: DecryptedKey[]; keysToReactivate: KeyReactivationRequestStateData[]; }; export type KeyReactivationRequest = | { user: User; address?: undefined; keys: DecryptedKey[]; keysToReactivate: Key[]; } | { user?: undefined; address: Address; keys: DecryptedKey[]; keysToReactivate: Key[]; };
6,371
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys/reactivateKeys/reactivateHelper.ts
import { c } from 'ttag'; import { KeySalt } from '@proton/shared/lib/interfaces'; import { decryptPrivateKeyWithSalt, getHasMigratedAddressKey } from '@proton/shared/lib/keys'; import { KeyReactivationData } from '@proton/shared/lib/keys/reactivation/interface'; import { KeyReactivationRequestStateData } from './interface'; interface KeyReactivationError { id: string; error: Error; } const getKey = async ( { id, Key }: KeyReactivationRequestStateData, oldPassword: string, keySalts: KeySalt[] ): Promise<KeyReactivationData | KeyReactivationError> => { if (getHasMigratedAddressKey(Key)) { return { id, Key, // Force the type here. Migrated address keys are not reactivated by a password. } as KeyReactivationData; } try { const { KeySalt } = keySalts.find(({ ID: keySaltID }) => Key.ID === keySaltID) || {}; const privateKey = await decryptPrivateKeyWithSalt({ PrivateKey: Key.PrivateKey, keySalt: KeySalt, password: oldPassword, }); return { id, Key, privateKey, }; } catch (e: any) { return { id, Key, error: new Error(c('Error').t`Incorrect password`), }; } }; export const getReactivatedKeys = async ( keysToReactivate: KeyReactivationRequestStateData[], oldPassword: string, keySalts: KeySalt[] ) => { const reactivatedKeys = await Promise.all( keysToReactivate.map(async (keyData) => { return getKey(keyData, oldPassword, keySalts); }) ); const errors = reactivatedKeys.filter((reactivatedKey): reactivatedKey is KeyReactivationError => { return 'error' in reactivatedKey; }); const process = reactivatedKeys.filter((reactivatedKey): reactivatedKey is KeyReactivationData => { return !('error' in reactivatedKey); }); return { process, errors }; };
6,372
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys/reactivateKeys/state.ts
import { CryptoProxy } from '@proton/crypto'; import getRandomString from '@proton/utils/getRandomString'; import { KeyReactivationRequest, KeyReactivationRequestState, KeyReactivationRequestStateData } from './interface'; export const getInitialStates = async (initial: KeyReactivationRequest[]): Promise<KeyReactivationRequestState[]> => { if (initial.length === 0) { throw new Error('Keys to reactivate needed'); } return Promise.all( initial.map(async (record) => { const keyStates = await Promise.all( record.keysToReactivate.map(async (Key): Promise<KeyReactivationRequestStateData> => { try { const { fingerprint } = await CryptoProxy.getKeyInfo({ armoredKey: Key.PrivateKey }); return { id: getRandomString(12), Key, fingerprint, result: undefined, }; } catch (e: any) { return { id: getRandomString(12), Key, fingerprint: '-', result: undefined, }; } }) ); return { ...record, keysToReactivate: keyStates, }; }) ); };
6,373
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys/shared/DecryptFileKeyModal.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { CryptoProxy, PrivateKeyReference } from '@proton/crypto'; import { useLoading } from '@proton/hooks'; import { requiredValidator } from '@proton/shared/lib/helpers/formValidators'; import { ArmoredKeyWithInfo } from '@proton/shared/lib/keys'; import noop from '@proton/utils/noop'; import { Form, InputFieldTwo, ModalTwo as Modal, ModalTwoContent as ModalContent, ModalTwoFooter as ModalFooter, ModalTwoHeader as ModalHeader, ModalProps, PasswordInputTwo, useFormErrors, } from '../../../components'; import { generateUID } from '../../../helpers'; interface Props extends ModalProps { privateKeyInfo: ArmoredKeyWithInfo; onSuccess: (privateKey: PrivateKeyReference) => void; } const DecryptFileKeyModal = ({ privateKeyInfo, onSuccess, onClose, ...rest }: Props) => { const id = generateUID('decryptKey'); const { fingerprint, armoredKey } = privateKeyInfo; const fingerprintCode = <code key="0">{fingerprint}</code>; const [password, setPassword] = useState(''); const [error, setError] = useState(''); const [loading, withLoading] = useLoading(); const { validator, onFormSubmit } = useFormErrors(); const handleSubmit = async () => { try { const decryptedPrivateKey = await CryptoProxy.importPrivateKey({ armoredKey, passphrase: password }); onSuccess(decryptedPrivateKey); onClose?.(); } catch (e: any) { setError(e.message); } }; const handleClose = loading ? noop : onClose; return ( <Modal as={Form} onSubmit={() => { if (!onFormSubmit()) { return; } void withLoading(handleSubmit()); }} onClose={handleClose} {...rest} > <ModalHeader title={c('Title').t`Decrypt key`} /> <ModalContent> <div className="mb-4"> {c('Label').jt`Enter the password for key with fingerprint: ${fingerprintCode}`} </div> <InputFieldTwo id={id} as={PasswordInputTwo} label={c('Label').t`Enter password`} placeholder={c('Placeholder').t`Password`} value={password} onValue={(value: string) => { setError(''); setPassword(value); }} error={validator([requiredValidator(password), error])} autoFocus /> </ModalContent> <ModalFooter> <Button onClick={handleClose} disabled={loading}> {c('Action').t`Close`} </Button> <Button loading={loading} type="submit" color="norm"> {c('Action').t`Decrypt`} </Button> </ModalFooter> </Modal> ); }; export default DecryptFileKeyModal;
6,374
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys/shared/SelectKeyFiles.tsx
import { ReactNode, Ref, forwardRef, useEffect, useRef } from 'react'; import { c } from 'ttag'; import { ButtonLikeShape } from '@proton/atoms'; import { ThemeColorUnion } from '@proton/colors'; import { useCombinedRefs } from '@proton/hooks'; import { ArmoredKeyWithInfo, parseKeyFiles } from '@proton/shared/lib/keys'; import FileInput from '../../../components/input/FileInput'; interface Props { onUpload: (keys: ArmoredKeyWithInfo[]) => void; autoClick?: boolean; multiple?: boolean; className?: string; children?: ReactNode; disabled?: boolean; shape?: ButtonLikeShape; color?: ThemeColorUnion; } const SelectKeyFiles = ( { onUpload, autoClick = false, multiple = false, className = '', children = c('Select files').t`Upload`, disabled, shape, color, }: Props, ref: Ref<HTMLInputElement> ) => { const fileRef = useRef<HTMLInputElement>(null); useEffect(() => { if (autoClick) { fileRef.current?.click(); } }, [autoClick]); return ( <FileInput accept=".txt,.asc" ref={useCombinedRefs(fileRef, ref)} className={className} multiple={multiple} onChange={async ({ target }) => { const files = Array.from(target.files as FileList); const keys = await parseKeyFiles(files); onUpload(keys); }} disabled={disabled} shape={shape} color={color} > {children} </FileInput> ); }; export default forwardRef<HTMLInputElement, Props>(SelectKeyFiles);
6,375
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys/shared/flags.ts
import { KEY_FLAG } from '@proton/shared/lib/constants'; import { clearBit, setBit } from '@proton/shared/lib/helpers/bitset'; import { FlagAction } from './interface'; export const getNewKeyFlags = (Flags = 0, action: FlagAction) => { if (action === FlagAction.MARK_OBSOLETE) { return clearBit(Flags, KEY_FLAG.FLAG_NOT_OBSOLETE); } if (action === FlagAction.MARK_NOT_OBSOLETE) { return setBit(Flags, KEY_FLAG.FLAG_NOT_OBSOLETE); } if (action === FlagAction.MARK_COMPROMISED) { return clearBit(Flags, KEY_FLAG.FLAG_NOT_COMPROMISED + KEY_FLAG.FLAG_NOT_OBSOLETE); } if (action === FlagAction.MARK_NOT_COMPROMISED) { return setBit(Flags, KEY_FLAG.FLAG_NOT_COMPROMISED); } if (action === FlagAction.ENABLE_ENCRYPTION) { return clearBit(Flags, KEY_FLAG.FLAG_EMAIL_NO_ENCRYPT); } if (action === FlagAction.DISABLE_ENCRYPTION) { return setBit(Flags, KEY_FLAG.FLAG_EMAIL_NO_ENCRYPT); } if (action === FlagAction.ENABLE_EXPECT_SIGNED) { return clearBit(Flags, KEY_FLAG.FLAG_EMAIL_NO_SIGN); } if (action === FlagAction.DISABLE_EXPECT_SIGNED) { return setBit(Flags, KEY_FLAG.FLAG_EMAIL_NO_SIGN); } throw new Error('Unknown action'); };
6,376
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys/shared/getDisplayKey.ts
import type { AlgorithmInfo } from '@proton/crypto'; import { KEY_FLAG } from '@proton/shared/lib/constants'; import { hasBit } from '@proton/shared/lib/helpers/bitset'; import { Address, Key, SignedKeyListItem, UserModel } from '@proton/shared/lib/interfaces'; import { SimpleMap } from '@proton/shared/lib/interfaces/utils'; import { getDefaultKeyFlags, getFormattedAlgorithmNames } from '@proton/shared/lib/keys'; import getPermissions from './getPermissions'; import { KeyDisplay, KeyStatus, KeyType } from './interface'; interface Arguments { User: UserModel; Address?: Address; fingerprint: string; isDecrypted: boolean; isLoading: boolean; Key: Key; algorithmInfos: AlgorithmInfo[]; signedKeyListMap: SimpleMap<SignedKeyListItem>; isWeak: boolean; isE2EEForwardingKey: boolean; } export const getDisplayKey = ({ User, Address, algorithmInfos, fingerprint, isDecrypted, isLoading, signedKeyListMap, Key, isWeak, isE2EEForwardingKey, }: Arguments): KeyDisplay => { const { isSubUser, isPrivate } = User; const signedKeyListItem = signedKeyListMap[fingerprint]; const { ID, Flags, Primary, AddressForwardingID } = Key; const flags = signedKeyListItem?.Flags ?? Flags ?? getDefaultKeyFlags(Address); const primary = signedKeyListItem?.Primary ?? Primary ?? 0; const isAddressKey = !!Address; const isAddressDisabled = Address?.Status === 0; const isPrimary = primary === 1; // Flags undefined for user keys const canEncrypt = flags === undefined ? true : hasBit(flags, KEY_FLAG.FLAG_NOT_OBSOLETE); const canSign = flags === undefined ? true : hasBit(flags, KEY_FLAG.FLAG_NOT_COMPROMISED); const canEncryptAndSign = canEncrypt && canSign; const isObsolete = isDecrypted && !isAddressDisabled && !canEncrypt; const isCompromised = !canEncrypt && !canSign; const isForwarding = isE2EEForwardingKey; const status: KeyStatus = { isAddressDisabled, isPrimary, isDecrypted, isLoading, isCompromised, isObsolete, isWeak, isForwarding, }; const hasUserPermission = !isSubUser || isPrivate; const canModify = isAddressKey && hasUserPermission && !isPrimary; const canDeleteForwarding = AddressForwardingID === null; return { ID, fingerprint, algorithmInfos, type: isAddressKey ? KeyType.Address : KeyType.User, flags, primary, algorithm: getFormattedAlgorithmNames(algorithmInfos), status, permissions: getPermissions({ ...status, canModify, canEncryptAndSign, isAddressKey, hasUserPermission, canDeleteForwarding, }), }; };
6,377
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys/shared/getPermissions.test.ts
import getPermissions from './getPermissions'; describe('getPermissions', () => { describe('when isForwarding is true', () => { it('should return the correct permissions', () => { const permissions = getPermissions({ canModify: false, isDecrypted: false, isAddressDisabled: false, isCompromised: false, isObsolete: false, canEncryptAndSign: false, isAddressKey: false, isPrimary: false, hasUserPermission: false, isForwarding: true, canDeleteForwarding: true, isLoading: false, isWeak: false, }); expect(permissions).toEqual({ canExportPublicKey: false, canExportPrivateKey: false, canSetPrimary: false, canSetObsolete: false, canSetNotObsolete: false, canSetCompromised: false, canSetNotCompromised: false, canDelete: true, }); }); }); describe('when isForwarding is false', () => { it('should return the correct permissions', () => { const permissions = getPermissions({ canModify: true, isDecrypted: true, isAddressDisabled: false, isCompromised: false, isObsolete: false, canEncryptAndSign: true, isAddressKey: true, isPrimary: false, hasUserPermission: true, isForwarding: false, canDeleteForwarding: true, isLoading: false, isWeak: false, }); expect(permissions).toEqual({ canExportPublicKey: true, canExportPrivateKey: true, canSetPrimary: true, canSetObsolete: true, canSetNotObsolete: false, canSetCompromised: true, canSetNotCompromised: false, canDelete: true, }); }); }); });
6,378
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys/shared/getPermissions.ts
import { KeyStatus } from './interface'; interface Arguments extends KeyStatus { canModify: boolean; canEncryptAndSign: boolean; isAddressKey: boolean; hasUserPermission: boolean; canDeleteForwarding: boolean; } const getPermissions = ({ canModify, isDecrypted, isAddressDisabled, isCompromised, isObsolete, canEncryptAndSign, isAddressKey, isPrimary, hasUserPermission, isForwarding, canDeleteForwarding, }: Arguments) => { if (isForwarding) { return { canExportPublicKey: false, canExportPrivateKey: false, canSetPrimary: false, canSetObsolete: false, canSetNotObsolete: false, canSetCompromised: false, canSetNotCompromised: false, canDelete: canDeleteForwarding, }; } return { canExportPublicKey: true, canExportPrivateKey: isDecrypted, canSetPrimary: canModify && !isAddressDisabled && isDecrypted && canEncryptAndSign, canSetObsolete: canModify && !isAddressDisabled && isDecrypted && !isObsolete && !isCompromised, canSetNotObsolete: canModify && isObsolete && !isCompromised, canSetCompromised: canModify && !isCompromised, canSetNotCompromised: canModify && isCompromised, canDelete: isAddressKey && hasUserPermission && !isPrimary, }; }; export default getPermissions;
6,379
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys/shared/helper.ts
export const getKeyByID = <T extends { ID: string }>(keys: T[], ID: string): T | undefined => { return keys.find(({ ID: otherID }) => otherID === ID); };
6,380
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys/shared/interface.ts
import type { AlgorithmInfo } from '@proton/crypto'; export interface KeyPermissions { canExportPublicKey: boolean; canExportPrivateKey: boolean; canSetPrimary: boolean; canSetObsolete: boolean; canSetNotObsolete: boolean; canSetCompromised: boolean; canSetNotCompromised: boolean; canDelete: boolean; } export interface KeyActions { onDeleteKey: (id: string) => void; onExportPrivateKey: (id: string) => void; onExportPublicKey: (id: string) => void; onSetPrimary: (id: string) => void; onSetCompromised: (id: string) => void; onSetNotCompromised: (id: string) => void; onSetObsolete: (id: string) => void; onSetNotObsolete: (id: string) => void; } export enum KeyType { User, Address, } export interface KeyStatus { isAddressDisabled: boolean; isPrimary: boolean; isDecrypted: boolean; isCompromised: boolean; isObsolete: boolean; isLoading: boolean; isWeak: boolean; isForwarding: boolean; } export interface KeyDisplay { type: KeyType; ID: string; fingerprint: string; flags: number; primary: 0 | 1; algorithm: string; algorithmInfos: AlgorithmInfo[]; status: KeyStatus; permissions: KeyPermissions; } export enum FlagAction { MARK_OBSOLETE, MARK_NOT_OBSOLETE, MARK_COMPROMISED, MARK_NOT_COMPROMISED, DISABLE_ENCRYPTION, ENABLE_ENCRYPTION, DISABLE_EXPECT_SIGNED, ENABLE_EXPECT_SIGNED, }
6,381
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys/shared/useDisplayKeys.ts
import { useEffect, useMemo, useRef, useState } from 'react'; import { AlgorithmInfo, CryptoProxy, PrivateKeyReference, PublicKeyReference } from '@proton/crypto'; import { Address, DecryptedKey, Key, UserModel } from '@proton/shared/lib/interfaces'; import { getParsedSignedKeyList, getSignedKeyListMap } from '@proton/shared/lib/keys'; import { getDisplayKey } from './getDisplayKey'; interface Props { keys: DecryptedKey[] | undefined; User: UserModel; Address?: Address; loadingKeyID?: string; } interface ParsedKey { Key: Key; privateKey?: PrivateKeyReference; fingerprint: string; algorithmInfos: AlgorithmInfo[]; isDecrypted: boolean; isWeak: boolean; isE2EEForwardingKey: boolean; } const useDisplayKeys = ({ keys: maybeKeys, User, Address, loadingKeyID }: Props) => { const [state, setState] = useState<ParsedKey[]>([]); const ref = useRef(0); useEffect(() => { if (!maybeKeys) { return; } const run = async () => { const Keys = Address ? Address.Keys : User.Keys; return Promise.all( Keys.map(async (Key): Promise<ParsedKey> => { // A PrivateKeyReference is always a decrypted key (stored inside CryptoProxy). // If we don't already have a key reference, then we need to import the armored key as a PublicKey since we do not know // the passphrase to successfully import it as PrivateKey. // Then we set `isDecrypted` to true for PrivateKeyReferences, false for PublicKeyReferences. const maybePrivateKey: PublicKeyReference | PrivateKeyReference = maybeKeys.find(({ ID }) => ID === Key.ID)?.privateKey || (await CryptoProxy.importPublicKey({ armoredKey: Key.PrivateKey })); return { Key, fingerprint: maybePrivateKey?.getFingerprint() || '', algorithmInfos: [ maybePrivateKey.getAlgorithmInfo(), ...maybePrivateKey.subkeys.map((key) => key.getAlgorithmInfo()), ], isDecrypted: maybePrivateKey.isPrivate(), isWeak: maybePrivateKey.isWeak(), isE2EEForwardingKey: await CryptoProxy.isE2EEForwardingKey({ key: maybePrivateKey }), }; }) ); }; const current = ++ref.current; run() .then((result) => { if (current === ref.current) { setState(result); } }) .catch(() => { if (current === ref.current) { setState([]); } }); }, [maybeKeys]); return useMemo(() => { const signedKeyListMap = getSignedKeyListMap(getParsedSignedKeyList(Address?.SignedKeyList?.Data)); return state.map((data) => { return getDisplayKey({ User, Address, isLoading: loadingKeyID === data.Key.ID, signedKeyListMap, ...data, }); }); }, [User, Address, state, loadingKeyID]); }; export default useDisplayKeys;
6,382
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/labels/ActionsLabel.tsx
import { c } from 'ttag'; import { Label } from '@proton/shared/lib/interfaces/Label'; import { DropdownActions, useModalState } from '../../components'; import DeleteLabelModal from './modals/DeleteLabelModal'; import EditLabelModal from './modals/EditLabelModal'; interface Props { label: Label; } function ActionsLabel({ label }: Props) { const [editLabelProps, setEditLabelModalOpen] = useModalState(); const [deleteLabelProps, setDeleteLabelModalOpen] = useModalState(); const list = [ { text: c('Action').t`Edit`, onClick: () => setEditLabelModalOpen(true), 'data-testid': 'folders/labels:item-edit', }, { text: c('Action').t`Delete`, actionType: 'delete' as const, onClick: () => setDeleteLabelModalOpen(true), 'data-testid': 'folders/labels:item-delete', }, ]; return ( <> <DropdownActions size="small" list={list} /> <EditLabelModal {...editLabelProps} label={label} mode="edition" /> <DeleteLabelModal label={label} {...deleteLabelProps} /> </> ); } export default ActionsLabel;
6,383
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/labels/FolderIcon.tsx
import { FolderWithSubFolders } from '@proton/shared/lib/interfaces/Folder'; import { Icon } from '../../components'; import { IconName, IconProps } from '../../components/icon/Icon'; import { useFolderColor } from '../../hooks'; interface Props extends Omit<IconProps, 'name'> { folder: FolderWithSubFolders; name?: IconName; alt?: string; } const getIconName = (isParent: boolean, color?: string, name?: IconName) => { let iconName: IconName; if (isParent) { iconName = color ? 'folders-filled' : 'folders'; } else { iconName = color ? 'folder-filled' : name || 'folder'; } return iconName; }; const FolderIcon = ({ folder, name, alt = folder.Name, ...rest }: Props) => { const isParent = !!folder.subfolders?.length; const color = useFolderColor(folder); return <Icon name={getIconName(isParent, color, name)} color={color} alt={alt} {...rest} />; }; export default FolderIcon;
6,384
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/labels/FolderTreeViewList.tsx
import { DragEvent, useEffect, useRef, useState } from 'react'; import { c } from 'ttag'; import { useLoading } from '@proton/hooks'; import { orderFolders, updateLabel } from '@proton/shared/lib/api/labels'; import { ROOT_FOLDER } from '@proton/shared/lib/constants'; import { getParents, order } from '@proton/shared/lib/helpers/folder'; import { Folder } from '@proton/shared/lib/interfaces/Folder'; import clsx from '@proton/utils/clsx'; import { Icon, Info, TreeViewContainer, TreeViewItem } from '../../components'; import { useActiveBreakpoint, useApi, useEventManager } from '../../hooks'; import ActionsLabel from './ActionsLabel'; import FolderIcon from './FolderIcon'; import ToggleNotify from './ToggleNotify'; const INSIDE = 'inside'; const AFTER = 'after'; const BEFORE = 'before'; interface HeaderProps { isNarrow: boolean; } const Header = ({ isNarrow }: HeaderProps) => { return ( <div className="flex flex-nowrap w-full border-bottom pb-2"> <span className="text-bold flex-item-fluid"> {isNarrow ? null : <Icon name="arrows-cross" className="mr-4" />} {c('Header').t`Folders`} </span> <span className="w-custom hidden md:flex flex-align-items-center gap-2" style={{ '--w-custom': '10em' }}> <span className="text-bold">{c('Header').t`Notifications`}</span> <Info title={c('Tooltip').t`Enable/disable desktop and mobile notifications`} /> </span> <span className="text-bold w-custom text-right" style={{ '--w-custom': '10em' }}>{c('Header') .t`Actions`}</span> </div> ); }; interface Props { items: Folder[]; } const FolderTreeViewList = ({ items = [] }: Props) => { const api = useApi(); const { isNarrow } = useActiveBreakpoint(); const { call } = useEventManager(); const [loading, withLoading] = useLoading(); const [grabbed, setGrabbed] = useState<Folder>(); const [position, setPosition] = useState<string>(); const overRef = useRef<Folder>(); const timeoutRef = useRef<NodeJS.Timeout>(); const parents = getParents(items); const rootFolders = items.filter(({ ParentID = ROOT_FOLDER }) => ParentID === ROOT_FOLDER); const clear = () => { // Delay clear to execute onDrop first timeoutRef.current = setTimeout(() => { setGrabbed(undefined); setPosition(undefined); overRef.current = undefined; }, 200); }; const buildTreeView = (items: Folder[] = [], level = 0) => { return ( <TreeViewContainer> {order(items).map((item) => { const isOverred = item.ID === overRef.current?.ID; const handleDrop = async () => { if (!grabbed) { return; } if (position === INSIDE) { if (grabbed.ID === overRef.current?.ID) { return; } await api(updateLabel(grabbed.ID, { ...grabbed, ParentID: overRef.current?.ID })); return call(); } const { ParentID = ROOT_FOLDER } = overRef.current as Folder; const LabelIDs = order(parents[ParentID]) .filter(({ ID }) => ID !== grabbed?.ID) .reduce<Folder[]>((acc, folder) => { const isOverred = folder.ID === overRef.current?.ID; if (isOverred && position === BEFORE) { acc.push(grabbed); } acc.push(folder); if (isOverred && position === AFTER) { acc.push(grabbed); } return acc; }, []) .map(({ ID }) => ID); await api(updateLabel(grabbed.ID, { ...grabbed, ParentID })); await api(orderFolders({ LabelIDs, ParentID })); return call(); }; return ( <TreeViewItem onDragStart={() => { setGrabbed(item); }} onDragEnd={() => { clear(); }} onDragOver={(event: DragEvent) => { event.preventDefault(); const { currentTarget, clientY } = event; const { height, y } = currentTarget.getBoundingClientRect(); const quarter = height / 4; const pointer = clientY - y; overRef.current = item; if (pointer < quarter) { setPosition(BEFORE); } else if (pointer > quarter * 3) { setPosition(AFTER); } else { setPosition(INSIDE); } }} onDrop={() => withLoading(handleDrop())} draggable={!isNarrow} disabled={loading} key={item.ID} toggled focussed={false} title={item.Path} content={ <div className={clsx([ 'flex flex-nowrap flex-align-items-center flex-justify-space-between w-full py-2 treeview-item relative', isOverred && position === BEFORE && 'treeview-item--move-top', isOverred && position === AFTER && 'treeview-item--move-bottom', isOverred && position === INSIDE && 'treeview-item--move-inside', grabbed && grabbed.ID === item.ID && 'treeview-item--self-grabbed', ])} > <div className="treeview-item-name flex flex-nowrap flex-align-items-center flex-item-fluid"> {isNarrow ? null : ( <Icon name="text-align-justify" className="mr-4 flex-item-noshrink cursor-row-resize" /> )} <FolderIcon className="mr-2 flex-item-noshrink" folder={{ ...item, subfolders: parents[item.ID] }} /> <span className="text-ellipsis" title={item.Name}> {item.Name} </span> </div> <div className="w-custom md:w-custom hidden md:inline-flex" style={{ '--w-custom': '6.25rem', '--md-w-custom': '10em' }} > <ToggleNotify label={item} /> </div> <div className="w-custom md:w-custom flex flex-column flex-align-items-end" style={{ '--w-custom': '6.25rem', '--md-w-custom': '10em' }} > <div className="my-auto"> <ActionsLabel label={item} /> </div> </div> </div> } > {buildTreeView(parents[item.ID], level + 1)} </TreeViewItem> ); })} </TreeViewContainer> ); }; useEffect(() => { return () => { if (timeoutRef.current) { clearTimeout(timeoutRef.current); } }; }, []); return ( <> <Header isNarrow={isNarrow} /> {buildTreeView(rootFolders)} </> ); }; export default FolderTreeViewList;
6,385
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/labels/FoldersSection.tsx
import { c } from 'ttag'; import { Button, Scroll } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { orderFolders } from '@proton/shared/lib/api/labels'; import { MAIL_UPSELL_PATHS, ROOT_FOLDER } from '@proton/shared/lib/constants'; import { hasReachedFolderLimit } from '@proton/shared/lib/helpers/folder'; import { Info, LabelsUpsellModal, Loader, MailUpsellButton, useModalState } from '../../components'; import { useApi, useEventManager, useFolders, useMailSettings, useNotifications, useUser } from '../../hooks'; import { SettingsSection } from '../account'; import SettingsLayout from '../account/SettingsLayout'; import SettingsLayoutLeft from '../account/SettingsLayoutLeft'; import SettingsLayoutRight from '../account/SettingsLayoutRight'; import FolderTreeViewList from './FolderTreeViewList'; import ToggleEnableFolderColor from './ToggleEnableFolderColor'; import ToggleInheritParentFolderColor from './ToggleInheritParentFolderColor'; import EditLabelModal from './modals/EditLabelModal'; function ScrollWrapper({ children, scroll }: { children: JSX.Element; scroll?: boolean }) { return scroll ? ( <Scroll className="overflow-hidden pb-2 h-custom" style={{ '--h-custom': '50rem' }}> {children} </Scroll> ) : ( children ); } export default function FoldersSection() { const [user] = useUser(); const [folders = [], loadingFolders] = useFolders(); const [mailSettings] = useMailSettings(); const [loading, withLoading] = useLoading(); const { call } = useEventManager(); const api = useApi(); const { createNotification } = useNotifications(); const canCreateFolder = !hasReachedFolderLimit(user, folders); const [editLabelProps, setEditLabelModalOpen] = useModalState(); const [upsellModalProps, handleUpsellModalDisplay, renderUpsellModal] = useModalState(); const handleSortFolders = async () => { const rootFolders = folders.filter(({ ParentID = ROOT_FOLDER }) => ParentID === ROOT_FOLDER); const LabelIDs = [...rootFolders] .sort((a, b) => a.Name.localeCompare(b.Name, undefined, { numeric: true })) .map(({ ID }) => ID); await api(orderFolders({ LabelIDs })); await call(); createNotification({ text: c('Success message after sorting folders').t`Folders sorted` }); }; return ( <SettingsSection> {loadingFolders ? ( <Loader /> ) : ( <> <SettingsLayout> <SettingsLayoutLeft> <label htmlFor="folder-colors" className="text-semibold"> {c('Label').t`Use folder colors`} </label> </SettingsLayoutLeft> <SettingsLayoutRight className="pt-2"> <ToggleEnableFolderColor id="folder-colors" /> </SettingsLayoutRight> </SettingsLayout> {mailSettings?.EnableFolderColor ? ( <SettingsLayout> <SettingsLayoutLeft> <label htmlFor="parent-folder-color" className="text-semibold flex flex-align-items-center gap-2" > <span>{c('Label').t`Inherit color from parent folder`}</span> <Info title={c('Info - folder colouring feature') .t`When enabled, sub-folders inherit the color of the parent folder.`} /> </label> </SettingsLayoutLeft> <SettingsLayoutRight className="pt-2"> <ToggleInheritParentFolderColor id="parent-folder-color" /> </SettingsLayoutRight> </SettingsLayout> ) : null} <div className="my-7"> {canCreateFolder ? ( <Button color="norm" onClick={() => setEditLabelModalOpen(true)}> {c('Action').t`Add folder`} </Button> ) : ( <MailUpsellButton onClick={() => handleUpsellModalDisplay(true)} text={c('Action').t`Get more folders`} /> )} {folders.length ? ( <Button className="ml-4" shape="outline" title={c('Title').t`Sort folders alphabetically`} loading={loading} onClick={() => withLoading(handleSortFolders())} > {c('Action').t`Sort`} </Button> ) : null} </div> {folders.length ? ( // 17 is the number of elements before we have more than 50rem, will be replaced soon by a fix in scroll component <ScrollWrapper scroll={folders.length > 17}> <FolderTreeViewList items={folders} /> </ScrollWrapper> ) : null} <EditLabelModal {...editLabelProps} type="folder" /> {renderUpsellModal && ( <LabelsUpsellModal modalProps={upsellModalProps} feature={MAIL_UPSELL_PATHS.UNLIMITED_FOLDERS} isSettings /> )} </> )} </SettingsSection> ); }
6,386
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/labels/LabelSortableItem.tsx
import { Label } from '@proton/shared/lib/interfaces/Label'; import { Icon, OrderableTableRow } from '../../components'; import ActionsLabel from './ActionsLabel'; interface Props { label: Label; index: number; } function LabelItem({ label, ...rest }: Props) { const { Name, Color } = label; return ( <OrderableTableRow cells={[ <div key="label" className="flex flex-nowrap"> <Icon name="tag" style={{ fill: Color }} className="icon-16p flex-item-noshrink mr-4 my-auto" /> <span className="text-ellipsis" title={Name} data-testid="folders/labels:item-name"> {Name} </span> </div>, <ActionsLabel key="actions" label={label} />, ]} {...rest} /> ); } export default LabelItem;
6,387
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/labels/LabelSortableList.tsx
import { SortableContainerProps } from 'react-sortable-hoc'; import { c } from 'ttag'; import { Scroll } from '@proton/atoms/Scroll'; import { Label } from '@proton/shared/lib/interfaces/Label'; import clsx from '@proton/utils/clsx'; import { Icon, OrderableTable, OrderableTableBody, OrderableTableHeader } from '../../components'; import LabelSortableItem from './LabelSortableItem'; interface Props extends SortableContainerProps { items: Label[]; } function LabelSortableList({ items, ...rest }: Props) { // 17 is the number of elements before we have more than 50rem, will be replaced soon by a fix in scroll component return ( <Scroll className={clsx('overflow-hidden', items.length > 17 && 'h-custom')} style={{ '--h-custom': '50rem' }}> <OrderableTable className="border-none simple-table--has-actions border-collapse mt-4 " {...rest}> <caption className="sr-only">{c('Settings/labels').t`Labels/Folders`}</caption> <OrderableTableHeader> <tr> <th scope="col" className="w-custom" style={{ '--w-custom': '5%' }}> <Icon name="arrows-cross" /> </th> <th scope="col">{c('Settings/labels - table').t`Labels`}</th> <th scope="col" className="w-custom" style={{ '--w-custom': '10em' }}>{c( 'Settings/labels - table' ).t`Actions`}</th> </tr> </OrderableTableHeader> <OrderableTableBody colSpan={0}> {items.map((label, index) => ( <LabelSortableItem key={`item-${label.ID}`} index={index} label={label} data-testid="folders/labels:item-type:label" /> ))} </OrderableTableBody> </OrderableTable> </Scroll> ); } export default LabelSortableList;
6,388
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/labels/LabelsSection.tsx
import { useEffect, useState } from 'react'; import { arrayMove } from 'react-sortable-hoc'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { orderLabels } from '@proton/shared/lib/api/labels'; import { MAIL_UPSELL_PATHS } from '@proton/shared/lib/constants'; import { hasReachedLabelLimit } from '@proton/shared/lib/helpers/folder'; import isDeepEqual from '@proton/shared/lib/helpers/isDeepEqual'; import { Label } from '@proton/shared/lib/interfaces'; import { LabelsUpsellModal, Loader, MailUpsellButton, useDebounceInput, useModalState } from '../../components'; import { useApi, useEventManager, useLabels, useNotifications, useUser } from '../../hooks'; import { SettingsSection } from '../account'; import LabelSortableList from './LabelSortableList'; import EditLabelModal from './modals/EditLabelModal'; const DEBOUNCE_VALUE = 1600; const toLabelIDs = (labels: Label[]) => labels.map(({ ID }) => ID).join(','); function LabelsSection() { const [user] = useUser(); const [labels = [], loadingLabels] = useLabels(); const { call } = useEventManager(); const api = useApi(); const { createNotification } = useNotifications(); const [loading, withLoading] = useLoading(); const [localLabels, setLocalLabels] = useState(labels); const debouncedLabels = useDebounceInput(localLabels, DEBOUNCE_VALUE); const labelsOrder = toLabelIDs(labels); const debouncedLabelOrder = toLabelIDs(debouncedLabels); const canCreateLabel = !hasReachedLabelLimit(user, labels); const [editLabelProps, setEditLabelModalOpen] = useModalState(); const [upsellModalProps, handleUpsellModalDisplay, renderUpsellModal] = useModalState(); /** * Refresh the list + update API and call event, it can be slow. * We want a responsive UI, if it fails the item will go back to its previous index * @param {Number} oldIndex cf https://github.com/clauderic/react-sortable-hoc#basic-example * @param {Number} newIndex */ const onSortEnd = async ({ oldIndex, newIndex }: { oldIndex: number; newIndex: number }) => { const newLabels = arrayMove(localLabels, oldIndex, newIndex); setLocalLabels(newLabels); }; const handleSortLabel = async () => { const newLabels = [...localLabels].sort((a, b) => a.Name.localeCompare(b.Name, undefined, { numeric: true })); setLocalLabels(newLabels); createNotification({ text: c('Success message after sorting labels').t`Labels sorted` }); }; useEffect(() => { if (!debouncedLabelOrder || debouncedLabelOrder === labelsOrder) { return; } const sync = async () => { await api(orderLabels({ LabelIDs: debouncedLabels.map(({ ID }) => ID) })); await call(); }; void sync(); }, [debouncedLabels]); useEffect(() => { if (isDeepEqual(debouncedLabels, labels)) { return; } setLocalLabels(labels); }, [labels]); return ( <SettingsSection> {loadingLabels ? ( <Loader /> ) : ( <> <div className="mb-7"> {canCreateLabel ? ( <Button color="norm" onClick={() => setEditLabelModalOpen(true)}> {c('Action').t`Add label`} </Button> ) : ( <MailUpsellButton onClick={() => handleUpsellModalDisplay(true)} text={c('Action').t`Get more labels`} /> )} {localLabels.length ? ( <Button shape="outline" className="ml-4" title={c('Title').t`Sort labels alphabetically`} loading={loading} onClick={() => withLoading(handleSortLabel())} > {c('Action').t`Sort`} </Button> ) : null} </div> {localLabels.length ? <LabelSortableList items={localLabels} onSortEnd={onSortEnd} /> : null} <EditLabelModal {...editLabelProps} type="label" /> {renderUpsellModal && ( <LabelsUpsellModal modalProps={upsellModalProps} feature={MAIL_UPSELL_PATHS.UNLIMITED_LABELS} isSettings /> )} </> )} </SettingsSection> ); } export default LabelsSection;
6,389
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/labels/NewLabelForm.tsx
import { c } from 'ttag'; import { getColorName } from '@proton/shared/lib/colors'; import { LABEL_TYPE } from '@proton/shared/lib/constants'; import { requiredValidator } from '@proton/shared/lib/helpers/formValidators'; import { Folder } from '@proton/shared/lib/interfaces/Folder'; import { Label as tsLabel } from '@proton/shared/lib/interfaces/Label'; import { ColorPicker, Info, InputFieldTwo, Label, Toggle } from '../../components'; import { useMailSettings } from '../../hooks'; import ParentFolderSelector from './ParentFolderSelector'; interface Props { label: Partial<tsLabel | Folder>; onChangeName: (value: string) => void; onChangeColor: (color: string) => void; onChangeParentID?: (parentID: string | number) => void; onChangeNotify?: (value: number) => void; validator: (validations: string[]) => string; } function NewLabelForm({ label: labelOrFolder, onChangeColor, onChangeName, onChangeParentID, onChangeNotify, validator, }: Props) { const [mailSettings] = useMailSettings(); const ColorPickerLabel = (color: string) => { const colorName = getColorName(color); return ( <> <span>{c('New Label form').t`Color`}:</span> {colorName && <span className="color-weak text-capitalize text-no-bold ml-2">{colorName}</span>} </> ); }; const labelRenderer = () => { const label = labelOrFolder as tsLabel; return ( <div> <InputFieldTwo as={ColorPicker} layout="inline" label={ColorPickerLabel(label.Color)} id="color-button" data-testid="color-button" color={label.Color} onChange={onChangeColor} /> </div> ); }; const folderRenderer = () => { const folder = labelOrFolder as Folder; return ( <> <div> <ParentFolderSelector id="parentID" label={c('Label').t`Folder location`} value={folder.ParentID || 0} onChange={onChangeParentID} disableOptions={[folder.ID]} /> </div> {mailSettings?.EnableFolderColor ? ( <div> {mailSettings?.InheritParentFolderColor && folder.ParentID ? ( <div className="mb-4"> <strong className="text-semibold">{c('New Label form').t`Color`} </strong> <div className="mt-2">{c('Info').t`Inherited from parent folder`}</div> </div> ) : ( <InputFieldTwo as={ColorPicker} layout="inline" label={ColorPickerLabel(folder.Color)} id="color-button" data-testid="color-button" color={folder.Color} onChange={onChangeColor} /> )} </div> ) : null} <div className="flex flex-justify-start flex-align-items-center"> <Label htmlFor="notification" className="w-auto"> <span className="inline-flex flex-align-items-center"> <span className="mr-2 text-semibold">{c('Label').t`Notification`}</span> <Info title={c('Info') .t`You can turn on notifications to get alerts when new email messages arrive in this folder.`} /> </span> </Label> <div className="pt-2 ml-4"> <Toggle id="notification" checked={folder.Notify === 1} onChange={({ target }) => onChangeNotify?.(+target.checked)} /> </div> </div> </> ); }; return ( <div className="mx-auto flex-item-fluid"> {!labelOrFolder.ID && labelOrFolder.Type === LABEL_TYPE.MESSAGE_FOLDER ? ( <div className="mb-4"> {c('Info') .t`Name your new folder and select the parent folder you want to put it in. If you do not select a parent folder, this new folder will be created as a top level folder.`} </div> ) : null} <div> <InputFieldTwo id="folder" label={ labelOrFolder.Type === LABEL_TYPE.MESSAGE_FOLDER ? c('New Label form').t`Folder name` : c('New Label form').t`Label name` } value={labelOrFolder.Name} onValue={onChangeName} placeholder={ labelOrFolder.Type === LABEL_TYPE.MESSAGE_FOLDER ? c('New Label form').t`Folder name` : c('New Label form').t`Label name` } data-testid="label/folder-modal:name" autoFocus error={validator([requiredValidator(labelOrFolder.Name)])} /> </div> {labelOrFolder.Type === LABEL_TYPE.MESSAGE_LABEL && labelRenderer()} {labelOrFolder.Type === LABEL_TYPE.MESSAGE_FOLDER && folderRenderer()} </div> ); } export default NewLabelForm;
6,390
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/labels/ParentFolderSelector.tsx
import { c } from 'ttag'; import { ROOT_FOLDER } from '@proton/shared/lib/constants'; import { buildTreeview, formatFolderName } from '@proton/shared/lib/helpers/folder'; import { FolderWithSubFolders } from '@proton/shared/lib/interfaces/Folder'; import { InputFieldTwo, Loader, Option, SelectTwo } from '../../components'; import { OptionProps } from '../../components/select/Select'; import { useFolders } from '../../hooks'; interface Props { id: string; className?: string; value: string | number; label: string; onChange?: (parentID: string | number) => void; disableOptions: string[]; } const ParentFolderSelector = ({ id, value, label, onChange, className, disableOptions = [] }: Props) => { const [folders, loading] = useFolders(); if (loading) { return <Loader />; } const formatOption = ({ Name, ID }: FolderWithSubFolders, level = 0): OptionProps => ({ disabled: disableOptions.includes(ID), value: ID, text: formatFolderName(level, Name, ' ∙ '), }); const reducer = (acc: OptionProps[] = [], folder: FolderWithSubFolders, level = 0) => { acc.push(formatOption(folder, level)); if (Array.isArray(folder.subfolders)) { folder.subfolders.forEach((folder) => reducer(acc, folder, level + 1)); } return acc; }; const treeview = buildTreeview(folders); const options = treeview.reduce<OptionProps[]>( (acc, folder) => reducer(acc, folder), [{ value: ROOT_FOLDER, text: c('Option').t`No parent folder` }] ); return ( <InputFieldTwo as={SelectTwo} label={label} id={id} className={className} value={value} onChange={({ value }: any) => onChange?.(value)} > {options.map((option) => { return <Option key={option.value} value={option.value} title={option.text.toString()} />; })} </InputFieldTwo> ); }; export default ParentFolderSelector;
6,391
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/labels/ToggleEnableFolderColor.tsx
import { ChangeEvent } from 'react'; import { c } from 'ttag'; import { useLoading } from '@proton/hooks'; import { updateEnableFolderColor } from '@proton/shared/lib/api/mailSettings'; import { Toggle } from '../../components'; import { useApi, useEventManager, useMailSettings, useNotifications } from '../../hooks'; interface Props { id?: string; className?: string; } const ToggleEnableFolderColor = ({ id, className }: Props) => { const api = useApi(); const { call } = useEventManager(); const { createNotification } = useNotifications(); const [loading, withLoading] = useLoading(); const [mailSettings] = useMailSettings(); const handleChange = async ({ target }: ChangeEvent<HTMLInputElement>) => { await api(updateEnableFolderColor(+target.checked)); await call(); createNotification({ text: c('label/folder notification').t`Preference saved`, }); }; return ( <Toggle id={id} checked={!!mailSettings?.EnableFolderColor} className={className} onChange={(e) => withLoading(handleChange(e))} loading={loading} /> ); }; export default ToggleEnableFolderColor;
6,392
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/labels/ToggleInheritParentFolderColor.tsx
import { ChangeEvent } from 'react'; import { c } from 'ttag'; import { useLoading } from '@proton/hooks'; import { updateInheritParentFolderColor } from '@proton/shared/lib/api/mailSettings'; import { Toggle } from '../../components'; import { useApi, useEventManager, useMailSettings, useNotifications } from '../../hooks'; interface Props { id?: string; className?: string; } const ToggleInheritParentFolderColor = ({ id, className }: Props) => { const api = useApi(); const { call } = useEventManager(); const { createNotification } = useNotifications(); const [loading, withLoading] = useLoading(); const [mailSettings] = useMailSettings(); const handleChange = async ({ target }: ChangeEvent<HTMLInputElement>) => { await api(updateInheritParentFolderColor(+target.checked)); await call(); createNotification({ text: c('label/folder notification').t`Preference saved`, }); }; return ( <Toggle id={id} checked={!!mailSettings?.InheritParentFolderColor} className={className} onChange={(e) => withLoading(handleChange(e))} loading={loading} /> ); }; export default ToggleInheritParentFolderColor;
6,393
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/labels/ToggleNotify.tsx
import { ChangeEvent } from 'react'; import { c } from 'ttag'; import { useLoading } from '@proton/hooks'; import { updateLabel } from '@proton/shared/lib/api/labels'; import { Folder } from '@proton/shared/lib/interfaces/Folder'; import { Toggle, Tooltip } from '../../components'; import { useApi, useEventManager, useNotifications } from '../../hooks'; interface Props { label: Folder; } const ToggleNotify = ({ label }: Props) => { const api = useApi(); const { call } = useEventManager(); const { createNotification } = useNotifications(); const [loading, withLoading] = useLoading(); const handleChange = async ({ target }: ChangeEvent<HTMLInputElement>) => { const newLabel = { ...label, Notify: +target.checked, }; await api(updateLabel(label.ID, newLabel)); await call(); createNotification({ text: c('label/folder notification').t`${label.Name} updated`, }); }; return ( <Tooltip title={c('Tooltip').t`Enable/disable desktop and mobile notifications`}> <span className="inline-flex"> <Toggle id={`item-${label.ID}`} checked={label.Notify === 1} onChange={(e) => withLoading(handleChange(e))} loading={loading} /> </span> </Tooltip> ); }; export default ToggleNotify;
6,394
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/labels/index.ts
export { default as LabelsSection } from './LabelsSection'; export { default as FoldersSection } from './FoldersSection'; export { default as LabelModal } from './modals/EditLabelModal'; export { default as FolderIcon } from './FolderIcon';
6,395
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/labels
petrpan-code/ProtonMail/WebClients/packages/components/containers/labels/modals/DeleteLabelModal.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { useApi, useEventManager, useNotifications } from '@proton/components/hooks'; import { deleteLabel } from '@proton/shared/lib/api/labels'; import { LABEL_TYPE } from '@proton/shared/lib/constants'; import { Label } from '@proton/shared/lib/interfaces'; import { ErrorButton, ModalProps, Prompt } from '../../../components'; interface Props extends ModalProps { label: Label; onRemove?: () => void; } const DeleteLabelModal = ({ label, onRemove, ...rest }: Props) => { const api = useApi(); const { call } = useEventManager(); const { createNotification } = useNotifications(); const { onClose } = rest; const handleRemove = async () => { await api(deleteLabel(label.ID)); await call(); createNotification({ text: c('Success notification').t`${label.Name} removed`, }); onRemove?.(); }; const I18N: { [key: number]: any } = { [LABEL_TYPE.MESSAGE_LABEL]: { content: c('Info') .t`Emails tagged with this label will not be deleted and can still be found in the respective folder.`, confirm: c('Info').t`Are you sure you want to delete this label?`, }, [LABEL_TYPE.MESSAGE_FOLDER]: { content: c('Info') .t`Emails stored in this folder will not be deleted and can still be found in the All Mail folder.`, confirm: c('Info').t`Are you sure you want to delete this folder? All subfolders will also be deleted.`, }, }; return ( <Prompt title={ label.Type === LABEL_TYPE.MESSAGE_FOLDER ? c('Title').t`Delete ${label.Name} folder` : c('Title').t`Delete ${label.Name} label` } buttons={[ <ErrorButton onClick={handleRemove}>{c('Action').t`Delete`}</ErrorButton>, <Button onClick={onClose}>{c('Action').t`Cancel`}</Button>, ]} {...rest} > {I18N[label.Type].content} <br /> <br /> {I18N[label.Type].confirm} </Prompt> ); }; export default DeleteLabelModal;
6,396
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/labels
petrpan-code/ProtonMail/WebClients/packages/components/containers/labels/modals/EditLabelModal.tsx
import { FormEvent, useEffect, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { checkLabelAvailability, create as createLabel, updateLabel } from '@proton/shared/lib/api/labels'; import { getRandomAccentColor } from '@proton/shared/lib/colors'; import { LABEL_TYPE, ROOT_FOLDER } from '@proton/shared/lib/constants'; import { omit } from '@proton/shared/lib/helpers/object'; import { Folder } from '@proton/shared/lib/interfaces/Folder'; import { Label } from '@proton/shared/lib/interfaces/Label'; import noop from '@proton/utils/noop'; import { Form, ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, useFormErrors, } from '../../../components'; import { useApi, useEventManager, useNotifications } from '../../../hooks'; import NewLabelForm from '../NewLabelForm'; export interface LabelModel extends Pick<Folder | Label, 'Name' | 'Color' | 'Type'> { ID?: string; ParentID?: string | number; Notify?: number; Expanded?: number; Order?: number; Path?: string; } interface Props extends ModalProps { type?: 'label' | 'folder'; label?: LabelModel; mode?: 'create' | 'edition' | 'checkAvailable'; onAdd?: (label: LabelModel) => void; onEdit?: (label: LabelModel) => void; onCheckAvailable?: (label: LabelModel) => void; onCloseCustomAction?: () => void; } const prepareLabel = (label: LabelModel) => { if (label.ParentID === ROOT_FOLDER) { return omit(label, ['ParentID']); } return label; }; const EditLabelModal = ({ label, mode = 'create', onAdd = noop, onEdit = noop, onCheckAvailable = noop, type = 'label', onCloseCustomAction, ...rest }: Props) => { const { call } = useEventManager(); const { createNotification } = useNotifications(); const api = useApi(); const [loading, withLoading] = useLoading(); const { validator, onFormSubmit } = useFormErrors(); const { onClose } = rest; const [model, setModel] = useState<LabelModel>( label || { Name: '', Color: getRandomAccentColor(), Type: type === 'folder' ? LABEL_TYPE.MESSAGE_FOLDER : LABEL_TYPE.MESSAGE_LABEL, ParentID: type === 'folder' ? ROOT_FOLDER : undefined, Notify: type === 'folder' ? 1 : 0, } ); useEffect(() => { setModel( label || { Name: '', Color: getRandomAccentColor(), Type: type === 'folder' ? LABEL_TYPE.MESSAGE_FOLDER : LABEL_TYPE.MESSAGE_LABEL, ParentID: type === 'folder' ? ROOT_FOLDER : undefined, Notify: type === 'folder' ? 1 : 0, } ); }, [type]); const handleClose = () => { onCloseCustomAction?.(); onClose?.(); }; const create = async (label: LabelModel) => { const { Label } = await api(createLabel(prepareLabel(label))); await call(); createNotification({ text: c('label/folder notification').t`${Label.Name} created`, }); onAdd(Label); handleClose(); }; const update = async (label: LabelModel) => { if (label.ID) { const { Label } = await api(updateLabel(label.ID, prepareLabel(label))); await call(); createNotification({ text: c('Filter notification').t`${Label.Name} updated`, }); onEdit(Label); } handleClose(); }; const checkIsAvailable = async (label: LabelModel) => { await api(checkLabelAvailability(label)); onCheckAvailable(model); handleClose(); }; const handleSubmit = async (e: FormEvent) => { e.stopPropagation(); if (!onFormSubmit()) { return; } switch (mode) { case 'create': await withLoading(create(model)); return; case 'edition': await withLoading(update(model)); return; case 'checkAvailable': await withLoading(checkIsAvailable(model)); return; default: return undefined; } }; const handleChangeColor = (Color: string) => { setModel({ ...model, Color, }); }; const handleChangeName = (value: string) => { setModel({ ...model, Name: value, }); }; const handleChangeParentID = (ParentID: string | number) => { setModel({ ...model, ParentID, }); }; const handleChangeNotify = (Notify: number) => { setModel({ ...model, Notify, }); }; const getTitle = () => { const isFolder = model.Type === LABEL_TYPE.MESSAGE_FOLDER; if (mode === 'create') { return isFolder ? c('Label/folder modal').t`Create folder` : c('Label/folder modal').t`Create label`; } return isFolder ? c('Label/folder modal').t`Edit folder` : c('Label/folder modal').t`Edit label`; }; return ( <ModalTwo as={Form} onSubmit={handleSubmit} size="small" data-testid="label-modal" {...rest} onClose={handleClose} > <ModalTwoHeader title={getTitle()} /> <ModalTwoContent> <NewLabelForm label={model} onChangeName={handleChangeName} onChangeColor={handleChangeColor} onChangeParentID={handleChangeParentID} onChangeNotify={handleChangeNotify} validator={validator} /> </ModalTwoContent> <ModalTwoFooter> <Button data-testid="label-modal:cancel" onClick={handleClose}>{c('Action').t`Cancel`}</Button> <Button data-testid="label-modal:save" color="norm" loading={loading} type="submit">{c('Action') .t`Save`}</Button> </ModalTwoFooter> </ModalTwo> ); }; export default EditLabelModal;
6,397
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/layout/PrivateMainArea.tsx
import { HTMLAttributes, ReactNode, Ref, forwardRef } from 'react'; import clsx from '@proton/utils/clsx'; import { useTheme } from '../themes'; interface Props extends HTMLAttributes<HTMLDivElement> { className?: string; children?: ReactNode; hasToolbar?: boolean; hasRowMode?: boolean; drawerSidebar?: ReactNode; drawerVisibilityButton?: ReactNode; isDrawerApp?: boolean; mainBordered?: boolean; } const PrivateMainAreaBase = ( { className, hasToolbar = false, children, hasRowMode = false, drawerSidebar, drawerVisibilityButton, isDrawerApp, mainBordered = true, ...rest }: Props, ref: Ref<HTMLDivElement> ) => { const hasDrawerSidebar = !!drawerSidebar && !isDrawerApp; const theme = useTheme(); const isProminent = theme.information.prominentHeader; return ( <main className={clsx([ hasToolbar ? 'main-area--with-toolbar' : 'main-area', hasRowMode ? 'main-area--row-mode' : undefined, !drawerSidebar ? 'main-area-border' : undefined, 'flex-item-fluid-auto relative h-full reset4print', className, ])} ref={ref} {...rest} > <div className={clsx( 'flex flex-nowrap w-full', drawerSidebar ? 'h-full relative overflow-hidden' : undefined, isProminent ? 'ui-prominent' : undefined )} > <div className={clsx( 'flex flex-nowrap w-full h-full', hasDrawerSidebar ? 'main-area-border overflow-hidden' : 'overflow-auto', hasDrawerSidebar && mainBordered ? 'main-area-rounded--right' : undefined, isProminent ? 'ui-standard main-area-rounded--left' : undefined )} > {children} </div> {drawerVisibilityButton} {drawerSidebar} </div> </main> ); }; const PrivateMainArea = forwardRef(PrivateMainAreaBase); export default PrivateMainArea;
6,398
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/layout/PrivateMainAreaLoading.tsx
import { PrivateMainArea, SettingsPageTitle, SettingsParagraph, SettingsSection, SettingsSectionTitle, } from '@proton/components'; const PrivateMainAreaLoading = () => { return ( <PrivateMainArea> <div className="container-section-sticky"> <SettingsPageTitle className="my-14 settings-loading-page-title" /> <section className="container-section-sticky-section"> <SettingsSectionTitle className="settings-loading-section-title" /> <SettingsSection> <SettingsParagraph className="mb-4"> <span className="block settings-loading-paragraph-line" /> <span className="block settings-loading-paragraph-line" /> <span className="block settings-loading-paragraph-line" /> </SettingsParagraph> </SettingsSection> </section> </div> </PrivateMainArea> ); }; export default PrivateMainAreaLoading;
6,399