Warn users before front components navigate to an external site (#23270)
https://github.com/user-attachments/assets/af3fb042-d066-4e0c-9348-f86ea92a6fcd Front component anchors render a real host `<a>`, so clicking a link to another domain performed an uncontrolled full-page navigation. This adds a phishing-resistant "you're leaving Twenty" confirmation modal before navigating to an external origin (Fixes [#23260](https://github.com/twentyhq/twenty/issues/23260)). The renderer intercepts external anchor clicks in `createHtmlHostWrapper` and hands the destination to a host callback via context; twenty-front owns the modal (reuses `ConfirmationModal`) and a per-application list of trusted origins persisted in localStorage. A "Don't ask again for this site" checkbox (checked by default) skips the modal next time for that app. Scope is external cross-origin http(s) links only; same-origin links keep native behavior. External links always open in a new tab, so a component can never navigate the Twenty tab away, even once its origin is trusted. The modal is rendered by the trusted host, so components cannot style or suppress it. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23270?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. -->
This commit is contained in:
+54
@@ -0,0 +1,54 @@
|
||||
import { type Meta, type StoryObj } from '@storybook/react-vite';
|
||||
import { expect, fn, userEvent, waitFor, within } from 'storybook/test';
|
||||
|
||||
import { FrontComponentRenderer } from '@/host/components/FrontComponentRenderer';
|
||||
import {
|
||||
FRONT_COMPONENT_STORY_DEFAULT_ARGS,
|
||||
resetFrontComponentStoryMocks,
|
||||
} from '@/__stories__/shared/test-utils/createFrontComponentStoryMeta';
|
||||
import { expectFrontComponentMounted } from '@/__stories__/shared/test-utils/matchers/expectFrontComponentMounted';
|
||||
import { runFrontComponentStory } from '@/__stories__/shared/test-utils/runFrontComponentStory';
|
||||
import { INTERACTION_TIMEOUT } from '@/__stories__/shared/test-utils/timeouts';
|
||||
|
||||
const requestExternalNavigation = fn();
|
||||
|
||||
const meta: Meta<typeof FrontComponentRenderer> = {
|
||||
title: 'FrontComponent/HtmlTag/Interactive/A/ExternalNavigation',
|
||||
component: FrontComponentRenderer,
|
||||
parameters: { layout: 'centered' },
|
||||
args: {
|
||||
...FRONT_COMPONENT_STORY_DEFAULT_ARGS,
|
||||
onRequestExternalNavigation: requestExternalNavigation,
|
||||
},
|
||||
beforeEach: () => {
|
||||
resetFrontComponentStoryMocks();
|
||||
requestExternalNavigation.mockClear();
|
||||
},
|
||||
};
|
||||
|
||||
export default meta;
|
||||
|
||||
type Story = StoryObj<typeof FrontComponentRenderer>;
|
||||
|
||||
export const ExternalAnchorClickIsHandedToTheHost: Story =
|
||||
runFrontComponentStory({
|
||||
frontComponentBundleName: 'a-properties',
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
|
||||
await expectFrontComponentMounted(canvas);
|
||||
|
||||
const link = await canvas.findByTestId('subject');
|
||||
|
||||
await userEvent.click(link);
|
||||
|
||||
await waitFor(
|
||||
() => {
|
||||
expect(requestExternalNavigation).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ url: 'https://example.com/probe' }),
|
||||
);
|
||||
},
|
||||
{ timeout: INTERACTION_TIMEOUT },
|
||||
);
|
||||
},
|
||||
});
|
||||
+12
-4
@@ -1,3 +1,5 @@
|
||||
import { FrontComponentExternalNavigationContext } from '@/host/contexts/FrontComponentExternalNavigationContext';
|
||||
import { type RequestExternalNavigation } from '@/host/types/RequestExternalNavigation';
|
||||
import { FrontComponentConfirmationModalResultEffect } from '@/remote/components/FrontComponentConfirmationModalResultEffect';
|
||||
import { FrontComponentErrorEffect } from '@/remote/components/FrontComponentErrorEffect';
|
||||
import { FrontComponentInitializeHostCommunicationApiEffect } from '@/remote/components/FrontComponentInitializeHostCommunicationApiEffect';
|
||||
@@ -33,6 +35,7 @@ type FrontComponentRendererProps = {
|
||||
applicationVariables?: Record<string, string>;
|
||||
executionContext: FrontComponentExecutionContext;
|
||||
frontComponentHostCommunicationApi: FrontComponentHostCommunicationApi;
|
||||
onRequestExternalNavigation?: RequestExternalNavigation;
|
||||
onError: (error?: Error) => void;
|
||||
colorScheme: 'light' | 'dark';
|
||||
loadingFallback?: ReactNode;
|
||||
@@ -47,6 +50,7 @@ export const FrontComponentRenderer = ({
|
||||
applicationVariables,
|
||||
executionContext,
|
||||
frontComponentHostCommunicationApi,
|
||||
onRequestExternalNavigation,
|
||||
onError,
|
||||
colorScheme,
|
||||
loadingFallback,
|
||||
@@ -114,10 +118,14 @@ export const FrontComponentRenderer = ({
|
||||
resetKeys={[componentUrl]}
|
||||
fallbackRender={() => null}
|
||||
>
|
||||
<RemoteRootRenderer
|
||||
receiver={receiver}
|
||||
components={fallbackComponentRegistry}
|
||||
/>
|
||||
<FrontComponentExternalNavigationContext.Provider
|
||||
value={onRequestExternalNavigation ?? null}
|
||||
>
|
||||
<RemoteRootRenderer
|
||||
receiver={receiver}
|
||||
components={fallbackComponentRegistry}
|
||||
/>
|
||||
</FrontComponentExternalNavigationContext.Provider>
|
||||
</ErrorBoundary>
|
||||
</ThemeProvider>
|
||||
)}
|
||||
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
import { createContext } from 'react';
|
||||
|
||||
import { type RequestExternalNavigation } from '@/host/types/RequestExternalNavigation';
|
||||
|
||||
export const FrontComponentExternalNavigationContext =
|
||||
createContext<RequestExternalNavigation | null>(null);
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useContext } from 'react';
|
||||
|
||||
import { FrontComponentExternalNavigationContext } from '@/host/contexts/FrontComponentExternalNavigationContext';
|
||||
import {
|
||||
FrontComponentInputFocusContext,
|
||||
type SetEditableFocused,
|
||||
@@ -8,6 +9,7 @@ import { useComposedElementRef } from '@/host/hooks/useComposedElementRef';
|
||||
import { useReactUnsupportedEventListenerRef } from '@/host/hooks/useReactUnsupportedEventListenerRef';
|
||||
import { type ElementRefCallback } from '@/host/types/ElementRefCallback';
|
||||
import { buildHostReactPropsFromRemoteProps } from '@/host/utils/buildHostReactPropsFromRemoteProps';
|
||||
import { createAnchorNavigationClickHandler } from '@/host/utils/createAnchorNavigationClickHandler';
|
||||
import { createDropTargetGuardProps } from '@/host/utils/createDropTargetGuardProps';
|
||||
import { extractReactUnsupportedEventHandlers } from '@/host/utils/extractReactUnsupportedEventHandlers';
|
||||
import { preventDefaultThenForwardToRemote } from '@/host/utils/preventDefaultThenForwardToRemote';
|
||||
@@ -25,6 +27,9 @@ export const useHtmlHostElementProps = (
|
||||
htmlTag: string,
|
||||
): HtmlHostElementProps => {
|
||||
const setEditableFocused = useContext(FrontComponentInputFocusContext);
|
||||
const requestExternalNavigation = useContext(
|
||||
FrontComponentExternalNavigationContext,
|
||||
);
|
||||
|
||||
const { reactUnsupportedEventHandlers, reactBindableProps } =
|
||||
extractReactUnsupportedEventHandlers(
|
||||
@@ -39,6 +44,14 @@ export const useHtmlHostElementProps = (
|
||||
reactUnsupportedEventListenerRef,
|
||||
]);
|
||||
|
||||
const anchorNavigationClickHandler =
|
||||
htmlTag === 'a' &&
|
||||
createAnchorNavigationClickHandler({
|
||||
href: reactBindableProps.href,
|
||||
remoteOnClick: reactBindableProps.onClick,
|
||||
requestExternalNavigation,
|
||||
});
|
||||
|
||||
const hostEnforcedProps: Record<string, unknown> = {
|
||||
...createDropTargetGuardProps(reactBindableProps),
|
||||
...(htmlTag === 'iframe' && {
|
||||
@@ -48,6 +61,10 @@ export const useHtmlHostElementProps = (
|
||||
...(htmlTag === 'form' && {
|
||||
onSubmit: preventDefaultThenForwardToRemote(reactBindableProps.onSubmit),
|
||||
}),
|
||||
...(anchorNavigationClickHandler && {
|
||||
onClick: anchorNavigationClickHandler,
|
||||
onAuxClick: anchorNavigationClickHandler,
|
||||
}),
|
||||
};
|
||||
|
||||
return {
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
export type RequestExternalNavigation = (request: { url: string }) => void;
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
import { type MouseEvent } from 'react';
|
||||
|
||||
import { createAnchorNavigationClickHandler } from '../createAnchorNavigationClickHandler';
|
||||
|
||||
const createMouseEvent = (
|
||||
button: number,
|
||||
modifierKeys: {
|
||||
metaKey?: boolean;
|
||||
ctrlKey?: boolean;
|
||||
shiftKey?: boolean;
|
||||
} = {},
|
||||
) => {
|
||||
const preventDefault = jest.fn();
|
||||
|
||||
return {
|
||||
event: {
|
||||
button,
|
||||
preventDefault,
|
||||
metaKey: modifierKeys.metaKey ?? false,
|
||||
ctrlKey: modifierKeys.ctrlKey ?? false,
|
||||
shiftKey: modifierKeys.shiftKey ?? false,
|
||||
} as unknown as MouseEvent<HTMLAnchorElement>,
|
||||
preventDefault,
|
||||
};
|
||||
};
|
||||
|
||||
describe('createAnchorNavigationClickHandler', () => {
|
||||
it('should intercept an external primary click without forwarding to the remote handler', () => {
|
||||
const requestExternalNavigation = jest.fn();
|
||||
const remoteOnClick = jest.fn();
|
||||
const { event, preventDefault } = createMouseEvent(0);
|
||||
|
||||
createAnchorNavigationClickHandler({
|
||||
href: 'https://example.com/probe',
|
||||
remoteOnClick,
|
||||
requestExternalNavigation,
|
||||
})(event);
|
||||
|
||||
expect(preventDefault).toHaveBeenCalledTimes(1);
|
||||
expect(requestExternalNavigation).toHaveBeenCalledWith({
|
||||
url: 'https://example.com/probe',
|
||||
});
|
||||
expect(remoteOnClick).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should ignore the anchor target so the host always decides how to open the url', () => {
|
||||
const requestExternalNavigation = jest.fn();
|
||||
const { event } = createMouseEvent(0);
|
||||
|
||||
createAnchorNavigationClickHandler({
|
||||
href: 'https://example.com/probe',
|
||||
remoteOnClick: undefined,
|
||||
requestExternalNavigation,
|
||||
})(event);
|
||||
|
||||
expect(requestExternalNavigation).toHaveBeenCalledWith({
|
||||
url: 'https://example.com/probe',
|
||||
});
|
||||
});
|
||||
|
||||
it('should not intercept a same-origin click but still forward it', () => {
|
||||
const requestExternalNavigation = jest.fn();
|
||||
const remoteOnClick = jest.fn();
|
||||
const { event, preventDefault } = createMouseEvent(0);
|
||||
|
||||
createAnchorNavigationClickHandler({
|
||||
href: 'http://localhost/objects/people',
|
||||
remoteOnClick,
|
||||
requestExternalNavigation,
|
||||
})(event);
|
||||
|
||||
expect(preventDefault).not.toHaveBeenCalled();
|
||||
expect(requestExternalNavigation).not.toHaveBeenCalled();
|
||||
expect(remoteOnClick).toHaveBeenCalledWith(event);
|
||||
});
|
||||
|
||||
it('should not prevent default when no navigation handler is provided', () => {
|
||||
const remoteOnClick = jest.fn();
|
||||
const { event, preventDefault } = createMouseEvent(0);
|
||||
|
||||
createAnchorNavigationClickHandler({
|
||||
href: 'https://example.com/probe',
|
||||
remoteOnClick,
|
||||
requestExternalNavigation: null,
|
||||
})(event);
|
||||
|
||||
expect(preventDefault).not.toHaveBeenCalled();
|
||||
expect(remoteOnClick).toHaveBeenCalledWith(event);
|
||||
});
|
||||
|
||||
it('should intercept an external middle click without forwarding to the remote handler', () => {
|
||||
const requestExternalNavigation = jest.fn();
|
||||
const remoteOnClick = jest.fn();
|
||||
const { event, preventDefault } = createMouseEvent(1);
|
||||
|
||||
createAnchorNavigationClickHandler({
|
||||
href: 'https://example.com/probe',
|
||||
remoteOnClick,
|
||||
requestExternalNavigation,
|
||||
})(event);
|
||||
|
||||
expect(preventDefault).toHaveBeenCalledTimes(1);
|
||||
expect(requestExternalNavigation).toHaveBeenCalledWith({
|
||||
url: 'https://example.com/probe',
|
||||
});
|
||||
expect(remoteOnClick).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
['a cmd (meta) modifier', { metaKey: true }],
|
||||
['a ctrl modifier', { ctrlKey: true }],
|
||||
['a shift modifier', { shiftKey: true }],
|
||||
] as Array<
|
||||
[string, { metaKey?: boolean; ctrlKey?: boolean; shiftKey?: boolean }]
|
||||
>)(
|
||||
'should intercept a primary click with %s without forwarding to the remote handler',
|
||||
(_label, modifierKeys) => {
|
||||
const requestExternalNavigation = jest.fn();
|
||||
const remoteOnClick = jest.fn();
|
||||
const { event } = createMouseEvent(0, modifierKeys);
|
||||
|
||||
createAnchorNavigationClickHandler({
|
||||
href: 'https://example.com/probe',
|
||||
remoteOnClick,
|
||||
requestExternalNavigation,
|
||||
})(event);
|
||||
|
||||
expect(requestExternalNavigation).toHaveBeenCalledWith({
|
||||
url: 'https://example.com/probe',
|
||||
});
|
||||
expect(remoteOnClick).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it('should ignore a right click', () => {
|
||||
const requestExternalNavigation = jest.fn();
|
||||
const remoteOnClick = jest.fn();
|
||||
const { event, preventDefault } = createMouseEvent(2);
|
||||
|
||||
createAnchorNavigationClickHandler({
|
||||
href: 'https://example.com/probe',
|
||||
remoteOnClick,
|
||||
requestExternalNavigation,
|
||||
})(event);
|
||||
|
||||
expect(preventDefault).not.toHaveBeenCalled();
|
||||
expect(requestExternalNavigation).not.toHaveBeenCalled();
|
||||
expect(remoteOnClick).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+85
@@ -4,6 +4,8 @@ import { act, createElement } from 'react';
|
||||
import { createRoot, type Root } from 'react-dom/client';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
|
||||
import { FrontComponentExternalNavigationContext } from '@/host/contexts/FrontComponentExternalNavigationContext';
|
||||
|
||||
import { createHtmlHostWrapper } from '../createHtmlHostWrapper';
|
||||
|
||||
(
|
||||
@@ -259,3 +261,86 @@ describe('createHtmlHostWrapper client events', () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('createHtmlHostWrapper anchor navigation', () => {
|
||||
let container: HTMLDivElement;
|
||||
let root: Root;
|
||||
|
||||
beforeEach(() => {
|
||||
container = document.createElement('div');
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
act(() => {
|
||||
root.unmount();
|
||||
});
|
||||
container.remove();
|
||||
});
|
||||
|
||||
const renderAnchor = (
|
||||
props: Record<string, unknown>,
|
||||
requestExternalNavigation: ((request: unknown) => void) | null,
|
||||
) => {
|
||||
const Wrapper = createHtmlHostWrapper('a');
|
||||
|
||||
act(() => {
|
||||
root.render(
|
||||
createElement(
|
||||
FrontComponentExternalNavigationContext.Provider,
|
||||
{ value: requestExternalNavigation },
|
||||
createElement(Wrapper, props, 'link'),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
return container.querySelector('a') as HTMLAnchorElement;
|
||||
};
|
||||
|
||||
const clickAnchor = (anchor: HTMLAnchorElement): MouseEvent => {
|
||||
const clickEvent = new MouseEvent('click', {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
button: 0,
|
||||
});
|
||||
|
||||
act(() => {
|
||||
anchor.dispatchEvent(clickEvent);
|
||||
});
|
||||
|
||||
return clickEvent;
|
||||
};
|
||||
|
||||
it('should prevent default and request navigation for an external anchor click', () => {
|
||||
const requestExternalNavigation = jest.fn();
|
||||
const remoteOnClick = jest.fn();
|
||||
|
||||
const anchor = renderAnchor(
|
||||
{ href: 'https://example.com/probe', onClick: remoteOnClick },
|
||||
requestExternalNavigation,
|
||||
);
|
||||
|
||||
const clickEvent = clickAnchor(anchor);
|
||||
|
||||
expect(clickEvent.defaultPrevented).toBe(true);
|
||||
expect(requestExternalNavigation).toHaveBeenCalledWith({
|
||||
url: 'https://example.com/probe',
|
||||
});
|
||||
expect(remoteOnClick).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should not request navigation for a same-origin anchor click', () => {
|
||||
const requestExternalNavigation = jest.fn();
|
||||
|
||||
const anchor = renderAnchor(
|
||||
{ href: 'http://localhost/objects/people' },
|
||||
requestExternalNavigation,
|
||||
);
|
||||
|
||||
const clickEvent = clickAnchor(anchor);
|
||||
|
||||
expect(clickEvent.defaultPrevented).toBe(false);
|
||||
expect(requestExternalNavigation).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
import { isExternalNavigationUrl } from '../isExternalNavigationUrl';
|
||||
|
||||
describe('isExternalNavigationUrl (jest jsdom test page origin is http://localhost)', () => {
|
||||
it('should return true for a cross-origin https url', () => {
|
||||
expect(isExternalNavigationUrl('https://example.com/probe')).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true for a cross-origin http url', () => {
|
||||
expect(isExternalNavigationUrl('http://example.com')).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false for a same-origin absolute url', () => {
|
||||
expect(isExternalNavigationUrl('http://localhost/settings')).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false for a relative path', () => {
|
||||
expect(isExternalNavigationUrl('/objects/people')).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false for a mailto url', () => {
|
||||
expect(isExternalNavigationUrl('mailto:hello@example.com')).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false for a tel url', () => {
|
||||
expect(isExternalNavigationUrl('tel:+15551234567')).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false for a javascript url', () => {
|
||||
expect(isExternalNavigationUrl('javascript:alert(1)')).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false for an empty href', () => {
|
||||
expect(isExternalNavigationUrl('')).toBe(false);
|
||||
});
|
||||
});
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
import { isFunction, isNonEmptyString } from '@sniptt/guards';
|
||||
import { type MouseEvent } from 'react';
|
||||
import { isDefined } from 'twenty-shared/utils';
|
||||
|
||||
import { type RemoteEventHandler } from '@/host/types/RemoteEventHandler';
|
||||
import { type RequestExternalNavigation } from '@/host/types/RequestExternalNavigation';
|
||||
import { isExternalNavigationUrl } from '@/host/utils/isExternalNavigationUrl';
|
||||
|
||||
const PRIMARY_MOUSE_BUTTON = 0;
|
||||
const MIDDLE_MOUSE_BUTTON = 1;
|
||||
|
||||
type CreateAnchorNavigationClickHandlerParams = {
|
||||
href: unknown;
|
||||
remoteOnClick: unknown;
|
||||
requestExternalNavigation: RequestExternalNavigation | null;
|
||||
};
|
||||
|
||||
export const createAnchorNavigationClickHandler =
|
||||
({
|
||||
href,
|
||||
remoteOnClick,
|
||||
requestExternalNavigation,
|
||||
}: CreateAnchorNavigationClickHandlerParams) =>
|
||||
(event: MouseEvent<HTMLAnchorElement>) => {
|
||||
// Bound to both onClick and onAuxClick: a middle click opens a new tab
|
||||
// through auxclick, never click. auxclick also fires on right click, which
|
||||
// must stay untouched so the native context menu keeps working.
|
||||
const clickCanOpenNavigation =
|
||||
event.button === PRIMARY_MOUSE_BUTTON ||
|
||||
event.button === MIDDLE_MOUSE_BUTTON;
|
||||
|
||||
if (
|
||||
isDefined(requestExternalNavigation) &&
|
||||
clickCanOpenNavigation &&
|
||||
isNonEmptyString(href) &&
|
||||
isExternalNavigationUrl(href)
|
||||
) {
|
||||
event.preventDefault();
|
||||
|
||||
requestExternalNavigation({
|
||||
url: new URL(href, window.location.href).href,
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const clickIsPrimaryActivation = event.button === PRIMARY_MOUSE_BUTTON;
|
||||
|
||||
if (clickIsPrimaryActivation && isFunction(remoteOnClick)) {
|
||||
(remoteOnClick as RemoteEventHandler)(event);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,13 @@
|
||||
export const isExternalNavigationUrl = (href: string): boolean => {
|
||||
try {
|
||||
const resolvedUrl = new URL(href, window.location.href);
|
||||
|
||||
if (resolvedUrl.protocol !== 'http:' && resolvedUrl.protocol !== 'https:') {
|
||||
return false;
|
||||
}
|
||||
|
||||
return resolvedUrl.origin !== window.location.origin;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
@@ -1,8 +1,10 @@
|
||||
export { FrontComponentRenderer } from './host/components/FrontComponentRenderer';
|
||||
export { FrontComponentExternalNavigationContext } from './host/contexts/FrontComponentExternalNavigationContext';
|
||||
export {
|
||||
FrontComponentInputFocusContext,
|
||||
type SetEditableFocused,
|
||||
} from './host/contexts/FrontComponentInputFocusContext';
|
||||
export { type RequestExternalNavigation } from './host/types/RequestExternalNavigation';
|
||||
export { componentRegistry } from './host/generated/host-component-registry';
|
||||
export { FrontComponentConfirmationModalResultEffect } from './remote/components/FrontComponentConfirmationModalResultEffect';
|
||||
export { FrontComponentErrorEffect } from './remote/components/FrontComponentErrorEffect';
|
||||
|
||||
@@ -16,6 +16,7 @@ import { CommandRunner } from '@/command-menu-item/engine-command/components/Com
|
||||
import { MainContextStoreProvider } from '@/context-store/components/MainContextStoreProvider';
|
||||
import { ErrorMessageEffect } from '@/error-handler/components/ErrorMessageEffect';
|
||||
import { PromiseRejectionEffect } from '@/error-handler/components/PromiseRejectionEffect';
|
||||
import { FrontComponentExternalLinkModalManager } from '@/front-components/components/FrontComponentExternalLinkModalManager';
|
||||
import { IsMinimalMetadataReadyEffect } from '@/metadata-store/effect-components/IsMinimalMetadataReadyEffect';
|
||||
import { MinimalMetadataLoadEffect } from '@/metadata-store/effect-components/MinimalMetadataLoadEffect';
|
||||
import { UserMetadataProviderInitialEffect } from '@/metadata-store/effect-components/UserMetadataProviderInitialEffect';
|
||||
@@ -69,6 +70,7 @@ export const WorkspaceAppProviders = () => {
|
||||
<Outlet />
|
||||
<GlobalFilePreviewModal />
|
||||
<CommandMenuConfirmationModalManager />
|
||||
<FrontComponentExternalLinkModalManager />
|
||||
<CommandRunner />
|
||||
</StrictMode>
|
||||
</DialogManager>
|
||||
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
import { t } from '@lingui/core/macro';
|
||||
import { useState } from 'react';
|
||||
import { isDefined } from 'twenty-shared/utils';
|
||||
|
||||
import { FrontComponentExternalLinkModalSubtitle } from '@/front-components/components/FrontComponentExternalLinkModalSubtitle';
|
||||
import { FRONT_COMPONENT_EXTERNAL_LINK_MODAL_ID } from '@/front-components/constants/FrontComponentExternalLinkModalId';
|
||||
import { frontComponentExternalLinkModalConfigState } from '@/front-components/states/frontComponentExternalLinkModalConfigState';
|
||||
import { trustedFrontComponentExternalOriginsState } from '@/front-components/states/trustedFrontComponentExternalOriginsState';
|
||||
import { openExternalUrl } from '@/front-components/utils/openExternalUrl';
|
||||
import { ConfirmationModal } from '@/ui/layout/modal/components/ConfirmationModal';
|
||||
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
|
||||
import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';
|
||||
|
||||
export const FrontComponentExternalLinkModalManager = () => {
|
||||
const frontComponentExternalLinkModalConfig = useAtomStateValue(
|
||||
frontComponentExternalLinkModalConfigState,
|
||||
);
|
||||
const setFrontComponentExternalLinkModalConfig = useSetAtomState(
|
||||
frontComponentExternalLinkModalConfigState,
|
||||
);
|
||||
const setTrustedFrontComponentExternalOrigins = useSetAtomState(
|
||||
trustedFrontComponentExternalOriginsState,
|
||||
);
|
||||
const [shouldTrustOrigin, setShouldTrustOrigin] = useState(true);
|
||||
|
||||
if (!isDefined(frontComponentExternalLinkModalConfig)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const { applicationId, url, origin } = frontComponentExternalLinkModalConfig;
|
||||
|
||||
const handleConfirmClick = () => {
|
||||
if (shouldTrustOrigin) {
|
||||
setTrustedFrontComponentExternalOrigins((previousTrustedOrigins) => ({
|
||||
...previousTrustedOrigins,
|
||||
[applicationId]: [
|
||||
...(previousTrustedOrigins[applicationId] ?? []),
|
||||
origin,
|
||||
],
|
||||
}));
|
||||
}
|
||||
|
||||
openExternalUrl(url);
|
||||
setFrontComponentExternalLinkModalConfig(null);
|
||||
setShouldTrustOrigin(true);
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
setFrontComponentExternalLinkModalConfig(null);
|
||||
setShouldTrustOrigin(true);
|
||||
};
|
||||
|
||||
return (
|
||||
<ConfirmationModal
|
||||
modalInstanceId={FRONT_COMPONENT_EXTERNAL_LINK_MODAL_ID}
|
||||
title={t`You're leaving Twenty`}
|
||||
subtitle={
|
||||
<FrontComponentExternalLinkModalSubtitle
|
||||
url={url}
|
||||
origin={origin}
|
||||
shouldTrustOrigin={shouldTrustOrigin}
|
||||
onShouldTrustOriginChange={setShouldTrustOrigin}
|
||||
/>
|
||||
}
|
||||
confirmButtonText={t`Continue`}
|
||||
confirmButtonAccent="blue"
|
||||
onConfirmClick={handleConfirmClick}
|
||||
onClose={handleClose}
|
||||
/>
|
||||
);
|
||||
};
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
import { styled } from '@linaria/react';
|
||||
import { Trans } from '@lingui/react/macro';
|
||||
import { useId } from 'react';
|
||||
import { Checkbox } from 'twenty-ui/input';
|
||||
import { themeCssVariables } from 'twenty-ui/theme-constants';
|
||||
|
||||
const StyledContent = styled.div`
|
||||
align-items: center;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: ${themeCssVariables.spacing[4]};
|
||||
overflow-wrap: anywhere;
|
||||
`;
|
||||
|
||||
const StyledTrustRow = styled.div`
|
||||
align-items: center;
|
||||
align-self: stretch;
|
||||
display: flex;
|
||||
gap: ${themeCssVariables.spacing[2]};
|
||||
text-align: left;
|
||||
`;
|
||||
|
||||
const StyledTrustLabel = styled.span`
|
||||
cursor: pointer;
|
||||
`;
|
||||
|
||||
type FrontComponentExternalLinkModalSubtitleProps = {
|
||||
url: string;
|
||||
origin: string;
|
||||
shouldTrustOrigin: boolean;
|
||||
onShouldTrustOriginChange: (shouldTrustOrigin: boolean) => void;
|
||||
};
|
||||
|
||||
export const FrontComponentExternalLinkModalSubtitle = ({
|
||||
url,
|
||||
origin,
|
||||
shouldTrustOrigin,
|
||||
onShouldTrustOriginChange,
|
||||
}: FrontComponentExternalLinkModalSubtitleProps) => {
|
||||
const trustOriginLabelId = useId();
|
||||
|
||||
return (
|
||||
<StyledContent>
|
||||
<span>
|
||||
<Trans>
|
||||
This link will take you to an external site: <strong>{url}</strong>
|
||||
</Trans>
|
||||
</span>
|
||||
<StyledTrustRow>
|
||||
<Checkbox
|
||||
checked={shouldTrustOrigin}
|
||||
onCheckedChange={onShouldTrustOriginChange}
|
||||
aria-labelledby={trustOriginLabelId}
|
||||
/>
|
||||
<StyledTrustLabel
|
||||
id={trustOriginLabelId}
|
||||
onClick={() => onShouldTrustOriginChange(!shouldTrustOrigin)}
|
||||
>
|
||||
<Trans>
|
||||
Don't ask again for <strong>{origin}</strong>
|
||||
</Trans>
|
||||
</StyledTrustLabel>
|
||||
</StyledTrustRow>
|
||||
</StyledContent>
|
||||
);
|
||||
};
|
||||
+6
@@ -4,6 +4,7 @@ import { FrontComponentRendererProvider } from '@/front-components/components/Fr
|
||||
import { useFrontComponentExecutionContext } from '@/front-components/hooks/useFrontComponentExecutionContext';
|
||||
import { useOnApplicationSdkClientChecksumsUpdated } from '@/front-components/hooks/useOnApplicationSdkClientChecksumsUpdated';
|
||||
import { useOnFrontComponentUpdated } from '@/front-components/hooks/useOnFrontComponentUpdated';
|
||||
import { useRequestFrontComponentExternalNavigation } from '@/front-components/hooks/useRequestFrontComponentExternalNavigation';
|
||||
import { getFrontComponentUrl } from '@/front-components/utils/getFrontComponentUrl';
|
||||
import { getSdkClientUrls } from '@/front-components/utils/getSdkClientUrls';
|
||||
import { useGetLogicFunctionHttpUrl } from '@/settings/logic-functions/hooks/useGetLogicFunctionHttpUrl';
|
||||
@@ -91,6 +92,10 @@ const FrontComponentRendererContent = ({
|
||||
colorScheme,
|
||||
});
|
||||
|
||||
const requestExternalNavigation = useRequestFrontComponentExternalNavigation({
|
||||
applicationId,
|
||||
});
|
||||
|
||||
const handleError = useCallback(
|
||||
(error?: Error) => {
|
||||
if (!isDefined(error)) {
|
||||
@@ -157,6 +162,7 @@ const FrontComponentRendererContent = ({
|
||||
frontComponentHostCommunicationApi={
|
||||
frontComponentHostCommunicationApi
|
||||
}
|
||||
onRequestExternalNavigation={requestExternalNavigation}
|
||||
applicationVariables={applicationVariables}
|
||||
onError={handleError}
|
||||
loadingFallback={loadingFallback}
|
||||
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
export const FRONT_COMPONENT_EXTERNAL_LINK_MODAL_ID =
|
||||
'front-component-external-link-modal';
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { Provider as JotaiProvider } from 'jotai';
|
||||
import { type ReactNode } from 'react';
|
||||
|
||||
import { useRequestFrontComponentExternalNavigation } from '@/front-components/hooks/useRequestFrontComponentExternalNavigation';
|
||||
import { frontComponentExternalLinkModalConfigState } from '@/front-components/states/frontComponentExternalLinkModalConfigState';
|
||||
import { trustedFrontComponentExternalOriginsState } from '@/front-components/states/trustedFrontComponentExternalOriginsState';
|
||||
import { jotaiStore } from '@/ui/utilities/state/jotai/jotaiStore';
|
||||
|
||||
const mockOpenModal = jest.fn();
|
||||
|
||||
jest.mock('@/ui/layout/modal/hooks/useModal', () => ({
|
||||
useModal: () => ({
|
||||
openModal: mockOpenModal,
|
||||
closeModal: jest.fn(),
|
||||
toggleModal: jest.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
const APPLICATION_ID = 'application-1';
|
||||
|
||||
const wrapper = ({ children }: { children: ReactNode }) => (
|
||||
<JotaiProvider store={jotaiStore}>{children}</JotaiProvider>
|
||||
);
|
||||
|
||||
const renderRequestNavigation = () =>
|
||||
renderHook(
|
||||
() =>
|
||||
useRequestFrontComponentExternalNavigation({
|
||||
applicationId: APPLICATION_ID,
|
||||
}),
|
||||
{ wrapper },
|
||||
);
|
||||
|
||||
describe('useRequestFrontComponentExternalNavigation', () => {
|
||||
const originalWindowOpen = window.open;
|
||||
|
||||
beforeEach(() => {
|
||||
mockOpenModal.mockClear();
|
||||
window.open = jest.fn();
|
||||
jotaiStore.set(trustedFrontComponentExternalOriginsState.atom, {});
|
||||
jotaiStore.set(frontComponentExternalLinkModalConfigState.atom, null);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
window.open = originalWindowOpen;
|
||||
});
|
||||
|
||||
it('should open the confirmation modal for an untrusted origin', () => {
|
||||
const { result } = renderRequestNavigation();
|
||||
|
||||
act(() => {
|
||||
result.current({ url: 'https://example.com/pricing' });
|
||||
});
|
||||
|
||||
expect(mockOpenModal).toHaveBeenCalledTimes(1);
|
||||
expect(
|
||||
jotaiStore.get(frontComponentExternalLinkModalConfigState.atom),
|
||||
).toEqual({
|
||||
applicationId: APPLICATION_ID,
|
||||
url: 'https://example.com/pricing',
|
||||
origin: 'https://example.com',
|
||||
});
|
||||
expect(window.open).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should navigate directly when the origin is already trusted by the application', () => {
|
||||
jotaiStore.set(trustedFrontComponentExternalOriginsState.atom, {
|
||||
[APPLICATION_ID]: ['https://example.com'],
|
||||
});
|
||||
|
||||
const { result } = renderRequestNavigation();
|
||||
|
||||
act(() => {
|
||||
result.current({ url: 'https://example.com/pricing' });
|
||||
});
|
||||
|
||||
expect(window.open).toHaveBeenCalledWith(
|
||||
'https://example.com/pricing',
|
||||
'_blank',
|
||||
'noopener,noreferrer',
|
||||
);
|
||||
expect(mockOpenModal).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should not reuse trust granted to a different application', () => {
|
||||
jotaiStore.set(trustedFrontComponentExternalOriginsState.atom, {
|
||||
'other-application': ['https://example.com'],
|
||||
});
|
||||
|
||||
const { result } = renderRequestNavigation();
|
||||
|
||||
act(() => {
|
||||
result.current({ url: 'https://example.com/pricing' });
|
||||
});
|
||||
|
||||
expect(mockOpenModal).toHaveBeenCalledTimes(1);
|
||||
expect(window.open).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
import { useStore } from 'jotai';
|
||||
import { useCallback } from 'react';
|
||||
import { type RequestExternalNavigation } from 'twenty-front-component-renderer';
|
||||
|
||||
import { FRONT_COMPONENT_EXTERNAL_LINK_MODAL_ID } from '@/front-components/constants/FrontComponentExternalLinkModalId';
|
||||
import { frontComponentExternalLinkModalConfigState } from '@/front-components/states/frontComponentExternalLinkModalConfigState';
|
||||
import { trustedFrontComponentExternalOriginsState } from '@/front-components/states/trustedFrontComponentExternalOriginsState';
|
||||
import { openExternalUrl } from '@/front-components/utils/openExternalUrl';
|
||||
import { useModal } from '@/ui/layout/modal/hooks/useModal';
|
||||
import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';
|
||||
|
||||
export const useRequestFrontComponentExternalNavigation = ({
|
||||
applicationId,
|
||||
}: {
|
||||
applicationId: string;
|
||||
}): RequestExternalNavigation => {
|
||||
const jotaiStore = useStore();
|
||||
const setFrontComponentExternalLinkModalConfig = useSetAtomState(
|
||||
frontComponentExternalLinkModalConfigState,
|
||||
);
|
||||
const { openModal } = useModal();
|
||||
|
||||
return useCallback(
|
||||
({ url }) => {
|
||||
const origin = new URL(url).origin;
|
||||
|
||||
const trustedFrontComponentExternalOrigins = jotaiStore.get(
|
||||
trustedFrontComponentExternalOriginsState.atom,
|
||||
);
|
||||
|
||||
const applicationTrustsOrigin =
|
||||
trustedFrontComponentExternalOrigins[applicationId]?.includes(origin) ??
|
||||
false;
|
||||
|
||||
if (applicationTrustsOrigin) {
|
||||
openExternalUrl(url);
|
||||
return;
|
||||
}
|
||||
|
||||
setFrontComponentExternalLinkModalConfig({
|
||||
applicationId,
|
||||
url,
|
||||
origin,
|
||||
});
|
||||
openModal(FRONT_COMPONENT_EXTERNAL_LINK_MODAL_ID);
|
||||
},
|
||||
[
|
||||
applicationId,
|
||||
jotaiStore,
|
||||
setFrontComponentExternalLinkModalConfig,
|
||||
openModal,
|
||||
],
|
||||
);
|
||||
};
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
import { type FrontComponentExternalLinkModalConfig } from '@/front-components/types/FrontComponentExternalLinkModalConfig';
|
||||
import { createAtomState } from '@/ui/utilities/state/jotai/utils/createAtomState';
|
||||
|
||||
export const frontComponentExternalLinkModalConfigState =
|
||||
createAtomState<FrontComponentExternalLinkModalConfig | null>({
|
||||
key: 'frontComponentExternalLinkModalConfigState',
|
||||
defaultValue: null,
|
||||
});
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
import { type TrustedExternalOriginsByApplicationId } from '@/front-components/types/TrustedExternalOriginsByApplicationId';
|
||||
import { isTrustedExternalOriginsByApplicationId } from '@/front-components/utils/isTrustedExternalOriginsByApplicationId';
|
||||
import { createAtomState } from '@/ui/utilities/state/jotai/utils/createAtomState';
|
||||
|
||||
export const trustedFrontComponentExternalOriginsState =
|
||||
createAtomState<TrustedExternalOriginsByApplicationId>({
|
||||
key: 'trustedFrontComponentExternalOriginsState',
|
||||
defaultValue: {},
|
||||
useLocalStorage: true,
|
||||
localStorageOptions: { getOnInit: true },
|
||||
validateInitFn: (payload) =>
|
||||
isTrustedExternalOriginsByApplicationId(payload),
|
||||
});
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
export type FrontComponentExternalLinkModalConfig = {
|
||||
applicationId: string;
|
||||
url: string;
|
||||
origin: string;
|
||||
};
|
||||
+1
@@ -0,0 +1 @@
|
||||
export type TrustedExternalOriginsByApplicationId = Record<string, string[]>;
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
import { isTrustedExternalOriginsByApplicationId } from '@/front-components/utils/isTrustedExternalOriginsByApplicationId';
|
||||
|
||||
describe('isTrustedExternalOriginsByApplicationId', () => {
|
||||
it('should accept an empty object', () => {
|
||||
expect(isTrustedExternalOriginsByApplicationId({})).toBe(true);
|
||||
});
|
||||
|
||||
it('should accept a well-formed map of application id to origin list', () => {
|
||||
expect(
|
||||
isTrustedExternalOriginsByApplicationId({
|
||||
'application-1': ['https://example.com', 'https://twenty.com'],
|
||||
'application-2': [],
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should reject a value whose origins are not an array', () => {
|
||||
expect(
|
||||
isTrustedExternalOriginsByApplicationId({
|
||||
'application-1': 'https://example.com',
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('should reject a value whose origins contain a non-string', () => {
|
||||
expect(
|
||||
isTrustedExternalOriginsByApplicationId({ 'application-1': [123] }),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('should reject an array payload', () => {
|
||||
expect(
|
||||
isTrustedExternalOriginsByApplicationId(['https://example.com']),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('should reject a primitive payload', () => {
|
||||
expect(isTrustedExternalOriginsByApplicationId('not-an-object')).toBe(
|
||||
false,
|
||||
);
|
||||
expect(isTrustedExternalOriginsByApplicationId(null)).toBe(false);
|
||||
expect(isTrustedExternalOriginsByApplicationId(42)).toBe(false);
|
||||
});
|
||||
});
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
import { isArray, isObject, isString } from '@sniptt/guards';
|
||||
|
||||
import { type TrustedExternalOriginsByApplicationId } from '@/front-components/types/TrustedExternalOriginsByApplicationId';
|
||||
|
||||
export const isTrustedExternalOriginsByApplicationId = (
|
||||
payload: unknown,
|
||||
): payload is TrustedExternalOriginsByApplicationId =>
|
||||
isObject(payload) &&
|
||||
!isArray(payload) &&
|
||||
Object.values(payload).every(
|
||||
(origins) => isArray(origins) && origins.every(isString),
|
||||
);
|
||||
@@ -0,0 +1,5 @@
|
||||
// Always a new tab: a front component must not be able to navigate the Twenty
|
||||
// tab away, which would let a trusted origin replace the app with a lookalike.
|
||||
export const openExternalUrl = (url: string) => {
|
||||
window.open(url, '_blank', 'noopener,noreferrer');
|
||||
};
|
||||
+42
-64
File diff suppressed because one or more lines are too long
+11
@@ -107,6 +107,17 @@ const HelloWorld = () => {
|
||||
Render count: {renderCount}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<a
|
||||
href="https://github.com/twentyhq/twenty"
|
||||
style={{
|
||||
color: '#0284c7',
|
||||
fontSize: 14,
|
||||
fontWeight: 600,
|
||||
}}
|
||||
>
|
||||
Twenty on GitHub
|
||||
</a>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user