Revert the external link confirmation popup for front components (#23567)

Reverts #23270 and #23404.

Links in front components navigate natively again, with no confirmation
popup and no per-app trusted-origins state in localStorage.

<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/twentyhq/twenty/pull/23567?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:
Raphaël Bosi
2026-07-30 14:55:55 +02:00
committed by GitHub
parent 66e7093524
commit a3beea893d
30 changed files with 68 additions and 1057 deletions
@@ -1,54 +0,0 @@
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 },
);
},
});
@@ -1,7 +1,5 @@
import { ROOT_CONTAINER_STYLE } from '@/host/constants/RootContainerStyle';
import { FrontComponentExternalNavigationContext } from '@/host/contexts/FrontComponentExternalNavigationContext';
import { FrontComponentGeometryTrackerContext } from '@/host/contexts/FrontComponentGeometryTrackerContext';
import { type RequestExternalNavigation } from '@/host/types/RequestExternalNavigation';
import { createGeometryTracker } from '@/host/utils/createGeometryTracker';
import { FrontComponentConfirmationModalResultEffect } from '@/remote/components/FrontComponentConfirmationModalResultEffect';
import { FrontComponentErrorEffect } from '@/remote/components/FrontComponentErrorEffect';
@@ -39,7 +37,6 @@ type FrontComponentRendererProps = {
applicationVariables?: Record<string, string>;
executionContext: FrontComponentExecutionContext;
frontComponentHostCommunicationApi: FrontComponentHostCommunicationApi;
onRequestExternalNavigation?: RequestExternalNavigation;
onError: (error?: Error) => void;
colorScheme: 'light' | 'dark';
loadingFallback?: ReactNode;
@@ -54,7 +51,6 @@ export const FrontComponentRenderer = ({
applicationVariables,
executionContext,
frontComponentHostCommunicationApi,
onRequestExternalNavigation,
onError,
colorScheme,
loadingFallback,
@@ -131,14 +127,10 @@ export const FrontComponentRenderer = ({
resetKeys={[componentUrl]}
fallbackRender={() => null}
>
<FrontComponentExternalNavigationContext.Provider
value={onRequestExternalNavigation ?? null}
>
<RemoteRootRenderer
receiver={receiver}
components={fallbackComponentRegistry}
/>
</FrontComponentExternalNavigationContext.Provider>
<RemoteRootRenderer
receiver={receiver}
components={fallbackComponentRegistry}
/>
</ErrorBoundary>
</ThemeProvider>
)}
@@ -1,6 +0,0 @@
import { createContext } from 'react';
import { type RequestExternalNavigation } from '@/host/types/RequestExternalNavigation';
export const FrontComponentExternalNavigationContext =
createContext<RequestExternalNavigation | null>(null);
@@ -1,6 +1,5 @@
import { useContext } from 'react';
import { FrontComponentExternalNavigationContext } from '@/host/contexts/FrontComponentExternalNavigationContext';
import {
FrontComponentInputFocusContext,
type SetEditableFocused,
@@ -10,7 +9,6 @@ import { useGeometryNodeRef } from '@/host/hooks/useGeometryNodeRef';
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 { getRemoteElementIdFromProps } from '@/host/utils/getRemoteElementIdFromProps';
@@ -29,9 +27,6 @@ export const useHtmlHostElementProps = (
htmlTag: string,
): HtmlHostElementProps => {
const setEditableFocused = useContext(FrontComponentInputFocusContext);
const requestExternalNavigation = useContext(
FrontComponentExternalNavigationContext,
);
const remoteElementId = getRemoteElementIdFromProps(props);
@@ -51,14 +46,6 @@ export const useHtmlHostElementProps = (
geometryNodeRef,
]);
const anchorNavigationClickHandler =
htmlTag === 'a' &&
createAnchorNavigationClickHandler({
href: reactBindableProps.href,
remoteOnClick: reactBindableProps.onClick,
requestExternalNavigation,
});
const hostEnforcedProps: Record<string, unknown> = {
...createDropTargetGuardProps(reactBindableProps),
...(htmlTag === 'iframe' && {
@@ -68,10 +55,6 @@ export const useHtmlHostElementProps = (
...(htmlTag === 'form' && {
onSubmit: preventDefaultThenForwardToRemote(reactBindableProps.onSubmit),
}),
...(anchorNavigationClickHandler && {
onClick: anchorNavigationClickHandler,
onAuxClick: anchorNavigationClickHandler,
}),
};
return {
@@ -1 +0,0 @@
export type RequestExternalNavigation = (request: { url: string }) => void;
@@ -1,150 +0,0 @@
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();
});
});
@@ -6,8 +6,6 @@ import { createRoot, type Root } from 'react-dom/client';
import { renderToStaticMarkup } from 'react-dom/server';
import { jsx } from 'react/jsx-runtime';
import { FrontComponentExternalNavigationContext } from '@/host/contexts/FrontComponentExternalNavigationContext';
import { createHtmlHostWrapper } from '../createHtmlHostWrapper';
(
@@ -337,86 +335,3 @@ 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();
});
});
@@ -1,35 +0,0 @@
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);
});
});
@@ -1,52 +0,0 @@
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);
}
};
@@ -1,13 +0,0 @@
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,10 +1,8 @@
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,7 +16,6 @@ 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';
@@ -71,7 +70,6 @@ export const WorkspaceAppProviders = () => {
<Outlet />
<GlobalFilePreviewModal />
<CommandMenuConfirmationModalManager />
<FrontComponentExternalLinkModalManager />
<CommandRunner />
</StrictMode>
</DialogManager>
@@ -1,153 +0,0 @@
import { styled } from '@linaria/react';
import { t } from '@lingui/core/macro';
import { useId } from 'react';
import { Button, Checkbox } from 'twenty-ui/input';
import { themeCssVariables } from 'twenty-ui/theme-constants';
import { H1Title, H1TitleFontColor } from 'twenty-ui/typography';
import { FRONT_COMPONENT_EXTERNAL_LINK_MODAL_ID } from '@/front-components/constants/FrontComponentExternalLinkModalId';
import { getExternalLinkDisplayUrl } from '@/front-components/utils/getExternalLinkDisplayUrl';
import { ModalStatefulWrapper } from '@/ui/layout/modal/components/ModalStatefulWrapper';
import { useModal } from '@/ui/layout/modal/hooks/useModal';
const FRONT_COMPONENT_EXTERNAL_LINK_MODAL_WIDTH = 320;
const StyledCenteredTitle = styled.div`
text-align: center;
h2 {
margin-bottom: 0;
}
`;
const StyledDestinationUrl = styled.span`
align-items: center;
align-self: center;
background-color: ${themeCssVariables.background.transparent.lighter};
border: 1px solid ${themeCssVariables.border.color.strong};
border-radius: ${themeCssVariables.border.radius.pill};
color: ${themeCssVariables.font.color.primary};
corner-shape: round;
display: inline-flex;
font-size: ${themeCssVariables.font.size.md};
height: 20px;
justify-content: center;
max-width: 100%;
overflow: hidden;
padding: 0 ${themeCssVariables.spacing[2]};
`;
const StyledDestinationUrlText = styled.span`
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
`;
const StyledActions = styled.div`
display: flex;
flex-direction: column;
gap: ${themeCssVariables.spacing[2]};
`;
const StyledTrustOriginRow = styled.div`
align-items: center;
display: flex;
gap: ${themeCssVariables.spacing[1]};
justify-content: center;
`;
const StyledTrustOriginLabel = styled.span`
color: ${themeCssVariables.font.color.primary};
cursor: pointer;
font-size: ${themeCssVariables.font.size.sm};
`;
type FrontComponentExternalLinkModalProps = {
url: string;
shouldTrustOrigin: boolean;
onShouldTrustOriginChange: (shouldTrustOrigin: boolean) => void;
onConfirm: () => void;
onClose: () => void;
};
export const FrontComponentExternalLinkModal = ({
url,
shouldTrustOrigin,
onShouldTrustOriginChange,
onConfirm,
onClose,
}: FrontComponentExternalLinkModalProps) => {
const { closeModal } = useModal();
const trustOriginLabelId = useId();
const handleConfirmClick = () => {
closeModal(FRONT_COMPONENT_EXTERNAL_LINK_MODAL_ID);
onConfirm();
};
const handleCancelClick = () => {
closeModal(FRONT_COMPONENT_EXTERNAL_LINK_MODAL_ID);
onClose();
};
return (
<ModalStatefulWrapper
modalInstanceId={FRONT_COMPONENT_EXTERNAL_LINK_MODAL_ID}
onClose={onClose}
onEnter={handleConfirmClick}
isClosable={true}
padding="large"
gap={6}
dataGloballyPreventClickOutside
renderInDocumentBody
smallBorderRadius
width={FRONT_COMPONENT_EXTERNAL_LINK_MODAL_WIDTH}
autoHeight
>
<StyledCenteredTitle>
<H1Title
title={t`Open external link?`}
fontColor={H1TitleFontColor.Primary}
/>
</StyledCenteredTitle>
<StyledDestinationUrl>
<StyledDestinationUrlText>
{getExternalLinkDisplayUrl(url)}
</StyledDestinationUrlText>
</StyledDestinationUrl>
<StyledActions>
<StyledTrustOriginRow>
<Checkbox
checked={shouldTrustOrigin}
onCheckedChange={onShouldTrustOriginChange}
aria-labelledby={trustOriginLabelId}
/>
<StyledTrustOriginLabel
id={trustOriginLabelId}
onClick={() => onShouldTrustOriginChange(!shouldTrustOrigin)}
>
{t`Always allow links to this domain`}
</StyledTrustOriginLabel>
</StyledTrustOriginRow>
<Button
onClick={handleCancelClick}
variant="secondary"
title={t`Cancel`}
fullWidth
justify="center"
dataTestId="front-component-external-link-modal-cancel-button"
/>
<Button
onClick={handleConfirmClick}
variant="primary"
accent="blue"
title={t`Open link`}
fullWidth
justify="center"
dataTestId="front-component-external-link-modal-confirm-button"
/>
</StyledActions>
</ModalStatefulWrapper>
);
};
@@ -1,59 +0,0 @@
import { useState } from 'react';
import { isDefined } from 'twenty-shared/utils';
import { FrontComponentExternalLinkModal } from '@/front-components/components/FrontComponentExternalLinkModal';
import { frontComponentExternalLinkModalConfigState } from '@/front-components/states/frontComponentExternalLinkModalConfigState';
import { trustedFrontComponentExternalOriginsState } from '@/front-components/states/trustedFrontComponentExternalOriginsState';
import { openExternalUrl } from '@/front-components/utils/openExternalUrl';
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 handleConfirm = () => {
if (shouldTrustOrigin) {
setTrustedFrontComponentExternalOrigins((previousTrustedOrigins) => ({
...previousTrustedOrigins,
[applicationId]: [
...(previousTrustedOrigins[applicationId] ?? []),
origin,
],
}));
}
openExternalUrl(url);
setFrontComponentExternalLinkModalConfig(null);
setShouldTrustOrigin(true);
};
const handleClose = () => {
setFrontComponentExternalLinkModalConfig(null);
setShouldTrustOrigin(true);
};
return (
<FrontComponentExternalLinkModal
url={url}
shouldTrustOrigin={shouldTrustOrigin}
onShouldTrustOriginChange={setShouldTrustOrigin}
onConfirm={handleConfirm}
onClose={handleClose}
/>
);
};
@@ -4,7 +4,6 @@ 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';
@@ -92,10 +91,6 @@ const FrontComponentRendererContent = ({
colorScheme,
});
const requestExternalNavigation = useRequestFrontComponentExternalNavigation({
applicationId,
});
const handleError = useCallback(
(error?: Error) => {
if (!isDefined(error)) {
@@ -162,7 +157,6 @@ const FrontComponentRendererContent = ({
frontComponentHostCommunicationApi={
frontComponentHostCommunicationApi
}
onRequestExternalNavigation={requestExternalNavigation}
applicationVariables={applicationVariables}
onError={handleError}
loadingFallback={loadingFallback}
@@ -1,72 +0,0 @@
import {
type Decorator,
type Meta,
type StoryObj,
} from '@storybook/react-vite';
import { fn } from 'storybook/test';
import { FrontComponentExternalLinkModal } from '@/front-components/components/FrontComponentExternalLinkModal';
import { FRONT_COMPONENT_EXTERNAL_LINK_MODAL_ID } from '@/front-components/constants/FrontComponentExternalLinkModalId';
import { isModalOpenedComponentState } from '@/ui/layout/modal/states/isModalOpenedComponentState';
import { focusStackState } from '@/ui/utilities/focus/states/focusStackState';
import { FocusComponentType } from '@/ui/utilities/focus/types/FocusComponentType';
import { jotaiStore } from '@/ui/utilities/state/jotai/jotaiStore';
import { ComponentDecorator } from 'twenty-ui/testing';
import { RootDecorator } from '~/testing/decorators/RootDecorator';
const OpenedModalDecorator: Decorator = (Story) => {
jotaiStore.set(
isModalOpenedComponentState.atomFamily({
instanceId: FRONT_COMPONENT_EXTERNAL_LINK_MODAL_ID,
}),
true,
);
jotaiStore.set(focusStackState.atom, [
{
focusId: FRONT_COMPONENT_EXTERNAL_LINK_MODAL_ID,
componentInstance: {
componentType: FocusComponentType.MODAL,
componentInstanceId: FRONT_COMPONENT_EXTERNAL_LINK_MODAL_ID,
},
globalHotkeysConfig: {
enableGlobalHotkeysWithModifiers: true,
enableGlobalHotkeysConflictingWithKeyboard: true,
},
},
]);
return <Story />;
};
const meta: Meta<typeof FrontComponentExternalLinkModal> = {
title: 'Modules/FrontComponents/FrontComponentExternalLinkModal',
component: FrontComponentExternalLinkModal,
decorators: [OpenedModalDecorator, RootDecorator, ComponentDecorator],
parameters: {
disableHotkeyInitialization: true,
},
args: {
url: 'https://nvidia.com',
shouldTrustOrigin: true,
onShouldTrustOriginChange: fn(),
onConfirm: fn(),
onClose: fn(),
},
};
export default meta;
type Story = StoryObj<typeof FrontComponentExternalLinkModal>;
export const Default: Story = {};
export const WithTrustedOriginUnchecked: Story = {
args: {
shouldTrustOrigin: false,
},
};
export const WithLongUrl: Story = {
args: {
url: 'https://developer.nvidia.com/blog/category/generative-ai/very-long-article-slug?utm_source=twenty',
},
};
@@ -1,2 +0,0 @@
export const FRONT_COMPONENT_EXTERNAL_LINK_MODAL_ID =
'front-component-external-link-modal';
@@ -1,100 +0,0 @@
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();
});
});
@@ -1,54 +0,0 @@
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,
],
);
};
@@ -1,8 +0,0 @@
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,
});
@@ -1,13 +0,0 @@
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),
});
@@ -1,5 +0,0 @@
export type FrontComponentExternalLinkModalConfig = {
applicationId: string;
url: string;
origin: string;
};
@@ -1 +0,0 @@
export type TrustedExternalOriginsByApplicationId = Record<string, string[]>;
@@ -1,29 +0,0 @@
import { getExternalLinkDisplayUrl } from '@/front-components/utils/getExternalLinkDisplayUrl';
describe('getExternalLinkDisplayUrl', () => {
it('should strip the scheme and the trailing slash of a bare domain', () => {
expect(getExternalLinkDisplayUrl('https://nvidia.com/')).toBe('nvidia.com');
});
it('should strip the www subdomain', () => {
expect(getExternalLinkDisplayUrl('https://www.nvidia.com')).toBe(
'nvidia.com',
);
});
it('should keep the path, the search params and the hash', () => {
expect(
getExternalLinkDisplayUrl('https://nvidia.com/drivers?os=mac#latest'),
).toBe('nvidia.com/drivers?os=mac#latest');
});
it('should keep the port', () => {
expect(getExternalLinkDisplayUrl('http://localhost:3000/app')).toBe(
'localhost:3000/app',
);
});
it('should return the untouched value when the url cannot be parsed', () => {
expect(getExternalLinkDisplayUrl('not-a-url')).toBe('not-a-url');
});
});
@@ -1,44 +0,0 @@
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);
});
});
@@ -1,12 +0,0 @@
export const getExternalLinkDisplayUrl = (url: string) => {
try {
const { host, pathname, search, hash } = new URL(url);
const displayedHost = host.startsWith('www.') ? host.slice(4) : host;
const displayedPathname = pathname === '/' ? '' : pathname;
return `${displayedHost}${displayedPathname}${search}${hash}`;
} catch {
return url;
}
};
@@ -1,12 +0,0 @@
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),
);
@@ -1,5 +0,0 @@
// 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');
};
File diff suppressed because one or more lines are too long
@@ -107,17 +107,6 @@ 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>
);
};