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/applications/pass-extension/src/app/content
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/context/types.ts
import type { AutofillService } from 'proton-pass-extension/app/content/services/form/autofill'; import type { AutosaveService } from 'proton-pass-extension/app/content/services/form/autosave'; import type { DetectorService } from 'proton-pass-extension/app/content/services/form/detector'; import type { FormManager } from 'proton-pass-extension/app/content/services/form/manager'; import type { IFrameService } from 'proton-pass-extension/app/content/services/iframes/service'; import type { ExtensionContextType } from 'proton-pass-extension/lib/context/extension-context'; import type { FeatureFlagState } from '@proton/pass/store/reducers'; import type { ProxiedSettings } from '@proton/pass/store/reducers/settings'; import type { AppState } from '@proton/pass/types'; export type WorkerStateChangeHandler = (state: AppState) => void; export type CSContextState = AppState & { active: boolean }; export type CSFeatures = 'Autofill' | 'Autofill2FA' | 'AutosuggestAlias' | 'AutosuggestPassword' | 'Autosave'; export interface ContentScriptContext { mainFrame: boolean; service: { autofill: AutofillService; autosave: AutosaveService; detector: DetectorService; formManager: FormManager; iframe: IFrameService; }; scriptId: string; destroy: (options: { reason: string; recycle?: boolean }) => void; getExtensionContext: () => ExtensionContextType; getFeatureFlags: () => FeatureFlagState; getFeatures: () => Record<CSFeatures, boolean>; getSettings: () => ProxiedSettings; getState: () => CSContextState; setFeatureFlags: (update: FeatureFlagState) => void; setSettings: (update: Partial<ProxiedSettings>) => void; setState: (update: Partial<CSContextState>) => void; }
4,300
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/firefox/auth-fallback.ts
import { contentScriptMessage, sendMessage, successMessage } from '@proton/pass/lib/extension/message'; import { WorkerMessageType } from '@proton/pass/types'; import { logger } from '@proton/pass/utils/logger'; import { APPS, EXTENSIONS } from '@proton/shared/lib/constants'; export const authFallback = () => { window.addEventListener('message', async (message) => { try { if ( message.data && message.data?.type !== undefined && (message.data?.extension === EXTENSIONS[APPS.PROTONEXTENSION].ID || message.data?.extension === EXTENSIONS[APPS.PROTONPASSBROWSEREXTENSION].ID) ) { switch (message.data.type) { case WorkerMessageType.ACCOUNT_FORK: const { keyPassword, selector, state, persistent, trusted } = message.data.payload; return await sendMessage.on( contentScriptMessage({ type: WorkerMessageType.ACCOUNT_FORK, payload: { selector, state, keyPassword, persistent, trusted, }, }), (response) => window.postMessage({ token: message.data?.token, ...response }) ); case WorkerMessageType.ACCOUNT_EXTENSION: return await sendMessage(contentScriptMessage({ type: WorkerMessageType.ACCOUNT_EXTENSION })); case WorkerMessageType.ACCOUNT_ONBOARDING: return await sendMessage(contentScriptMessage({ type: WorkerMessageType.ACCOUNT_ONBOARDING })); case WorkerMessageType.ACCOUNT_PROBE: return window.postMessage(successMessage({ token: message.data?.token })); } } } catch (e) { logger.warn('[ContentScript::Fork]', e); } }); };
4,301
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/firefox/index.ts
import { authFallback } from './auth-fallback'; authFallback();
4,302
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/cleanup.ts
import { INPUT_BASE_STYLES_ATTR } from '../constants.static'; import { cleanupInputInjectedStyles } from './icon'; export const DOMCleanUp = () => { /* remove all injected DOM nodes */ const injectedNodes = document.querySelectorAll('protonpass-control, protonpass-root'); injectedNodes.forEach((node) => node.remove()); /* reset input field styles */ const inputs = document.querySelectorAll<HTMLInputElement>(`input[${INPUT_BASE_STYLES_ATTR}]`); inputs.forEach((input) => cleanupInputInjectedStyles(input)); };
4,303
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/common/PauseListDropdown.tsx
import { type FC } from 'react'; import { type IFrameCloseOptions } from 'proton-pass-extension/app/content/types/iframe'; import { DropdownMenuButton } from '@proton/pass/components/Layout/Dropdown/DropdownMenuButton'; import { QuickActionsDropdown } from '@proton/pass/components/Layout/Dropdown/QuickActionsDropdown'; import { contentScriptMessage, sendMessage } from '@proton/pass/lib/extension/message'; import { WorkerMessageType } from '@proton/pass/types'; import { type CriteriaMasks } from '@proton/pass/types/worker/settings'; type Props = { criteria: CriteriaMasks; dense?: boolean; hostname: string; label: string; visible?: boolean; onClose?: (options?: IFrameCloseOptions) => void; }; export const PauseListDropdown: FC<Props> = ({ criteria, dense, hostname, label, visible, onClose }) => { const addToPauseList = () => { if (hostname) { void sendMessage( contentScriptMessage({ type: WorkerMessageType.PAUSE_WEBSITE, payload: { hostname, criteria }, }) ); } onClose?.(); }; return ( <QuickActionsDropdown /* Trick to re-render this component so that quickActions * dropdown is closed when iframe visibility changes */ key={`item-quick-actions-dropdown-${visible}`} color="weak" originalPlacement="bottom-end" shape="solid" {...(dense ? { className: 'flex-item-noshrink button-xs', iconSize: 12, menuClassName: 'text-xs', offset: 2, size: 'small', } : { size: 'small', iconSize: 18, className: 'flex-item-noshrink' })} > <DropdownMenuButton onClick={addToPauseList} label={label} ellipsis={false} /> </QuickActionsDropdown> ); };
4,304
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/context/IFrameContextProvider.tsx
import { type FC, createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react'; import type { IFrameCloseOptions, IFrameEndpoint, IFrameMessage, IFrameMessageWithSender, IFramePortMessageHandler, IFrameSecureMessage, } from 'proton-pass-extension/app/content/types'; import { IFrameMessageType } from 'proton-pass-extension/app/content/types'; import locales from 'proton-pass-extension/app/locales'; import { PassExtensionCore } from 'proton-pass-extension/lib/components/Extension/PassExtensionCore'; import type { Runtime } from 'webextension-polyfill'; import { useActivityProbe } from '@proton/pass/hooks/useActivityProbe'; import { clientReady } from '@proton/pass/lib/client'; import { contentScriptMessage, portForwardingMessage, sendMessage } from '@proton/pass/lib/extension/message'; import browser from '@proton/pass/lib/globals/browser'; import type { FeatureFlagState } from '@proton/pass/store/reducers'; import { INITIAL_SETTINGS, type ProxiedSettings } from '@proton/pass/store/reducers/settings'; import type { AppState, Maybe, MaybeNull, RecursivePartial, WorkerMessage } from '@proton/pass/types'; import { WorkerMessageType } from '@proton/pass/types'; import { safeCall } from '@proton/pass/utils/fp/safe-call'; import { logger } from '@proton/pass/utils/logger'; import { DEFAULT_LOCALE } from '@proton/shared/lib/constants'; import { loadLocale } from '@proton/shared/lib/i18n/loadLocale'; import { setTtagLocales } from '@proton/shared/lib/i18n/locales'; import noop from '@proton/utils/noop'; type IFrameContextValue = { endpoint: string; features: RecursivePartial<FeatureFlagState>; locale: string; port: MaybeNull<Runtime.Port>; settings: ProxiedSettings; userEmail: MaybeNull<string>; visible: boolean; workerState: Maybe<Omit<AppState, 'UID'>>; closeIFrame: (options?: IFrameCloseOptions) => void; postMessage: (message: IFrameMessage) => void; registerHandler: <M extends IFrameMessage['type']>(type: M, handler: IFramePortMessageHandler<M>) => void; resizeIFrame: (height: number) => void; }; type PortContext = { port: MaybeNull<Runtime.Port>; forwardTo: MaybeNull<string> }; const IFrameContext = createContext<IFrameContextValue>({ endpoint: '', features: {}, locale: DEFAULT_LOCALE, port: null, settings: INITIAL_SETTINGS, userEmail: null, visible: false, workerState: undefined, closeIFrame: noop, postMessage: noop, registerHandler: noop, resizeIFrame: noop, }); /* The IFrameContextProvider is responsible for opening a new * dedicated port with the service-worker and sending out port- * forwarding messages to the content-script's ports. We retrieve * the content-script's parent port name through postMessaging */ export const IFrameContextProvider: FC<{ endpoint: IFrameEndpoint }> = ({ endpoint, children }) => { const [{ port, forwardTo }, setPortContext] = useState<PortContext>({ port: null, forwardTo: null }); const [workerState, setWorkerState] = useState<IFrameContextValue['workerState']>(); const [settings, setSettings] = useState<ProxiedSettings>(INITIAL_SETTINGS); const [features, setFeatures] = useState<RecursivePartial<FeatureFlagState>>({}); const [userEmail, setUserEmail] = useState<MaybeNull<string>>(null); const [visible, setVisible] = useState<boolean>(false); const [locale, setLocale] = useState(DEFAULT_LOCALE); const activityProbe = useActivityProbe(contentScriptMessage); const destroyFrame = () => { logger.info(`[IFrame::${endpoint}] Unauthorized iframe injection`); safeCall(() => port?.disconnect())(); setPortContext({ port: null, forwardTo: null }); /* unload the content-script & remove iframe content */ void sendMessage(contentScriptMessage({ type: WorkerMessageType.UNLOAD_CONTENT_SCRIPT })); window.document?.documentElement?.remove(); }; /* when processing an `IFRAME_INJECT_PORT` message : verify the * `message.key` against the resolved extension key. This avoids * malicious websites from trying to spoof our content-script port * injection. If we detect a mismatch between the keys : destroy. */ const handlePortInjection = useCallback( async (message: IFrameSecureMessage<IFrameMessageType.IFRAME_INJECT_PORT>) => sendMessage.onSuccess( contentScriptMessage({ type: WorkerMessageType.RESOLVE_EXTENSION_KEY }), ({ key }) => { if (key !== message.key) return destroyFrame(); const framePortName = `${message.payload.port}-${endpoint}`; const port = browser.runtime.connect({ name: framePortName }); const forwardTo = message.payload.port; setPortContext({ port, forwardTo }); } ), [] ); const onPostMessageHandler = useCallback( safeCall((event: MessageEvent<Maybe<IFrameSecureMessage>>) => { if ( event.data && event.data?.type === IFrameMessageType.IFRAME_INJECT_PORT && event.data.sender === 'contentscript' ) { handlePortInjection(event.data).catch(noop); } }), [] ); useEffect(() => { if (userEmail === null && workerState && clientReady(workerState?.status)) { sendMessage .onSuccess( contentScriptMessage({ type: WorkerMessageType.RESOLVE_USER_DATA }), (response) => response.user?.Email && setUserEmail(response.user.Email) ) .catch(noop); } }, [workerState, userEmail]); useEffect(() => { setTtagLocales(locales); window.addEventListener('message', onPostMessageHandler); return () => window.removeEventListener('message', onPostMessageHandler); }, []); useEffect(() => { if (port && forwardTo) { port.onMessage.addListener((message: Maybe<IFrameMessage | WorkerMessage>) => { switch (message?.type) { case IFrameMessageType.IFRAME_INIT: setWorkerState(message.payload.workerState); setSettings(message.payload.settings); setFeatures(message.payload.features); return; case IFrameMessageType.IFRAME_HIDDEN: return setVisible(false); case IFrameMessageType.IFRAME_OPEN: return setVisible(true); case WorkerMessageType.FEATURE_FLAGS_UPDATE: return setFeatures(message.payload); case WorkerMessageType.SETTINGS_UPDATE: return setSettings(message.payload); /* If for any reason we get a `PORT_UNAUTHORIZED` * message : it likely means the iframe was injected * without being controlled by a content-script either * accidentally or intentionnally. Just to be safe, clear * the frame's innerHTML */ case WorkerMessageType.PORT_UNAUTHORIZED: return destroyFrame(); case WorkerMessageType.WORKER_STATUS: return setWorkerState(message.payload.state); } }); port.postMessage( portForwardingMessage<IFrameMessageWithSender<IFrameMessageType.IFRAME_CONNECTED>>(forwardTo, { sender: endpoint, type: IFrameMessageType.IFRAME_CONNECTED, payload: { framePort: port.name, id: endpoint }, }) ); port.onDisconnect.addListener(() => { setPortContext({ port: null, forwardTo: null }); window.addEventListener('message', onPostMessageHandler); }); } return safeCall(() => port?.disconnect()); }, [port, forwardTo]); /* Every message sent will be forwarded to the content-script * through the worker's MessageBroker. * see `@proton/pass/lib/extension/message/message-broker` */ const postMessage = useCallback( (rawMessage: IFrameMessage) => { try { port?.postMessage( portForwardingMessage<IFrameMessageWithSender>(forwardTo!, { ...rawMessage, sender: endpoint, }) ); } catch (_) {} }, [port, forwardTo] ); const closeIFrame = useCallback( (payload: IFrameCloseOptions = {}) => postMessage({ type: IFrameMessageType.IFRAME_CLOSE, payload }), [postMessage] ); const resizeIFrame = useCallback( (height: number) => { if (height > 0) postMessage({ type: IFrameMessageType.IFRAME_DIMENSIONS, payload: { height } }); }, [postMessage] ); const registerHandler = useCallback( <M extends IFrameMessage['type']>(type: M, handler: IFramePortMessageHandler<M>) => { const onMessageHandler = (message: Maybe<IFrameMessageWithSender>) => message?.type === type && message.sender === 'contentscript' && handler(message as IFrameMessageWithSender<M>); port?.onMessage.addListener(onMessageHandler); return () => port?.onMessage.removeListener(onMessageHandler); }, [port] ); useEffect(() => { if (visible) activityProbe.start(); else activityProbe.cancel(); }, [visible]); useEffect(() => { if (settings?.locale) { const nextLocale = settings.locale ?? DEFAULT_LOCALE; loadLocale(nextLocale, locales) .then(() => setLocale(nextLocale)) .catch(noop); } }, [settings?.locale]); const context = useMemo<IFrameContextValue>( () => ({ endpoint, features, locale, port, settings, userEmail, visible, workerState, closeIFrame, resizeIFrame, postMessage, registerHandler, }), [ features, locale, port, settings, userEmail, visible, workerState, closeIFrame, resizeIFrame, postMessage, registerHandler, ] ); return ( <PassExtensionCore endpoint={endpoint}> <IFrameContext.Provider value={context}>{children}</IFrameContext.Provider> </PassExtensionCore> ); }; export const useIFrameContext = () => useContext(IFrameContext); export const useRegisterMessageHandler = <M extends IFrameMessage['type']>( type: M, handler: IFramePortMessageHandler<M> ) => { const { registerHandler } = useIFrameContext(); useEffect(() => registerHandler(type, handler), [type, handler, registerHandler]); };
4,305
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/dropdown/Dropdown.scss
@import '~@proton/pass/styles/common'; body { background: transparent; } .item-icon { background-color: var(--field-norm); padding: em(4); border-radius: var(--border-radius-md); }
4,306
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/dropdown/Dropdown.tsx
import type { VFC } from 'react'; import { Icons } from '@proton/components'; import { ThemeProvider } from '@proton/pass/components/Layout/Theme/ThemeProvider'; import { IFrameContextProvider } from '../context/IFrameContextProvider'; import { DropdownContent } from './views/DropdownContent'; import './Dropdown.scss'; export const Dropdown: VFC = () => ( <IFrameContextProvider endpoint="dropdown"> <Icons /> <ThemeProvider /> <DropdownContent /> </IFrameContextProvider> );
4,307
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/dropdown/index.tsx
import ReactDOM from 'react-dom'; import { Dropdown } from './Dropdown'; const root = document.getElementById('root') as HTMLElement; ReactDOM.render(<Dropdown />, root);
4,308
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/dropdown
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/dropdown/components/DropdownHeader.tsx
import type { ReactElement, VFC } from 'react'; type Props = { title: string; extra?: ReactElement }; export const DropdownHeader: VFC<Props> = ({ title, extra }) => ( <div className="flex flex-nowrap flex-item-noshrink flex-align-items-center flex-justify-space-between pl-3 pr-2 pt-2"> <span className="text-xs text-semibold text-ellipsis">{title}</span> {extra} </div> );
4,309
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/dropdown
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/dropdown/components/DropdownItem.scss
button.pass-injected-dropdown--item { padding-inline: 0.75em; padding-block: 0.5em; .pass-injected-dropdown--subtitle { line-height: 1.2; } }
4,310
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/dropdown
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/dropdown/components/DropdownItem.tsx
import type { ReactNode, VFC } from 'react'; import { DropdownMenuButton } from '@proton/components/components'; import { SubTheme } from '@proton/pass/components/Layout/Theme/types'; import clsx from '@proton/utils/clsx'; import { DropdownItemIcon, type DropdownItemIconProps } from './DropdownItemIcon'; import './DropdownItem.scss'; export const DROPDOWN_ITEM_HEIGHT = 3.75; /* rem */ export const DropdownItem: VFC< { onClick?: () => void; title?: string; subTitle: ReactNode; disabled?: boolean; autogrow?: boolean; subTheme?: SubTheme; } & DropdownItemIconProps > = ({ onClick, title, subTitle, icon, url, disabled, autogrow, subTheme = SubTheme.VIOLET }) => ( <DropdownMenuButton className={clsx('pass-injected-dropdown--item text-left min-h-custom h-custom', subTheme)} style={ autogrow ? { '--min-h-custom': `${DROPDOWN_ITEM_HEIGHT}rem` } : { '--h-custom': `${DROPDOWN_ITEM_HEIGHT}rem` } } onClick={onClick} disabled={disabled} > <div className="flex flex-align-items-center gap-3"> <DropdownItemIcon {...(url ? { url, icon } : { icon })} /> <div className="flex-item-fluid"> {title && <span className="block text-ellipsis">{title}</span>} <span className={clsx( 'pass-injected-dropdown--subtitle block color-weak text-xs', !autogrow && 'text-ellipsis' )} > {subTitle} </span> </div> </div> </DropdownMenuButton> );
4,311
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/dropdown
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/dropdown/components/DropdownItemIcon.tsx
import { type VFC } from 'react'; import { type IconName } from '@proton/components/components'; import { IconBox } from '@proton/pass/components/Layout/Icon/IconBox'; import { BaseItemIcon } from '@proton/pass/components/Layout/Icon/ItemIcon'; import { PassIcon } from '@proton/pass/components/Layout/Icon/PassIcon'; import type { DropdownIcon } from '@proton/pass/types/data/pass-icon'; import { isPassIcon } from '@proton/pass/types/data/pass-icon'; export type DropdownItemIconProps = { url: string; icon: IconName } | { url?: never; icon: DropdownIcon }; export const DropdownItemIcon: VFC<DropdownItemIconProps> = ({ url, icon }) => isPassIcon(icon) ? ( <IconBox size={20} mode="transparent"> <PassIcon status={icon} size={24} className="absolute-center" /> </IconBox> ) : ( <BaseItemIcon url={url} icon={icon} size={20} alt="" /> );
4,312
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/dropdown
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/dropdown/components/DropdownItemsList.tsx
import type { FC } from 'react'; import { Scroll } from '@proton/atoms'; import { DropdownMenu } from '@proton/components/components'; import { DROPDOWN_ITEM_HEIGHT } from './DropdownItem'; const DROPDOWN_MAX_VISIBLE_ITEMS = 3; const DROPDOWN_LIST_MAX_HEIGHT = DROPDOWN_MAX_VISIBLE_ITEMS * DROPDOWN_ITEM_HEIGHT; export const DropdownItemsList: FC = ({ children }) => ( <DropdownMenu> <div className="max-h-custom overflow-hidden" style={{ '--max-h-custom': `${DROPDOWN_LIST_MAX_HEIGHT}rem` }}> <Scroll {...(Array.isArray(children) && children.length >= DROPDOWN_MAX_VISIBLE_ITEMS ? { style: { height: `${DROPDOWN_LIST_MAX_HEIGHT}rem` } } : {})} > {children} </Scroll> </div> </DropdownMenu> );
4,313
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/dropdown
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/dropdown/components/DropdownPinUnlock.tsx
import type { VFC } from 'react'; import { useEffect, useState } from 'react'; import { c } from 'ttag'; import { PinCodeInput } from '@proton/pass/components/Lock/PinCodeInput'; import { useEnsureMounted } from '@proton/pass/hooks/useEnsureMounted'; import { useSessionLockPinSubmitEffect } from '@proton/pass/hooks/useSessionLockPinSubmitEffect'; import { contentScriptMessage, sendMessage } from '@proton/pass/lib/extension/message'; import type { MaybeNull } from '@proton/pass/types'; import { WorkerMessageType } from '@proton/pass/types'; import { PassIconStatus } from '@proton/pass/types/data/pass-icon'; import { PASS_APP_NAME } from '@proton/shared/lib/constants'; import clsx from '@proton/utils/clsx'; import { DropdownItemIcon } from './DropdownItemIcon'; export const DropdownPinUnlock: VFC<{ onUnlock?: () => void; visible?: boolean; }> = ({ onUnlock, visible }) => { const ensureMounted = useEnsureMounted(); const [value, setValue] = useState<string>(''); const [loading, setLoading] = useState<boolean>(false); const [error, setError] = useState<MaybeNull<string>>(null); const onSubmit = async (value: string) => { try { setLoading(true); await sendMessage.onSuccess( contentScriptMessage({ type: WorkerMessageType.UNLOCK_REQUEST, payload: { pin: value } }), ensureMounted((res) => { if (!res.ok) setError(res.error); else onUnlock?.(); }) ); } catch { } finally { ensureMounted(setLoading)(false); } }; useSessionLockPinSubmitEffect(value, { onSubmit }); useEffect(() => { if (!visible) setError(null); }, [visible]); return ( <div className="px-4 py-3"> <div className="flex flex-align-items-center gap-3 mb-3"> <DropdownItemIcon icon={PassIconStatus.LOCKED_DROPDOWN} /> <div className="flex-item-fluid"> <span className="block text-ellipsis">{c('Title').t`Unlock ${PASS_APP_NAME}`}</span> <span className={clsx('block color-weak text-sm text-ellipsis')}>{c('Info') .t`Enter your PIN code`}</span> </div> </div> <PinCodeInput loading={loading} value={value} onValue={setValue} autoFocus={visible} /> {error && <div className="text-center text-sm color-danger mt-3">{error}</div>} </div> ); };
4,314
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/dropdown
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/dropdown/components/DropdownSwitch.tsx
import { type ForwardRefRenderFunction, forwardRef } from 'react'; import { AliasAutoSuggest } from 'proton-pass-extension/app/content/injections/apps/dropdown/views/AliasAutoSuggest'; import { ItemsList } from 'proton-pass-extension/app/content/injections/apps/dropdown/views/ItemsList'; import { PasswordAutoSuggest } from 'proton-pass-extension/app/content/injections/apps/dropdown/views/PasswordAutoSuggest'; import type { DropdownActions, IFrameCloseOptions, IFrameMessage } from 'proton-pass-extension/app/content/types'; import { DropdownAction } from 'proton-pass-extension/app/content/types'; import { useRequestFork } from 'proton-pass-extension/lib/hooks/useRequestFork'; import { c } from 'ttag'; import { CircleLoader } from '@proton/atoms/CircleLoader'; import { clientBusy } from '@proton/pass/lib/client'; import type { MaybeNull } from '@proton/pass/types'; import { AppStatus } from '@proton/pass/types'; import { PassIconStatus } from '@proton/pass/types/data/pass-icon'; import { pipe, tap } from '@proton/pass/utils/fp/pipe'; import { FORK_TYPE } from '@proton/shared/lib/authentication/ForkInterface'; import { BRAND_NAME, PASS_APP_NAME } from '@proton/shared/lib/constants'; import noop from '@proton/utils/noop'; import { DROPDOWN_ITEM_HEIGHT, DropdownItem } from './DropdownItem'; import { DropdownPinUnlock } from './DropdownPinUnlock'; type Props = { state: MaybeNull<DropdownActions>; status: AppStatus; loggedIn: boolean; visible?: boolean; onClose?: (options?: IFrameCloseOptions) => void; onMessage?: (message: IFrameMessage) => void; onReset?: () => void; }; const DropdownSwitchRender: ForwardRefRenderFunction<HTMLDivElement, Props> = ( { state, loggedIn, status, visible, onClose, onReset = noop, onMessage = noop }, ref ) => { const accountFork = useRequestFork(); const onMessageWithReset = pipe(onMessage, tap(onReset)); return ( <div ref={ref} className="min-h-custom bg-norm relative" style={{ '--min-h-custom': `${DROPDOWN_ITEM_HEIGHT}rem` }} > {(() => { if (state === null || clientBusy(status)) { return <CircleLoader className="absolute-center m-auto" />; } if (status === AppStatus.LOCKED) { return <DropdownPinUnlock onUnlock={() => onClose?.({ refocus: true })} visible={visible} />; } if (!loggedIn) { return ( <DropdownItem onClick={async () => { onClose?.(); await accountFork(FORK_TYPE.SWITCH); }} subTitle={c('Info').t`Enable ${PASS_APP_NAME} by connecting your ${BRAND_NAME} account`} icon={PassIconStatus.DISABLED} autogrow /> ); } switch (state.action) { case DropdownAction.AUTOFILL: return ( <ItemsList hostname={state.hostname} items={state.items} needsUpgrade={state.needsUpgrade} onMessage={onMessageWithReset} onClose={onClose} visible={visible} /> ); case DropdownAction.AUTOSUGGEST_PASSWORD: return ( <PasswordAutoSuggest passwordOptions={state.options} hostname={state.hostname} onMessage={onMessage} onClose={onClose} visible={visible} /> ); case DropdownAction.AUTOSUGGEST_ALIAS: return ( <AliasAutoSuggest prefix={state.prefix} hostname={state.hostname} onClose={onClose} onMessage={onMessageWithReset} visible={visible} /> ); } })()} </div> ); }; export const DropdownSwitch = forwardRef(DropdownSwitchRender);
4,315
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/dropdown
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/dropdown/views/AliasAutoSuggest.tsx
import { type VFC, useCallback, useEffect, useState } from 'react'; import { PauseListDropdown } from 'proton-pass-extension/app/content/injections/apps/common/PauseListDropdown'; import { useIFrameContext } from 'proton-pass-extension/app/content/injections/apps/context/IFrameContextProvider'; import { DropdownHeader } from 'proton-pass-extension/app/content/injections/apps/dropdown/components/DropdownHeader'; import { DropdownItem } from 'proton-pass-extension/app/content/injections/apps/dropdown/components/DropdownItem'; import type { IFrameCloseOptions, IFrameMessage } from 'proton-pass-extension/app/content/types'; import { IFrameMessageType } from 'proton-pass-extension/app/content/types'; import { c } from 'ttag'; import { CircleLoader } from '@proton/atoms/CircleLoader'; import { AliasPreview } from '@proton/pass/components/Alias/legacy/Alias.preview'; import { SubTheme } from '@proton/pass/components/Layout/Theme/types'; import { useEnsureMounted } from '@proton/pass/hooks/useEnsureMounted'; import { useNavigateToUpgrade } from '@proton/pass/hooks/useNavigateToUpgrade'; import { contentScriptMessage, sendMessage } from '@proton/pass/lib/extension/message'; import { createTelemetryEvent } from '@proton/pass/lib/telemetry/event'; import type { AliasOptions, AliasState } from '@proton/pass/store/reducers'; import { type MaybeNull, WorkerMessageType } from '@proton/pass/types'; import { TelemetryEventName } from '@proton/pass/types/data/telemetry'; import { PASS_APP_NAME } from '@proton/shared/lib/constants'; import { wait } from '@proton/shared/lib/helpers/promise'; import noop from '@proton/utils/noop'; type Props = { hostname: string; prefix: string; visible?: boolean; onClose?: (options?: IFrameCloseOptions) => void; onMessage?: (message: IFrameMessage) => void; }; const isValidAliasOptions = (options: AliasState['aliasOptions']): options is AliasOptions => options !== null && options?.suffixes?.[0] !== undefined; const getInitialLoadingText = (): string => c('Info').t`Generating alias...`; export const AliasAutoSuggest: VFC<Props> = ({ hostname, prefix, visible, onClose, onMessage }) => { const ensureMounted = useEnsureMounted(); const navigateToUpgrade = useNavigateToUpgrade(); const { userEmail } = useIFrameContext(); const [aliasOptions, setAliasOptions] = useState<MaybeNull<AliasState['aliasOptions']>>(null); const [needsUpgrade, setNeedsUpgrade] = useState<boolean>(false); const [loadingText, setLoadingText] = useState<MaybeNull<string>>(getInitialLoadingText()); const [error, setError] = useState<MaybeNull<string>>(null); const requestAliasOptions = useCallback(async () => { try { setLoadingText(getInitialLoadingText()); setError(null); await wait(500); await sendMessage.onSuccess( contentScriptMessage({ type: WorkerMessageType.ALIAS_OPTIONS }), ensureMounted((response) => { if (response.ok) { setAliasOptions(response.options); setNeedsUpgrade(response.needsUpgrade); } else setError(response.error ?? c('Error').t`Alias options could not be resolved`); }) ); } catch { } finally { ensureMounted(setLoadingText)(null); } }, []); const createAlias = useCallback( async ({ suffixes, mailboxes }: AliasOptions) => { const defaultSuffix = suffixes[0]; setLoadingText(c('Info').t`Creating alias...`); const aliasEmail = `${prefix}${defaultSuffix.suffix}`; try { await sendMessage.onSuccess( contentScriptMessage({ type: WorkerMessageType.ALIAS_CREATE, payload: { url: hostname, alias: { prefix, mailboxes: [mailboxes[0]], signedSuffix: defaultSuffix.signedSuffix, aliasEmail, }, }, }), ensureMounted((response) => { if (response.ok) { onMessage?.({ type: IFrameMessageType.DROPDOWN_AUTOFILL_EMAIL, payload: { email: aliasEmail }, }); void sendMessage( contentScriptMessage({ type: WorkerMessageType.TELEMETRY_EVENT, payload: { event: createTelemetryEvent(TelemetryEventName.AutosuggestAliasCreated, {}, {}), }, }) ); } else setError(response.error); }) ); } catch { } finally { ensureMounted(setLoadingText)(null); } }, [hostname] ); useEffect(() => { requestAliasOptions().catch(noop); }, []); useEffect(() => { if (error) setLoadingText(null); }, [error]); const validAliasOptions = isValidAliasOptions(aliasOptions); return ( <> <DropdownHeader title={c('Title').t`Email`} extra={ <PauseListDropdown criteria="Autosuggest" dense hostname={hostname} label={c('Action').t`Do not suggest on this website`} onClose={onClose} visible={visible} /> } /> <DropdownItem title={c('Title').t`Use my email`} disabled={!userEmail} subTitle={ userEmail ?? ( <span className="block flex flex-align-items-center"> <CircleLoader className="mr-1" /> <span>{c('Info').t`Loading...`}</span> </span> ) } icon="envelope" onClick={ userEmail ? () => onMessage?.({ type: IFrameMessageType.DROPDOWN_AUTOFILL_EMAIL, payload: { email: userEmail }, }) : noop } /> <DropdownItem title={needsUpgrade ? c('Info').t`Upgrade ${PASS_APP_NAME}` : c('Title').t`Hide my email`} autogrow subTitle={(() => { if (loadingText) { return ( <span className="block flex flex-align-items-center flex-nowrap"> <CircleLoader className="mr-1" /> <span className="block text-ellipsis">{loadingText}</span> </span> ); } if (needsUpgrade) { return ( <span className="text-sm block">{c('Warning') .t`Your plan does not allow you to create more aliases`}</span> ); } if (error) { return ( <span className="color-danger text-sm block"> {c('Error').t`Cannot create alias (${error}).`}{' '} <span className="text-semibold text-underline">{c('Action').t`Try again`}</span> </span> ); } if (validAliasOptions) { return ( <AliasPreview prefix={prefix} suffix={aliasOptions.suffixes[0].suffix} standalone key="alias-preview" /> ); } })()} icon={needsUpgrade ? 'arrow-out-square' : 'alias'} subTheme={SubTheme.TEAL} disabled={loadingText !== null} onClick={(() => { if (needsUpgrade) return navigateToUpgrade; if (error) return requestAliasOptions; if (validAliasOptions) return () => createAlias(aliasOptions); })()} /> </> ); };
4,316
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/dropdown
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/dropdown/views/DropdownContent.tsx
import { type VFC, useCallback, useEffect, useRef, useState } from 'react'; import { AppStatus, type MaybeNull } from '@proton/pass/types'; import { pipe } from '@proton/pass/utils/fp/pipe'; import { type DropdownActions, type IFrameMessage, IFrameMessageType } from '../../../../types'; import { useIFrameContext, useRegisterMessageHandler } from '../../context/IFrameContextProvider'; import { DropdownSwitch } from '../components/DropdownSwitch'; export const DropdownContent: VFC = () => { const dropdownRef = useRef<HTMLDivElement>(null); const { workerState, visible, resizeIFrame, closeIFrame, postMessage } = useIFrameContext(); const [dropdownState, setDropdownState] = useState<MaybeNull<DropdownActions>>(null); const onReset = () => setDropdownState(null); const onClose = pipe(closeIFrame, onReset); const onResize = resizeIFrame; const handleAction = useCallback( ({ payload }: IFrameMessage<IFrameMessageType.DROPDOWN_ACTION>) => setDropdownState(payload), [] ); useRegisterMessageHandler(IFrameMessageType.DROPDOWN_ACTION, handleAction); useEffect(() => { if (dropdownRef.current) { const obs = new ResizeObserver(([entry]) => onResize(entry.contentRect.height)); obs.observe(dropdownRef.current); return () => obs.disconnect(); } }); return ( <DropdownSwitch ref={dropdownRef} state={dropdownState} status={workerState?.status ?? AppStatus.IDLE} loggedIn={workerState?.loggedIn ?? false} onMessage={postMessage} onClose={onClose} onReset={onReset} visible={visible} /> ); };
4,317
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/dropdown
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/dropdown/views/ItemsList.tsx
import type { VFC } from 'react'; import { useEffect, useMemo } from 'react'; import { PauseListDropdown } from 'proton-pass-extension/app/content/injections/apps/common/PauseListDropdown'; import { useIFrameContext } from 'proton-pass-extension/app/content/injections/apps/context/IFrameContextProvider'; import { DropdownHeader } from 'proton-pass-extension/app/content/injections/apps/dropdown/components/DropdownHeader'; import { DropdownItem } from 'proton-pass-extension/app/content/injections/apps/dropdown/components/DropdownItem'; import { DropdownItemsList } from 'proton-pass-extension/app/content/injections/apps/dropdown/components/DropdownItemsList'; import type { IFrameCloseOptions, IFrameMessage } from 'proton-pass-extension/app/content/types'; import { IFrameMessageType } from 'proton-pass-extension/app/content/types'; import { c } from 'ttag'; import { useNavigateToUpgrade } from '@proton/pass/hooks/useNavigateToUpgrade'; import { contentScriptMessage, sendMessage } from '@proton/pass/lib/extension/message'; import { createTelemetryEvent } from '@proton/pass/lib/telemetry/event'; import { type SafeLoginItem, WorkerMessageType } from '@proton/pass/types'; import { PassIconStatus } from '@proton/pass/types/data/pass-icon'; import { TelemetryEventName } from '@proton/pass/types/data/telemetry'; import { truthy } from '@proton/pass/utils/fp/predicates'; import { PASS_APP_NAME } from '@proton/shared/lib/constants'; type Props = { items: SafeLoginItem[]; hostname: string; needsUpgrade: boolean; visible?: boolean; onClose?: (options?: IFrameCloseOptions) => void; onMessage?: (message: IFrameMessage) => void; }; export const ItemsList: VFC<Props> = ({ hostname, items, needsUpgrade, visible, onMessage, onClose }) => { const { settings } = useIFrameContext(); const navigateToUpgrade = useNavigateToUpgrade(); useEffect(() => { if (visible) { void sendMessage( contentScriptMessage({ type: WorkerMessageType.TELEMETRY_EVENT, payload: { event: createTelemetryEvent(TelemetryEventName.AutofillDisplay, {}, { location: 'source' }), }, }) ); } }, [visible]); const dropdownItems = useMemo( () => [ needsUpgrade && ( <DropdownItem key={'upgrade-autofill'} icon="arrow-out-square" title={c('Info').t`Upgrade ${PASS_APP_NAME}`} subTitle={c('Warning').t`Your plan only allows you to autofill from your first two vaults`} onClick={navigateToUpgrade} autogrow /> ), ...items.map(({ shareId, itemId, username, name, url }) => ( <DropdownItem key={itemId} title={name} subTitle={username} url={settings.loadDomainImages ? url : undefined} icon="user" onClick={() => sendMessage.onSuccess( contentScriptMessage({ type: WorkerMessageType.AUTOFILL_SELECT, payload: { shareId, itemId }, }), ({ username, password }) => { onMessage?.({ type: IFrameMessageType.DROPDOWN_AUTOFILL_LOGIN, payload: { username, password }, }); } ) } /> )), ].filter(truthy), [items, needsUpgrade, onMessage] ); return ( <> <DropdownHeader title={c('Title').t`Log in as...`} extra={ <PauseListDropdown criteria="Autofill" dense hostname={hostname} label={c('Action').t`Do not suggest on this website`} onClose={onClose} visible={visible} /> } /> {dropdownItems.length > 0 ? ( <DropdownItemsList>{dropdownItems}</DropdownItemsList> ) : ( <DropdownItem icon={PassIconStatus.ACTIVE} onClick={() => onClose?.()} title={PASS_APP_NAME} subTitle={c('Info').t`No login found`} /> )} </> ); };
4,318
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/dropdown
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/dropdown/views/PasswordAutoSuggest.tsx
/* eslint-disable deprecation/deprecation */ import { type VFC, useEffect, useRef, useState } from 'react'; import { PauseListDropdown } from 'proton-pass-extension/app/content/injections/apps/common/PauseListDropdown'; import { DropdownHeader } from 'proton-pass-extension/app/content/injections/apps/dropdown/components/DropdownHeader'; import { DropdownItem } from 'proton-pass-extension/app/content/injections/apps/dropdown/components/DropdownItem'; import type { IFrameCloseOptions, IFrameMessage } from 'proton-pass-extension/app/content/types'; import { IFrameMessageType } from 'proton-pass-extension/app/content/types'; import { c } from 'ttag'; import { SubTheme } from '@proton/pass/components/Layout/Theme/types'; import { getCharsGroupedByColor } from '@proton/pass/hooks/usePasswordGenerator'; import type { GeneratePasswordOptions } from '@proton/pass/lib/password/generator'; import { generatePassword } from '@proton/pass/lib/password/generator'; import { type Maybe } from '@proton/pass/types'; type Props = { hostname: string; passwordOptions: GeneratePasswordOptions; visible?: boolean; onClose?: (options?: IFrameCloseOptions) => void; onMessage?: (message: IFrameMessage) => void; }; export const PasswordAutoSuggest: VFC<Props> = ({ hostname, passwordOptions, visible, onMessage, onClose }) => { const timer = useRef<Maybe<ReturnType<typeof setTimeout>>>(); const inputRef = useRef<HTMLInputElement>(null); const password = generatePassword(passwordOptions); const [copied, setCopied] = useState(false); useEffect(() => { if (copied) timer.current = setTimeout(() => onClose?.(), 1_500); return () => clearTimeout(timer.current); }, [copied]); useEffect(() => setCopied(false), [visible]); /* FIXME: move away from from `execCommand` and * prefer `navigator.clipboard` API */ const handleClick = async () => { inputRef.current?.select(); document.execCommand('copy'); setCopied(true); onMessage?.({ type: IFrameMessageType.DROPDOWN_AUTOFILL_GENERATED_PW, payload: { password }, }); }; return ( <> <DropdownHeader title={c('Title').t`Password`} extra={ <PauseListDropdown criteria="Autosuggest" dense hostname={hostname} label={c('Action').t`Do not suggest on this website`} onClose={onClose} visible={visible} /> } /> <DropdownItem subTheme={SubTheme.RED} {...(copied ? { icon: 'checkmark', subTitle: c('Info').t`Password copied`, onClick: () => onClose?.(), } : { icon: 'key', title: c('Title').t`Fill & copy password`, subTitle: <span className="text-monospace">{getCharsGroupedByColor(password)}</span>, onClick: handleClick, })} /> <input ref={inputRef} className="absolute" style={{ top: -9999, left: -9990 }} value={password} readOnly /> </> ); };
4,319
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/notification/Notification.scss
@import '~@proton/pass/styles/common'; body { background: transparent; } #root { block-size: 100%; } .item-icon { background-color: rgba(#6d4aff, 0.16); padding: em(4); block-size: em(24); inline-size: em(24); border-radius: var(--border-radius-md); }
4,320
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/notification/Notification.tsx
import { type VFC } from 'react'; import { Icons, NotificationsProvider } from '@proton/components'; import { ThemeProvider } from '@proton/pass/components/Layout/Theme/ThemeProvider'; import { IFrameContextProvider } from '../context/IFrameContextProvider'; import { NotificationContent } from './views/NotificationContent'; import './Notification.scss'; export const Notification: VFC = () => ( <IFrameContextProvider endpoint="notification"> <Icons /> <ThemeProvider /> <NotificationsProvider> <NotificationContent /> </NotificationsProvider> </IFrameContextProvider> );
4,321
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/notification/index.tsx
import ReactDOM from 'react-dom'; import { Notification } from './Notification'; const root = document.getElementById('root') as HTMLElement; ReactDOM.render(<Notification />, root);
4,322
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/notification
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/notification/components/AutofillOTP.tsx
import { type VFC, useEffect } from 'react'; import { PauseListDropdown } from 'proton-pass-extension/app/content/injections/apps/common/PauseListDropdown'; import type { IFrameCloseOptions, IFrameMessage } from 'proton-pass-extension/app/content/types'; import { IFrameMessageType } from 'proton-pass-extension/app/content/types'; import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import { usePassCore } from '@proton/pass/components/Core/PassCoreProvider'; import { OTPDonut } from '@proton/pass/components/Otp/OTPDonut'; import { OTPValue } from '@proton/pass/components/Otp/OTPValue'; import { usePeriodicOtpCode } from '@proton/pass/hooks/usePeriodicOtpCode'; import { contentScriptMessage, sendMessage } from '@proton/pass/lib/extension/message'; import { createTelemetryEvent } from '@proton/pass/lib/telemetry/event'; import { type SelectedItem, WorkerMessageType } from '@proton/pass/types'; import { TelemetryEventName } from '@proton/pass/types/data/telemetry'; import { NotificationHeader } from './NotificationHeader'; type Props = { hostname: string; item: SelectedItem; visible?: boolean; onMessage?: (message: IFrameMessage) => void; onClose?: (options?: IFrameCloseOptions) => void; }; export const AutofillOTP: VFC<Props> = ({ hostname, item, visible, onMessage, onClose }) => { const { generateOTP } = usePassCore(); const [otp, percent] = usePeriodicOtpCode({ generate: generateOTP, payload: { ...item, type: 'item' }, }); useEffect(() => { void sendMessage( contentScriptMessage({ type: WorkerMessageType.TELEMETRY_EVENT, payload: { event: createTelemetryEvent(TelemetryEventName.TwoFADisplay, {}, {}), }, }) ); }, []); return ( <div className="flex flex-column flex-nowrap flex-justify-space-between h-full"> <NotificationHeader title={c('Info').t`Verification code`} extra={ <PauseListDropdown criteria="Autofill2FA" hostname={hostname} label={c('Action').t`Do not show on this website`} onClose={onClose} visible={visible} /> } onClose={onClose} /> <div className="max-w-full"> <div className="flex flex-nowrap flex-align-items-center flex-justify-center mb-2 gap-4"> <div className="text-4xl max-w-4/5 text-ellipsis"> <span className="text-4xl"> <OTPValue code={otp?.token} /> </span> </div> <div className="h-custom w-custom" style={{ '--w-custom': '2rem', '--h-custom': '2rem' }}> <OTPDonut enabled={otp !== null} percent={percent} period={otp?.period} /> </div> </div> </div> <div className="flex flex-justify-space-between gap-3"> <Button pill color="norm" type="submit" className="flex-item-fluid-auto" onClick={() => { if (otp?.token) { onMessage?.({ type: IFrameMessageType.NOTIFICATION_AUTOFILL_OTP, payload: { code: otp.token }, }); onClose?.(); } }} > {c('Action').t`Copy & fill in`} </Button> </div> </div> ); };
4,323
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/notification
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/notification/components/Autosave.scss
input.item-name--input { border: 0; outline: none; padding: 0; }
4,324
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/notification
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/notification/components/Autosave.tsx
import { type VFC, useEffect, useState } from 'react'; import type { FormikErrors } from 'formik'; import { Field, Form, FormikProvider, useFormik } from 'formik'; import { PauseListDropdown } from 'proton-pass-extension/app/content/injections/apps/common/PauseListDropdown'; import type { IFrameCloseOptions } from 'proton-pass-extension/app/content/types'; import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import { useNotifications } from '@proton/components/hooks'; import { FieldsetCluster } from '@proton/pass/components/Form/Field/Layout/FieldsetCluster'; import { TextField } from '@proton/pass/components/Form/Field/TextField'; import { TitleField } from '@proton/pass/components/Form/Field/TitleField'; import { BaseItemIcon } from '@proton/pass/components/Layout/Icon/ItemIcon'; import { MAX_ITEM_NAME_LENGTH } from '@proton/pass/constants'; import { contentScriptMessage, sendMessage } from '@proton/pass/lib/extension/message'; import { createTelemetryEvent } from '@proton/pass/lib/telemetry/event'; import { validateItemName } from '@proton/pass/lib/validation/item'; import type { ProxiedSettings } from '@proton/pass/store/reducers/settings'; import type { Item } from '@proton/pass/types'; import { AutoSaveType, type FormEntryPrompt, WorkerMessageType } from '@proton/pass/types'; import { TelemetryEventName } from '@proton/pass/types/data/telemetry'; import { obfuscate } from '@proton/pass/utils/obfuscate/xor'; import { partialMerge } from '@proton/pass/utils/object/merge'; import { uniqueId } from '@proton/pass/utils/string/unique-id'; import { isValidURL } from '@proton/pass/utils/url/is-valid-url'; import noop from '@proton/utils/noop'; import { NotificationHeader } from './NotificationHeader'; import './Autosave.scss'; type Props = { settings: ProxiedSettings; submission: FormEntryPrompt; visible?: boolean; onClose?: (options?: IFrameCloseOptions) => void; }; type AutosaveFormValues = { name: string; username: string; password: string }; export const Autosave: VFC<Props> = ({ settings, submission, visible, onClose }) => { const { createNotification } = useNotifications(); const [busy, setBusy] = useState(false); const submissionURL = submission.subdomain ?? submission.domain; useEffect(() => { if (visible) { void sendMessage( contentScriptMessage({ type: WorkerMessageType.TELEMETRY_EVENT, payload: { event: createTelemetryEvent(TelemetryEventName.AutosaveDisplay, {}, {}), }, }) ); } }, [visible]); const form = useFormik<AutosaveFormValues>({ initialValues: { name: submission.autosave.data.action === AutoSaveType.UPDATE ? submission.autosave.data.item.data.metadata.name : submissionURL, username: submission.data.username, password: submission.data.password, }, validateOnChange: true, validate: (values) => { const errors: FormikErrors<AutosaveFormValues> = {}; const nameError = validateItemName(values.name); if (nameError) errors.name = nameError; return errors; }, onSubmit: async ({ name, username, password }) => { setBusy(true); const { valid, url } = isValidURL(submissionURL); const item: Item<'login'> = submission.autosave.data.action === AutoSaveType.UPDATE ? partialMerge(submission.autosave.data.item.data, { metadata: { name }, content: { username: obfuscate(username), password: obfuscate(password), urls: Array.from( new Set(submission.autosave.data.item.data.content.urls.concat(valid ? [url] : [])) ), }, }) : { type: 'login', metadata: { name, // translator: full sentence is: Autosaved on account.proton.me note: obfuscate(c('Info').t`Autosaved on ${submissionURL}`), itemUuid: uniqueId(), }, content: { username: obfuscate(username), password: obfuscate(password), urls: valid ? [url] : [], totpUri: obfuscate(''), }, extraFields: [], }; try { const result = await sendMessage( contentScriptMessage({ type: WorkerMessageType.AUTOSAVE_REQUEST, payload: { submission, item }, }) ); if (result.type === 'success') { sendMessage( contentScriptMessage({ type: WorkerMessageType.TELEMETRY_EVENT, payload: { event: createTelemetryEvent(TelemetryEventName.AutosaveDone, {}, {}), }, }) ).catch(noop); return onClose?.({ discard: true }); } return createNotification({ text: c('Warning').t`Unable to save`, type: 'error' }); } catch (_) { } finally { setBusy(false); } }, }); return ( <FormikProvider value={form}> <Form className="ui-violet flex flex-column flex-nowrap flex-justify-space-between h-full"> <NotificationHeader title={(() => { switch (submission.autosave.data.action) { case AutoSaveType.NEW: return c('Info').t`Save login`; case AutoSaveType.UPDATE: return c('Info').t`Update login`; } })()} extra={ <PauseListDropdown criteria="Autosave" hostname={submission.subdomain ?? submission.domain} label={c('Action').t`Disable autosave on this website`} onClose={onClose} visible={visible} /> } onClose={onClose} /> <div> <div className="flex flex-nowrap flex-align-items-center mb-2"> <BaseItemIcon url={submission.domain} icon={'user'} size={20} alt="" className="flex-item-noshrink" loadImage={settings.loadDomainImages} /> <div className="flex-item-fluid-auto"> <Field lengthLimiters name="name" component={TitleField} spellCheck={false} autoComplete={'off'} placeholder={c('Placeholder').t`Untitled`} maxLength={MAX_ITEM_NAME_LENGTH} className="pr-0" dense /> </div> </div> <FieldsetCluster> <Field name="username" component={TextField} label={c('Label').t`Username`} /> <Field hidden name="password" component={TextField} label={c('Label').t`Password`} /> </FieldsetCluster> </div> <div className="flex flex-justify-space-between gap-3"> <Button pill color="norm" shape="outline" onClick={() => onClose?.({ discard: true })}>{c('Action') .t`Not now`}</Button> <Button pill color="norm" type="submit" loading={busy} disabled={busy} className="flex-item-fluid-auto" > {(() => { switch (submission.autosave.data.action) { case AutoSaveType.NEW: return busy ? c('Action').t`Saving` : c('Action').t`Add`; case AutoSaveType.UPDATE: return busy ? c('Action').t`Updating` : c('Action').t`Update`; } })()} </Button> </div> </Form> </FormikProvider> ); };
4,325
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/notification
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/notification/components/NotificationHeader.tsx
import type { ReactElement, VFC } from 'react'; import type { IFrameCloseOptions } from 'proton-pass-extension/app/content/types'; import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import { Icon } from '@proton/components/components'; import { PassIcon } from '@proton/pass/components/Layout/Icon/PassIcon'; import { PassIconStatus } from '@proton/pass/types/data/pass-icon'; type Props = { extra?: ReactElement; title: string; onClose?: (options?: IFrameCloseOptions) => void }; export const NotificationHeader: VFC<Props> = ({ extra, title, onClose }) => { return ( <div className="flex flex-nowrap flex-item-noshrink flex-align-items-center flex-justify-space-between gap-2"> <h3 className="flex text-bold text-lg flex-align-items-center gap-2"> <PassIcon status={PassIconStatus.ACTIVE} size={22} /> <span className="flex-item-fluid text-ellipsis">{title}</span> </h3> <div className="flex flex-item-noshrink gap-1"> {extra} <Button key="close-button" icon pill shape="solid" color="weak" size="small" className="flex-item-noshrink" onClick={() => onClose?.({ discard: true })} title={c('Action').t`Cancel`} > <Icon name="cross" alt={c('Action').t`Cancel`} size={16} /> </Button> </div> </div> ); };
4,326
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/notification
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/notification/components/NotificationSwitch.tsx
import type { ReactNode, VFC } from 'react'; import { CircleLoader } from '@proton/atoms/CircleLoader'; import type { ProxiedSettings } from '@proton/pass/store/reducers/settings'; import type { MaybeNull } from '@proton/pass/types'; import type { IFrameCloseOptions, IFrameMessage, NotificationActions } from '../../../../types'; import { NotificationAction } from '../../../../types'; import { AutofillOTP } from './AutofillOTP'; import { Autosave } from './Autosave'; type Props = { children?: ReactNode; settings: ProxiedSettings; state: MaybeNull<NotificationActions>; visible?: boolean; onMessage?: (message: IFrameMessage) => void; onClose?: (options?: IFrameCloseOptions) => void; }; export const NotificationSwitch: VFC<Props> = ({ children, visible, state, settings, onMessage, onClose }) => { return ( <div className="h-full p-4 bg-norm relative"> {children} {(() => { if (!state) return <CircleLoader className="absolute absolute-center m-auto" />; switch (state.action) { case NotificationAction.AUTOSAVE_PROMPT: { return ( <Autosave submission={state.submission} settings={settings} onClose={onClose} visible={visible} /> ); } case NotificationAction.AUTOFILL_OTP_PROMPT: { return ( <AutofillOTP item={state.item} onMessage={onMessage} onClose={onClose} hostname={state.hostname} /> ); } } })()} </div> ); };
4,327
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/notification
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/apps/notification/views/NotificationContent.tsx
import { type VFC, useCallback, useState } from 'react'; import { NotificationsChildren } from '@proton/components/containers'; import type { MaybeNull } from '@proton/pass/types'; import type { NotificationActions } from '../../../../types'; import { type IFrameMessage, IFrameMessageType } from '../../../../types'; import { useIFrameContext, useRegisterMessageHandler } from '../../context/IFrameContextProvider'; import { NotificationSwitch } from '../components/NotificationSwitch'; export const NotificationContent: VFC = () => { const { closeIFrame, postMessage, settings, visible, locale } = useIFrameContext(); const [notificationState, setNotificationState] = useState<MaybeNull<NotificationActions>>(null); const handleAction = useCallback( ({ payload }: IFrameMessage<IFrameMessageType.NOTIFICATION_ACTION>) => setNotificationState(payload), [] ); useRegisterMessageHandler(IFrameMessageType.NOTIFICATION_ACTION, handleAction); return ( <NotificationSwitch key={locale} state={notificationState} visible={visible} settings={settings} onMessage={postMessage} onClose={(options) => { setNotificationState(null); closeIFrame(options); }} > <NotificationsChildren /> </NotificationSwitch> ); };
4,328
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/custom-elements/ProtonPassControl.scss
$base-font-size: 14 !default; @use 'sass:meta'; @import '@proton/styles/scss/lib/em'; @import '../styles/reset'; button { @include reset; pointer-events: all; margin: auto; inset-block-start: 0; inset-inline-end: em(5); opacity: 0.9; max-inline-size: 0; animation: icon-fade-in 0.25s ease-in-out 0.05s both !important; transition: opacity 0.2s ease-in-out; margin-block-start: 0 !important; cursor: pointer !important; position: absolute !important; background-size: cover !important; border-radius: unset !important; &:hover, &:focus, &:active { transform: none !important; } &::before { content: none !important; } &::after { content: var(--control-count) !important; position: absolute !important; inset: 0 !important; margin: auto !important; inline-size: 100% !important; color: white !important; text-align: center !important; font-family: system-ui, sans-serif !important; line-height: var(--control-lineheight) !important; font-size: var(--control-fontsize) !important; display: block !important; font-weight: bold !important; text-shadow: 0 0.5px 3px #320dc5 !important; } &:hover { opacity: 1; } } @keyframes icon-fade-in { from { opacity: 0; max-inline-size: 0; } to { opacity: 0.9; max-inline-size: em(35); } }
4,329
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/custom-elements/ProtonPassControl.ts
import { StyledShadowHost } from './StyledShadowHost'; export class ProtonPassControl extends StyledShadowHost { constructor() { super('styles/styles.control.css'); } }
4,330
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/custom-elements/ProtonPassRoot.scss
iframe { position: absolute; inline-size: var(--frame-width) !important; block-size: var(--frame-height) !important; inset-block-start: var(--frame-top) !important; inset-inline-start: var(--frame-left) !important; inset-inline-end: var(--frame-right) !important; z-index: var(--frame-zindex) !important; background: #191927 !important; // FIXME: support themes box-shadow: 0 2px 10px rgb(0 0 0 / 0.3) !important; // FIXME: support themes border-radius: 12px !important; border: none !important; display: none; margin: 0 !important; &.visible { display: block; transition: block-size 0.15s ease-in-out 0.05s; animation: var(--frame-animation) 0.25s ease-in-out 0.05s both !important; } &.fixed { position: fixed !important; z-index: 9999 !important; } } @keyframes fadein { from { opacity: 0; max-block-size: 0; } to { opacity: 1; max-block-size: 180px; } } @keyframes slidein { from { transform: translateX(380px); } to { transform: translateX(0); } }
4,331
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/custom-elements/ProtonPassRoot.ts
import { StyledShadowHost } from './StyledShadowHost'; export class ProtonPassRoot extends StyledShadowHost { constructor() { super('styles/styles.root.css'); } }
4,332
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/custom-elements/StyledShadowHost.ts
export class StyledShadowHost extends HTMLElement { static publicPath: string; constructor(href: string) { super(); const shadowRoot = this.attachShadow({ mode: 'open' }); const styleElement = document.createElement('link'); const readyEvent = new Event('ready', { bubbles: true, composed: true }); styleElement.setAttribute('rel', 'stylesheet'); styleElement.setAttribute('href', `${StyledShadowHost.publicPath}${href}`); styleElement.addEventListener('load', () => this.dispatchEvent(readyEvent), { once: true }); shadowRoot.appendChild(styleElement); } }
4,333
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/icon/index.ts
import type { MaybeNull } from '@proton/pass/types'; import { type BoundComputeStyles, createStyleCompute, getComputedHeight, pixelEncoder, pixelParser, } from '@proton/pass/utils/dom/computed-styles'; import { createElement } from '@proton/pass/utils/dom/create-element'; import { repaint } from '@proton/pass/utils/dom/repaint'; import { ICON_MAX_HEIGHT, ICON_MIN_HEIGHT, ICON_PADDING, INPUT_BASE_STYLES_ATTR } from '../../constants.static'; import type { FieldHandle } from '../../types'; import type { ProtonPassControl } from '../custom-elements/ProtonPassControl'; type InjectionElements = { form: HTMLElement; input: HTMLInputElement; inputBox: HTMLElement; icon: HTMLButtonElement; control: ProtonPassControl; }; type SharedInjectionOptions = { inputBox: HTMLElement; getInputStyle: BoundComputeStyles; getBoxStyle: BoundComputeStyles; }; /* input styles we may override */ type InputInitialStyles = { ['padding-right']?: string }; const getOverlayedElement = (options: { x: number; y: number; inputBox: HTMLElement; form: HTMLElement; }): MaybeNull<HTMLElement> => { try { const { x, y, form, inputBox } = options; const maxWidth = inputBox.offsetWidth; if (Number.isNaN(x) || Number.isNaN(y)) return null; const overlays = Array.from(document.elementsFromPoint(x, y)); return ( overlays.find((el): el is HTMLElement => { /* exclude non-html elements */ if (!(el instanceof HTMLElement)) return false; /* exclude svg elements */ if (el.matches('svg *')) return false; /* exclude our own injected elements */ if (el.matches('protonpass-control')) return false; /* exclude elements not in the current form stack */ if (!form.contains(el)) return false; /* exclude "placeholder" overlays */ if (el.innerText.length > 0 && el.offsetWidth >= maxWidth * 0.85) return false; return true; }) ?? null ); } catch (e) { return null; } }; /* Force re-render/re-paint of the input element * before computing the icon injection styles in * order to avoid certain browser rendering optimisations * which cause incorrect DOMRect / styles to be resolved. * ie: check amazon sign-in page without repaint to * reproduce issue */ const computeIconInjectionStyles = ( { input, control, form }: Omit<InjectionElements, 'icon'>, { getInputStyle, getBoxStyle, inputBox }: SharedInjectionOptions ) => { repaint(input); const { right: inputRight, top: inputTop, height: inputHeight } = input.getBoundingClientRect(); const { top: boxTop, height: boxMaxHeight } = inputBox.getBoundingClientRect(); const { top: controlTop, right: controlRight } = control.getBoundingClientRect(); /* If inputBox is not the input element in the case we * resolved a bounding element : compute inner height * without offsets in order to correctly position icon * if bounding element has some padding-top/border-top */ const boxed = inputBox !== input; const { value: boxHeight, offset: boxOffset } = getComputedHeight(getBoxStyle, { node: inputBox, mode: boxed ? 'inner' : 'outer', }); const size = Math.max(Math.min(boxMaxHeight - ICON_PADDING, ICON_MAX_HEIGHT), ICON_MIN_HEIGHT); const pl = getInputStyle('padding-left', pixelParser); const pr = getInputStyle('padding-right', pixelParser); const iconPaddingLeft = size / 5; /* dynamic "responsive" padding */ const iconPaddingRight = Math.max(Math.min(pl, pr) / 1.5, iconPaddingLeft); /* look for any overlayed elements if we were to inject * the icon on the right hand-side of the input element * accounting for icon size and padding */ const overlayEl = getOverlayedElement({ x: inputRight - (iconPaddingRight + size / 2), y: inputTop + inputHeight / 2, inputBox, form, }); const overlayWidth = (() => { if (!overlayEl) return 0; const { clientWidth, offsetWidth } = overlayEl; if (clientWidth === 0) return offsetWidth; /* support :before pseudo elements */ return clientWidth; })(); const overlayDx = overlayEl !== input && overlayWidth !== 0 ? overlayWidth + iconPaddingLeft : 0; /* Compute the new input padding : * Take into account the input element's current padding as it * may already cover the necessary space to inject the icon without * the need to mutate the input's padding style. Account for potential * overlayed element offset */ const newPaddingRight = Math.max(pr, size + iconPaddingLeft + iconPaddingRight + overlayDx); /* `mt` represents the vertical offset needed to align the * center of the injected icon with the top-most part of * the bounding box : * mt = boxTop - boxOffset.top - controlTop - size / 2 * top = mt + boxHeight / 2 */ const top = boxTop - controlTop + boxOffset.top + (boxHeight - size) / 2; const right = controlRight - inputRight + iconPaddingRight + overlayDx; return { input: { paddingRight: pixelEncoder(newPaddingRight), }, icon: { top: pixelEncoder(top), right: pixelEncoder(right), size: pixelEncoder(size), fontSize: size / 2.5, }, }; }; export const getInputInitialStyles = (el: HTMLElement): InputInitialStyles => { const initialStyles = el.getAttribute(INPUT_BASE_STYLES_ATTR); return initialStyles ? JSON.parse(initialStyles) : {}; }; export const cleanupInputInjectedStyles = (input: HTMLInputElement) => { Object.entries(getInputInitialStyles(input)).forEach( ([prop, value]) => Boolean(value) ? input.style.setProperty(prop, value) /* if has initial style -> reset */ : input.style.removeProperty(prop) /* else remove override */ ); input.removeAttribute(INPUT_BASE_STYLES_ATTR); }; export const cleanupInjectionStyles = ({ control, input }: Pick<InjectionElements, 'control' | 'input'>) => { control.style.removeProperty('float'); control.style.removeProperty('max-width'); control.style.removeProperty('margin-left'); cleanupInputInjectedStyles(input); }; const applyIconInjectionStyles = (elements: InjectionElements, shared: SharedInjectionOptions) => { const { icon, input } = elements; const styles = computeIconInjectionStyles(elements, shared); /* Handle a specific scenario where input has transitions or * animations set, which could affect width change detection * and repositioning triggers. To avoid unwanted side-effects * when applying the injection style, temporarily disable these * properties */ const { transition, animation } = input.style; input.style.setProperty('transition', 'none'); input.style.setProperty('animation', 'none'); /* Get the width of the input element before applying the injection styles */ const widthBefore = input.getBoundingClientRect().width; icon.style.top = styles.icon.top; icon.style.right = styles.icon.right; icon.style.width = styles.icon.size; icon.style.height = styles.icon.size; icon.style.setProperty(`--control-lineheight`, styles.icon.size); icon.style.setProperty(`--control-fontsize`, pixelEncoder(styles.icon.fontSize)); /* Store the original input styles to handle potential clean-up * on extension updates or code hot-reload. */ input.setAttribute(INPUT_BASE_STYLES_ATTR, JSON.stringify({ 'padding-right': input.style.paddingRight })); input.style.setProperty('padding-right', styles.input.paddingRight, 'important'); const widthAfter = input.getBoundingClientRect().width; /* If the input width has increased due to padding, remove the override * and set it back to its original value (This can hapen on `content-box * box-sized elements or certain flexbox edge-cases ) */ if (widthAfter !== widthBefore) { input.style.removeProperty('padding-right'); input.style.setProperty('padding-right', input.style.paddingRight); } /* Restore transition and animation properties in the next rendering frame * to ensure they work as expected. */ requestAnimationFrame(() => { input.style.setProperty('transition', transition); input.style.setProperty('animation', animation); }); }; /* The injection styles application is a two pass process : * - First correctly position the control element by computing * its possible margin left offset + max width * - Use the re-renderer control element for positioning the icon * + Pre-compute shared styles and DOMRects between two passes */ export const applyInjectionStyles = (elements: InjectionElements) => { const { input, inputBox } = elements; cleanupInputInjectedStyles(input); const sharedOptions = { inputBox, getInputStyle: createStyleCompute(input), getBoxStyle: createStyleCompute(inputBox), }; applyIconInjectionStyles(elements, sharedOptions); }; export const createIcon = (field: FieldHandle): InjectionElements => { const input = field.element as HTMLInputElement; const inputBox = field.boxElement; const control = createElement<ProtonPassControl>({ type: 'protonpass-control' }); control.style.display = 'none'; control.addEventListener('ready', () => control.style.removeProperty('display'), { once: true }); const icon = createElement<HTMLButtonElement>({ type: 'button', classNames: [] }); icon.tabIndex = -1; icon.style.zIndex = field.zIndex.toString(); icon.setAttribute('type', 'button'); const elements = { icon, control, input, inputBox, form: field.getFormHandle().element }; const boxed = input !== inputBox; if (boxed) inputBox.insertBefore(control, inputBox.firstElementChild); else input.parentElement!.insertBefore(control, input); control.shadowRoot?.appendChild(icon); return elements; };
4,334
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/iframe/create-iframe-app.ts
import type { Runtime } from 'webextension-polyfill'; import { contentScriptMessage, portForwardingMessage, sendMessage } from '@proton/pass/lib/extension/message'; import type { Maybe, MaybeNull } from '@proton/pass/types'; import { WorkerMessageType } from '@proton/pass/types'; import type { Dimensions, Rect } from '@proton/pass/types/utils/dom'; import { pixelEncoder } from '@proton/pass/utils/dom/computed-styles'; import { createElement } from '@proton/pass/utils/dom/create-element'; import { safeCall } from '@proton/pass/utils/fp/safe-call'; import { waitUntil } from '@proton/pass/utils/fp/wait-until'; import { createListenerStore } from '@proton/pass/utils/listener/factory'; import { merge } from '@proton/pass/utils/object/merge'; import type { IFrameApp, IFrameCloseOptions, IFrameEndpoint, IFrameInitPayload, IFrameMessageWithSender, IFramePortMessageHandler, IFramePosition, IFrameSecureMessage, IFrameState, } from '../../types/iframe'; import { type IFrameMessage, IFrameMessageType } from '../../types/iframe'; import { createIframeRoot } from './create-iframe-root'; type CreateIFrameAppOptions<A> = { id: IFrameEndpoint; src: string; animation: 'slidein' | 'fadein'; classNames?: string[]; backdropClose: boolean; backdropExclude?: () => HTMLElement[]; onReady?: () => void; onOpen?: (state: IFrameState<A>) => void; onClose?: (state: IFrameState<A>, options: IFrameCloseOptions) => void; position: (iframeRoot: HTMLElement) => Partial<Rect>; dimensions: (state: IFrameState<A>) => Dimensions; }; export const createIFrameApp = <A>({ id, src, animation, classNames = [], backdropClose, backdropExclude, onOpen, onClose, position, dimensions, }: CreateIFrameAppOptions<A>): IFrameApp<A> => { const iframeRoot = createIframeRoot(); const portMessageHandlers: Map<IFrameMessageType, IFramePortMessageHandler> = new Map(); const state: IFrameState<A> = { visible: false, ready: false, loaded: false, port: null, framePort: null, position: { top: -1, left: -1, right: -1, bottom: -1, zIndex: -1 }, action: null, }; const listeners = createListenerStore(); const iframe = createElement<HTMLIFrameElement>({ type: 'iframe', classNames, attributes: { src }, parent: iframeRoot, shadow: true, }); iframe.style.setProperty(`--frame-animation`, animation); iframe.addEventListener('load', () => (state.loaded = true), { once: true }); /* Securing the posted message's allowed target origins. * Ensure the iframe has been correctly loaded before sending * out any message: the iframe.contentWindow::origin may be * incorrect otherwise */ const sendSecurePostMessage = async (message: IFrameMessage) => { await sendMessage.onSuccess( contentScriptMessage({ type: WorkerMessageType.RESOLVE_EXTENSION_KEY }), async ({ key }) => waitUntil(() => state.loaded, 100).then(() => { const secureMessage: IFrameSecureMessage = { ...message, key, sender: 'contentscript' }; iframe.contentWindow?.postMessage(secureMessage, iframe.src); }) ); }; /* In order to communicate with the iframe, we're leveraging * the worker's MessageBroker port-forwarding capabilities. * This allows by-passing a FF limitation not letting us access * the Tabs API in an iframe-injected `web_accessible_resource` * to directly open a port with the current tab */ const sendPortMessage = (rawMessage: IFrameMessage) => { const message: IFrameMessageWithSender = { ...rawMessage, sender: 'contentscript' }; void waitUntil(() => state.ready, 100).then( () => state.port?.postMessage(portForwardingMessage(state.framePort!, message)) ); }; /* As we are now using a single port for the whole content-script, * make sure to filter messages not only by type but by sender id */ const registerMessageHandler = <M extends IFrameMessageType>( type: M, handler: (message: IFrameMessageWithSender<M>) => void ) => { const safeHandler = (message: Maybe<IFrameMessageWithSender>) => message?.type === type && message.sender === id && handler(message as IFrameMessageWithSender<M>); portMessageHandlers.set(type, safeHandler); return () => portMessageHandlers.delete(type); }; const getPosition = (): IFramePosition => state.position; const setIframePosition = (values: IFramePosition) => { state.position = values; const { top, left, right, zIndex } = values; iframe.style.setProperty(`--frame-zindex`, `${zIndex ?? 1}`); iframe.style.setProperty(`--frame-top`, top ? pixelEncoder(top) : 'unset'); iframe.style.setProperty(`--frame-left`, left ? pixelEncoder(left) : 'unset'); iframe.style.setProperty(`--frame-right`, right ? pixelEncoder(right) : 'unset'); }; const setIframeDimensions = ({ width, height }: Dimensions) => { iframe.style.setProperty(`--frame-width`, pixelEncoder(width)); iframe.style.setProperty(`--frame-height`, pixelEncoder(height)); }; const updatePosition = () => requestAnimationFrame(() => setIframePosition(position(iframeRoot))); const close = (options: IFrameCloseOptions = {}) => { if (state.visible) { const target = (options?.event?.target ?? null) as MaybeNull<HTMLElement>; if (!target || !backdropExclude?.().includes(target)) { listeners.removeAll(); onClose?.(state, options); /* ⚠️ call before resetting state */ iframe.classList.remove('visible'); state.visible = false; state.action = null; sendPortMessage({ type: IFrameMessageType.IFRAME_HIDDEN }); } } }; const open = (action: A, scrollRef?: HTMLElement) => { if (!state.visible) { state.action = action; state.visible = true; listeners.addListener(window, 'resize', updatePosition); listeners.addListener(scrollRef, 'scroll', updatePosition); if (backdropClose) { listeners.addListener(window, 'mousedown', (event) => close({ event, discard: true, refocus: false })); } sendPortMessage({ type: IFrameMessageType.IFRAME_OPEN }); iframe.classList.add('visible'); setIframeDimensions(dimensions(state)); updatePosition(); onOpen?.(state); } }; const onMessageHandler = (message: Maybe<IFrameMessageWithSender>) => message && message?.type !== undefined && portMessageHandlers.get(message.type)?.(message); const setPort = (port: Runtime.Port) => { state.port = port; state.port.onMessage.addListener(onMessageHandler); state.port.onDisconnect.addListener(() => (state.ready = false)); void sendSecurePostMessage({ type: IFrameMessageType.IFRAME_INJECT_PORT, payload: { port: port.name }, }); }; const init = (payload: IFrameInitPayload) => sendPortMessage({ type: IFrameMessageType.IFRAME_INIT, payload }); const destroy = () => { close({ discard: false, refocus: false }); listeners.removeAll(); state.port?.onMessage.removeListener(onMessageHandler); safeCall(() => iframeRoot.removeChild(iframe))(); state.port = null; }; registerMessageHandler(IFrameMessageType.IFRAME_CONNECTED, ({ payload: { framePort } }) => { state.ready = true; state.framePort = framePort; }); registerMessageHandler(IFrameMessageType.IFRAME_CLOSE, (message) => close(message.payload)); registerMessageHandler(IFrameMessageType.IFRAME_DIMENSIONS, (message) => { const { width, height } = merge(dimensions(state), { height: message.payload.height }); return setIframeDimensions({ width, height }); }); return { element: iframe, state, close, destroy, getPosition, init, open, registerMessageHandler, sendPortMessage, setPort, updatePosition, }; };
4,335
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/iframe/create-iframe-root.ts
import { createElement } from '@proton/pass/utils/dom/create-element'; import type { ProtonPassRoot } from '../custom-elements/ProtonPassRoot'; export const getIFrameRoot = () => document.querySelector<ProtonPassRoot>('protonpass-root'); export const isIFrameRootAttached = () => getIFrameRoot() !== null; export const createIframeRoot = (): ProtonPassRoot => { const root = getIFrameRoot(); if (root !== null) return root; const iframeRoot = createElement<ProtonPassRoot>({ type: 'protonpass-root', parent: document.body, }); iframeRoot.style.display = 'none'; iframeRoot.addEventListener('ready', () => iframeRoot.style.removeProperty('display'), { once: true }); return iframeRoot; };
4,336
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/styles/injection.scss
/* stylelint-disable selector-type-no-unknown */ @import './reset'; protonpass-root { @include reset; position: absolute !important; inline-size: 100% !important; border: 0 !important; z-index: unset !important; inset: unset !important; inset-block-start: 0 !important; inset-inline-start: 0 !important; block-size: 0 !important; } protonpass-control { @include reset; pointer-events: none; position: absolute !important; /* force reset element */ margin: 0 !important; opacity: 1; z-index: unset !important; order: 0 !important; block-size: 0 !important; inline-size: 0 !important; /* stylelint-disable-next-line */ float: left !important; animation: none !important; /* if parent display: flex */ flex: 0 0 0; /* if parent display: grid */ grid-row: auto / span 1 !important; grid-column: auto / span 1 !important; > input { pointer-events: all; } }
4,337
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/injections/styles/reset.scss
@mixin reset { margin-inline-start: unset; padding: 0 !important; outline: none !important; outline-color: none !important; background-color: transparent !important; border: none !important; box-shadow: none !important; min-inline-size: unset !important; min-block-size: unset !important; overflow: unset !important; }
4,338
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/services/index.ts
/* This file defines the core client code for the browser extension's content script. * The client sets up the context, manages the state and provides functions to start and destroy * the content script service. It listens to messages from the background script, * and registers or unregisters the content script service based on state changes / errors. * * Sequences: * - Normal start: client is registered with the background script and starts normally. * - Unregister request: background requests to unregister -> client destroys itself. * - Successful recovery: extension context change with successful recovery (i.e., port disconnected). * - Failed recovery: extension context change with failed recovery -> destroy. * - Error during setup: client encounters an error during setup -> destroy. */ import { CSContext } from 'proton-pass-extension/app/content/context/context'; import { createContentScriptContext } from 'proton-pass-extension/app/content/context/factory'; import { DOMCleanUp } from 'proton-pass-extension/app/content/injections/cleanup'; import type { ExtensionContextType } from 'proton-pass-extension/lib/context/extension-context'; import { ExtensionContext, setupExtensionContext } from 'proton-pass-extension/lib/context/extension-context'; import { clientReady } from '@proton/pass/lib/client'; import { contentScriptMessage, sendMessage } from '@proton/pass/lib/extension/message'; import type { FeatureFlagState } from '@proton/pass/store/reducers'; import type { ProxiedSettings } from '@proton/pass/store/reducers/settings'; import { type AppState, WorkerMessageType, type WorkerMessageWithSender } from '@proton/pass/types'; import { createListenerStore } from '@proton/pass/utils/listener/factory'; import { logger } from '@proton/pass/utils/logger'; import noop from '@proton/utils/noop'; import 'proton-pass-extension/app/content/injections/styles/injection.scss'; export const createContentScriptClient = (scriptId: string, mainFrame: boolean) => { const listeners = createListenerStore(); const context = createContentScriptContext({ scriptId, mainFrame, destroy: (options) => { if (context.getState().active) { logger.info(`[ContentScript::${scriptId}] destroying.. [reason: "${options.reason}"]`); listeners.removeAll(); context.setState({ active: false }); context.service.formManager.destroy(); context.service.iframe.destroy(); CSContext.clear(); DOMCleanUp(); ExtensionContext.read()?.destroy(); } }, }); const reconciliate = async () => { const { status, loggedIn } = context.getState(); context.service.formManager.sync(); if (!loggedIn) context.service.autofill.reset(); else if (clientReady(status)) await context.service.autofill.reconciliate(); }; const onFeatureFlagsChange = (features: FeatureFlagState) => context.setFeatureFlags(features); const onSettingsChange = (settings: ProxiedSettings) => { context.setSettings(settings); if (context.getState().active) void reconciliate(); }; const onWorkerStateChange = (workerState: AppState) => { context.setState(workerState); if (context.getState().active) void reconciliate(); }; const onPortMessage = async (message: WorkerMessageWithSender): Promise<void> => { if (message.sender === 'background') { switch (message.type) { case WorkerMessageType.AUTOFILL_SYNC: return context.service.autofill.sync(message.payload); case WorkerMessageType.FEATURE_FLAGS_UPDATE: return onFeatureFlagsChange(message.payload); case WorkerMessageType.SETTINGS_UPDATE: return onSettingsChange(message.payload); case WorkerMessageType.WORKER_STATUS: return onWorkerStateChange(message.payload.state); case WorkerMessageType.UNLOAD_CONTENT_SCRIPT: return context.destroy({ reason: 'unload script' }); } } }; const handleStart = async ({ tabId, port }: ExtensionContextType) => { const res = await sendMessage( contentScriptMessage({ type: WorkerMessageType.WORKER_WAKEUP, payload: { endpoint: 'contentscript', tabId }, }) ); if (res.type === 'success' && context.getState().active) { logger.debug(`[ContentScript::${scriptId}] Worker status resolved "${res.status}"`); context.setState({ loggedIn: res.loggedIn, status: res.status, UID: res.UID }); context.setSettings(res.settings); context.setFeatureFlags(res.features); context.service.iframe.reset(); await reconciliate(); /* if the user has disabled every injection setting or added the current * domain to the pause list we can safely destroy the content-script context */ const enable = Object.values(context.getFeatures()).reduce((pass, feat) => pass || feat); if (!enable) return context.destroy({ reason: 'injection settings' }); /* if we're in an iframe and the initial detection should not * be triggered : destroy this content-script service */ if (!mainFrame) return context.destroy({ reason: 'subframe discarded' }); port.onMessage.addListener(onPortMessage); context.service.formManager.observe(); const didDetect = await context.service.formManager .detect({ reason: 'InitialLoad', flush: true }) .catch(() => false); if (!didDetect) await context.service.autosave.reconciliate().catch(noop); } }; const start = async () => { try { const extensionContext = await setupExtensionContext({ endpoint: 'contentscript', onDisconnect: () => { const recycle = context.getState().active; if (!recycle) context.destroy({ reason: 'port disconnected' }); return { recycle }; }, onRecycle: handleStart, }); logger.debug(`[ContentScript::${scriptId}] Starting content-script service`); return await handleStart(extensionContext); } catch (e) { logger.debug(`[ContentScript::${scriptId}] Setup error`, e); context.destroy({ reason: 'setup error' }); } }; return { start, destroy: context.destroy }; }; export type ContentScriptClientService = ReturnType<typeof createContentScriptClient>;
4,339
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/services
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/services/form/autofill.ts
import { withContext } from 'proton-pass-extension/app/content/context/context'; import { FieldType, FormType } from '@proton/pass/fathom'; import { contentScriptMessage, sendMessage } from '@proton/pass/lib/extension/message'; import { createTelemetryEvent } from '@proton/pass/lib/telemetry/event'; import { passwordSave } from '@proton/pass/store/actions/creators/pw-history'; import type { MaybeNull, WorkerMessageResponse } from '@proton/pass/types'; import { WorkerMessageType } from '@proton/pass/types'; import { TelemetryEventName } from '@proton/pass/types/data/telemetry'; import type { AutofillResult } from '@proton/pass/types/worker/autofill'; import { first } from '@proton/pass/utils/array/first'; import { asyncLock } from '@proton/pass/utils/fp/promises'; import { uniqueId } from '@proton/pass/utils/string/unique-id'; import { getEpoch } from '@proton/pass/utils/time/get-epoch'; import noop from '@proton/utils/noop'; import { DropdownAction, type FormHandle, NotificationAction } from '../../types'; type AutofillState = { cache: MaybeNull<AutofillResult> }; export const createAutofillService = () => { const state: AutofillState = { cache: null }; /* on autofill data change : update tracked login field counts & * trigger a dropdown sync in order to update the autofill data */ const onAutofillChange = withContext((ctx) => { const dropdown = ctx.service.iframe.dropdown; const trackedForms = ctx.service.formManager.getTrackedForms(); const loginForms = trackedForms.filter((form) => form.formType === FormType.LOGIN); const count = state.cache?.items.length ?? 0; loginForms.forEach((form) => form.getFields().forEach((field) => field.icon?.setCount(count))); if (dropdown) { const { visible, action } = dropdown.getState(); if (visible && action === DropdownAction.AUTOFILL) void dropdown.sync(); } }); const sync = (data: AutofillResult): void => { state.cache = data; onAutofillChange(); }; const reset = () => { state.cache = null; onAutofillChange(); }; const query = asyncLock( withContext<() => Promise<WorkerMessageResponse<WorkerMessageType.AUTOFILL_QUERY>>>(async ({ mainFrame }) => { if (state.cache) return state.cache; const result = await sendMessage.on( contentScriptMessage({ type: WorkerMessageType.AUTOFILL_QUERY, payload: { mainFrame }, }), (response) => response.type === 'success' ? { items: response.items, needsUpgrade: response.needsUpgrade } : { items: [], needsUpgrade: false } ); sync(result); return result; }) ); const autofillTelemetry = (type: '2fa' | 'login') => { const event = (() => { switch (type) { case 'login': return createTelemetryEvent(TelemetryEventName.AutofillTriggered, {}, { location: 'source' }); case '2fa': return createTelemetryEvent(TelemetryEventName.TwoFAAutofill, {}, {}); } })(); void sendMessage( contentScriptMessage({ type: WorkerMessageType.TELEMETRY_EVENT, payload: { event, }, }) ); }; const autofillLogin = (form: FormHandle, data: { username: string; password: string }) => { first(form.getFieldsFor(FieldType.USERNAME) ?? [])?.autofill(data.username); first(form.getFieldsFor(FieldType.EMAIL) ?? [])?.autofill(data.username); form.getFieldsFor(FieldType.PASSWORD_CURRENT).forEach((field) => field.autofill(data.password)); autofillTelemetry('login'); }; const autofillGeneratedPassword = withContext<(form: FormHandle, password: string) => void>( ({ getExtensionContext }, form, password) => { const { domain, subdomain, hostname } = getExtensionContext().url; form.getFieldsFor(FieldType.PASSWORD_NEW).forEach((field) => field.autofill(password)); void sendMessage( contentScriptMessage({ type: WorkerMessageType.STORE_ACTION, payload: { action: passwordSave({ id: uniqueId(), value: password, origin: subdomain ?? domain ?? hostname, createTime: getEpoch(), }), }, }) ); } ); /* if we have multiple OTP fields then we're dealing * with an OTP code field spread out into multiple text * inputs : in this case, prefer a "paste autofill" */ const autofillOTP = (form: FormHandle, code: string) => { const otps = form.getFieldsFor(FieldType.OTP); if (otps.length === 0) return; if (otps.length === 1) otps[0].autofill(code, { paste: false }); if (otps.length > 1) { /* for FF : sanity check in case the paste failed */ otps[0].autofill(code, { paste: true }); otps.forEach((otp, i) => { const token = code?.[i] ?? ''; if (!otp.element.value || otp.element.value !== token) otp.autofill(code?.[i] ?? ''); }); } autofillTelemetry('2fa'); }; /* The `AUTOFILL_OTP_CHECK` message handler will take care of parsing * the current tab's url & check for any tracked form submissions in order * to pick the correct login item from which to derive the OTP code */ const reconciliate = withContext<() => Promise<boolean>>(async ({ service, getFeatures, getExtensionContext }) => { query().catch(noop); const otpFieldDetected = service.formManager .getTrackedForms() .some((form) => form.formType === FormType.MFA && form.getFieldsFor(FieldType.OTP).length > 0); if (otpFieldDetected && getFeatures().Autofill2FA) { const { subdomain, domain } = getExtensionContext().url; return sendMessage.on(contentScriptMessage({ type: WorkerMessageType.AUTOFILL_OTP_CHECK }), (res) => { if (res.type === 'success' && res.shouldPrompt) { service.iframe.attachNotification(); service.iframe.notification?.open({ action: NotificationAction.AUTOFILL_OTP_PROMPT, item: { shareId: res.shareId, itemId: res.itemId }, hostname: subdomain ?? domain ?? '', }); return true; } return false; }); } return false; }); return { autofillLogin, autofillGeneratedPassword, autofillOTP, getState: () => state.cache, reconciliate, reset, sync, }; }; export type AutofillService = ReturnType<typeof createAutofillService>;
4,340
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/services
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/services/form/autosave.ts
import { withContext } from 'proton-pass-extension/app/content/context/context'; import { NotificationAction } from 'proton-pass-extension/app/content/types'; import { isFormEntryPromptable } from 'proton-pass-extension/lib/utils/form-entry'; import { contentScriptMessage, sendMessage } from '@proton/pass/lib/extension/message'; import type { FormEntryPrompt } from '@proton/pass/types'; import { FormEntryStatus, WorkerMessageType } from '@proton/pass/types'; export const createAutosaveService = () => { const promptAutoSave: (submission: FormEntryPrompt) => boolean = withContext( ({ getFeatures, service: { iframe } }, submission) => { if (getFeatures().Autosave) { iframe.attachNotification(); iframe.notification?.open({ action: NotificationAction.AUTOSAVE_PROMPT, submission, }); return true; } return false; } ); /* Reconciliation is responsible for syncing the service * worker state with our local detection in order to take * the appropriate action for auto-save */ const reconciliate = withContext<() => Promise<boolean>>( async ({ getExtensionContext, service: { formManager } }) => { const submission = await sendMessage.on( contentScriptMessage({ type: WorkerMessageType.FORM_ENTRY_REQUEST }), (response) => (response.type === 'success' ? response.submission : undefined) ); if (submission !== undefined) { const { status, partial, domain, type } = submission; const currentDomain = getExtensionContext().url.domain; const formTypeChangeOrRemoved = !formManager .getTrackedForms() .some(({ formType }) => formType === type); const domainmatch = currentDomain === domain; const canCommit = domainmatch && formTypeChangeOrRemoved; /* if we have a non-partial staging form submission at * this stage either commit it if no forms of the same * type are present in the DOM - or stash it if it's the * case : we may be dealing with a failed login */ if (status === FormEntryStatus.STAGING && !partial && canCommit) { return sendMessage.on( contentScriptMessage({ type: WorkerMessageType.FORM_ENTRY_COMMIT, payload: { reason: 'FORM_TYPE_REMOVED' }, }), (res) => (res.type === 'success' && res.committed ? promptAutoSave(res.committed) : false) ); } if (isFormEntryPromptable(submission) && formTypeChangeOrRemoved) return promptAutoSave(submission); /* if the form type is still detected on the current page : * only stash the form submission if it is not "partial". This * avois losing form data on multi-step forms */ if (!formTypeChangeOrRemoved && !partial) { void sendMessage( contentScriptMessage({ type: WorkerMessageType.FORM_ENTRY_STASH, payload: { reason: 'FORM_TYPE_PRESENT' }, }) ); } } return false; } ); return { reconciliate }; }; export type AutosaveService = ReturnType<typeof createAutosaveService>;
4,341
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/services
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/services/form/detector.ts
import { MAX_MAX_DETECTION_TIME, MIN_MAX_DETECTION_TIME } from 'proton-pass-extension/app/content/constants.static'; import type { DetectedField, DetectedForm } from 'proton-pass-extension/app/content/types'; import type { FieldType } from '@proton/pass/fathom'; import { FormType, clearDetectionCache, fieldTypes, formTypes, prepass, rulesetMaker, shouldRunClassifier, } from '@proton/pass/fathom'; import type { Fnode } from '@proton/pass/fathom/fathom'; import { logger } from '@proton/pass/utils/logger'; import { withMaxExecutionTime } from '@proton/pass/utils/time/performance'; import { wait } from '@proton/shared/lib/helpers/promise'; const ruleset = rulesetMaker(); const NOOP_EL = document.createElement('form'); type BoundRuleset = ReturnType<typeof ruleset.against>; type PredictionResult<T extends string> = { fnode: Fnode; type: T; score: number }; type PredictionBestSelector<T extends string> = (a: PredictionResult<T>, b: PredictionResult<T>) => PredictionResult<T>; /* We should run the detection when : * - a stale form is now considered of interest * - a tracked form has new visible input fields * - new dangling inputs can be clustered * * To keep track of these we leverage the `PROCESSED_INPUT_ATTR` * attribute which is added to processed fields. Run in async * `requestAnimationFrame` to avoid blocking the UI on costly * visibility checks * * When considering dangling fields, only look * for fields not in a processed form and that is actually visible * to avoid flagging input fields as processed and missing out * on detection */ const shouldRunDetection = (): Promise<boolean> => new Promise(async (resolve) => { await wait(50); requestIdleCallback(() => { prepass(); resolve(shouldRunClassifier()); }); }); const getPredictionsFor = <T extends string>( boundRuleset: BoundRuleset, options: { type: 'form' | 'field'; subTypes: T[]; selectBest: PredictionBestSelector<T>; } ): PredictionResult<T>[] => { /* The following `get` call is necessary to trigger the * `allThrough` effect which will flag the nodes */ boundRuleset.get(options.type); const predictions = options.subTypes.reduce<Map<Fnode, PredictionResult<T>>>((results, subType) => { const fnodes: Fnode[] = boundRuleset.get(subType); fnodes.forEach((fnode) => { const score = fnode.hasType('cache') ? 1 : fnode.scoreFor(subType); const candidate = { type: subType, fnode, score }; const bestSoFar = results.get(fnode); if (!bestSoFar) results.set(fnode, candidate); else results.set(fnode, options.selectBest(candidate, bestSoFar)); }); return results; }, new Map()); return Array.from(predictions.values()); }; /* cluster each predicted field by its parent predicted * form. If no such form exists, keep a reference to all * "dangling" fields in order to process them accordingly */ const groupFields = ( formPredictions: PredictionResult<FormType>[], fieldPredictions: PredictionResult<FieldType>[] ) => { const grouping = new WeakMap<HTMLElement, DetectedField[]>(); fieldPredictions.forEach(({ fnode: fieldFNode, type: fieldType }) => { const field = fieldFNode.element as HTMLInputElement; const parent: HTMLElement = formPredictions.find(({ fnode: formFNode }) => { const form = formFNode.element; return form.contains(field); })?.fnode.element ?? NOOP_EL; const entry = grouping?.get(parent) ?? []; entry.push({ fieldType, field }); return grouping.set(parent, entry); }); return grouping; }; const selectBest = <T extends string>(a: PredictionResult<T>, b: PredictionResult<T>): PredictionResult<T> => a.score > b.score ? a : b; /* if we have a tie with a login form : always prefer the login type * as it is less deceptive for the user. FIXME: on tie between login & * register, we should query the autofillable candidates and adapt the * form-type accordingly */ const selectBestForm = (a: PredictionResult<FormType>, b: PredictionResult<FormType>): PredictionResult<FormType> => { if (a.type !== FormType.LOGIN && b.type !== FormType.LOGIN) return selectBest(a, b); return a.type === FormType.LOGIN ? a : b; }; /* Runs the fathom detection and returns a form handle for each detected form.. */ const createDetectionRunner = (ruleset: ReturnType<typeof rulesetMaker>, doc: Document) => (options: { onBottleneck: (data: {}) => void }): DetectedForm[] => { const [formPredictions, fieldPredictions] = withMaxExecutionTime( (): [PredictionResult<FormType>[], PredictionResult<FieldType>[]] => { const boundRuleset = ruleset.against(doc.body); return [ getPredictionsFor<FormType>(boundRuleset, { type: 'form', subTypes: formTypes, selectBest: selectBestForm, }), getPredictionsFor(boundRuleset, { type: 'field', subTypes: fieldTypes, selectBest, }), ]; }, { maxTime: MIN_MAX_DETECTION_TIME, onMaxTime: (ms) => { const host = window.location.hostname; logger.info(`[Detector::run] detector slow down detected on ${host} (took ${ms}ms)`); if (ms >= MAX_MAX_DETECTION_TIME) { options.onBottleneck({ ms, host }); throw new Error(); } }, } )(); const fieldMap = groupFields(formPredictions, fieldPredictions); const forms = formPredictions.map(({ fnode: formFNode, type: formType }) => ({ form: formFNode.element as HTMLElement, formType, fields: fieldMap.get(formFNode.element) ?? [], })); /* Form / fields flagging : * each detected form should be flagged via the `data-protonpass-form` attribute so as to * avoid triggering unnecessary detections if nothing of interest has changed in the DOM. * · `formPredictions` will include only visible forms : flag them with prediction class * · all form fields which have been detected should be flagged as processed with the * `data-protonpass-field` attr. The remaining fields without classification results * should only be flagged as processed if they are visible or `[type="hidden"]`. This * heuristic flagging allows detection triggers to monitor new fields correctly. * · query all unprocessed forms (including invisible ones) and flag them as `NOOP` */ /* only start tracking forms which have a positive detection result or * dangling forms which have at least one detected field */ const formsToTrack = forms.filter(({ formType, fields }) => formType !== FormType.NOOP || fields.length > 0); clearDetectionCache(); /* clear visibility cache on each detection run */ return formsToTrack; }; export const createDetectorService = () => { return { shouldRunDetection, runDetection: createDetectionRunner(ruleset, document), }; }; export type DetectorService = ReturnType<typeof createDetectorService>;
4,342
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/services
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/services/form/manager.ts
import { withContext } from 'proton-pass-extension/app/content/context/context'; import { createFormHandles } from 'proton-pass-extension/app/content/services/handles/form'; import type { FormHandle } from 'proton-pass-extension/app/content/types'; import { hasUnprocessedFields, hasUnprocessedForms, isNodeOfInterest, } from 'proton-pass-extension/app/content/utils/nodes'; import { clearDetectionCache, getIgnoredParent, getParentFormPrediction, removeClassifierFlags, } from '@proton/pass/fathom'; import { contentScriptMessage, sendMessage } from '@proton/pass/lib/extension/message'; import { WorkerMessageType } from '@proton/pass/types'; import { createListenerStore } from '@proton/pass/utils/listener/factory'; import { logger } from '@proton/pass/utils/logger'; import debounce from '@proton/utils/debounce'; type FormManagerOptions = { onDetection: (forms: FormHandle[]) => void }; export type FormManagerContext = { /* form manager state flag */ active: boolean; /* ongoing detection flag */ busy: boolean; /* detection request */ detectionRequest: number; /* tracked forms have been detected */ trackedForms: Map<HTMLElement, FormHandle>; }; export const createFormManager = (options: FormManagerOptions) => { const ctx: FormManagerContext = { active: false, busy: false, detectionRequest: -1, trackedForms: new Map(), }; const listeners = createListenerStore(); const getTrackedForms = () => Array.from(ctx.trackedForms.values()); const detachTrackedForm = (formEl: HTMLElement) => { ctx.trackedForms.get(formEl)?.detach(); ctx.trackedForms.delete(formEl); }; /* Garbage collection is used to detach tracked forms * if they have been removed from the DOM - this may be the case * in SPA apps. Once a form is detected, it will be tracked until * removed : form visibility changes have no effect on detachment * for performance reasons (costly `isVisible` check) */ const garbagecollect = () => ctx.trackedForms.forEach((form) => form.shouldRemove() && detachTrackedForm(form.element)); /* Detection : * - runs in `requestAnimationFrame` to defer costly DOM operations * - if a stale form has been detected: unsubscribe * - on each detected form: recycle/create form handle and reconciliate its fields * Returns a boolean flag indicating wether or not the detection was ran */ const runDetection = debounce( withContext<(reason: string) => Promise<boolean>>(async ({ destroy, service }, reason: string) => { garbagecollect(); if (await service.detector.shouldRunDetection()) { ctx.detectionRequest = requestIdleCallback(async () => { ctx.busy = true; if (ctx.active) { logger.info(`[FormTracker::Detector] Running detection for "${reason}"`); try { const forms = service.detector.runDetection({ onBottleneck: (data) => { void sendMessage( contentScriptMessage({ type: WorkerMessageType.SENTRY_CS_EVENT, payload: { message: 'DetectorBottleneck', data }, }) ); destroy({ reason: 'detector bottleneck' }); }, }); forms.forEach((options) => { const formHandle = ctx.trackedForms.get(options.form) ?? createFormHandles(options); ctx.trackedForms.set(options.form, formHandle); formHandle.reconciliate(options.formType, options.fields); formHandle.attach(); }); const didPrompt = await service.autofill.reconciliate(); await (!didPrompt && service.autosave.reconciliate()); options.onDetection(getTrackedForms()); ctx.busy = false; } catch (err) { logger.warn(`[FormTracker::Detector] ${err}`); } } }); return true; } else clearDetectionCache(); ctx.busy = false; return false; }), 250 ); const detect = async (options: { reason: string; flush?: boolean }) => { if (ctx.busy || !ctx.active) return false; cancelIdleCallback(ctx.detectionRequest); if (options.flush) { void runDetection(options.reason); return Boolean(await runDetection.flush()); } return Boolean(await runDetection(options.reason)); }; /* if a new field was added to a currently ignored form : * reset all detection flags: the classification result * may change (ie: dynamic form recycling) */ const onNewField = (field?: HTMLElement) => { const ignored = getIgnoredParent(field); if (ignored) removeClassifierFlags(ignored); }; /* if a field was deleted from a currently detected form : * reset all detection flags: the classification result * may change (ie: dynamic form recycling) */ const onDeletedField = (field?: HTMLElement) => { const detected = getParentFormPrediction(field); if (detected) removeClassifierFlags(detected); }; /** * Form Detection Trigger via DOM Mutation : * * This mutation observer handler is set up to track changes on the DOM, * specifically looking for mutations related to form or field elements. * It employs a combination of heuristics to determine whether the observed * mutations contain changes that warrant running the detection algorithm. * * The observer is configured to listen for mutations in the subtree of * the document body, including changes to the 'style' and 'aria-hidden' * attributes (this handles the case for certain modals being pre-rendered * in the DOM not being currently tracked) * The callback analyzes the mutations and checks for the following : * · New input fields, forms, or elements with unprocessed fields * · Deleted input fields or forms being removed from the DOM * · Attribute changes in elements with unprocessed fields * * If any of the mutations indicate relevant changes, the detection algorithm * is triggered. Note: The heuristic checks may need further fine-tuning to * ensure all relevant mutations are captured.*/ const onMutation = (mutations: MutationRecord[]) => { const triggerFormChange = mutations.some((mutation) => { if (mutation.type === 'childList') { const deletedFields = Array.from(mutation.removedNodes).some(isNodeOfInterest); const addedFields = Array.from(mutation.addedNodes).some(isNodeOfInterest); if (addedFields) onNewField(mutation.target as HTMLElement); if (deletedFields) onDeletedField(mutation.target as HTMLElement); return addedFields || deletedFields; } if (mutation.type === 'attributes') { const target = mutation.target as HTMLElement; return mutation.type === 'attributes' && hasUnprocessedFields(target); } return false; }); if (triggerFormChange) void detect({ reason: 'DomMutation' }); }; /** * Form Detection Trigger via Transition Events * * We want to avoid swarming detection requests on every `transitionend` * event as we are listening for them on the `document.body` and will * catch all bubbling events. The function is debounced to ensure it runs * only when necessary, and only if there are unprocessed forms in the DOM. * · The detection is executed only if there are unprocessed forms * · The purpose is to catch appearing forms that may have been previously * filtered out by the ML algorithm when it was first triggered */ const onTransition = debounce( () => requestAnimationFrame(() => hasUnprocessedForms() && detect({ reason: 'TransitionEnd' })), 250, { leading: true } ); const observe = () => { if (!ctx.active) { ctx.active = true; listeners.addObserver(document.body, onMutation, { childList: true, subtree: true, attributeFilter: ['style', 'class'], attributes: true, }); listeners.addListener(document.body, 'transitionend', onTransition); listeners.addListener(document.body, 'animationend', onTransition); } }; const destroy = () => { ctx.active = false; ctx.busy = false; cancelIdleCallback(ctx.detectionRequest); runDetection.cancel(); listeners.removeAll(); ctx.trackedForms.forEach((form) => detachTrackedForm(form.element)); ctx.trackedForms.clear(); }; const sync = () => ctx.trackedForms.forEach((form) => form.tracker?.reconciliate()); return { getTrackedForms, observe, detect, sync, destroy }; }; export type FormManager = ReturnType<typeof createFormManager>;
4,343
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/services
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/services/form/tracker.ts
import { FORM_TRACKER_CONFIG } from 'proton-pass-extension/app/content/constants.runtime'; import { withContext } from 'proton-pass-extension/app/content/context/context'; import type { FieldHandle, FormHandle, FormTracker } from 'proton-pass-extension/app/content/types'; import { DropdownAction, FieldInjectionRule } from 'proton-pass-extension/app/content/types'; import { FieldType, FormType } from '@proton/pass/fathom'; import { contentScriptMessage, sendMessage } from '@proton/pass/lib/extension/message'; import { type MaybeNull, WorkerMessageType } from '@proton/pass/types'; import { first } from '@proton/pass/utils/array/first'; import { parseFormAction } from '@proton/pass/utils/dom/form'; import { createListenerStore } from '@proton/pass/utils/listener/factory'; import { logger } from '@proton/pass/utils/logger'; import { isEmptyString } from '@proton/pass/utils/string/is-empty-string'; import lastItem from '@proton/utils/lastItem'; type FormTrackerState = { isSubmitting: boolean }; type FieldsForFormResults = WeakMap< FieldHandle, { action: MaybeNull<DropdownAction>; field: FieldHandle; attachIcon: boolean; } >; const canProcessAction = withContext<(action: DropdownAction) => boolean>(({ getFeatures }, action) => { const features = getFeatures(); switch (action) { case DropdownAction.AUTOFILL: return features.Autofill; case DropdownAction.AUTOSUGGEST_ALIAS: return features.AutosuggestAlias; case DropdownAction.AUTOSUGGEST_PASSWORD: return features.AutosuggestPassword; } }); export const createFormTracker = (form: FormHandle): FormTracker => { logger.debug(`[FormTracker] Tracking form [${form.formType}:${form.id}]`); const listeners = createListenerStore(); const state: FormTrackerState = { isSubmitting: false }; /* FIXME: should account for hidden fields - should also * account for different form types for more control */ const getFormData = (): { username?: string; password?: string } => { const nonEmptyField = (field: FieldHandle) => !isEmptyString(field.value); /* in the case of username or email fields : we always consider the * first non-empty field as the final `username` candidate */ const username = first(form.getFieldsFor(FieldType.USERNAME, nonEmptyField)); const usernameHidden = first(form.getFieldsFor(FieldType.USERNAME_HIDDEN, nonEmptyField)); const email = first(form.getFieldsFor(FieldType.EMAIL, nonEmptyField)); /* in the case of passwords : we may be dealing with confirmation * cases and/or temporary passwords being detected - as a heuristic : * always choose the last one.*/ const passwordNew = lastItem(form.getFieldsFor(FieldType.PASSWORD_NEW, nonEmptyField)); const passwordCurrent = lastItem(form.getFieldsFor(FieldType.PASSWORD_CURRENT, nonEmptyField)); return { username: (username ?? email ?? usernameHidden)?.value, password: (passwordNew ?? passwordCurrent)?.value, }; }; const submit = async () => { /* Exit early when there is nothing to stage (eg. MFA and NOOP forms). * This check is done here instead of not binding the listener in the * first place because the `formType` can change for a particular form * (eg. rerendering in SPAs). */ if ([FormType.MFA, FormType.NOOP].includes(form.formType)) return; const { username, password } = getFormData(); if (!state.isSubmitting && username !== undefined) { state.isSubmitting = true; await sendMessage( contentScriptMessage({ type: WorkerMessageType.FORM_ENTRY_STAGE, payload: { type: form.formType, reason: 'FORM_SUBMIT_HANDLER', action: parseFormAction(form.element), data: { username, password }, }, }) ); /* TODO: attach a short-lived mutation observer to * detect if the form is still there in order to * stash the submission if we can infer a failure * TODO: for SPA forms we should also handle the * xmlhttprequests intercepted failures here */ setTimeout(() => (state.isSubmitting = false), 500); } }; const onSubmitHandler = withContext(async ({ service: { iframe } }) => { iframe.dropdown?.close(); await submit(); }); const getTrackableFields = (): FieldsForFormResults => { const results: FieldsForFormResults = new WeakMap(); const status = { injections: new Map<FieldType, boolean>(), injected: false }; FORM_TRACKER_CONFIG[form.formType].forEach(({ type, injection, action: fieldAction }) => { form.getFieldsFor(type).forEach((field) => { let attachIcon = false; switch (injection) { case FieldInjectionRule.NEVER: break; case FieldInjectionRule.ALWAYS: attachIcon = true; break; /* inject only if no previous injections */ case FieldInjectionRule.FIRST_OF_FORM: attachIcon = !status.injected; break; /* inject only if no other field of type attached */ case FieldInjectionRule.FIRST_OF_TYPE: attachIcon = !status.injections.get(type); break; } status.injections.set(type, status.injections.get(type) || attachIcon); status.injected = status.injected || attachIcon; const action = fieldAction && canProcessAction(fieldAction) ? fieldAction : null; results.set(field, { field, action, attachIcon: action !== null && attachIcon }); }); }); return results; }; /* reconciliating the form trackers involves syncing * the form's trackable fields.*/ const reconciliate = withContext<() => Promise<void>>(async ({ getState, service }) => { const { loggedIn } = getState(); const fieldsToTrack = getTrackableFields(); const autofillCount = service.autofill.getState()?.items.length ?? 0; form.getFields().forEach((field) => { const match = fieldsToTrack.get(field); if (match === undefined) return field.detach(); field.setAction(match.action); /* if the field is not currently tracked, attach listeners */ if (!field.tracked) field.attach(onSubmitHandler); if (!match.attachIcon) return field.detachIcon(); const icon = field.attachIcon(); icon.setCount(loggedIn && match.action === DropdownAction.AUTOFILL ? autofillCount : 0); }); /* trigger auto-focus on current active field if value is empty: * This handles autofocused simple forms, and dynamic forms where * fields may be added incrementally */ form .getFields() .find((field) => field.element === document.activeElement && !field.value) ?.focus(); }); /* when detaching the form tracker : remove every listener * for both the current tracker and all fields*/ const detach = () => { listeners.removeAll(); form.getFields().forEach((field) => field.detach()); }; listeners.addListener(form.element, 'submit', onSubmitHandler); return { detach, reconciliate, submit }; };
4,344
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/services
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/services/handles/field.ts
import { withContext } from 'proton-pass-extension/app/content/context/context'; import type { FieldHandle, FormHandle } from 'proton-pass-extension/app/content/types'; import { allowActions, preventActions, shouldPreventActions, withActionTrap, } from 'proton-pass-extension/app/content/utils/action-trap'; import { createAutofill } from 'proton-pass-extension/app/content/utils/autofill'; import type { FormType } from '@proton/pass/fathom'; import { FieldType } from '@proton/pass/fathom'; import { findBoundingInputElement } from '@proton/pass/utils/dom/input'; import { createListenerStore } from '@proton/pass/utils/listener/factory'; import { createFieldIconHandle } from './icon'; type CreateFieldHandlesOptions = { element: HTMLInputElement; formType: FormType; fieldType: FieldType; zIndex: number; getFormHandle: () => FormHandle; }; /* on input focus : close the dropdown only if the current target * does not match the dropdown's current field : this maybe the case * when changing focus with the dropdown open */ const onFocusField = (field: FieldHandle): ((evt?: FocusEvent) => void) => withContext(({ service: { iframe }, getSettings, getState }, evt) => { const { action, element } = field; if (shouldPreventActions(element)) return allowActions(element); if (!action) return; requestAnimationFrame(() => { const target = evt?.target; const current = iframe.dropdown?.getCurrentField()?.element; const opened = iframe.dropdown?.getState().visible; const shouldClose = opened && current !== target; const shouldOpen = getState().loggedIn && (!opened || shouldClose) && getSettings().autofill.openOnFocus; if (shouldClose) iframe.dropdown?.close(); if (shouldOpen) { iframe.attachDropdown(); iframe.dropdown?.open({ action, autofocused: true, field, }); } }); }); /* on input change : close the dropdown if it was visible * and update the field's handle tracked value */ const onInputField = (field: FieldHandle): (() => void) => withContext(({ service: { iframe } }) => { if (iframe.dropdown?.getState().visible && !shouldPreventActions(field.element)) iframe.dropdown?.close(); field.setValue((field.element as HTMLInputElement).value); }); /* when the type attribute of a field changes : detach it from * the tracked form and re-trigger the detection */ const onFieldAttributeChange = (field: FieldHandle): MutationCallback => withContext<MutationCallback>(({ service: { formManager } }, mutations) => { if ([FieldType.PASSWORD_CURRENT, FieldType.PASSWORD_NEW].includes(field.fieldType)) return; mutations.forEach((mutation) => { const target = mutation.target as HTMLInputElement; if (mutation.type === 'attributes' && mutation.oldValue !== target.type) { field.getFormHandle().detachField(mutation.target as HTMLInputElement); void formManager.detect({ reason: 'FieldTypeChange' }); } }); }); /* trigger the submit handler on keydown enter */ const onKeyDownField = (onSubmit: () => void) => ({ key }: KeyboardEvent) => key === 'Enter' && onSubmit(); export const createFieldHandles = ({ element, formType, fieldType, zIndex, getFormHandle, }: CreateFieldHandlesOptions): FieldHandle => { const listeners = createListenerStore(); let boxElement = findBoundingInputElement(element); const field: FieldHandle = { formType, fieldType, element, boxElement, icon: null, action: null, value: element.value, tracked: false, zIndex, getFormHandle, getBoxElement: (options) => options?.revalidate ? (boxElement = findBoundingInputElement(element)) : boxElement, setValue: (value) => (field.value = value), setAction: (action) => (field.action = action), /* if the field is already focused we need to re-dispatch the event on the input * element to trigger initial dropdown autofocus. Calling `el.focus()` will not * re-dispatch the focus event if it is already the document's active element. * In certain cases, we may want to re-focus the element without triggering the * attached action effect : as there is no way to attach extra data to a focus event, * so we rely on adding custom properties on the field element itself */ focus(options) { const isFocusedField = document.activeElement === field.element; if (options?.preventAction) preventActions(field.element); field.element.focus(); if (isFocusedField) { const focusEvent = new FocusEvent('focus', { bubbles: true, cancelable: true, relatedTarget: null, }); return field.element.dispatchEvent(focusEvent); } }, autofill: withActionTrap(element, createAutofill(element)), /* if an icon is already attached recycle it */ attachIcon: () => (field.icon = field.icon ?? createFieldIconHandle({ field })), detachIcon() { field.icon?.detach(); field.icon = null; }, attach(onSubmit) { field.tracked = true; listeners.removeAll(); listeners.addListener(field.element, 'focus', onFocusField(field)); listeners.addListener(field.element, 'input', onInputField(field)); listeners.addListener(field.element, 'keydown', onKeyDownField(onSubmit)); listeners.addObserver(field.element, onFieldAttributeChange(field), { attributeFilter: ['type'], attributeOldValue: true, }); }, detach: () => { field.tracked = false; field.detachIcon(); listeners.removeAll(); }, }; return field; };
4,345
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/services
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/services/handles/form.ts
import { withContext } from 'proton-pass-extension/app/content/context/context'; import { createFormTracker } from 'proton-pass-extension/app/content/services/form/tracker'; import type { DetectedField, DetectedForm, FormHandle } from 'proton-pass-extension/app/content/types'; import { hasUnprocessedFields } from 'proton-pass-extension/app/content/utils/nodes'; import { type FormType, removeProcessedFlag } from '@proton/pass/fathom'; import { getMaxZIndex } from '@proton/pass/utils/dom/zindex'; import { createListenerStore } from '@proton/pass/utils/listener/factory'; import { logger } from '@proton/pass/utils/logger'; import { uniqueId } from '@proton/pass/utils/string/unique-id'; import debounce from '@proton/utils/debounce'; import { createFieldHandles } from './field'; export type FormHandlesProps = { zIndex: number }; export const createFormHandles = (options: DetectedForm): FormHandle => { const { form, formType, fields: detectedFields } = options; const listeners = createListenerStore(); const zIndex = getMaxZIndex(form) + 5; const formHandle: FormHandle = { id: uniqueId(), element: form, formType: formType, fields: new Map( detectedFields.map(({ fieldType, field }) => [ field, createFieldHandles({ element: field, formType, fieldType, zIndex, getFormHandle: () => formHandle, }), ]) ), getFieldsFor: (type, predicate) => { const fields = Array.from(formHandle.fields.values()); return fields.filter((field) => field.fieldType === type && (predicate?.(field) ?? true)); }, getFields: (predicate) => { const fields = Array.from(formHandle.fields.values()); return predicate ? fields.filter(predicate) : fields; }, detachField: (field: HTMLInputElement) => { formHandle.fields.get(field)?.detach(); formHandle.fields.delete(field); removeProcessedFlag(field); }, shouldRemove: () => !document.body.contains(form), reconciliate: (formType: FormType, fields: DetectedField[]) => { formHandle.formType = formType; formHandle.getFields().forEach((field) => { const shouldDetach = !fields.some((incoming) => field.element === incoming.field); return shouldDetach && formHandle.detachField(field.element); }); /* attach incoming new fields */ fields.forEach(({ field, fieldType }) => { if (formHandle.fields.get(field) === undefined) { formHandle.fields.set( field, createFieldHandles({ element: field, formType, fieldType, zIndex, getFormHandle: () => formHandle, }) ); } }); }, /* Form tracker is responsible for setting * up the submission handlers and the input * changes handler */ attach() { formHandle.tracker = formHandle.tracker ?? createFormTracker(formHandle); formHandle.tracker.reconciliate(); }, detach() { logger.debug(`[FormHandles]: Detaching tracker for form [${formType}:${formHandle.id}]`); listeners.removeAll(); formHandle.tracker?.detach(); formHandle.getFields().forEach((field) => field.detach()); removeProcessedFlag(form); form.querySelectorAll('input').forEach(removeProcessedFlag); }, }; /** * Detection trigger & repositioning via Form Resize * * This handler is responsible for triggering the repositioning flow for * our injections when tooltips or error messages appear. Additionally, it * checks if the form's parent element has unprocessed fields. This detection * mechanism during a resize is particularly useful for "stacked" or "multi- * step" forms where multiple forms (or clusters of inputs) are overlayed on * top of each other. The purpose is to handle dynamic changes in form layouts * and stacked forms effectively without looking for unprocessed fields * on the full DOM as this may lead to too many detection triggers */ const onFormResize = debounce( withContext(({ service: { formManager } }) => { const fields = formHandle.getFields(); fields.forEach((field) => field.icon?.reposition()); if (options.form.parentElement === null || hasUnprocessedFields(options.form.parentElement)) { void formManager.detect({ reason: 'NewFormFieldsOnResize' }); } }), 50 ); listeners.addResizeObserver(options.form, onFormResize); return formHandle; };
4,346
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/services
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/services/handles/icon.ts
import { ACTIVE_ICON_SRC, COUNTER_ICON_SRC, DISABLED_ICON_SRC, LOCKED_ICON_SRC, } from 'proton-pass-extension/app/content/constants.runtime'; import { withContext } from 'proton-pass-extension/app/content/context/context'; import { applyInjectionStyles, cleanupInjectionStyles, createIcon, } from 'proton-pass-extension/app/content/injections/icon'; import type { FieldHandle, FieldIconHandle } from 'proton-pass-extension/app/content/types'; import { clientErrored, clientLocked, clientStale, clientUnauthorized } from '@proton/pass/lib/client'; import type { AppStatus } from '@proton/pass/types'; import { animatePositionChange } from '@proton/pass/utils/dom/position'; import { or } from '@proton/pass/utils/fp/predicates'; import { safeCall } from '@proton/pass/utils/fp/safe-call'; import { createListenerStore } from '@proton/pass/utils/listener/factory'; import debounce from '@proton/utils/debounce'; type CreateIconOptions = { field: FieldHandle }; export const createFieldIconHandle = ({ field }: CreateIconOptions): FieldIconHandle => { const listeners = createListenerStore(); let repositionRequest: number = -1; /* track repositioning requests */ const input = field.element as HTMLInputElement; const { icon, control } = createIcon(field); const setStatus = (status: AppStatus) => { const iconUrl = (() => { if (clientLocked(status)) return LOCKED_ICON_SRC; if (or(clientUnauthorized, clientErrored, clientStale)(status)) return DISABLED_ICON_SRC; return ACTIVE_ICON_SRC; })(); icon.style.setProperty('background-image', `url("${iconUrl}")`, 'important'); }; const setCount = withContext<(count: number) => void>(({ getState }, count: number) => { const safeCount = count === 0 || !count ? '' : String(count); icon.style.setProperty(`--control-count`, `"${safeCount}"`); if (count > 0) return icon.style.setProperty('background-image', `url("${COUNTER_ICON_SRC}")`, 'important'); return setStatus(getState().status); }); const reposition = debounce( (revalidate: boolean = false) => { cancelAnimationFrame(repositionRequest); repositionRequest = requestAnimationFrame(() => { animatePositionChange({ get: () => field.element.getBoundingClientRect(), set: () => { const inputBox = field.getBoxElement({ revalidate }); cleanupInjectionStyles({ input, control }); applyInjectionStyles({ icon, control, input, inputBox, form: field.getFormHandle().element, }); }, }); }); }, 50, { leading: true, trailing: true } ); /* `reposition` is debounced and wrapped in a `requestAnimationFrame` * for performance reasons. If form is detached, we must cancel the * ongoing repositioning */ const cancelReposition = () => { cancelAnimationFrame(repositionRequest); reposition.cancel(); }; const onClick: (evt: MouseEvent) => void = withContext(({ service: { iframe } }, evt) => { evt.preventDefault(); evt.stopPropagation(); if (field.action) { return iframe.dropdown?.getState().visible ? iframe.dropdown?.close() : iframe.dropdown?.open({ action: field.action, field }); } }); const detach = safeCall(() => { listeners.removeAll(); cancelReposition(); cleanupInjectionStyles({ input, control }); icon.remove(); control.remove(); }); /* repositioning the icon can happen either : * · on window resize * · on form resize (handled in `FormHandles`) * · on new elements added to the field box (ie: icons) */ const target = field.element === field.boxElement ? field.element.parentElement! : field.boxElement; listeners.addListener(icon, 'mousedown', onClick); listeners.addListener(window, 'resize', () => reposition(false)); listeners.addResizeObserver(target, () => reposition(false)); listeners.addObserver( target, () => { /* if the subtree changes we may be dealing with error messages, * tooltips or even icon indicators appearing : in this case we * should revalidate the input field's bounding box as it we may * have resolved an element which is no longer a correct fit for * injection */ reposition.cancel(); reposition(true); }, { childList: true, subtree: true } ); reposition(); /* fire reposition on initial icon handle creation */ return { element: icon, setStatus, setCount, detach, reposition }; };
4,347
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/services
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/services/iframes/dropdown.ts
import { DROPDOWN_IFRAME_SRC } from 'proton-pass-extension/app/content/constants.runtime'; import { DROPDOWN_WIDTH, MIN_DROPDOWN_HEIGHT } from 'proton-pass-extension/app/content/constants.static'; import { withContext } from 'proton-pass-extension/app/content/context/context'; import { createIFrameApp } from 'proton-pass-extension/app/content/injections/iframe/create-iframe-app'; import type { DropdownActions, DropdownOpenOptions, FieldHandle, InjectedDropdown, } from 'proton-pass-extension/app/content/types'; import { DropdownAction, IFrameMessageType } from 'proton-pass-extension/app/content/types'; import { DEFAULT_RANDOM_PW_OPTIONS } from '@proton/pass/hooks/usePasswordGenerator'; import { contentScriptMessage, sendMessage } from '@proton/pass/lib/extension/message'; import { deriveAliasPrefix } from '@proton/pass/lib/validation/alias'; import { type MaybeNull, WorkerMessageType } from '@proton/pass/types'; import { createStyleCompute, getComputedHeight } from '@proton/pass/utils/dom/computed-styles'; import { animatePositionChange } from '@proton/pass/utils/dom/position'; import { pipe } from '@proton/pass/utils/fp/pipe'; import { truthy } from '@proton/pass/utils/fp/predicates'; import { waitUntil } from '@proton/pass/utils/fp/wait-until'; import { createListenerStore } from '@proton/pass/utils/listener/factory'; import { getScrollParent } from '@proton/shared/lib/helpers/dom'; type DropdownFieldRef = { current: MaybeNull<FieldHandle> }; export const createDropdown = (): InjectedDropdown => { const fieldRef: DropdownFieldRef = { current: null }; const listeners = createListenerStore(); const iframe = createIFrameApp<DropdownAction>({ id: 'dropdown', src: DROPDOWN_IFRAME_SRC, animation: 'fadein', backdropClose: true, onClose: (_, options) => options?.refocus && fieldRef.current?.focus(), backdropExclude: () => [fieldRef.current?.icon?.element, fieldRef.current?.element].filter(truthy), position: (iframeRoot: HTMLElement) => { const field = fieldRef.current; if (!field) return { top: 0, left: 0 }; const { boxElement, element, zIndex } = field; const boxed = boxElement !== element; const bodyTop = iframeRoot.getBoundingClientRect().top; const { value: height, offset: offsetBox } = getComputedHeight(createStyleCompute(boxElement), { node: boxElement, mode: boxed ? 'inner' : 'outer', }); const { left: boxLeft, top, width } = boxElement.getBoundingClientRect(); return { top: top - bodyTop + offsetBox.top + height, left: boxLeft + width - DROPDOWN_WIDTH, zIndex, }; }, dimensions: () => ({ width: DROPDOWN_WIDTH, height: MIN_DROPDOWN_HEIGHT }), }); /* if the dropdown is opened while the field is being animated * we must update its position until the position stabilizes */ const updatePosition = () => animatePositionChange({ get: () => iframe.getPosition(), set: () => iframe.updatePosition(), }); const getPayloadForAction = withContext<(action: DropdownAction) => Promise<DropdownActions>>( async (ctx, action) => { const { loggedIn } = ctx.getState(); const { domain, subdomain, displayName } = ctx.getExtensionContext().url; const hostname = subdomain ?? domain ?? ''; switch (action) { case DropdownAction.AUTOFILL: { if (!loggedIn) return { action, hostname: '', items: [], needsUpgrade: false }; const { items, needsUpgrade } = ctx.service.autofill.getState() ?? {}; return { action, hostname, items: items ?? [], needsUpgrade: Boolean(needsUpgrade) }; } case DropdownAction.AUTOSUGGEST_ALIAS: { return { action, hostname, prefix: deriveAliasPrefix(displayName!) }; } case DropdownAction.AUTOSUGGEST_PASSWORD: { const options = await sendMessage.on( contentScriptMessage({ type: WorkerMessageType.AUTOFILL_PASSWORD_OPTIONS }), (res) => (res.type === 'success' ? res.options : DEFAULT_RANDOM_PW_OPTIONS) ); return { action, options, hostname }; } } } ); /* As we are recyling the dropdown iframe sub-app instead of * re-injecting for each field - opening the dropdown involves * passing the actual field handle to attach it to * Dropdown opening may be automatically triggered on initial * page load with a positive ifion : ensure the iframe is * in a ready state in order to send out the dropdown action */ const open = async ({ field, action, autofocused }: DropdownOpenOptions): Promise<void> => { await waitUntil(() => iframe.state.ready, 50); fieldRef.current = field; const payload = await getPayloadForAction(action); /* If the opening action is coming from a focus event for an autofill action and the we * have no login items that match the current domain, avoid auto-opening the dropdown */ if (autofocused && payload.action === DropdownAction.AUTOFILL && payload.items.length === 0) return; iframe.sendPortMessage({ type: IFrameMessageType.DROPDOWN_ACTION, payload }); const scrollParent = getScrollParent(field.element); iframe.open(action, scrollParent); updatePosition(); }; const sync = async () => { const action = fieldRef.current?.action; if (action) { iframe.sendPortMessage({ type: IFrameMessageType.DROPDOWN_ACTION, payload: await getPayloadForAction(action), }); } }; /* On a login autofill request - resolve the credentials via * worker communication and autofill the parent form of the * field the current dropdown is attached to. */ iframe.registerMessageHandler( IFrameMessageType.DROPDOWN_AUTOFILL_LOGIN, withContext(({ service }, { payload }) => { const form = fieldRef.current?.getFormHandle(); if (!form) return; service.autofill.autofillLogin(form, payload); iframe.close({ refocus: false }); fieldRef.current?.focus({ preventAction: true }); }) ); /* For a password auto-suggestion - the password will have * been generated in the injected iframe and passed in clear * text through the secure extension port channel */ iframe.registerMessageHandler( IFrameMessageType.DROPDOWN_AUTOFILL_GENERATED_PW, withContext(({ service }, { payload }) => { const form = fieldRef.current?.getFormHandle(); if (!form) return; service.autofill.autofillGeneratedPassword(form, payload.password); fieldRef.current?.focus({ preventAction: true }); form.tracker?.submit(); }) ); /* When suggesting an alias on a register form, the alias will * only be created upon user action - this avoids creating * aliases everytime the injected iframe dropdown is opened */ iframe.registerMessageHandler(IFrameMessageType.DROPDOWN_AUTOFILL_EMAIL, ({ payload }) => { iframe.close(); fieldRef.current?.autofill(payload.email); fieldRef.current?.focus({ preventAction: true }); fieldRef.current?.getFormHandle()?.tracker?.submit(); }); const destroy = () => { fieldRef.current = null; listeners.removeAll(); iframe.destroy(); }; listeners.addListener(window, 'popstate', () => iframe.close({ discard: false })); listeners.addListener(window, 'hashchange', () => iframe.close({ discard: false })); listeners.addListener(window, 'unload', () => iframe.close({ discard: false })); listeners.addListener(window, 'beforeunload', () => iframe.close({ discard: false })); const dropdown: InjectedDropdown = { close: pipe(iframe.close, () => dropdown), destroy, getCurrentField: () => fieldRef.current, getState: () => iframe.state, init: pipe(iframe.init, () => dropdown), open: pipe(open, () => dropdown), setPort: pipe(iframe.setPort, () => dropdown), sync, }; return dropdown; };
4,348
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/services
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/services/iframes/notification.ts
import { NOTIFICATION_IFRAME_SRC } from 'proton-pass-extension/app/content/constants.runtime'; import { NOTIFICATION_HEIGHT, NOTIFICATION_HEIGHT_SM, NOTIFICATION_WIDTH, } from 'proton-pass-extension/app/content/constants.static'; import { withContext } from 'proton-pass-extension/app/content/context/context'; import { createIFrameApp } from 'proton-pass-extension/app/content/injections/iframe/create-iframe-app'; import type { InjectedNotification, NotificationActions } from 'proton-pass-extension/app/content/types'; import { IFrameMessageType, NotificationAction } from 'proton-pass-extension/app/content/types'; import { FormType, flagAsIgnored, removeClassifierFlags } from '@proton/pass/fathom'; import { contentScriptMessage, sendMessage } from '@proton/pass/lib/extension/message'; import { WorkerMessageType } from '@proton/pass/types'; import { pipe } from '@proton/pass/utils/fp/pipe'; import { waitUntil } from '@proton/pass/utils/fp/wait-until'; import noop from '@proton/utils/noop'; export const createNotification = (): InjectedNotification => { const iframe = createIFrameApp<NotificationAction>({ id: 'notification', src: NOTIFICATION_IFRAME_SRC, animation: 'slidein', backdropClose: false, classNames: ['fixed'], onClose: withContext(({ service }, { action }, options) => { switch (action) { /* stash the form submission if the user discarded * the autosave prompt */ case NotificationAction.AUTOSAVE_PROMPT: return ( options?.discard && sendMessage( contentScriptMessage({ type: WorkerMessageType.FORM_ENTRY_STASH, payload: { reason: 'AUTOSAVE_DISMISSED' }, }) ) ); /* flag all MFA forms as ignorable on user discards the * OTP autofill prompt */ case NotificationAction.AUTOFILL_OTP_PROMPT: if (options?.discard) { service.formManager .getTrackedForms() .filter(({ formType }) => formType === FormType.MFA) .forEach(({ element }) => { removeClassifierFlags(element); flagAsIgnored(element); }); } /* handle OTP -> AutoSave sequence */ return service.autosave.reconciliate().catch(noop); } }), position: () => ({ top: 15, right: 15 }), dimensions: ({ action }) => ({ width: NOTIFICATION_WIDTH, height: action === NotificationAction.AUTOFILL_OTP_PROMPT ? NOTIFICATION_HEIGHT_SM : NOTIFICATION_HEIGHT, }), }); const open = async (payload: NotificationActions) => { await waitUntil(() => iframe.state.ready, 50); if (!iframe.state.visible) { iframe.sendPortMessage({ type: IFrameMessageType.NOTIFICATION_ACTION, payload }); iframe.open(payload.action); } }; iframe.registerMessageHandler( IFrameMessageType.NOTIFICATION_AUTOFILL_OTP, withContext(({ service: { formManager, autofill } }, { payload: { code } }) => { const form = formManager.getTrackedForms().find(({ formType }) => formType === FormType.MFA); if (!form) return; autofill.autofillOTP(form, code); }) ); const notification: InjectedNotification = { close: pipe(iframe.close, () => notification), destroy: iframe.destroy, getState: () => iframe.state, init: pipe(iframe.init, () => notification), open: pipe(open, () => notification), setPort: pipe(iframe.setPort, () => notification), }; return notification; };
4,349
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/services
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/services/iframes/service.ts
import type { MaybeNull } from '@proton/pass/types'; import { logger } from '@proton/pass/utils/logger'; import { withContext } from '../../context/context'; import type { IFrameAppService, InjectedDropdown, InjectedNotification } from '../../types'; import { createDropdown } from './dropdown'; import { createNotification } from './notification'; type IFrameServiceContext = { apps: { dropdown: MaybeNull<InjectedDropdown>; notification: MaybeNull<InjectedNotification>; }; }; export const createIFrameService = () => { const ctx: IFrameServiceContext = { apps: { dropdown: null, notification: null }, }; /* only re-init the iframe sub-apps if the extension * context port has changed */ const onAttached: <T extends IFrameAppService<any>>(app: T) => void = withContext( ({ getExtensionContext, getFeatureFlags, getState, getSettings }, app) => { const port = getExtensionContext().port; if (app.getState().port !== port) app.setPort(port); app.init({ features: getFeatureFlags(), settings: getSettings(), workerState: getState(), }); } ); const attachDropdown = withContext(({ scriptId }) => { if (ctx.apps.dropdown === null) { logger.info(`[ContentScript::${scriptId}] attaching dropdown iframe`); ctx.apps.dropdown = createDropdown(); } onAttached(ctx.apps.dropdown); }); const detachDropdown = withContext(({ scriptId }) => { if (ctx.apps.dropdown) { logger.info(`[ContentScript::${scriptId}] detaching dropdown iframe`); ctx.apps.dropdown.destroy(); ctx.apps.dropdown = null; } }); const attachNotification = withContext(({ scriptId }) => { if (ctx.apps.notification === null) { logger.info(`[ContentScript::${scriptId}] attaching notification iframe`); ctx.apps.notification = createNotification(); } onAttached(ctx.apps.notification); }); const detachNotification = withContext(({ scriptId }) => { if (ctx.apps.notification) { logger.info(`[ContentScript::${scriptId}] detaching notification iframe`); ctx.apps.notification.destroy(); ctx.apps.notification = null; } }); const reset = () => { if (ctx.apps.dropdown) onAttached(ctx.apps.dropdown); if (ctx.apps.notification) onAttached(ctx.apps.notification); }; const destroy = () => { detachDropdown(); detachNotification(); }; return { get dropdown() { return ctx.apps.dropdown; }, get notification() { return ctx.apps.notification; }, attachDropdown, attachNotification, detachDropdown, detachNotification, reset, destroy, }; }; export type IFrameService = ReturnType<typeof createIFrameService>;
4,350
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/types/dropdown.ts
import type { GeneratePasswordOptions } from '@proton/pass/lib/password/generator'; import type { MaybeNull, SafeLoginItem } from '@proton/pass/types'; import type { FieldHandle } from './form'; import type { IFrameAppService } from './iframe'; export enum DropdownAction { AUTOFILL = 'AUTOFILL', AUTOSUGGEST_PASSWORD = 'AUTOSUGGEST_PASSWORD', AUTOSUGGEST_ALIAS = 'AUTOSUGGEST_ALIAS', } export type DropdownActions = | { action: DropdownAction.AUTOFILL; hostname: string; items: SafeLoginItem[]; needsUpgrade: boolean } | { action: DropdownAction.AUTOSUGGEST_PASSWORD; hostname: string; options: GeneratePasswordOptions } | { action: DropdownAction.AUTOSUGGEST_ALIAS; hostname: string; prefix: string }; export type DropdownOpenOptions = { action: DropdownAction; field: FieldHandle; autofocused?: boolean; }; export interface InjectedDropdown extends IFrameAppService<DropdownOpenOptions> { getCurrentField: () => MaybeNull<FieldHandle>; sync: () => Promise<void>; }
4,351
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/types/form.ts
import type { FieldType, FormType } from '@proton/pass/fathom'; import type { MaybeNull } from '@proton/pass/types'; import { type AutofillOptions } from '../utils/autofill'; import type { DropdownAction } from './dropdown'; import type { FieldIconHandle } from './icon'; export type DetectedForm = { formType: FormType; form: HTMLElement; fields: DetectedField[] }; export type DetectedField = { fieldType: FieldType; field: HTMLInputElement }; export interface FormHandle { id: string; formType: FormType; element: HTMLElement; fields: Map<HTMLInputElement, FieldHandle>; tracker?: FormTracker; detachField: (field: HTMLInputElement) => void; getFieldsFor: (type: FieldType, predicate?: (handle: FieldHandle) => boolean) => FieldHandle[]; getFields: (predicate?: (handle: FieldHandle) => boolean) => FieldHandle[]; reconciliate: (type: FormType, fields: DetectedField[]) => void; shouldRemove: () => boolean; attach: () => void; detach: () => void; } export interface FieldHandle { formType: FormType; fieldType: FieldType; element: HTMLInputElement; boxElement: HTMLElement; icon: FieldIconHandle | null; action: MaybeNull<DropdownAction>; value: string; tracked: boolean; zIndex: number; getFormHandle: () => FormHandle; getBoxElement: (options?: { revalidate: boolean }) => HTMLElement; setValue: (value: string) => void; setAction: (action: MaybeNull<DropdownAction>) => void; autofill: (value: string, options?: AutofillOptions) => void; focus: (options?: { preventAction?: boolean }) => void; attachIcon: () => FieldIconHandle; detachIcon: () => void; attach: (onSubmit: () => void) => void; detach: () => void; } export enum FieldInjectionRule { ALWAYS /* always inject */, FIRST_OF_TYPE /* first field for field type */, FIRST_OF_FORM /* first field in form */, NEVER /* never inject */, } export type FormTrackerFieldConfig = { type: FieldType; injection: FieldInjectionRule; action?: DropdownAction; }; export interface FormTracker { detach: () => void; reconciliate: () => void; submit: () => void; }
4,352
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/types/icon.ts
import type { AppStatus } from '@proton/pass/types'; import { type Maybe } from '@proton/pass/types'; export type IconHandleState = { timer: Maybe<NodeJS.Timeout>; loading: boolean }; export interface FieldIconHandle { element: HTMLElement; setStatus: (status: AppStatus) => void; setCount: (count: number) => void; detach: () => void; reposition: () => void; }
4,353
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/types/iframe.ts
import type { Runtime } from 'webextension-polyfill'; import type { FeatureFlagState } from '@proton/pass/store/reducers'; import type { ProxiedSettings } from '@proton/pass/store/reducers/settings'; import type { AppState, MaybeNull } from '@proton/pass/types'; import type { Rect } from '@proton/pass/types/utils/dom'; import type { DropdownActions } from './dropdown'; import type { NotificationActions } from './notification'; export type IFramePosition = Partial<Rect> & { zIndex?: number }; export type IFrameState<A> = { action: MaybeNull<A>; framePort: MaybeNull<string>; loaded: boolean; port: MaybeNull<Runtime.Port>; position: IFramePosition; ready: boolean; visible: boolean; }; export type IFramePortMessageHandler<T extends IFrameMessageType = IFrameMessageType> = ( message: IFrameMessageWithSender<T> ) => void; export type IFrameCloseOptions = { discard?: boolean; event?: Event; refocus?: boolean; }; export interface IFrameApp<A = any> { element: HTMLIFrameElement; state: IFrameState<A>; close: (options?: IFrameCloseOptions) => void; destroy: () => void; getPosition: () => IFramePosition; init: (payload: IFrameInitPayload) => void; open: (action: A, scrollRef?: HTMLElement) => void; registerMessageHandler: <M extends IFrameMessage['type']>(type: M, handler: IFramePortMessageHandler<M>) => void; sendPortMessage: (message: IFrameMessage) => void; setPort: (port: Runtime.Port) => void; updatePosition: () => void; } export interface IFrameAppService<T extends { action: any }> { close: () => IFrameAppService<T>; destroy: () => void; getState: () => IFrameState<T['action']>; init: (payload: IFrameInitPayload) => IFrameAppService<T>; open: (options: T) => IFrameAppService<T>; setPort: (port: Runtime.Port) => IFrameAppService<T>; } export enum IFrameMessageType { DROPDOWN_ACTION = 'DROPDOWN_ACTION', DROPDOWN_AUTOFILL_EMAIL = 'DROPDOWN_AUTOFILL_EMAIL', DROPDOWN_AUTOFILL_GENERATED_PW = 'DROPDOWN_AUTOFILL_GENERATED_PASSWORD', DROPDOWN_AUTOFILL_LOGIN = 'DROPDOWN_AUTOFILL_LOGIN', IFRAME_CLOSE = 'IFRAME_CLOSE', IFRAME_CONNECTED = 'IFRAME_CONNECTED', IFRAME_DIMENSIONS = 'IFRAME_DIMENSIONS', IFRAME_HIDDEN = 'IFRAME_HIDDEN', IFRAME_INIT = 'IFRAME_INIT', IFRAME_INJECT_PORT = 'IFRAME_INJECT_PORT', IFRAME_OPEN = 'IFRAME_OPEN', NOTIFICATION_ACTION = 'NOTIFICATION_ACTION', NOTIFICATION_AUTOFILL_OTP = 'NOTIFICATION_AUTOFILL_OTP', NOTIFICATION_AUTOSAVE_FAILURE = 'NOTIFICATION_AUTOSAVE_FAILURE', NOTIFICATION_AUTOSAVE_REQUEST = 'NOTIFICATION_AUTOSAVE_REQUEST', NOTIFICATION_AUTOSAVE_SUCCESS = 'NOTIFICATION_AUTOSAVE_SUCCESS', } export type IFrameEndpoint = 'contentscript' | 'notification' | 'dropdown'; export type IFrameInitPayload = { workerState: AppState; settings: ProxiedSettings; features: FeatureFlagState }; export type IFrameMessage<T extends IFrameMessageType = IFrameMessageType> = Extract< | { type: IFrameMessageType.DROPDOWN_ACTION; payload: DropdownActions } | { type: IFrameMessageType.DROPDOWN_AUTOFILL_EMAIL; payload: { email: string } } | { type: IFrameMessageType.DROPDOWN_AUTOFILL_GENERATED_PW; payload: { password: string } } | { type: IFrameMessageType.DROPDOWN_AUTOFILL_LOGIN; payload: { username: string; password: string } } | { type: IFrameMessageType.IFRAME_CLOSE; payload: IFrameCloseOptions } | { type: IFrameMessageType.IFRAME_CONNECTED; payload: { framePort: string; id: IFrameEndpoint } } | { type: IFrameMessageType.IFRAME_DIMENSIONS; payload: { height: number; width?: number } } | { type: IFrameMessageType.IFRAME_HIDDEN } | { type: IFrameMessageType.IFRAME_INIT; payload: IFrameInitPayload } | { type: IFrameMessageType.IFRAME_INJECT_PORT; payload: { port: string } } | { type: IFrameMessageType.IFRAME_OPEN } | { type: IFrameMessageType.NOTIFICATION_ACTION; payload: NotificationActions } | { type: IFrameMessageType.NOTIFICATION_AUTOFILL_OTP; payload: { code: string } }, { type: T } >; export type IFrameMessageWithSender<T extends IFrameMessageType = IFrameMessageType> = { frameId?: number; sender: IFrameEndpoint; } & IFrameMessage<T>; export type IFrameSecureMessage<T extends IFrameMessageType = IFrameMessageType> = IFrameMessageWithSender<T> & { key: string; };
4,354
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/types/index.ts
export * from './dropdown'; export * from './icon'; export * from './form'; export * from './iframe'; export * from './notification';
4,355
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/types/notification.ts
import type { FormEntryPrompt, Item, SelectedItem } from '@proton/pass/types'; import type { IFrameAppService } from './iframe'; export enum NotificationAction { AUTOSAVE_PROMPT = 'AUTOSAVE_PROMPT', AUTOFILL_OTP_PROMPT = 'AUTOFILL_OTP_PROMPT', } export type NotificationActions = | { action: NotificationAction.AUTOSAVE_PROMPT; submission: FormEntryPrompt } | { action: NotificationAction.AUTOFILL_OTP_PROMPT; item: SelectedItem; hostname: string }; export type NotificationAutosaveRequestPayload = { item: Item<'login'>; submission: FormEntryPrompt }; export interface InjectedNotification extends IFrameAppService<NotificationActions> {}
4,356
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/utils/action-trap.ts
import type { Callback } from '@proton/pass/types'; export type HTMLElementWithActionTrap = HTMLInputElement & { preventAction?: boolean }; export const preventActions = (el: HTMLElementWithActionTrap) => (el.preventAction = true); export const shouldPreventActions = (el: HTMLElementWithActionTrap) => el.preventAction === true; export const allowActions = (el: HTMLElementWithActionTrap) => delete el.preventAction; export const withActionTrap = <F extends Callback>(el: HTMLElementWithActionTrap, fn: F) => (...args: Parameters<F>): ReturnType<F> => { preventActions(el); const result = fn(...args); allowActions(el); return result; };
4,357
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/utils/autofill.ts
/* eslint-disable deprecation/deprecation */ export type AutofillOptions = { paste?: boolean }; /* Autofilling is based on chromium's autofill service * strategy - references can be found here : * https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/core/exported/web_form_control_element.cc;l=181-202;drc=64b271ee7f3527374c718fe24383e087405ce520 * * Dispatched events need to bubble up as certain websites * attach their event listeners not directly on the input * elements (ie: account.google.com) */ export const createAutofill = (input: HTMLInputElement) => (data: string, options?: AutofillOptions) => { if (options?.paste) { input.focus(); const clipboardData = new DataTransfer(); clipboardData.setData('text/plain', data); const pasteEvent = new ClipboardEvent('paste', { bubbles: true, cancelable: true, clipboardData, }); input.dispatchEvent(new FocusEvent('focusin')); return input.dispatchEvent(pasteEvent); } const focused = input === document.activeElement; input.value = data; const events = [ !focused && new FocusEvent('focusin'), new KeyboardEvent('keydown', { bubbles: true }), new InputEvent('input', { data, bubbles: true }), new KeyboardEvent('keyup', { bubbles: true }), new KeyboardEvent('keypress', { bubbles: true }) /* support legacy websites */, !focused && new FocusEvent('blur'), ].filter(Boolean) as Event[]; events.forEach((event) => input.dispatchEvent(event)); };
4,358
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/content/utils/nodes.ts
import { isProcessed, selectFormCandidates, selectInputCandidates } from '@proton/pass/fathom'; import { invert } from '@proton/pass/utils/fp/predicates'; const unprocessed = invert(isProcessed); export const hasUnprocessedForms = () => selectFormCandidates().some(unprocessed); export const hasUnprocessedFields = (target?: Document | HTMLElement) => selectInputCandidates(target).some(unprocessed); export const isNodeOfInterest = (node: Node): node is HTMLElement => node instanceof HTMLInputElement || node instanceof HTMLFormElement || (node instanceof HTMLElement && hasUnprocessedFields(node));
4,359
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/pages
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/pages/onboarding/Onboarding.scss
@import '~@proton/styles/scss/lib'; body { overflow: auto !important; } .pass-onboarding--dot { inline-size: rem(24); block-size: rem(24); font-size: rem(11); } .pass-onboarding--heading { line-height: rem(42); } .pass-onboarding { background: transparent !important; } .pass-onboarding--gradient { position: fixed; background: radial-gradient( 110% 110% at 133.07% 133.41%, rgb(255 213 128 / 0.5) 0%, rgb(246 204 136 / 0.5) 6.25%, rgb(228 187 152 / 0.5) 18.23%, rgb(210 170 168 / 0.5) 29.17%, rgb(201 162 171 / 0.5) 34.37%, rgb(187 149 177 / 0.5) 45.31%, rgb(154 117 163 / 0.5) 58.33%, rgb(114 76 145 / 0.5) 72.4%, rgb(49 34 85 / 0.5) 89.58%, rgb(27 19 64 / 0.25) 100% ); block-size: 100%; inline-size: 100%; inset-block-start: 0; inset-inline-start: 0; z-index: -1; } .pass-onboarding--white-text { color: white; }
4,360
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/pages
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/pages/onboarding/Onboarding.tsx
import { Fragment, type VFC } from 'react'; import { HashRouter, Route, Switch } from 'react-router-dom'; import { ExtensionApp } from 'proton-pass-extension/lib/components/Extension/ExtensionApp'; import { InstallationSuccess } from './Views/InstallationSuccess'; import { ResumeSession } from './Views/ResumeSession'; import { Welcome } from './Views/Welcome'; import './Onboarding.scss'; export const Onboarding: VFC = () => ( <ExtensionApp endpoint="page"> {(ready, locale) => ready && ( <Fragment key={locale}> <HashRouter> <Switch> <Route path="/resume"> <ResumeSession /> </Route> <Route path="/success"> <InstallationSuccess /> </Route> <Route path="/welcome"> <Welcome /> </Route> </Switch> </HashRouter> </Fragment> ) } </ExtensionApp> );
4,361
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/pages
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/pages/onboarding/index.tsx
import ReactDOM from 'react-dom'; import '@proton/pass/styles/common.scss'; import { Onboarding } from './Onboarding'; const root = document.getElementById('root') as HTMLElement; ReactDOM.render(<Onboarding />, root);
4,362
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/pages/onboarding
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/pages/onboarding/Views/InstallationSuccess.scss
@import '~@proton/styles/scss/lib'; .pass-installation { &--dot { inline-size: rem(24); block-size: rem(24); font-size: rem(11); color: var(--background-invert); background: var(--primary); } &--connect-illustration { block-size: 160px !important; } &--white-separator { background-color: var(--text-weak); } }
4,363
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/pages/onboarding
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/pages/onboarding/Views/InstallationSuccess.tsx
import type { VFC } from 'react'; import { useEffect, useState } from 'react'; import { ExtensionHead } from 'proton-pass-extension/lib/components/Extension/ExtensionHead'; import { useRequestForkWithPermissions } from 'proton-pass-extension/lib/hooks/useRequestFork'; import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import { useNotifications } from '@proton/components'; import passBrandText from '@proton/pass/assets/protonpass-brand.svg'; import { SubTheme } from '@proton/pass/components/Layout/Theme/types'; import { chromeAPI } from '@proton/pass/lib/globals/browser'; import type { MaybeNull } from '@proton/pass/types'; import { FORK_TYPE } from '@proton/shared/lib/authentication/ForkInterface'; import { BRAND_NAME, PASS_APP_NAME } from '@proton/shared/lib/constants'; import './InstallationSuccess.scss'; const getSteps = () => [ { key: 'open', icon: '/assets/extension-menu.svg', description: c('Info').t`Open the Extensions menu`, }, { key: 'pin', icon: '/assets/extension-pin.svg', description: c('Info').t`Pin ${PASS_APP_NAME} to your toolbar`, }, { key: 'access', icon: '/assets/protonpass-icon.svg', description: c('Info').t`Click the icon to open it anytime.`, }, ]; const brandNameJSX = ( <img src={passBrandText} className="ml-2 h-custom" style={{ '--h-custom': '1.75rem' }} key="brand" alt="" /> ); export const InstallationSuccess: VFC = () => { const login = useRequestForkWithPermissions({ replace: true }); const [isPinned, setIsPinned] = useState<MaybeNull<boolean>>(null); const { createNotification } = useNotifications(); const nextStep = (): Promise<boolean> | true => BUILD_TARGET === 'chrome' ? chromeAPI.action .getUserSettings() .then((setting) => setting.isOnToolbar) .catch(() => true) : true; useEffect(() => { if (isPinned === false) { createNotification({ text: c('Error').t`Please pin the extension or select "Continue without pinning".`, type: 'error', showCloseButton: false, }); } }, [isPinned]); const handleNextStepClick = async () => { setIsPinned(null); setIsPinned(await nextStep()); }; const steps = getSteps(); return ( <> <ExtensionHead title={c('Title').t`Thank you for installing ${PASS_APP_NAME}`} /> <div className="pass-onboarding ui-prominent w-full min-h-custom mw" style={{ '--min-h-custom': '100vh' }}> <div className="m-auto p-14 color-norm flex flex-justify-center"> <div className="pass-onboarding--gradient"></div> <div className="flex flex-column"> <div className="flex flex-column"> <div className="pt-2 flex flex-align-items-center gap-2 mb-4"> { <img src="/assets/protonpass-icon.svg" className="h-custom" style={{ '--h-custom': '2.25rem' }} alt={PASS_APP_NAME} /> } <span>{brandNameJSX}</span> </div> <h1 className="pass-onboarding--white-text mt-4 mb-8 text-semibold">{c('Title') .jt`Welcome to your new password manager!`}</h1> </div> <div className="flex flex-align-items-center gap-2 mb-4"> <span className="text-bold">Step {isPinned ? 2 : 1} of 2</span> <hr className="pass-installation--white-separator my-2 flex flex-item-fluid-auto" /> </div> <div className="mx-auto flex flex-justify-center flex-nowrap flex-column lg:flex-row gap-12"> {!isPinned && ( <> <div className="flex flex-nowrap flex-column"> <h2 className="text-3xl pass-onboarding--white-text mb-4 text-bold"> {c('Title').jt`Pin the extension`} </h2> <h2 className="text-xl mb-5"> {c('Info').t`For easy access to your passwords and more.`} </h2> <div className="mb-1"> <ol className="unstyled m-0"> {steps.map(({ key, icon, description }, idx) => ( <li key={key} className="flex mb-5 flex-align-items-center"> <div className="pass-installation--dot rounded-50 text-center mr-3 relative" aria-hidden="true" > <span className="absolute absolute-center">{idx + 1}</span> </div> <div className="w-custom text-center mr-2" style={{ '--w-custom': '2.5rem' }} aria-hidden="true" > <img src={icon} className="h-custom" style={{ '--h-custom': '1.5rem' }} alt={BRAND_NAME} /> </div> <div className="flex-item-fluid text-left">{description}</div> </li> ))} </ol> </div> <Button icon pill size="large" shape="solid" color="norm" className="mt-5 mb-2" onClick={handleNextStepClick} aria-label={c('Action').t`Done`} > <span className="flex flex-justify-center px-4"> {' '} {c('Action').t`Done`} </span> </Button> {BUILD_TARGET === 'chrome' && ( <Button onClick={() => setIsPinned(true)} shape="ghost" aria-label={c('Action').t`Continue without pinning`} color="norm" > {c('Action').t`Continue without pinning`} </Button> )} </div> <div className="flex"> <img src="/assets/pin-tutorial.gif" alt="" width="325" /> </div> </> )} {isPinned && ( <> <div className={`${SubTheme.VIOLET} flex flex-nowrap flex-column`}> <h2 className="text-3xl pass-onboarding--white-text mb-4 text-bold"> {c('Title').jt`Connect your ${BRAND_NAME} Account`} </h2> <h2 className="text-xl mb-5"> {c('Info').t`Sign in or create an account to continue.`} </h2> <Button pill size="large" shape="solid" color="norm" className="mb-4" onClick={() => login()} aria-label={c('Action').t`Sign in`} > <span className="flex flex-justify-center px-4"> {c('Action').t`Connect your ${BRAND_NAME} Account`} </span> </Button> <Button pill size="large" shape="outline" color="weak" onClick={() => login(FORK_TYPE.SIGNUP)} aria-label={c('Action').t`Create an account`} > <span className="flex flex-justify-center px-4"> {c('Action').t`Create a ${BRAND_NAME} Account`} </span> </Button> </div> <div className="flex flex-justify-center flex-align-items-center"> <img src="assets/onboarding-connect-illustration.svg" alt="" className="pass-installation--connect-illustration" width="428" /> </div> </> )} </div> </div> </div> </div> </> ); };
4,364
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/pages/onboarding
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/pages/onboarding/Views/ResumeSession.tsx
import { type VFC, useEffect } from 'react'; import { SSO_URL } from 'proton-pass-extension/app/config'; import { CircleLoader } from '@proton/atoms/CircleLoader'; import { pageMessage, sendMessage } from '@proton/pass/lib/extension/message/send-message'; import browser from '@proton/pass/lib/globals/browser'; import { WorkerMessageType } from '@proton/pass/types'; import { wait } from '@proton/shared/lib/helpers/promise'; import noop from '@proton/utils/noop'; /* By-pass SSL error on browser start-up when working with staging. * In the startup event listener - when the extension's target API * is set to staging - there seems to be an error during the initial SSL * handshake (net:ERR_SSL_CLIENT_AUTH_CERT_NEEDED) */ const bypass = async () => { const tab = await browser.tabs.getCurrent().catch(noop); const tabId = tab?.id; if (!tab || !tabId) return; try { await wait(500); await fetch(SSO_URL); await sendMessage(pageMessage({ type: WorkerMessageType.WORKER_INIT, payload: { forceLock: true } })); } finally { void browser.tabs.remove(tabId); } }; export const ResumeSession: VFC = () => { useEffect(() => { void bypass(); }, []); return ( <div className="pass-lobby flex" style={{ height: '100vh' }}> <main className="w-full max-w-custom relative flex m-auto rounded-lg" style={{ '--max-w-custom': '30rem' }}> <div className="flex p-14 w-full flex-column flex-align-items-center gap-4"> <h3 className="">Signing you back in</h3> <CircleLoader size="large" className="color-primary" /> <em>Don't close this tab</em> </div> </main> </div> ); };
4,365
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/pages/onboarding
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/pages/onboarding/Views/Welcome.scss
@import '~@proton/styles/scss/lib'; .pass-welcome { &--onboarding-video { position: relative; padding-block-end: 48%; block-size: 0; inline-size: 100%; overflow: hidden; iframe { position: absolute; inset-block-start: 0; inset-inline-start: 0; inline-size: 100%; block-size: 100%; } } &--on-medium-default-grow { @include media('<medium') { flex: 1 1 auto !important; } } &--import-btn { outline: 1px solid var(--interaction-norm-major-2); } }
4,366
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/pages/onboarding
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/pages/onboarding/Views/Welcome.tsx
import { type VFC, useState } from 'react'; import { ExtensionHead } from 'proton-pass-extension/lib/components/Extension/ExtensionHead'; import { ExtensionContext } from 'proton-pass-extension/lib/context/extension-context'; import { useWorkerStateEvents } from 'proton-pass-extension/lib/hooks/useWorkerStateEvents'; import { c } from 'ttag'; import { Href } from '@proton/atoms'; import { ButtonLike } from '@proton/atoms/Button'; import accountSetupImg from '@proton/pass/assets/protonpass-account.svg'; import passBrandText from '@proton/pass/assets/protonpass-brand.svg'; import { SubTheme } from '@proton/pass/components/Layout/Theme/types'; import '@proton/pass/components/Spotlight/Spotlight.scss'; import { SpotlightContent } from '@proton/pass/components/Spotlight/SpotlightContent'; import { PASS_ANDROID_URL, PASS_IOS_URL, PASS_VIDEO_URL } from '@proton/pass/constants'; import { clientReady } from '@proton/pass/lib/client'; import { pageMessage, sendMessage } from '@proton/pass/lib/extension/message'; import { OnboardingMessage, WorkerMessageType } from '@proton/pass/types'; import { PASS_APP_NAME } from '@proton/shared/lib/constants'; import appStoreSvg from '@proton/styles/assets/img/illustrations/app-store.svg'; import playStoreSvg from '@proton/styles/assets/img/illustrations/play-store.svg'; import clsx from '@proton/utils/clsx'; import './Welcome.scss'; const brandNameJSX = ( <img src={passBrandText} className="ml-2 h-custom" style={{ '--h-custom': '1.75rem' }} key="brand" alt="" /> ); export const Welcome: VFC = () => { const { tabId, endpoint } = ExtensionContext.get(); const [pendingAccess, setPendingAccess] = useState(false); useWorkerStateEvents({ endpoint, tabId, messageFactory: pageMessage, onWorkerStateChange: ({ status }) => { if (clientReady(status)) { void sendMessage.onSuccess( pageMessage({ type: WorkerMessageType.ONBOARDING_REQUEST }), async ({ message }) => setPendingAccess(message === OnboardingMessage.PENDING_SHARE_ACCESS) ); } }, }); return ( <> <ExtensionHead title={c('Title').t`Thank you for installing ${PASS_APP_NAME}`} /> <div className="pass-onboarding ui-standard w-full min-h-custom" style={{ '--min-h-custom': '100vh' }}> <div className="m-auto p-14 color-norm flex flex-justify-center"> <div className="pass-onboarding--gradient"></div> <div className="flex flex-column max-w-custom" style={{ '--max-w-custom': '64rem' }}> <div className="flex flex-align-items-center gap-2 mb-5"> { <img src="/assets/protonpass-icon.svg" className="h-custom" style={{ '--h-custom': '2.25rem' }} alt={PASS_APP_NAME} /> } <span>{brandNameJSX}</span> </div> <div className={clsx('pass-spotlight-panel', !pendingAccess && 'pass-spotlight-panel--hidden')}> {pendingAccess && ( <SpotlightContent className="mb-6" id="pending" icon={() => ( <img className="h-custom" style={{ '--h-custom': '4rem' }} src={accountSetupImg} alt="" /> )} message={c('Info').t`For security reason, your access needs to be confirmed`} title={c('Info').t`Pending access to the shared data`} /> )} </div> <div className="flex gap-14"> {/* left section */} <div className="flex pass-welcome--on-medium-default-grow" style={{ flex: 2 }}> <div className="flex flex-column flex-item-fluid"> <h1 className="text-xl pass-onboarding--white-text mb-4 text-bold"> <span className="text-rg">{c('Title') .jt`The extension is now ready to use.`}</span> </h1> <h3 className="mb-5 text-xl"> {c('Info') .t`Here you will find all the necessary information to get you started.`} </h3> <div className="pass-welcome--onboarding-video rounded-xl"> <iframe src={PASS_VIDEO_URL} title={c('Info').t`Discover ${PASS_APP_NAME} Youtube Video`} allowFullScreen /> </div> </div> </div> {/* right section */} <div className="flex pass-welcome--on-medium-default-grow" style={{ flex: 1 }}> <div className="flex flex-column flex-item-fluid gap-12"> {/* right section upper subsection */} <div className="flex flex-column gap-5"> <h1 className="text-xl pass-onboarding--white-text text-bold"> <span className="text-rg">{c('Title') .jt`Switching to ${PASS_APP_NAME}?`}</span> </h1> <img src="/assets/onboarding-import.png" alt="" /> <div className="text-xl"> {c('Info').t`Easily import your existing passwords into ${PASS_APP_NAME}.`} </div> <ButtonLike as="a" href="/settings.html#/import" className={`w-full ${SubTheme.VIOLET} pass-welcome--import-btn`} pill size="large" shape="solid" color="norm" aria-label={c('Action').t`Import your passwords`} > {c('Action').t`Import your passwords`} </ButtonLike> </div> {/* right section lower subsection */} <div className="flex flex-column gap-5"> <h1 className="text-xl pass-onboarding--white-text text-bold"> <span className="text-rg">{c('Title').jt`Get the mobile apps`}</span> </h1> <div className="text-xl">{c('Info') .t`Access your passwords on the go with our mobile apps.`}</div> <div className="flex gap-3 flex-nowrap"> <Href href={PASS_ANDROID_URL}> <img className="h-custom" style={{ '--h-custom': '2.5rem' }} src={playStoreSvg} alt="Play Store" /> </Href> <Href href={PASS_IOS_URL}> <img className="h-custom" style={{ '--h-custom': '2.5rem ' }} src={appStoreSvg} alt="App Store" /> </Href> </div> </div> </div> </div> </div> </div> </div> </div> </> ); };
4,367
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/pages
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/pages/settings/Settings.scss
@import '~@proton/styles/scss/lib'; @import '~@proton/pass/styles/common'; body { overflow: auto !important; block-size: 100%; } .pass-settings { max-inline-size: 45rem; } /* override checkboxes */ .checkbox-container { gap: 1rem; .checkbox-fakecheck { margin-inline: 0.625rem !important; } }
4,368
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/pages
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/pages/settings/Settings.tsx
import type { VFC } from 'react'; import { type ComponentProps, type FC, useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { Provider as ReduxProvider, useSelector } from 'react-redux'; import { HashRouter, Route, Switch, useHistory } from 'react-router-dom'; import { APP_VERSION } from 'proton-pass-extension/app/config'; import { ExtensionApp } from 'proton-pass-extension/lib/components/Extension/ExtensionApp'; import { ExtensionConnect } from 'proton-pass-extension/lib/components/Extension/ExtensionConnect'; import { ExtensionHead } from 'proton-pass-extension/lib/components/Extension/ExtensionHead'; import { ExtensionContext } from 'proton-pass-extension/lib/context/extension-context'; import { useExtensionConnectContext } from 'proton-pass-extension/lib/hooks/useExtensionConnectContext'; import { createClientStore } from 'proton-pass-extension/lib/store/client-store'; import { c, msgid } from 'ttag'; import { Avatar } from '@proton/atoms/Avatar'; import { Icon, Tabs, useNotifications } from '@proton/components'; import { UpgradeButton } from '@proton/pass/components/Layout/Button/UpgradeButton'; import { LockConfirmContextProvider } from '@proton/pass/components/Lock/LockConfirmContextProvider'; import { pageMessage } from '@proton/pass/lib/extension/message'; import { selectPassPlan, selectPlanDisplayName, selectTrialDaysRemaining, selectUser, } from '@proton/pass/store/selectors'; import { AppStatus, type Unpack, WorkerMessageType, type WorkerMessageWithSender } from '@proton/pass/types'; import { UserPassPlan } from '@proton/pass/types/api/plan'; import { PASS_APP_NAME } from '@proton/shared/lib/constants'; import { Developer } from './Views/Developer'; import { Export } from './Views/Export'; import { General } from './Views/General'; import { Import } from './Views/Import'; import { Security } from './Views/Security'; import { Support } from './Views/Support'; import './Settings.scss'; type Tab = Unpack<Exclude<ComponentProps<typeof Tabs>['tabs'], undefined>>; const getSettingsTabs: () => (Tab & { pathname: string })[] = () => { const tabs = [ { pathname: '/', title: c('Label').t`General`, content: <General />, }, { pathname: '/security', title: c('Label').t`Security`, content: <Security />, }, { pathname: '/import', title: c('Label').t`Import`, content: <Import />, }, { pathname: '/export', title: c('Label').t`Export`, content: <Export />, }, { pathname: '/support', title: c('Label').t`Support`, content: <Support />, }, ]; if (ENV === 'development') { tabs.push({ pathname: '/dev', title: 'Developer', content: <Developer />, }); } return tabs; }; const SettingsTabs: FC<{ pathname: string }> = ({ pathname }) => { const context = useExtensionConnectContext(); const user = useSelector(selectUser); const passPlan = useSelector(selectPassPlan); const planDisplayName = useSelector(selectPlanDisplayName); const trialDaysLeft = useSelector(selectTrialDaysRemaining); const tabs = useMemo(getSettingsTabs, []); const pathnameToIndex = (pathname: string) => { const idx = tabs.findIndex((tab) => tab.pathname === pathname); return idx !== -1 ? idx : 0; }; const history = useHistory(); const [activeTab, setActiveTab] = useState<number>(pathnameToIndex(pathname)); const handleOnChange = (nextTab: number) => history.push(tabs[nextTab].pathname); useEffect(() => { setActiveTab(pathnameToIndex(pathname)); }, [pathname]); if (context.state.loggedIn) { return ( <> <div className="mb-8"> <div className="flex w-full flex-justify-space-between flex-align-items-start"> <div className="flex flex-align-items-start"> <Avatar className="mr-2 mt-1">{user?.DisplayName?.toUpperCase()?.[0]}</Avatar> <span> <span className="block text-semibold text-ellipsis">{user?.DisplayName}</span> <span className="block text-sm text-ellipsis">{user?.Email}</span> <span className="block color-weak text-sm text-italic">{planDisplayName}</span> </span> </div> <div className="flex flex-align-items-end flex-column"> {passPlan !== UserPassPlan.PLUS && ( <> <span className="block mb-1"> {planDisplayName} <span className="color-weak text-italic text-sm"> {' '} {trialDaysLeft && `(${c('Info').ngettext( msgid`${trialDaysLeft} day left`, `${trialDaysLeft} days left`, trialDaysLeft )})`} </span> </span> <UpgradeButton inline /> </> )} </div> </div> </div> <Tabs className="w-full" contentClassName="p-0" navContainerClassName="mb-6" onChange={handleOnChange} tabs={tabs} value={activeTab} /> <div className="mt-auto"> <hr /> <span className="block text-sm color-weak text-center"> {PASS_APP_NAME} v{APP_VERSION} </span> </div> </> ); } return ( <div className="flex flex-column flex-align-items-center flex-justify-center my-auto"> <Icon name="lock-filled" size={42} className="mb-4" /> {context.state.status === AppStatus.LOCKED && ( <> <span className="block color-norm">{c('Info').t`Your ${PASS_APP_NAME} session is locked`}</span> <span className="block text-sm color-weak">{c('Info') .t`Unlock it with your PIN to access the settings`}</span> </> )} </div> ); }; const SettingsApp: VFC = () => { const { createNotification } = useNotifications(); const handleWorkerMessage = useCallback((message: WorkerMessageWithSender) => { if (message.type === WorkerMessageType.NOTIFICATION && message.payload.notification.endpoint === 'page') { createNotification(message.payload.notification); } }, []); return ( <HashRouter> <ExtensionConnect endpoint="page" messageFactory={pageMessage} onWorkerMessage={handleWorkerMessage}> <div className="pass-settings flex flex-column ui-standard w-full p-4 mx-auto bg-weak min-h-custom" style={{ '--min-h-custom': '100vh' }} > <Switch> <Route render={({ location: { pathname } }) => ( <LockConfirmContextProvider> <SettingsTabs pathname={pathname} /> </LockConfirmContextProvider> )} /> </Switch> </div> </ExtensionConnect> </HashRouter> ); }; export const Settings: VFC = () => { const store = useRef<ReturnType<typeof createClientStore>>(); return ( <> <ExtensionApp endpoint="page"> {(ready, locale) => ready && ( <ReduxProvider store={(() => store.current ?? (store.current = createClientStore('page', ExtensionContext.get().tabId)))()} > <ExtensionHead title={c('Title').t`${PASS_APP_NAME} Settings`} /> <SettingsApp key={locale} /> </ReduxProvider> ) } </ExtensionApp> </> ); };
4,369
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/pages
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/pages/settings/index.tsx
import ReactDOM from 'react-dom'; import '@proton/pass/styles/common.scss'; import sentry from '@proton/shared/lib/helpers/sentry'; import * as config from '../../config'; import { Settings } from './Settings'; sentry({ config, sentryConfig: { host: new URL(config.API_URL).host, release: config.APP_VERSION, environment: `browser-pass::settings`, }, ignore: () => false, denyUrls: [], }); const root = document.getElementById('root') as HTMLElement; ReactDOM.render(<Settings />, root);
4,370
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/pages/settings
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/pages/settings/Views/Developer.tsx
import { type VFC } from 'react'; import { Button } from '@proton/atoms/Button'; import Icon from '@proton/components/components/icon/Icon'; import { pageMessage, sendMessage } from '@proton/pass/lib/extension/message'; import { WorkerMessageType } from '@proton/pass/types'; import { SettingsPanel } from '../../../../lib/components/Settings/SettingsPanel'; import { DropdownDebug } from '../../../../lib/components/Settings/debug/DropdownDebug'; import { NotificationDebug } from '../../../../lib/components/Settings/debug/NotificationDebug'; export const Developer: VFC = () => { return ( <> <SettingsPanel title="Extension triggers"> <Button icon shape="ghost" className="w-full" onClick={() => sendMessage( pageMessage({ type: WorkerMessageType.DEBUG, payload: { debug: 'update_trigger' }, }) ) } > <div className="flex flex-align-items-center flex flex-align-items-center"> <Icon name="brand-chrome" className="mr-2" /> <span className="flex-item-fluid text-left">Trigger update</span> <span className="text-xs color-weak">Triggers a fake update (keep popup opened)</span> </div> </Button> <Button icon shape="ghost" className="w-full" onClick={() => sendMessage( pageMessage({ type: WorkerMessageType.DEBUG, payload: { debug: 'storage_full' }, }) ) } > <div className="flex flex-align-items-center flex flex-align-items-center"> <Icon name="drive" className="mr-2" /> <span className="flex-item-fluid text-left">Trigger full disk</span> <span className="text-xs color-weak">Triggers a fake disk full event (open popup after)</span> </div> </Button> </SettingsPanel> <DropdownDebug /> <NotificationDebug /> </> ); };
4,371
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/pages/settings
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/pages/settings/Views/Export.tsx
import type { FC } from 'react'; import { SettingsPanel } from 'proton-pass-extension/lib/components/Settings/SettingsPanel'; import { c } from 'ttag'; import { Exporter } from '@proton/pass/components/Export/Exporter'; export const Export: FC = () => { return ( <SettingsPanel title={c('Label').t`Export`}> <Exporter /> </SettingsPanel> ); };
4,372
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/pages/settings
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/pages/settings/Views/General.tsx
import { type VFC } from 'react'; import { ApplicationLogs } from 'proton-pass-extension/lib/components/Settings/ApplicationLogs'; import { Behaviors } from 'proton-pass-extension/lib/components/Settings/Behaviors'; import { Locale } from 'proton-pass-extension/lib/components/Settings/Locale'; export const General: VFC = () => { return ( <> <Locale /> <Behaviors /> <ApplicationLogs /> </> ); };
4,373
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/pages/settings
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/pages/settings/Views/Import.tsx
import { type VFC, useCallback, useRef, useState } from 'react'; import { Provider as ReduxProvider, useStore } from 'react-redux'; import { Form, FormikProvider } from 'formik'; import { SettingsPanel } from 'proton-pass-extension/lib/components/Settings/SettingsPanel'; import { c, msgid } from 'ttag'; import { Button } from '@proton/atoms/Button'; import { useNotifications } from '@proton/components'; import { ImportForm } from '@proton/pass/components/Import/ImportForm'; import { ImportProgress } from '@proton/pass/components/Import/ImportProgress'; import { ImportVaultsPickerModal } from '@proton/pass/components/Import/ImportVaultsPickerModal'; import { type UseImportFormBeforeSubmit, type UseImportFormBeforeSubmitValue, useImportForm, } from '@proton/pass/hooks/useImportForm'; import type { ImportPayload } from '@proton/pass/lib/import/types'; import { PROVIDER_INFO_MAP } from '@proton/pass/lib/import/types'; import { importItemsRequest } from '@proton/pass/store/actions/requests'; import type { MaybeNull } from '@proton/pass/types'; import { pipe, tap } from '@proton/pass/utils/fp/pipe'; import { PASS_APP_NAME } from '@proton/shared/lib/constants'; export const Import: VFC = () => { const store = useStore(); const { createNotification } = useNotifications(); const [importData, setImportData] = useState<MaybeNull<ImportPayload>>(null); const beforeSubmitResolver = useRef<(value: UseImportFormBeforeSubmitValue) => void>(); const beforeSubmit = useCallback<UseImportFormBeforeSubmit>( async (payload) => new Promise((resolve) => { setImportData(payload); beforeSubmitResolver.current = pipe( resolve, tap(() => { beforeSubmitResolver.current = undefined; setImportData(null); }) ); }), [] ); const { form, dropzone, busy, result } = useImportForm({ beforeSubmit, onSubmit: (payload) => { const total = payload.vaults.reduce((count, vault) => count + vault.items.length, 0); createNotification({ key: importItemsRequest(), showCloseButton: false, expiration: -1, text: ( <ReduxProvider store={store}> <ImportProgress total={total} /> </ReduxProvider> ), }); }, }); const showResultDetails = (result?.ignored.length ?? 0) > 0 || (result?.warnings?.length ?? 0) > 0; const totalImportedItems = result?.total ?? 0; const totalItems = totalImportedItems + (result?.ignored.length ?? 0); return ( <> <SettingsPanel title={c('Label').t`Import`} subTitle={c('Info') .t`To migrate data from another password manager, go to the password manager, export your data, then upload it to ${PASS_APP_NAME}. Once your data has been imported, delete the exported file.`} > <FormikProvider value={form}> <Form className="modal-two-dialog-container"> <ImportForm form={form} dropzone={dropzone} busy={busy} /> {form.values.provider && ( <Button className="mt-2" type="submit" disabled={busy || !form.isValid} loading={busy} color="norm" > {busy ? c('Action').t`Importing` : c('Action').t`Import`} </Button> )} </Form> </FormikProvider> {importData !== null && ( <ImportVaultsPickerModal onClose={() => beforeSubmitResolver.current?.({ ok: false })} payload={importData} onSubmit={(payload) => beforeSubmitResolver?.current?.( payload.vaults.length === 0 ? { ok: false } : { ok: true, payload } ) } /> )} </SettingsPanel> {result && ( <SettingsPanel title={c('Label').t`Latest import`}> <div className="flex flex-column gap-y-1 text-sm"> <div> <span className="color-weak">{c('Label').t`Imported from : `}</span> <span className="rounded bg-primary px-1 user-select-none"> {PROVIDER_INFO_MAP[result.provider].title} </span> </div> <div> <span className="color-weak">{c('Label').t`Imported on : `}</span> <span>{new Date(result.importedAt * 1000).toLocaleString()}</span> </div> <div> <span className="color-weak">{c('Label').t`Total items : `}</span> <span> {c('Info').ngettext(msgid`${totalItems} item`, `${totalItems} items`, totalItems)} </span> </div> <div> <span className="color-weak">{c('Label').t`Total imported items : `}</span> <span> {c('Info').ngettext( msgid`${totalImportedItems} item`, `${totalImportedItems} items`, totalImportedItems )} </span> </div> {showResultDetails && ( <div className="bg-norm rounded-sm p-3 mt-2"> {result.ignored.length > 0 && ( <span className="mb-2 block"> {c('Info').ngettext( msgid`The following ${result.ignored.length} item could not be imported:`, `The following ${result.ignored.length} items could not be imported:`, result.ignored.length )} </span> )} <div className="color-weak scroll-if-needed" style={{ maxHeight: 150 }}> {result.ignored.map((description, idx) => ( <span className="block" key={`ignored-${idx}`}> {description} </span> ))} {result.warnings?.map((warning, idx) => ( <span className="block" key={`warning-${idx}`}> {warning} </span> ))} </div> </div> )} <div className="mt-2"> {c('Info').t`To review your imported data, click on the Pass icon in your browser toolbar.`} </div> </div> </SettingsPanel> )} </> ); };
4,374
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/pages/settings
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/pages/settings/Views/Security.tsx
import { type VFC, useState } from 'react'; import { useSelector } from 'react-redux'; import { SettingsPanel } from 'proton-pass-extension/lib/components/Settings/SettingsPanel'; import { c } from 'ttag'; import { Checkbox } from '@proton/components'; import { useSessionLockConfirmContext } from '@proton/pass/components/Lock/LockConfirmContextProvider'; import { LockCreate } from '@proton/pass/components/Lock/LockCreate'; import { LockTTLUpdate } from '@proton/pass/components/Lock/LockTTLUpdate'; import { useActionRequest } from '@proton/pass/hooks/useActionRequest'; import { sessionLockDisableIntent, sessionLockEnableIntent } from '@proton/pass/store/actions'; import { sessionLockDisableRequest, sessionLockEnableRequest } from '@proton/pass/store/actions/requests'; import { selectSessionLockSettings } from '@proton/pass/store/selectors'; import { PASS_APP_NAME } from '@proton/shared/lib/constants'; export const Security: VFC = () => { const [lockCreationModalOpened, setLockCreationModalOpened] = useState(false); const { confirmPin } = useSessionLockConfirmContext(); const { sessionLockRegistered, sessionLockTTL } = useSelector(selectSessionLockSettings); const enableLock = useActionRequest({ action: sessionLockEnableIntent, initialRequestId: sessionLockEnableRequest(), }); const disableLock = useActionRequest({ action: sessionLockDisableIntent, initialRequestId: sessionLockDisableRequest(), }); const loading = enableLock.loading || disableLock.loading; const handleSessionLockToggle = async () => sessionLockRegistered ? confirmPin({ onSubmit: (pin) => disableLock.dispatch({ pin }), assistiveText: c('Info').t`Please confirm your PIN code in order to unregister your current lock. ${PASS_APP_NAME} will then never lock.`, }) : setLockCreationModalOpened(true); return ( <SettingsPanel title={c('Label').t`Session locking`}> <Checkbox className="mb-4" checked={sessionLockRegistered} onChange={handleSessionLockToggle} loading={loading} > <span> {c('Label').t`Auto-lock ${PASS_APP_NAME}`} <span className="block color-weak text-sm">{c('Info') .t`Access to ${PASS_APP_NAME} will require a PIN code to unlock your session`}</span> </span> </Checkbox> <LockCreate opened={lockCreationModalOpened} onClose={() => setLockCreationModalOpened(false)} onSubmit={enableLock.dispatch} /> <LockTTLUpdate ttl={sessionLockTTL} disabled={!sessionLockRegistered || loading} onChange={enableLock.dispatch} /> </SettingsPanel> ); };
4,375
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/pages/settings
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/pages/settings/Views/Support.tsx
import { type VFC } from 'react'; import { ReportAProblem } from 'proton-pass-extension/lib/components/Settings/ReportAProblem'; export const Support: VFC = () => { return <ReportAProblem />; };
4,376
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/popup/App.tsx
import type { VFC } from 'react'; import { ItemEffects } from 'proton-pass-extension/lib/components/Context/Items/ItemEffects'; import { ItemsFilteringContext, ItemsFilteringContextProvider, } from 'proton-pass-extension/lib/components/Context/Items/ItemsFilteringContext'; import { NavigationContextProvider } from 'proton-pass-extension/lib/components/Context/Navigation/NavigationContext'; import { usePopupContext } from 'proton-pass-extension/lib/hooks/usePopupContext'; import { InviteContextProvider } from '@proton/pass/components/Invite/InviteContextProvider'; import { PasswordContextProvider } from '@proton/pass/components/PasswordGenerator/PasswordContext'; import { SpotlightContextProvider } from '@proton/pass/components/Spotlight/SpotlightContext'; import { Lobby } from './Views/Lobby/Lobby'; import { Main } from './Views/Main'; export const App: VFC = () => { const { state, initialized } = usePopupContext(); /* navigate away from the `Lobby` only when the worker * is in a ready & logged in state and the popup context * is initialized (initial popup state was resolved) */ return state.loggedIn && initialized ? ( <NavigationContextProvider> <ItemsFilteringContextProvider> <ItemsFilteringContext.Consumer> {({ setShareId }) => ( <InviteContextProvider onVaultCreated={setShareId}> <ItemEffects /> <PasswordContextProvider initial={state.initial.passwordOptions}> <SpotlightContextProvider> <Main /> </SpotlightContextProvider> </PasswordContextProvider> </InviteContextProvider> )} </ItemsFilteringContext.Consumer> </ItemsFilteringContextProvider> </NavigationContextProvider> ) : ( <Lobby /> ); };
4,377
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/popup/Popup.scss
@import '~@proton/pass/styles/common'; @import '~@proton/styles/scss/lib/config'; body { // Extensions seem to have injected style sheets // by default which override the font-family to // "system-ui" and "font-size: 75%" font-family: var(--optional-font-family, 'Inter', #{$fallback-fonts}); }
4,378
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/popup/Popup.tsx
import { useRef } from 'react'; import { Provider as ReduxProvider } from 'react-redux'; import { MemoryRouter as Router } from 'react-router-dom'; import { PopupContextProvider } from 'proton-pass-extension/lib/components/Context/Popup/PopupContext'; import { ExtensionApp } from 'proton-pass-extension/lib/components/Extension/ExtensionApp'; import { ExtensionError } from 'proton-pass-extension/lib/components/Extension/ExtensionError'; import { ExtensionContext } from 'proton-pass-extension/lib/context/extension-context'; import { usePopupSizeSurgery } from 'proton-pass-extension/lib/hooks/usePopupSizeSurgery'; import { createClientStore } from 'proton-pass-extension/lib/store/client-store'; import { ErrorBoundary } from '@proton/components'; import { App } from './App'; import './Popup.scss'; const Popup = () => { usePopupSizeSurgery(); const store = useRef<ReturnType<typeof createClientStore>>(); return ( <ExtensionApp endpoint="popup"> {(ready, locale) => ready && ( <ReduxProvider store={(() => store.current ?? (store.current = createClientStore('popup', ExtensionContext.get().tabId)))()} > <Router> <ErrorBoundary component={<ExtensionError />}> <PopupContextProvider> <App key={locale} /> </PopupContextProvider> </ErrorBoundary> </Router> </ReduxProvider> ) } </ExtensionApp> ); }; export default Popup;
4,379
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/popup/index.tsx
import ReactDOM from 'react-dom'; import sentry from '@proton/shared/lib/helpers/sentry'; import * as config from '../../app/config'; import Popup from './Popup'; sentry({ config, sentryConfig: { host: new URL(config.API_URL).host, release: config.APP_VERSION, environment: `browser-pass::popup`, }, ignore: () => false, denyUrls: [], }); const root = document.querySelector('.app-root') as HTMLElement; ReactDOM.render(<Popup />, root);
4,380
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/popup
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/popup/Views/Main.scss
@import '~@proton/styles/scss/lib';
4,381
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/popup
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/popup/Views/Main.tsx
import { type VFC, useEffect } from 'react'; import { Route, Switch } from 'react-router-dom'; import { useNotifications } from '@proton/components/hooks'; import { Content } from '@proton/pass/components/Layout/Section/Content'; import { SubSidebar } from '@proton/pass/components/Layout/Section/SubSidebar'; import { Header } from './Header/Header'; import { ItemEditContainer } from './Item/ItemEditContainer'; import { ItemNewContainer } from './Item/ItemNewContainer'; import { ItemViewContainer } from './Item/ItemViewContainer'; import { ItemsList } from './Sidebar/ItemsList'; import { TrashItemsList } from './Sidebar/TrashItemsList'; import './Main.scss'; export const Main: VFC = () => { const { clearNotifications } = useNotifications(); useEffect(() => () => clearNotifications(), []); return ( <main key="main" id="main" className="flex flex-column flex-nowrap w-full h-full overflow-hidden anime-fade-in" style={{ '--anime-delay': '50ms' }} > <Header /> <div className="flex flex-align-items-center flex-justify-center flex-nowrap w-full h-full"> <SubSidebar> <Switch> <Route path="/trash"> <TrashItemsList /> </Route> <Route> <ItemsList /> </Route> </Switch> </SubSidebar> <Content> <Switch> <Route exact path={['/share/:shareId/item/:itemId', '/trash/share/:shareId/item/:itemId']}> <ItemViewContainer /> </Route> <Route exact path="/share/:shareId/item/:itemId/edit"> <ItemEditContainer /> </Route> <Route exact path="/item/new/:itemType"> <ItemNewContainer /> </Route> </Switch> </Content> </div> </main> ); };
4,382
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/popup/Views
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/popup/Views/Header/Header.tsx
import { type VFC } from 'react'; import { useDispatch } from 'react-redux'; import { useHistory } from 'react-router-dom'; import { vaultDeletionEffect } from 'proton-pass-extension/lib/components/Context/Items/ItemEffects'; import { useItemsFilteringContext } from 'proton-pass-extension/lib/hooks/useItemsFilteringContext'; import { usePopupContext } from 'proton-pass-extension/lib/hooks/usePopupContext'; import { useSpotlightEffect } from 'proton-pass-extension/lib/hooks/useSpotlightEffect'; import { Header as HeaderComponent } from '@proton/components'; import { SearchBar } from '@proton/pass/components/Item/Search/SearchBar'; import { ItemQuickActions } from '@proton/pass/components/Menu/Item/ItemQuickActions'; import { SpotlightContent } from '@proton/pass/components/Spotlight/SpotlightContent'; import { useSpotlightContext } from '@proton/pass/components/Spotlight/SpotlightContext'; import { VaultActionsProvider } from '@proton/pass/components/Vault/VaultActionsProvider'; import { passwordSave } from '@proton/pass/store/actions/creators/pw-history'; import type { ItemType } from '@proton/pass/types'; import { uniqueId } from '@proton/pass/utils/string/unique-id'; import { getEpoch } from '@proton/pass/utils/time/get-epoch'; import clsx from '@proton/utils/clsx'; import { MenuDropdown } from './MenuDropdown'; export const Header: VFC = () => { const { ready, context } = usePopupContext(); const history = useHistory(); const filtering = useItemsFilteringContext(); const { search, shareId, sort, type, setSearch } = filtering; const dispatch = useDispatch(); const onVaultDeleted = (shareId: string) => vaultDeletionEffect(shareId, filtering); const onVaultCreated = filtering.setShareId; const onNewItem = (type: ItemType) => { /* Trick to be able to return to the initial route using * history.goBack() if user switches from item creation * routes for multiple subsequent item types. */ const shouldReplace = history.location.pathname.includes('/item/new/'); history[shouldReplace ? 'replace' : 'push'](`/item/new/${type}`); }; const onPasswordGenerated = (password: string) => { const { domain, subdomain, hostname } = context?.url ?? {}; const url = subdomain ?? domain ?? hostname ?? null; dispatch(passwordSave({ createTime: getEpoch(), id: uniqueId(), origin: url, value: password })); }; const spotlight = useSpotlightContext(); const hideSpotlight = !spotlight.state.open || spotlight.state.pendingShareAccess || spotlight.state.upselling; useSpotlightEffect(); return ( <VaultActionsProvider onVaultCreated={onVaultCreated} onVaultDeleted={onVaultDeleted}> <HeaderComponent className="border-bottom h-auto p-2"> <div className="flex flex-align-items-center gap-x-2 w-full"> <MenuDropdown /> <SearchBar disabled={!ready} filters={{ search, selectedShareId: shareId, sort, type }} onChange={setSearch} /> <ItemQuickActions onNewItem={onNewItem} onPasswordGenerated={onPasswordGenerated} /> <div className="flex-item-fluid-auto w-full"> <div className={clsx('pass-spotlight-panel', hideSpotlight && 'pass-spotlight-panel--hidden')}> {spotlight.state.message && <SpotlightContent {...spotlight.state.message} />} </div> </div> </div> </HeaderComponent> </VaultActionsProvider> ); };
4,383
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/popup/Views
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/popup/Views/Header/MenuDropdown.tsx
import { type VFC } from 'react'; import { useSelector } from 'react-redux'; import { useHistory } from 'react-router-dom'; import { useExpandPopup } from 'proton-pass-extension/lib/hooks/useExpandPopup'; import { useItemsFilteringContext } from 'proton-pass-extension/lib/hooks/useItemsFilteringContext'; import { useNavigationContext } from 'proton-pass-extension/lib/hooks/useNavigationContext'; import { useOpenSettingsTab } from 'proton-pass-extension/lib/hooks/useOpenSettingsTab'; import { usePopupContext } from 'proton-pass-extension/lib/hooks/usePopupContext'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import type { DropdownProps } from '@proton/components'; import { Collapsible, CollapsibleContent, CollapsibleHeader, CollapsibleHeaderIconButton, Dropdown, DropdownMenu, DropdownSizeUnit, Icon, usePopperAnchor, } from '@proton/components'; import { UpgradeButton } from '@proton/pass/components/Layout/Button/UpgradeButton'; import { DropdownMenuButton } from '@proton/pass/components/Layout/Dropdown/DropdownMenuButton'; import { Submenu } from '@proton/pass/components/Menu/Submenu'; import { VaultMenu } from '@proton/pass/components/Menu/Vault/VaultMenu'; import { useVaultActions } from '@proton/pass/components/Vault/VaultActionsProvider'; import { VaultIcon } from '@proton/pass/components/Vault/VaultIcon'; import { useMenuItems } from '@proton/pass/hooks/useMenuItems'; import { selectHasRegisteredLock, selectPassPlan, selectPlanDisplayName, selectShare, selectUser, } from '@proton/pass/store/selectors'; import type { ShareType } from '@proton/pass/types'; import { UserPassPlan } from '@proton/pass/types/api/plan'; import { VaultColor } from '@proton/pass/types/protobuf/vault-v1'; import { withTap } from '@proton/pass/utils/fp/pipe'; import clsx from '@proton/utils/clsx'; const DROPDOWN_SIZE: NonNullable<DropdownProps['size']> = { height: DropdownSizeUnit.Dynamic, maxHeight: '30em', width: `22em`, }; export const MenuDropdown: VFC = () => { const history = useHistory(); const { lock, logout, ready, expanded } = usePopupContext(); const { inTrash, unselectItem } = useNavigationContext(); const { shareId, setSearch, setShareId } = useItemsFilteringContext(); const vaultActions = useVaultActions(); const vault = useSelector(selectShare<ShareType.Vault>(shareId)); const passPlan = useSelector(selectPassPlan); const planDisplayName = useSelector(selectPlanDisplayName); const user = useSelector(selectUser); const canLock = useSelector(selectHasRegisteredLock); const openSettings = useOpenSettingsTab(); const expandPopup = useExpandPopup(); const { anchorRef, isOpen, toggle, close } = usePopperAnchor<HTMLButtonElement>(); const menu = useMenuItems({ onAction: close }); const withClose = withTap(close); const onVaultSelect = (selected: string) => { unselectItem(); setSearch(''); switch (selected) { case 'all': case 'trash': setShareId(null); return history.push(`/${selected === 'trash' ? 'trash' : ''}`); default: { setShareId(selected); return history.push(`/share/${selected}`); } } }; return ( <> <nav> <Button icon shape="solid" color="weak" pill ref={anchorRef} onClick={toggle} size="small" title={isOpen ? c('Action').t`Close navigation` : c('Action').t`Open navigation`} > <VaultIcon className="flex-item-noshrink" size={16} color={inTrash ? VaultColor.COLOR_UNSPECIFIED : vault?.content.display.color} icon={inTrash ? 'pass-trash' : vault?.content.display.icon} /> </Button> <Dropdown anchorRef={anchorRef} autoClose={false} isOpen={isOpen} onClose={close} originalPlacement="bottom" size={DROPDOWN_SIZE} > <DropdownMenu> <div className="flex flex-align-items-center flex-justify-space-between flex-nowrap gap-2 py-2 px-4"> <span className={clsx( 'flex flex-align-items-center flex-nowrap', passPlan === UserPassPlan.PLUS && 'ui-orange' )} > <Icon name="star" className="mr-3" color="var(--interaction-norm)" /> <span className="text-left"> <div className="text-sm text-ellipsis">{user?.Email}</div> <div className="text-sm" style={{ color: 'var(--interaction-norm)' }}> {planDisplayName} </div> </span> </span> </div> {passPlan !== UserPassPlan.PLUS && ( <div className="pb-2 px-4"> <UpgradeButton className="w-full" /> </div> )} <hr className="dropdown-item-hr my-2 mx-4" aria-hidden="true" /> <VaultMenu dense inTrash={inTrash} onAction={close} onSelect={onVaultSelect} selectedShareId={shareId} render={(selected, menu) => ( <Collapsible> <CollapsibleHeader className="pl-4 pr-2" suffix={ <CollapsibleHeaderIconButton className="p-0" pill size="small"> <Icon name="chevron-down" /> </CollapsibleHeaderIconButton> } > <span className="flex flex-align-items-center flex-nowrap gap-2"> <VaultIcon className="flex-item-noshrink" size={16} color={selected.color} icon={selected?.icon} /> <span className="block text-ellipsis">{selected.label}</span> </span> </CollapsibleHeader> <CollapsibleContent as="ul" className="unstyled mx-2"> <hr className="dropdown-item-hr my-2 mx-2" aria-hidden="true" /> {menu} <div className="mt-2 mb-4 w-full"> <Button className="w-full" color="weak" pill shape="solid" onClick={withClose(vaultActions.create)} > {c('Action').t`Create vault`} </Button> </div> </CollapsibleContent> </Collapsible> )} /> <hr className="dropdown-item-hr my-2 mx-4" aria-hidden="true" /> <DropdownMenuButton onClick={withClose(() => openSettings())} label={c('Label').t`Settings`} icon={'cog-wheel'} /> {canLock && ( <DropdownMenuButton onClick={withClose(lock)} disabled={!ready} label={c('Action').t`Lock extension`} icon="lock" /> )} {!expanded && ( <DropdownMenuButton onClick={expandPopup} label={c('Action').t`Open in a window`} icon="arrow-out-square" /> )} <Submenu icon="notepad-checklist" label={c('Action').t`Advanced`} items={menu.advanced} /> <hr className="dropdown-item-hr my-3 mx-4" aria-hidden="true" /> <Submenu icon="bug" label={c('Action').t`Feedback`} items={menu.feedback} /> <Submenu icon="mobile" label={c('Action').t`Get mobile apps`} items={menu.download} /> <DropdownMenuButton onClick={() => logout({ soft: false })} label={c('Action').t`Sign out`} icon="arrow-out-from-rectangle" /> </DropdownMenu> </Dropdown> </nav> </> ); };
4,384
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/popup/Views
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/popup/Views/Item/ItemEditContainer.tsx
import { type VFC } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { Redirect, useParams } from 'react-router-dom'; import { useNavigationContext } from 'proton-pass-extension/lib/hooks/useNavigationContext'; import { usePopupContext } from 'proton-pass-extension/lib/hooks/usePopupContext'; import { AliasEdit } from '@proton/pass/components/Item/Alias/Alias.edit'; import { CreditCardEdit } from '@proton/pass/components/Item/CreditCard/CreditCard.edit'; import { LoginEdit } from '@proton/pass/components/Item/Login/Login.edit'; import { NoteEdit } from '@proton/pass/components/Item/Note/Note.edit'; import type { ItemEditViewProps } from '@proton/pass/components/Views/types'; import { itemEditIntent } from '@proton/pass/store/actions'; import { selectItemByShareIdAndId, selectShareOrThrow } from '@proton/pass/store/selectors'; import type { ItemEditIntent, ItemType, SelectedItem, ShareType } from '@proton/pass/types'; const itemEditMap: { [T in ItemType]: VFC<ItemEditViewProps<T>> } = { login: LoginEdit, note: NoteEdit, alias: AliasEdit, creditCard: CreditCardEdit, }; export const ItemEditContainer: VFC = () => { const { url } = usePopupContext(); const { selectItem } = useNavigationContext(); const dispatch = useDispatch(); const { shareId, itemId } = useParams<SelectedItem>(); const vault = useSelector(selectShareOrThrow<ShareType.Vault>(shareId)); const item = useSelector(selectItemByShareIdAndId(shareId, itemId)); const handleSubmit = (data: ItemEditIntent) => { dispatch(itemEditIntent(data)); selectItem(shareId, itemId); }; const handleCancel = () => selectItem(shareId, itemId); if (!item) { return <Redirect to="/" />; } const EditViewComponent = itemEditMap[item.data.type] as VFC<ItemEditViewProps>; return ( <EditViewComponent vault={vault} revision={item} onSubmit={handleSubmit} onCancel={handleCancel} url={url} /> ); };
4,385
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/popup/Views
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/popup/Views/Item/ItemNewContainer.tsx
import { type VFC } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { useHistory, useParams } from 'react-router-dom'; import { useItemsFilteringContext } from 'proton-pass-extension/lib/hooks/useItemsFilteringContext'; import { useNavigationContext } from 'proton-pass-extension/lib/hooks/useNavigationContext'; import { usePopupContext } from 'proton-pass-extension/lib/hooks/usePopupContext'; import { AliasNew } from '@proton/pass/components/Item/Alias/Alias.new'; import { CreditCardNew } from '@proton/pass/components/Item/CreditCard/CreditCard.new'; import { LoginNew } from '@proton/pass/components/Item/Login/Login.new'; import { NoteNew } from '@proton/pass/components/Item/Note/Note.new'; import type { ItemNewViewProps } from '@proton/pass/components/Views/types'; import { itemCreationIntent } from '@proton/pass/store/actions'; import { selectDefaultVault, selectVaultLimits } from '@proton/pass/store/selectors'; import type { ItemCreateIntent, ItemType } from '@proton/pass/types'; const itemNewMap: { [T in ItemType]: VFC<ItemNewViewProps<T>> } = { login: LoginNew, note: NoteNew, alias: AliasNew, creditCard: CreditCardNew, }; export const ItemNewContainer: VFC = () => { const history = useHistory(); const dispatch = useDispatch(); const { url } = usePopupContext(); const { itemType } = useParams<{ shareId: string; itemType: ItemType }>(); const { selectItem } = useNavigationContext(); const { shareId: selectedShareId, setShareId } = useItemsFilteringContext(); const { didDowngrade } = useSelector(selectVaultLimits); /* if user downgraded - always auto-select the default vault id */ const defaultVault = useSelector(selectDefaultVault); const shareId = didDowngrade ? defaultVault.shareId : selectedShareId ?? defaultVault.shareId; const ItemNewComponent = itemNewMap[itemType]; const handleSubmit = (createIntent: ItemCreateIntent) => { const action = itemCreationIntent(createIntent); dispatch(action); /* if the user put the item in a vault which is * currently not selected - autoselect it so the * following call to `selectItem` passes */ if (selectedShareId && selectedShareId !== createIntent.shareId) { setShareId(createIntent.shareId); } selectItem(createIntent.shareId, action.payload.optimisticId); }; const handleCancel = () => history.goBack(); return <ItemNewComponent shareId={shareId} onSubmit={handleSubmit} onCancel={handleCancel} url={url} />; };
4,386
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/popup/Views
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/popup/Views/Item/ItemViewContainer.tsx
import { type VFC, useMemo, useState } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { useHistory, useParams } from 'react-router-dom'; import { useItemsFilteringContext } from 'proton-pass-extension/lib/hooks/useItemsFilteringContext'; import { useNavigationContext } from 'proton-pass-extension/lib/hooks/useNavigationContext'; import { c } from 'ttag'; import { useInviteContext } from '@proton/pass/components/Invite/InviteContextProvider'; import { VaultInviteFromItemModal } from '@proton/pass/components/Invite/VaultInviteFromItemModal'; import { AliasView } from '@proton/pass/components/Item/Alias/Alias.view'; import { CreditCardView } from '@proton/pass/components/Item/CreditCard/CreditCard.view'; import { LoginView } from '@proton/pass/components/Item/Login/Login.view'; import { NoteView } from '@proton/pass/components/Item/Note/Note.view'; import { Panel } from '@proton/pass/components/Layout/Panel/Panel'; import { VaultSelect, useVaultSelectModalHandles } from '@proton/pass/components/Vault/VaultSelect'; import type { ItemViewProps } from '@proton/pass/components/Views/types'; import { isTrashed } from '@proton/pass/lib/items/item.predicates'; import { getItemActionId } from '@proton/pass/lib/items/item.utils'; import { itemCreationDismiss, itemCreationIntent, itemDeleteIntent, itemEditDismiss, itemEditIntent, itemMoveIntent, itemRestoreIntent, itemTrashIntent, } from '@proton/pass/store/actions'; import selectFailedAction from '@proton/pass/store/optimistic/selectors/select-failed-action'; import { selectByShareId, selectItemWithOptimistic, selectShareOrThrow, selectWritableSharedVaultsWithItemsCount, selectWritableVaultsWithItemsCount, } from '@proton/pass/store/selectors'; import type { ItemType, SelectedItem, ShareType } from '@proton/pass/types'; import { pipe } from '@proton/pass/utils/fp/pipe'; import { uniqueId } from '@proton/pass/utils/string/unique-id'; const itemTypeViewMap: { [T in ItemType]: VFC<ItemViewProps<T>> } = { login: LoginView, note: NoteView, alias: AliasView, creditCard: CreditCardView, }; export const ItemViewContainer: VFC = () => { const { selectItem } = useNavigationContext(); const filters = useItemsFilteringContext(); const inviteContext = useInviteContext(); const dispatch = useDispatch(); const history = useHistory(); const { shareId, itemId } = useParams<SelectedItem>(); const [inviteOpen, setInviteOpen] = useState(false); const { closeVaultSelect, openVaultSelect, modalState } = useVaultSelectModalHandles(); const optimisticItemId = getItemActionId({ itemId, shareId }); const itemSelector = useMemo(() => selectItemWithOptimistic(shareId, itemId), [shareId, itemId]); const failedItemActionSelector = pipe(selectByShareId, selectFailedAction(optimisticItemId)); const vault = useSelector(selectShareOrThrow<ShareType.Vault>(shareId)); const item = useSelector(itemSelector); const failure = useSelector(failedItemActionSelector); if (item === undefined) return <Panel />; const trashed = isTrashed(item); const handleEdit = () => history.push(`/share/${shareId}/item/${itemId}/edit`); const handleRetry = () => failure !== undefined && dispatch(failure.action); const handleTrash = () => dispatch(itemTrashIntent({ itemId, shareId, item })); const handleMove = () => openVaultSelect(item.shareId, selectWritableVaultsWithItemsCount); const handleMoveToSharedVault = () => openVaultSelect(item.shareId, selectWritableSharedVaultsWithItemsCount); const handleRestore = () => dispatch(itemRestoreIntent({ item, itemId, shareId })); const handleDelete = () => dispatch(itemDeleteIntent({ item, itemId, shareId })); const handleInviteClick = () => setInviteOpen(true); const handleVaultManage = () => inviteContext.manageAccess(shareId); const handleCreateSharedVault = () => { inviteContext.createSharedVault({ item: { shareId, itemId } }); setInviteOpen(false); }; const handleShareVaultClick = () => { inviteContext.createInvite({ vault }); setInviteOpen(false); }; const handleDismiss = () => { if (failure === undefined) return; if (itemCreationIntent.match(failure.action)) { dispatch(itemCreationDismiss({ shareId, optimisticId: itemId, item })); } if (itemEditIntent.match(failure.action)) { dispatch(itemEditDismiss({ shareId, itemId, item })); } }; const doMoveItem = (destinationShareId: string) => { const optimisticId = uniqueId(); dispatch(itemMoveIntent({ item, shareId: destinationShareId, optimisticId })); if (filters.shareId) filters.setShareId(destinationShareId); selectItem(destinationShareId, optimisticId); closeVaultSelect(); setInviteOpen(false); }; const ItemTypeViewComponent = itemTypeViewMap[item.data.type] as VFC<ItemViewProps>; return ( <> <ItemTypeViewComponent key={item.itemId} vault={vault} revision={item} handleEditClick={handleEdit} handleRetryClick={handleRetry} handleMoveToTrashClick={handleTrash} handleMoveToVaultClick={handleMove} handleDismissClick={handleDismiss} handleRestoreClick={handleRestore} handleDeleteClick={handleDelete} handleInviteClick={handleInviteClick} handleManageClick={handleVaultManage} optimistic={item.optimistic} failed={item.failed} trashed={trashed} /> <VaultSelect downgradeMessage={c('Info') .t`You have exceeded the number of vaults included in your subscription. Items can only be moved to your first two vaults. To move items between all vaults upgrade your subscription.`} onSubmit={doMoveItem} onClose={closeVaultSelect} {...modalState} /> <VaultInviteFromItemModal vault={vault} shareId={shareId} itemId={itemId} open={inviteOpen} onClose={() => setInviteOpen(false)} handleMoveToSharedVaultClick={handleMoveToSharedVault} handleShareVaultClick={handleShareVaultClick} handleCreateSharedVaultClick={handleCreateSharedVault} /> </> ); };
4,387
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/popup/Views
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/popup/Views/Lobby/Lobby.tsx
import { type VFC, useCallback } from 'react'; import { PromptForReload } from 'proton-pass-extension/lib/components/Extension/ExtensionError'; import { usePopupContext } from 'proton-pass-extension/lib/hooks/usePopupContext'; import { useRequestForkWithPermissions } from 'proton-pass-extension/lib/hooks/useRequestFork'; import { c } from 'ttag'; import { LobbyContent } from '@proton/pass/components/Layout/Lobby/LobbyContent'; import { LobbyLayout } from '@proton/pass/components/Layout/Lobby/LobbyLayout'; import { clientErrored } from '@proton/pass/lib/client'; import { popupMessage, sendMessage } from '@proton/pass/lib/extension/message'; import { WorkerMessageType } from '@proton/pass/types'; import { FORK_TYPE } from '@proton/shared/lib/authentication/ForkInterface'; import { PASS_APP_NAME } from '@proton/shared/lib/constants'; export const Lobby: VFC = () => { const { state, logout } = usePopupContext(); const errored = clientErrored(state.status); const login = useRequestForkWithPermissions({ autoClose: true }); const handleLogin = () => (errored ? sendMessage(popupMessage({ type: WorkerMessageType.WORKER_INIT })) : login()); const handleRegister = useCallback(async () => login(FORK_TYPE.SIGNUP), []); return ( <LobbyLayout overlay> <LobbyContent status={state.status} onLogin={handleLogin} onLogout={logout} onRegister={handleRegister} renderError={() => ( <PromptForReload message={c('Warning') .t`Something went wrong while starting ${PASS_APP_NAME}. Please try refreshing or reloading the extension`} /> )} /> </LobbyLayout> ); };
4,388
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/popup/Views
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/popup/Views/Sidebar/ItemsList.tsx
import { type VFC, useEffect, useMemo, useRef } from 'react'; import type { List } from 'react-virtualized'; import { useItems } from 'proton-pass-extension/lib/hooks/useItems'; import { useNavigationContext } from 'proton-pass-extension/lib/hooks/useNavigationContext'; import { useSelectItemClick } from 'proton-pass-extension/lib/hooks/useSelectItemClick'; import { SortFilter } from '@proton/pass/components/Item/Filters/Sort'; import { TypeFilter } from '@proton/pass/components/Item/Filters/Type'; import { ItemsListItem } from '@proton/pass/components/Item/List/ItemsList.Item'; import { VirtualList } from '@proton/pass/components/Layout/List/VirtualList'; import { itemEq } from '@proton/pass/lib/items/item.predicates'; import { interpolateRecentItems } from '@proton/pass/lib/items/item.utils'; import { ItemsListPlaceholder } from './ItemsListPlaceholder'; export const ItemsList: VFC = () => { const { selectedItem } = useNavigationContext(); const onSelectItem = useSelectItemClick(); const { filtering: { search, type, sort, setSort, setType }, filtered, searched, totalCount, } = useItems(); const listRef = useRef<List>(null); useEffect(() => listRef.current?.scrollToRow(0), [type, sort]); const { interpolation, interpolationIndexes } = useMemo( () => interpolateRecentItems(filtered)(sort === 'recent'), [filtered, sort] ); return ( <> {totalCount > 0 && ( <div className="flex flex-row flex-item-nogrow flex-item-noshrink flex-nowrap p-3 gap-1 scroll-horizontal-if-needed"> <TypeFilter items={searched} value={type} onChange={setType} /> <SortFilter value={sort} onChange={setSort} /> </div> )} {filtered.length === 0 ? ( <div className="flex flex-justify-center flex-align-items-center w-full m-auto overflow-x-auto py-3"> <ItemsListPlaceholder /> </div> ) : ( <VirtualList ref={listRef} rowCount={interpolation.length} interpolationIndexes={interpolationIndexes} rowRenderer={({ style, index, key }) => { const row = interpolation[index]; switch (row.type) { case 'entry': { const item = row.entry; return ( <div style={style} key={key}> <ItemsListItem item={item} onClick={onSelectItem(item)} id={`item-${item.shareId}-${item.itemId}`} search={search} active={selectedItem && itemEq(selectedItem)(item)} /> </div> ); } case 'interpolation': { return ( <div style={style} key={key} className="flex color-weak text-sm pt-2 pb-1 pl-3"> {row.cluster.label} </div> ); } } }} /> )} </> ); };
4,389
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/popup/Views
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/popup/Views/Sidebar/ItemsListPlaceholder.tsx
import { type MouseEvent, type VFC, useMemo } from 'react'; import { useSelector } from 'react-redux'; import { useHistory } from 'react-router-dom'; import { useItems } from 'proton-pass-extension/lib/hooks/useItems'; import { useNavigationContext } from 'proton-pass-extension/lib/hooks/useNavigationContext'; import { useOpenSettingsTab } from 'proton-pass-extension/lib/hooks/useOpenSettingsTab'; import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import type { IconName } from '@proton/components/components'; import { Icon } from '@proton/components/components'; import { UpgradeButton } from '@proton/pass/components/Layout/Button/UpgradeButton'; import { Card } from '@proton/pass/components/Layout/Card/Card'; import { itemTypeToIconName } from '@proton/pass/components/Layout/Icon/ItemIcon'; import { SubTheme } from '@proton/pass/components/Layout/Theme/types'; import { isWritableVault } from '@proton/pass/lib/vaults/vault.predicates'; import { selectAllVaults, selectOwnReadOnlyVaults, selectShare, selectVaultLimits } from '@proton/pass/store/selectors'; import type { ItemType } from '@proton/pass/types'; import { prop } from '@proton/pass/utils/fp/lens'; import clsx from '@proton/utils/clsx'; type QuickAction = { type: ItemType | 'import'; icon: IconName; label: string; onClick: (e: MouseEvent<HTMLElement>) => void; subTheme?: SubTheme; }; export const ItemsListPlaceholder: VFC = () => { const history = useHistory(); const openSettings = useOpenSettingsTab(); const { isCreating } = useNavigationContext(); const { filtering, totalCount } = useItems(); const { search } = filtering; const { didDowngrade } = useSelector(selectVaultLimits); const selectedShare = useSelector(selectShare(filtering.shareId)); const ownedReadOnlyShareIds = useSelector(selectOwnReadOnlyVaults).map(prop('shareId')); const isOwnedReadOnly = filtering.shareId && ownedReadOnlyShareIds.includes(filtering.shareId); const hasMultipleVaults = useSelector(selectAllVaults).length > 1; const quickActions = useMemo<QuickAction[]>( () => [ { type: 'login', icon: itemTypeToIconName.login, label: c('Label').t`Create a login`, onClick: () => history.push(`/item/new/login`), subTheme: SubTheme.VIOLET, }, { type: 'alias', icon: itemTypeToIconName.alias, label: c('Label').t`Create a hide-my-email alias`, onClick: () => history.push(`/item/new/alias`), subTheme: SubTheme.TEAL, }, { type: 'creditCard', icon: itemTypeToIconName.creditCard, label: c('Label').t`Create a credit card`, onClick: () => history.push(`/item/new/creditCard`), subTheme: SubTheme.LIME, }, { type: 'note', icon: itemTypeToIconName.note, label: c('Label').t`Create an encrypted note`, onClick: () => history.push(`/item/new/note`), subTheme: SubTheme.ORANGE, }, { type: 'import', icon: 'arrow-up-line', label: c('Label').t`Import passwords`, onClick: () => openSettings('import'), }, ], [] ); if (isOwnedReadOnly && totalCount === 0 && didDowngrade) { return ( <div className="flex flex-column flex-align-items-center gap-3 text-center p-2 w-2/3 max-w-custom" style={{ '--max-w-custom': '20rem' }} > <span className="text-semibold inline-block">{c('Title').t`Your vault is empty`}</span> <Card> {c('Info') .t`You have exceeded the number of vaults included in your subscription. New items can only be created in your first two vaults. To create new items in all vaults upgrade your subscription.`} </Card> <UpgradeButton /> </div> ); } if (totalCount === 0) { return ( <div className="flex flex-column gap-3 text-center"> <strong className="inline-block">{c('Title').t`Your vault is empty`}</strong> <span className="color-weak inline-block mb-4"> {hasMultipleVaults ? c('Info').t`Switch to another vault or create an item in this vault` : c('Info').t`Let's get you started by creating your first item`} </span> {!isCreating && quickActions.map(({ type, icon, label, onClick, subTheme }) => ( <Button pill shape="solid" color="weak" key={`quick-action-${type}`} className={clsx('w-full relative', subTheme)} onClick={onClick} disabled={selectedShare && !isWritableVault(selectedShare)} > <Icon name={icon} color="var(--interaction-norm)" className="absolute left-custom top bottom my-auto" style={{ '--left-custom': '1rem' }} /> <span>{label}</span> </Button> ))} </div> ); } return ( <span className="block text-break color-weak text-sm p-2 text-center text-break"> {search.trim() ? ( <span> {c('Warning').t`No items matching`} <br />"{search}" </span> ) : ( <>{c('Warning').t`No items`}</> )} </span> ); };
4,390
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/popup/Views
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/popup/Views/Sidebar/TrashItemsList.tsx
import { type FC, useRef } from 'react'; import type { List } from 'react-virtualized'; import { useItems } from 'proton-pass-extension/lib/hooks/useItems'; import { useNavigationContext } from 'proton-pass-extension/lib/hooks/useNavigationContext'; import { useSelectItemClick } from 'proton-pass-extension/lib/hooks/useSelectItemClick'; import { c } from 'ttag'; import { ItemsListItem } from '@proton/pass/components/Item/List/ItemsList.Item'; import { VirtualList } from '@proton/pass/components/Layout/List/VirtualList'; import { itemEq } from '@proton/pass/lib/items/item.predicates'; export const TrashItemsList: FC = () => { const { selectedItem } = useNavigationContext(); const onSelectItem = useSelectItemClick(); const { filtering, searched, totalCount } = useItems({ trashed: true }); const { search } = filtering; const listRef = useRef<List>(null); return searched.length === 0 ? ( <div className="absolute-center flex flex-justify-center flex-align-items-center w-4/6"> <span className="block text-break color-weak text-sm p-2 text-center text-break"> {totalCount === 0 ? ( <span> <strong>{c('Title').t`Trash empty`}</strong> <br /> {c('Info').t`Deleted items will be moved here first`} </span> ) : ( <span> {c('Warning').t`No items in trash matching`} <br />"{search}" </span> )} </span> </div> ) : ( <VirtualList ref={listRef} rowCount={searched.length} rowRenderer={({ style, index }) => { const item = searched[index]; return ( <div style={style} key={item.itemId}> <ItemsListItem item={item} id={`item-${item.shareId}-${item.itemId}`} onClick={onSelectItem(item, { inTrash: true })} search={search} active={selectedItem && itemEq(selectedItem)(item)} /> </div> ); }} /> ); };
4,391
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker/channel.ts
import { createMessageBroker } from '@proton/pass/lib/extension/message'; import { cacheRequest } from '@proton/pass/store/actions'; import { SessionLockStatus, WorkerMessageType } from '@proton/pass/types'; import noop from '@proton/utils/noop'; import { withContext } from './context'; import store from './store'; /* For security reasons : limit the type of messages that * can be processed via externally connectable resources. * When we detect a popup port being disconnected : this * likely means the popup was closed : dispatch a cache request * in order to save the latest popup state */ const WorkerMessageBroker = createMessageBroker({ allowExternal: [ WorkerMessageType.ACCOUNT_FORK, WorkerMessageType.ACCOUNT_EXTENSION, WorkerMessageType.ACCOUNT_PROBE, WorkerMessageType.ACCOUNT_ONBOARDING, ], strictOriginCheck: [ WorkerMessageType.ACTIVITY_PROBE, WorkerMessageType.ALIAS_CREATE, WorkerMessageType.ALIAS_OPTIONS, WorkerMessageType.AUTOFILL_SELECT, WorkerMessageType.AUTOSAVE_REQUEST, WorkerMessageType.EXPORT_REQUEST, WorkerMessageType.EXPORT_DECRYPT, WorkerMessageType.LOG_REQUEST, WorkerMessageType.ONBOARDING_ACK, WorkerMessageType.ONBOARDING_REQUEST, WorkerMessageType.OTP_CODE_GENERATE, WorkerMessageType.POPUP_INIT, WorkerMessageType.UNLOCK_REQUEST, ], onDisconnect: withContext((ctx, portName) => { const isPopup = portName.startsWith('popup'); const hasRegisteredLock = ctx.authStore.getLockStatus() === SessionLockStatus.REGISTERED; if (isPopup) { store.dispatch(cacheRequest()); if (hasRegisteredLock) ctx.service.auth.checkLock().catch(noop); } }), }); export default WorkerMessageBroker;
4,392
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker/index.ts
import * as config from 'proton-pass-extension/app/config'; import { createDevReloader } from 'proton-pass-extension/lib/utils/dev-reload'; import { generateKey } from '@proton/pass/lib/crypto/utils/crypto-helpers'; import { backgroundMessage } from '@proton/pass/lib/extension/message'; import browser from '@proton/pass/lib/globals/browser'; import { WorkerMessageType } from '@proton/pass/types'; import { uint8ArrayToBase64String } from '@proton/shared/lib/helpers/encoding'; import sentry from '@proton/shared/lib/helpers/sentry'; import noop from '@proton/utils/noop'; import WorkerMessageBroker from './channel'; import { createWorkerContext } from './context'; if (BUILD_TARGET === 'chrome') { /* FIXME: create a custom webpack plugin to automatically register * chunks loaded through `importScripts` for the chromium build * https://bugs.chromium.org/p/chromium/issues/detail?id=1198822#c10*/ const globalScope = self as any as ServiceWorkerGlobalScope; const getLocaleAsset = (locale: string) => browser.runtime.getURL(`chunk.locales/${locale}-json.js`); const chunks = Object.keys(config.LOCALES).map(getLocaleAsset); globalScope.oninstall = async () => { importScripts(...chunks); /* In order to alleviate MV3 service worker potentially ending up * in a broken state after an update or a manual refresh, force the * incoming service worker to skip its waiting state * https://bugs.chromium.org/p/chromium/issues/detail?id=1271154#c66 * return globalScope.skipWaiting(); // fixed in chrome v117 */ }; } /* The `EXTENSION_KEY` is a random & unique identifier for the current * extension runtime. It is currently used for verifiying the origin of * messages sent through unsecure channels (ie: iframe postmessaging). * see: `IFrameContextProvider.tsx` */ const EXTENSION_KEY = uint8ArrayToBase64String(generateKey()); WorkerMessageBroker.registerMessage(WorkerMessageType.RESOLVE_EXTENSION_KEY, () => ({ key: EXTENSION_KEY })); if (ENV === 'development') { createDevReloader(async () => { const tabs = await browser.tabs.query({}); const csUnloads = tabs .filter((tab) => tab.id !== undefined) .map((tab) => browser.tabs .sendMessage(tab.id!, backgroundMessage({ type: WorkerMessageType.UNLOAD_CONTENT_SCRIPT })) .catch(noop) ); await Promise.all(csUnloads); setTimeout(() => browser.runtime.reload(), 250); }, '[DEV] Reloading runtime'); } sentry({ config, sentryConfig: { host: new URL(config.API_URL).host, release: config.APP_VERSION, environment: `browser-pass::worker`, }, ignore: () => false, denyUrls: [], }); const context = createWorkerContext(config); browser.runtime.onConnect.addListener(WorkerMessageBroker.ports.onConnect); browser.runtime.onMessageExternal.addListener(WorkerMessageBroker.onMessage); browser.runtime.onMessage.addListener(WorkerMessageBroker.onMessage); browser.runtime.onStartup.addListener(context.service.activation.onStartup); browser.runtime.onInstalled.addListener(context.service.activation.onInstall); browser.runtime.onUpdateAvailable.addListener(context.service.activation.onUpdateAvailable); if (BUILD_TARGET === 'firefox' && ENV === 'production') { /* Block direct access to certain `web_accessible_resources` * at their direct runtime url: only allow through page actions * or iframe injections. Only works on FF as we don't have access * to tab information on chrome for `web_accessible_resources` */ browser.tabs.onUpdated.addListener(async (tabId, _, { url, status }) => { try { const BLOCKING = ['/dropdown.html', '/notification.html']; const regex = new RegExp(`^(${BLOCKING.map((path) => browser.runtime.getURL(path)).join('|')})`); return await (status === 'complete' && regex.test(url ?? '') && browser.tabs.remove(tabId)); } catch (_) {} }); }
4,393
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker/context/context.ts
import type { Callback, Maybe } from '@proton/pass/types'; import type { SharedContext, SharedContextInjector } from '@proton/pass/utils/context'; import { createSharedContext, createSharedContextInjector } from '@proton/pass/utils/context'; import type { WorkerContextInterface } from './types'; export const WorkerContext = createSharedContext<WorkerContextInterface>('worker'); export const withContext = createSharedContextInjector(WorkerContext); export const onContextReady = <F extends Maybe<Callback>>( fn: SharedContextInjector<F, SharedContext<WorkerContextInterface>> ) => { const injector = (async (ctx: WorkerContextInterface, ...args: any[]) => { await ctx.ensureReady(); return fn(ctx, ...args); }) as SharedContextInjector<F, SharedContext<WorkerContextInterface>>; return withContext<F>(injector); };
4,394
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker/context/factory.ts
import WorkerMessageBroker from 'proton-pass-extension/app/worker/channel'; import { createActivationService } from 'proton-pass-extension/app/worker/services/activation'; import { createAliasService } from 'proton-pass-extension/app/worker/services/alias'; import { SESSION_LOCK_ALARM, createAuthService } from 'proton-pass-extension/app/worker/services/auth'; import { createAutoFillService } from 'proton-pass-extension/app/worker/services/autofill'; import { createAutoSaveService } from 'proton-pass-extension/app/worker/services/autosave'; import { createCacheProxyService } from 'proton-pass-extension/app/worker/services/cache-proxy'; import { createExportService } from 'proton-pass-extension/app/worker/services/export'; import { createFormTrackerService } from 'proton-pass-extension/app/worker/services/form.tracker'; import { createI18nService } from 'proton-pass-extension/app/worker/services/i18n'; import { createInjectionService } from 'proton-pass-extension/app/worker/services/injection'; import { createLoggerService } from 'proton-pass-extension/app/worker/services/logger'; import { createOnboardingService } from 'proton-pass-extension/app/worker/services/onboarding'; import { createOTPService } from 'proton-pass-extension/app/worker/services/otp'; import { createSettingsService } from 'proton-pass-extension/app/worker/services/settings'; import { createStorageService } from 'proton-pass-extension/app/worker/services/storage'; import { createStoreService } from 'proton-pass-extension/app/worker/services/store'; import { createTelemetryService } from 'proton-pass-extension/app/worker/services/telemetry'; import { setPopupIcon } from 'proton-pass-extension/lib/utils/popup-icon'; import { getExtensionVersion } from 'proton-pass-extension/lib/utils/version'; import { exposeApi } from '@proton/pass/lib/api/api'; import { createApi } from '@proton/pass/lib/api/factory'; import { SESSION_KEYS, isValidPersistedSession } from '@proton/pass/lib/auth/session'; import { createAuthStore, exposeAuthStore } from '@proton/pass/lib/auth/store'; import { clientAuthorized, clientErrored, clientLocked, clientReady, clientStale, clientStatusResolved, clientUnauthorized, } from '@proton/pass/lib/client'; import { PassCrypto } from '@proton/pass/lib/crypto/pass-crypto'; import { backgroundMessage } from '@proton/pass/lib/extension/message'; import browser from '@proton/pass/lib/globals/browser'; import { cacheCancel, notification, sessionLockSync, stateDestroy, stopEventPolling } from '@proton/pass/store/actions'; import { AppStatus, SessionLockStatus, WorkerMessageType } from '@proton/pass/types'; import { or } from '@proton/pass/utils/fp/predicates'; import { waitUntil } from '@proton/pass/utils/fp/wait-until'; import { logger } from '@proton/pass/utils/logger'; import { getEpoch } from '@proton/pass/utils/time/get-epoch'; import { setUID as setSentryUID } from '@proton/shared/lib/helpers/sentry'; import createStore from '@proton/shared/lib/helpers/store'; import type { ProtonConfig } from '@proton/shared/lib/interfaces'; import noop from '@proton/utils/noop'; import store from '../store'; import { WorkerContext, withContext } from './context'; export const createWorkerContext = (config: ProtonConfig) => { const authStore = exposeAuthStore(createAuthStore(createStore())); const api = createApi({ config, getAuth: () => { const AccessToken = authStore.getAccessToken(); const RefreshToken = authStore.getRefreshToken(); const RefreshTime = authStore.getRefreshTime(); const UID = authStore.getUID(); if (!(UID && AccessToken && RefreshToken)) return undefined; return { UID, AccessToken, RefreshToken, RefreshTime }; }, }); exposeApi(api); const context = WorkerContext.set({ status: AppStatus.IDLE, authStore, service: { auth: createAuthService({ api, authStore, onInit: withContext(async (ctx, options) => { /* if worker is logged out (unauthorized or locked) during an init call, * this means the login or resumeSession calls failed - we can safely early * return as the authentication store will have been configured */ if (clientUnauthorized(ctx.status)) return false; if (clientAuthorized(ctx.status)) return true; return context.service.auth.resumeSession(undefined, options); }), getPersistedSession: async () => { const { ps } = await context.service.storage.local.get(['ps']); if (!ps) return null; const persistedSession = JSON.parse(ps); return isValidPersistedSession(persistedSession) ? persistedSession : null; }, getMemorySession: () => context.service.storage.session.get(SESSION_KEYS), onAuthorize: () => context.setStatus(AppStatus.AUTHORIZING), onAuthorized: () => { context.setStatus(AppStatus.AUTHORIZED); context.service.activation.boot(); context.service.autofill.updateTabsBadgeCount(); setSentryUID(authStore.getUID()); }, onUnauthorized: () => { store.dispatch(cacheCancel()); store.dispatch(stopEventPolling()); /* important to call setStatus before dispatching the * the `stateDestroy` action : we might have active * clients currently consuming the store data */ context.setStatus(AppStatus.UNAUTHORIZED); store.dispatch(stateDestroy()); setSentryUID(undefined); PassCrypto.clear(); context.service.formTracker.clear(); context.service.onboarding.reset(); context.service.autofill.clearTabsBadgeCount(); context.service.cacheProxy.clear?.().catch(noop); context.service.storage.session.clear().catch(noop); context.service.storage.local.clear().catch(noop); browser.alarms.clear(SESSION_LOCK_ALARM).catch(noop); }, onSessionInvalid: () => { authStore.clear(); context.service.storage.local.unset(['ps']).catch(noop); context.service.storage.session.clear().catch(noop); }, onSessionUnlocked: () => {}, onSessionEmpty: () => context.setStatus(AppStatus.UNAUTHORIZED), onSessionLocked: () => { store.dispatch(stopEventPolling()); context.setStatus(AppStatus.LOCKED); context.service.autofill.clearTabsBadgeCount(); PassCrypto.clear(); context.service.auth.init().catch(noop); }, onSessionLockCheck: (lock) => { browser.alarms.clear(SESSION_LOCK_ALARM).catch(noop); if (lock.status === SessionLockStatus.REGISTERED && lock.ttl) { browser.alarms.create(SESSION_LOCK_ALARM, { when: (getEpoch() + lock.ttl) * 1_000 }); } store.dispatch(sessionLockSync(lock)); }, onSessionPersist: (encryptedSession) => { context.service.storage.local.set({ ps: encryptedSession }).catch(noop); context.service.storage.session.set(authStore.getSession()).catch(noop); }, onSessionResumeFailure: () => context.setStatus(AppStatus.ERROR), onNotification: (text) => store.dispatch( notification({ text, type: 'error', key: 'authservice', deduplicate: true, }) ), onSessionRefresh: async (localID, { AccessToken, RefreshToken, RefreshTime }) => { const persistedSession = await context.service.auth.config.getPersistedSession(localID); if (persistedSession) { /* update the persisted session tokens without re-encrypting the * session blob as session refresh may happen before a full login * with a partially hydrated authentication store. */ persistedSession.AccessToken = AccessToken; persistedSession.RefreshToken = RefreshToken; persistedSession.RefreshTime = RefreshTime; context.service.storage.local.set({ ps: JSON.stringify(persistedSession) }).catch(noop); context.service.storage.session.set({ AccessToken, RefreshToken, RefreshTime }).catch(noop); } }, }), activation: createActivationService(), alias: createAliasService(), autofill: createAutoFillService(), autosave: createAutoSaveService(), cacheProxy: createCacheProxyService(), export: createExportService(), formTracker: createFormTrackerService(), i18n: createI18nService(), injection: createInjectionService(), logger: createLoggerService(), onboarding: createOnboardingService(), otp: createOTPService(), settings: createSettingsService(), storage: createStorageService(), store: createStoreService(), telemetry: BUILD_TARGET !== 'firefox' ? createTelemetryService() : null, }, async ensureReady() { const context = WorkerContext.get(); await waitUntil(() => clientStatusResolved(context.getState().status), 50); return context; }, getState: () => ({ loggedIn: authStore.hasSession() && clientReady(context.status), status: context.status, UID: authStore.getUID(), }), setStatus(status: AppStatus) { logger.info(`[Worker::Context] Status update : ${context.status} -> ${status}`); context.status = status; void setPopupIcon({ disabled: or(clientUnauthorized, clientErrored, clientStale)(status), locked: clientLocked(status), }); WorkerMessageBroker.ports.broadcast( backgroundMessage({ type: WorkerMessageType.WORKER_STATUS, payload: { state: context.getState() }, }) ); }, }); context.service.i18n.init().catch(noop); context.service.onboarding.hydrate(); context.service.cacheProxy.clean?.().catch(noop); if (ENV === 'development') { WorkerMessageBroker.registerMessage(WorkerMessageType.DEBUG, ({ payload }) => { switch (payload.debug) { case 'storage_full': context.service.storage.getState().storageFull = true; return true; case 'update_trigger': context.service.activation.onUpdateAvailable({ version: getExtensionVersion() }); return true; } return false; }); } return context; };
4,395
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker/context/index.ts
export * from './context'; export * from './factory'; export * from './types';
4,396
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker/context/types.ts
import type { AuthService } from '@proton/pass/lib/auth/service'; import type { AuthStore } from '@proton/pass/lib/auth/store'; import type { AppState, AppStatus, MaybeNull } from '@proton/pass/types'; import type { ActivationService } from '../services/activation'; import type { AliasService } from '../services/alias'; import type { AutoFillService } from '../services/autofill'; import type { AutoSaveService } from '../services/autosave'; import type { CacheProxyService } from '../services/cache-proxy'; import type { ExportService } from '../services/export'; import type { FormTrackerService } from '../services/form.tracker'; import type { I18NService } from '../services/i18n'; import type { InjectionService } from '../services/injection'; import type { LoggerService } from '../services/logger'; import type { OnboardingService } from '../services/onboarding'; import type { OTPService } from '../services/otp'; import type { SettingsService } from '../services/settings'; import type { StorageService } from '../services/storage'; import type { StoreService } from '../services/store'; import type { TelemetryService } from '../services/telemetry'; export type WorkerInitOptions = { sync?: boolean /* will clear local storage */; force?: boolean /* will bypass busy state */; }; export interface WorkerContextInterface { status: AppStatus; authStore: AuthStore; service: { auth: AuthService; activation: ActivationService; alias: AliasService; autofill: AutoFillService; autosave: AutoSaveService; cacheProxy: CacheProxyService; export: ExportService; formTracker: FormTrackerService; i18n: I18NService; injection: InjectionService; logger: LoggerService; onboarding: OnboardingService; otp: OTPService; settings: SettingsService; storage: StorageService; store: StoreService; telemetry: MaybeNull<TelemetryService>; }; /* status update : side-effects will be triggered */ setStatus: (status: AppStatus) => void; /* returns the current worker state */ getState: () => AppState; /* Returned promise will resolve when worker "ready" */ ensureReady: () => Promise<WorkerContextInterface>; }
4,397
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker/services/activation.ts
import { type Runtime } from 'webextension-polyfill'; import { clientCanBoot, clientStale } from '@proton/pass/lib/client'; import type { MessageHandlerCallback } from '@proton/pass/lib/extension/message'; import { backgroundMessage } from '@proton/pass/lib/extension/message'; import browser from '@proton/pass/lib/globals/browser'; import { bootIntent, wakeupIntent } from '@proton/pass/store/actions'; import { selectFeatureFlags, selectItemByShareIdAndId, selectItemDraft, selectPopupFilters, selectPopupPasswordOptions, selectPopupTabState, } from '@proton/pass/store/selectors'; import type { MaybeNull, WorkerMessageWithSender, WorkerWakeUpMessage } from '@proton/pass/types'; import { AppStatus, WorkerMessageType } from '@proton/pass/types'; import { getErrorMessage } from '@proton/pass/utils/errors/get-error-message'; import { logger } from '@proton/pass/utils/logger'; import { UNIX_HOUR } from '@proton/pass/utils/time/constants'; import { getEpoch } from '@proton/pass/utils/time/get-epoch'; import { parseUrl } from '@proton/pass/utils/url/parser'; import { checkExtensionPermissions } from '../../../lib/utils/permissions'; import { isPopupPort } from '../../../lib/utils/port'; import { isVivaldiBrowser } from '../../../lib/utils/vivaldi'; import WorkerMessageBroker from '../channel'; import { withContext } from '../context'; import store from '../store'; type ActivationServiceState = { updateAvailable: MaybeNull<string>; checkedUpdateAt: number; permissionsGranted: boolean; }; const UPDATE_ALARM_NAME = 'PassUpdateAlarm'; export const createActivationService = () => { const state: ActivationServiceState = { updateAvailable: null, checkedUpdateAt: 0, permissionsGranted: false }; /* Safety-net around worker boot-sequence : * Ensures no on-going booting sequence */ const handleBoot = withContext((ctx) => { if (clientCanBoot(ctx.status)) { ctx.setStatus(AppStatus.BOOTING); store.dispatch(bootIntent()); } }); const checkAvailableUpdate = async (): Promise<boolean> => { const now = getEpoch(); try { if (now - state.checkedUpdateAt > UNIX_HOUR) { const [updateStatus] = await browser.runtime.requestUpdateCheck(); if (updateStatus === 'update_available') { logger.info('[Worker::Activation] update detected'); return true; } } return false; } catch (_) { return false; } finally { state.checkedUpdateAt = now; } }; /* throttle update checks for updates every hour */ const setupUpdateAlarm = async () => { try { const alarmRegistered = await browser.alarms.get(UPDATE_ALARM_NAME); if (!alarmRegistered) browser.alarms.create(UPDATE_ALARM_NAME, { periodInMinutes: 60 }); } catch {} }; /* Try recovering the session when browser starts up * if any session was locally persisted * if not in production - use sync.html session to workaround the * the SSL handshake (net:ERR_SSL_CLIENT_AUTH_CERT_NEEDED) */ const handleStartup = withContext(async (ctx) => { const loggedIn = await ctx.service.auth.init({ forceLock: true }); if (ENV === 'development' && RESUME_FALLBACK) { if (!loggedIn) { const url = browser.runtime.getURL('/onboarding.html#/resume'); return browser.windows.create({ url, type: 'popup', height: 600, width: 540 }); } } }); /* On extension update : * - Re-init so as to resume session as soon as possible * - Re-inject content-scripts to avoid stale extension contexts * only on Chrome as Firefox handles content-script re-injection */ const handleInstall = withContext(async (ctx, details: Runtime.OnInstalledDetailsType) => { await browser.alarms.clearAll(); void setupUpdateAlarm(); if (details.reason === 'update') { if (ENV === 'production') { /* in production clear the cache on each extension * update in case the state/snapshot data-structure * has changed. FIXME: use version migrations */ await ctx.service.storage.local.unset(['salt', 'state', 'snapshot']); } if (BUILD_TARGET === 'chrome') void ctx.service.injection.updateInjections(); ctx.service.onboarding.onUpdate(); return ctx.service.auth.init(); } if (details.reason === 'install') { try { await Promise.all([ctx.service.storage.local.clear(), ctx.service.storage.session.clear()]); const url = browser.runtime.getURL('/onboarding.html#/success'); await browser.tabs.create({ url }); } catch (error: any) { logger.warn(`[Worker::Activation] requesting fork failed: ${getErrorMessage(error)}`); } void ctx.service.settings.onInstall(); void ctx.service.onboarding.onInstall(); if (BUILD_TARGET === 'chrome') void ctx.service.injection.updateInjections(); } }); const handleOnUpdateAvailable = (details: Runtime.OnUpdateAvailableDetailsType) => { if (details.version) { logger.info(`[Worker::Activation] update available ${details.version}`); state.updateAvailable = details.version; const popupPorts = WorkerMessageBroker.ports.query(isPopupPort()); /* on available update : only reload the runtime to force the * the extension update if the popup is not opened to avoid * discarding any ongoing user operations*/ if (popupPorts.length === 0) return browser.runtime.reload(); /* if we have ports opened to a popup : notify them in order * to manually prompt the user for a runtime reload */ logger.info(`[Worker::Activation] update deferred because popup is active`); popupPorts.forEach((port) => port.postMessage( backgroundMessage({ type: WorkerMessageType.UPDATE_AVAILABLE, }) ) ); } }; const checkPermissionsUpdate = async () => { state.permissionsGranted = await checkExtensionPermissions(); if (!state.permissionsGranted) logger.info(`[Worker::Activation] missing permissions`); WorkerMessageBroker.ports.broadcast( backgroundMessage({ type: WorkerMessageType.PERMISSIONS_UPDATE, payload: { check: state.permissionsGranted }, }) ); }; /* Vivaldi browser does not support setting the extension badge text * color and does not infer it correctly through background color. * On vivaldi, fallback to the default badge theme */ const setupExtensionBadge = async () => { if (!(await isVivaldiBrowser())) { return browser.action.setBadgeBackgroundColor({ color: '#FFFFFF' }); } }; /* When waking up from the pop-up (or page) we need to trigger the background wakeup * saga while immediately resolving the worker state so the UI can respond to state * changes as soon as possible. Regarding the content-script, we simply wait for a * ready state as its less "critical" */ const handleWakeup = withContext<MessageHandlerCallback<WorkerMessageType.WORKER_WAKEUP>>( async (ctx, message: WorkerMessageWithSender<WorkerWakeUpMessage>) => { const { sender: endpoint, payload } = message; const { tabId } = payload; const { status } = ctx.getState(); if (clientStale(status)) void ctx.service.auth.init(); /* dispatch a wakeup action for this specific receiver. * tracking the wakeup's request metadata can be consumed * in the UI to infer wakeup result - see `wakeup.saga.ts` * no need for any redux operations on content-script wakeup * as it doesn't hold any store. */ if (message.sender === 'popup' || message.sender === 'page') { store.dispatch(wakeupIntent({ status }, { endpoint, tabId })); } if (message.sender === 'popup') { WorkerMessageBroker.buffer.flush().forEach((notification) => { WorkerMessageBroker.ports .query(isPopupPort(tabId)) .forEach((port) => port.postMessage(notification)); }); } return { ...ctx.getState(), features: selectFeatureFlags(store.getState()) ?? {}, settings: await ctx.service.settings.resolve(), }; } ); const handleWorkerInit = withContext<MessageHandlerCallback<WorkerMessageType.WORKER_INIT>>( async (ctx, message) => { await ctx.service.auth.init(message.payload); return ctx.getState(); } ); const handlePopupInit = withContext<MessageHandlerCallback<WorkerMessageType.POPUP_INIT>>(async (ctx, message) => { const { payload } = message; const { tabId } = payload; /* dispatch a wakeup action for this specific receiver. * tracking the wakeup's request metadata can be consumed * in the UI to infer wakeup result - see `wakeup.saga.ts` */ const tab = await browser.tabs.get(tabId); const parsedUrl = parseUrl(tab.url ?? ''); const { subdomain, domain } = parsedUrl; const items = ctx.service.autofill.getAutofillCandidates(parsedUrl); const hasAutofillCandidates = items.length > 0; const state = store.getState(); const tabState = selectPopupTabState(tabId)(state); const filters = selectPopupFilters(state); const passwordOptions = selectPopupPasswordOptions(state); const pushTabState = tabState !== undefined && [subdomain, domain].includes(tabState.domain); const searchForAutofill = hasAutofillCandidates && domain ? domain : ''; const validItem = tabState?.selectedItem ? selectItemByShareIdAndId(tabState.selectedItem.shareId, tabState.selectedItem.itemId) !== undefined : false; const draft = selectItemDraft(state); const validDraft = draft ? selectItemByShareIdAndId(draft.shareId, draft.itemId) !== undefined : false; return { search: pushTabState ? tabState!.search : searchForAutofill, draft: validDraft ? draft : null, selectedItem: pushTabState && validItem ? tabState!.selectedItem : null, filters, passwordOptions, }; }); browser.permissions.onAdded.addListener(checkPermissionsUpdate); browser.permissions.onRemoved.addListener(checkPermissionsUpdate); browser.alarms.onAlarm.addListener(({ name }) => name === UPDATE_ALARM_NAME && checkAvailableUpdate()); WorkerMessageBroker.registerMessage(WorkerMessageType.WORKER_WAKEUP, handleWakeup); WorkerMessageBroker.registerMessage(WorkerMessageType.WORKER_INIT, handleWorkerInit); WorkerMessageBroker.registerMessage(WorkerMessageType.POPUP_INIT, handlePopupInit); WorkerMessageBroker.registerMessage(WorkerMessageType.RESOLVE_TAB, (_, { tab }) => ({ tab })); WorkerMessageBroker.registerMessage(WorkerMessageType.ACCOUNT_PROBE, () => true); void checkAvailableUpdate(); void checkPermissionsUpdate(); void setupExtensionBadge(); return { boot: handleBoot, onInstall: handleInstall, onStartup: handleStartup, onUpdateAvailable: handleOnUpdateAvailable, getAvailableUpdate: () => state.updateAvailable, getPermissionsGranted: () => state.permissionsGranted, }; }; export type ActivationService = ReturnType<typeof createActivationService>;
4,398
0
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker/services/alias.ts
import { c } from 'ttag'; import { getAliasOptionsIntent, getAliasOptionsSuccess, itemCreationIntent, itemCreationSuccess, } from '@proton/pass/store/actions'; import { withRevalidate } from '@proton/pass/store/actions/with-request'; import { selectAliasLimits, selectAutosaveVault } from '@proton/pass/store/selectors'; import type { ItemCreateIntent } from '@proton/pass/types'; import { WorkerMessageType } from '@proton/pass/types'; import { obfuscate } from '@proton/pass/utils/obfuscate/xor'; import { uniqueId } from '@proton/pass/utils/string/unique-id'; import { getEpoch } from '@proton/pass/utils/time/get-epoch'; import { getApiErrorMessage } from '@proton/shared/lib/api/helpers/apiErrorHelper'; import WorkerMessageBroker from '../channel'; import store from '../store'; export const createAliasService = () => { /* when resolving alias options for this message type, set the * the `needsUpgrade` accordingly for content-scripts to display * the upselling UI when alias limits have been reached */ WorkerMessageBroker.registerMessage(WorkerMessageType.ALIAS_OPTIONS, async () => { const { needsUpgrade } = selectAliasLimits(store.getState()); const { shareId } = selectAutosaveVault(store.getState()); return new Promise((resolve) => { store.dispatch( withRevalidate( getAliasOptionsIntent({ shareId }, (result) => { if (getAliasOptionsSuccess.match(result)) { const { options } = result.payload; return resolve({ ok: true, needsUpgrade, options }); } const error = result.error instanceof Error ? getApiErrorMessage(result.error) ?? null : null; return resolve({ ok: false, error }); }) ) ); }); }); WorkerMessageBroker.registerMessage(WorkerMessageType.ALIAS_CREATE, async (message) => { const { shareId } = selectAutosaveVault(store.getState()); const { url, alias } = message.payload; const { mailboxes, prefix, signedSuffix, aliasEmail } = alias; const optimisticId = uniqueId(); const aliasCreationIntent: ItemCreateIntent<'alias'> = { type: 'alias', optimisticId, shareId, createTime: getEpoch(), metadata: { name: url, note: obfuscate(c('Placeholder').t`Used on ${url}`), itemUuid: optimisticId, }, content: {}, extraFields: [], extraData: { mailboxes: mailboxes, prefix, signedSuffix, aliasEmail, }, }; return new Promise((resolve) => store.dispatch( itemCreationIntent(aliasCreationIntent, (result) => { if (itemCreationSuccess.match(result)) return resolve({ ok: true }); const error = result.error instanceof Error ? getApiErrorMessage(result.error) ?? null : null; return resolve({ ok: false, error }); }) ) ); }); return {}; }; export type AliasService = ReturnType<typeof createAliasService>;
4,399