The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Fix stored XSS via unsafe URL protocols in href attributes (#19282)
Félix Malfait8da69e0f77ea
diff --git a/packages/twenty-front/.oxlintrc.json b/packages/twenty-front/.oxlintrc.jsonindex 5b84f3ee978..e4658bd4e79 100644--- a/packages/twenty-front/.oxlintrc.json+++ b/packages/twenty-front/.oxlintrc.json@@ -21,6 +21,7 @@"rules": {"func-style": ["error", "declaration", { "allowArrowFunctions": true }],"no-console": ["warn", { "allow": ["group", "groupCollapsed", "groupEnd"] }],+ "no-script-url": "error","no-control-regex": "off","no-debugger": "error","no-duplicate-imports": "error",@@ -58,6 +59,7 @@"react/jsx-uses-react": "off","react/react-in-jsx-scope": "off","react/jsx-no-useless-fragment": "off",+ "react/jsx-no-script-url": "error","react/jsx-props-no-spreading": ["error", { "explicitSpread": "ignore" }],"react-hooks/rules-of-hooks": "error",diff --git a/packages/twenty-front/src/modules/activities/files/components/AttachmentRow.tsx b/packages/twenty-front/src/modules/activities/files/components/AttachmentRow.tsxindex 0d938c5725a..369b8cd5b6b 100644--- a/packages/twenty-front/src/modules/activities/files/components/AttachmentRow.tsx+++ b/packages/twenty-front/src/modules/activities/files/components/AttachmentRow.tsx@@ -11,7 +11,7 @@ import { getFileCategoryFromExtension } from '@/object-record/record-field/ui/utimport { SettingsTextInput } from '@/ui/input/components/SettingsTextInput';import { styled } from '@linaria/react';import { useState, useContext } from 'react';-import { isDefined } from 'twenty-shared/utils';+import { getSafeUrl, isDefined } from 'twenty-shared/utils';import { type AttachmentWithFile } from '@/activities/files/utils/filterAttachmentsWithFile';import { FileIcon } from '@/file/components/FileIcon';@@ -186,7 +186,7 @@ export const AttachmentRow = ({<StyledLinkContainer><StyledLinkonClick={handleOpenDocument}- href={fileUrl}+ href={getSafeUrl(fileUrl)}target="_blank"rel="noopener noreferrer">diff --git a/packages/twenty-front/src/modules/advanced-text-editor/components/EditLinkPopover.tsx b/packages/twenty-front/src/modules/advanced-text-editor/components/EditLinkPopover.tsxindex c1a61fff770..c1c1b71b996 100644--- a/packages/twenty-front/src/modules/advanced-text-editor/components/EditLinkPopover.tsx+++ b/packages/twenty-front/src/modules/advanced-text-editor/components/EditLinkPopover.tsx@@ -8,7 +8,7 @@ import { useLingui } from '@lingui/react/macro';import { isNonEmptyString } from '@sniptt/guards';import { type Editor } from '@tiptap/core';import { useId, useState, type FocusEvent, type FormEvent } from 'react';-import { isDefined } from 'twenty-shared/utils';+import { getSafeUrl, isDefined } from 'twenty-shared/utils';import { IconLink, IconPencil } from 'twenty-ui/display';type EditLinkPopoverProps = {@@ -33,15 +33,16 @@ export const EditLinkPopover = ({) => {event.preventDefault();- if (!isDefined(value)) {+ if (!isDefined(value) || !isNonEmptyString(value)) {editor.chain().focus().extendMarkRange('link').unsetLink().run();} else {- editor- .chain()- .focus()- .extendMarkRange('link')- .setLink({ href: value })- .run();+ const href = getSafeUrl(value);++ if (!href) {+ return;+ }++ editor.chain().focus().extendMarkRange('link').setLink({ href }).run();}toggleDropdown({ dropdownComponentInstanceIdFromProps: dropdownId });diff --git a/packages/twenty-front/src/modules/advanced-text-editor/components/LinkBubbleMenu.tsx b/packages/twenty-front/src/modules/advanced-text-editor/components/LinkBubbleMenu.tsxindex 01cd753e152..9a9f5311280 100644--- a/packages/twenty-front/src/modules/advanced-text-editor/components/LinkBubbleMenu.tsx+++ b/packages/twenty-front/src/modules/advanced-text-editor/components/LinkBubbleMenu.tsx@@ -5,6 +5,7 @@ import { type Editor } from '@tiptap/core';import { useEditorState } from '@tiptap/react';import { BubbleMenu } from '@tiptap/react/menus';import { IconExternalLink, IconLinkOff } from 'twenty-ui/display';+import { getSafeUrl } from 'twenty-shared/utils';type LinkBubbleMenuProps = {editor: Editor;@@ -28,7 +29,11 @@ export const LinkBubbleMenu = ({ editor }: LinkBubbleMenuProps) => {{Icon: IconExternalLink,onClick: () => {- window.open(state.linkHref, '_blank');+ const safeHref = getSafeUrl(state.linkHref);++ if (safeHref) {+ window.open(safeHref, '_blank', 'noopener,noreferrer');+ }},},{diff --git a/packages/twenty-front/src/modules/ai/components/LazyMarkdownRenderer.tsx b/packages/twenty-front/src/modules/ai/components/LazyMarkdownRenderer.tsxindex 51cc1fb56b8..315c21ad5b5 100644--- a/packages/twenty-front/src/modules/ai/components/LazyMarkdownRenderer.tsx+++ b/packages/twenty-front/src/modules/ai/components/LazyMarkdownRenderer.tsx@@ -18,7 +18,7 @@ import {useContext,} from 'react';import Skeleton, { SkeletonTheme } from 'react-loading-skeleton';-import { isDefined } from 'twenty-shared/utils';+import { getSafeUrl, isDefined } from 'twenty-shared/utils';import { ThemeContext } from 'twenty-ui/theme-constants';const TextWithRecordLinks = ({ text }: { text: string }) => {@@ -121,13 +121,13 @@ const MarkdownRenderer = lazy(async () => {li: ({ children }) => (<li>{processChildrenForRecordLinks(children)}</li>),- a: ({ children, href, title, target, rel, node: _node }) => (+ a: ({ children, href, title, node: _node }) => (<aclassName="markdown-link"- href={href}+ href={getSafeUrl(href)}title={title}- target={target}- rel={rel}+ target="_blank"+ rel="noopener noreferrer">{processChildrenForRecordLinks(children)}</a>diff --git a/packages/twenty-front/src/modules/blocknote-editor/blocks/FileBlock.tsx b/packages/twenty-front/src/modules/blocknote-editor/blocks/FileBlock.tsxindex baaf1c20374..7cce9d571b9 100644--- a/packages/twenty-front/src/modules/blocknote-editor/blocks/FileBlock.tsx+++ b/packages/twenty-front/src/modules/blocknote-editor/blocks/FileBlock.tsx@@ -9,7 +9,7 @@ import { type AttachmentFileCategory } from '@/activities/files/types/Attachmentimport { getFileType } from '@/activities/files/utils/getFileType';import { FileIcon } from '@/file/components/FileIcon';import { t } from '@lingui/core/macro';-import { isDefined } from 'twenty-shared/utils';+import { getSafeUrl, isDefined } from 'twenty-shared/utils';import { Button } from 'twenty-ui/input';const StyledFileInput = styled.input`@@ -86,13 +86,19 @@ export const FileBlock = createReactBlockSpec(handleUploadAttachment?.(e.target.files[0]);};- if (isNonEmptyString(block.props.url)) {+ const safeUrl = getSafeUrl(block.props.url);++ if (safeUrl) {return (<StyledFileLine><FileIconfileCategory={block.props.fileCategory as AttachmentFileCategory}/>- <StyledLink href={block.props.url} target="__blank">+ <StyledLink+ href={safeUrl}+ target="_blank"+ rel="noopener noreferrer"+ >{block.props.name}</StyledLink></StyledFileLine>diff --git a/packages/twenty-front/src/modules/information-banner/components/maintenance/InformationBannerMaintenance.tsx b/packages/twenty-front/src/modules/information-banner/components/maintenance/InformationBannerMaintenance.tsxindex 889eed90653..f6aa2e6e691 100644--- a/packages/twenty-front/src/modules/information-banner/components/maintenance/InformationBannerMaintenance.tsx+++ b/packages/twenty-front/src/modules/information-banner/components/maintenance/InformationBannerMaintenance.tsx@@ -6,8 +6,7 @@ import { useMaintenanceModeBannerDismissal } from '@/information-banner/hooks/usimport { useDateTimeFormat } from '@/localization/hooks/useDateTimeFormat';import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';import { t } from '@lingui/core/macro';-import { isNonEmptyString } from '@sniptt/guards';-import { isDefined } from 'twenty-shared/utils';+import { getSafeUrl, isDefined } from 'twenty-shared/utils';import { IconExternalLink } from 'twenty-ui/display';const formatMaintenanceDateTime = (@@ -49,9 +48,7 @@ export const InformationBannerMaintenance = () => {);const message = t`Scheduled maintenance: ${startFormatted} — ${endFormatted}`;- const maintenanceLink = isNonEmptyString(maintenanceMode.link?.trim())- ? maintenanceMode.link.trim()- : undefined;+ const maintenanceLink = getSafeUrl(maintenanceMode.link?.trim());return (<InformationBannerdiff --git a/packages/twenty-front/src/modules/page-layout/widgets/iframe/components/IframeWidget.tsx b/packages/twenty-front/src/modules/page-layout/widgets/iframe/components/IframeWidget.tsxindex 8bcde95a485..7d46c208010 100644--- a/packages/twenty-front/src/modules/page-layout/widgets/iframe/components/IframeWidget.tsx+++ b/packages/twenty-front/src/modules/page-layout/widgets/iframe/components/IframeWidget.tsx@@ -4,7 +4,7 @@ import { PageLayoutWidgetNoDataDisplay } from '@/page-layout/widgets/components/import { WidgetSkeletonLoader } from '@/page-layout/widgets/components/WidgetSkeletonLoader';import { styled } from '@linaria/react';import { useState } from 'react';-import { isDefined } from 'twenty-shared/utils';+import { getSafeUrl, isDefined } from 'twenty-shared/utils';import { themeCssVariables } from 'twenty-ui/theme-constants';const StyledContainer = styled.div<{ $isEditMode: boolean }>`@@ -79,7 +79,10 @@ export const IframeWidget = ({ widget }: IframeWidgetProps) => {setHasError(true);};- if (hasError || !isDefined(url)) {+ const safeUrl = isDefined(url) ? getSafeUrl(url) : undefined;+ const isHttpUrl = isDefined(safeUrl) && /^https?:\/\//i.test(safeUrl);++ if (hasError || !isHttpUrl) {return (<StyledContainer $isEditMode={isPageLayoutInEditMode}><StyledErrorContainer>@@ -98,7 +101,7 @@ export const IframeWidget = ({ widget }: IframeWidgetProps) => {)}<StyledIframe$isEditMode={isPageLayoutInEditMode}- src={url}+ src={safeUrl}title={title}onLoad={handleIframeLoad}onError={handleIframeError}diff --git a/packages/twenty-front/src/modules/ui/field/display/components/LinkDisplay.tsx b/packages/twenty-front/src/modules/ui/field/display/components/LinkDisplay.tsxindex 4e8047ba2f1..42d6fa26049 100644--- a/packages/twenty-front/src/modules/ui/field/display/components/LinkDisplay.tsx+++ b/packages/twenty-front/src/modules/ui/field/display/components/LinkDisplay.tsx@@ -1,6 +1,7 @@import { isNonEmptyString } from '@sniptt/guards';import { LinkType, RoundedLink, SocialLink } from 'twenty-ui/navigation';import { checkUrlType } from '~/utils/checkUrlType';+import { getSafeUrl } from 'twenty-shared/utils';type LinkDisplayProps = {value: { url: string; label?: string | null };@@ -13,11 +14,7 @@ export const LinkDisplay = ({ value }: LinkDisplayProps) => {return <></>;}- const absoluteUrl = url- ? url.startsWith('http')- ? url- : 'https://' + url- : '';+ const absoluteUrl = getSafeUrl(url) ?? '';const displayedValue = isNonEmptyString(value.label)? value.labeldiff --git a/packages/twenty-front/src/modules/ui/field/display/components/URLDisplay.tsx b/packages/twenty-front/src/modules/ui/field/display/components/URLDisplay.tsxindex b266cf70e38..7a8294e5ac9 100644--- a/packages/twenty-front/src/modules/ui/field/display/components/URLDisplay.tsx+++ b/packages/twenty-front/src/modules/ui/field/display/components/URLDisplay.tsx@@ -2,6 +2,7 @@ import { type MouseEvent } from 'react';import { LinkType, RoundedLink, SocialLink } from 'twenty-ui/navigation';import { checkUrlType } from '~/utils/checkUrlType';+import { getSafeUrl } from 'twenty-shared/utils';import { EllipsisDisplay } from './EllipsisDisplay';type URLDisplayProps = {@@ -13,11 +14,7 @@ export const URLDisplay = ({ value }: URLDisplayProps) => {event.stopPropagation();};- const absoluteUrl = value- ? value.startsWith('http')- ? value- : 'https://' + value- : '';+ const absoluteUrl = value ? (getSafeUrl(value) ?? '') : '';const displayedValue = value ?? '';diff --git a/packages/twenty-server/src/engine/api/common/common-args-processors/data-arg-processor/validator-utils/validate-rich-text-field-or-throw.util.ts b/packages/twenty-server/src/engine/api/common/common-args-processors/data-arg-processor/validator-utils/validate-rich-text-field-or-throw.util.tsindex 1ae75b5cccb..39787901b8c 100644--- a/packages/twenty-server/src/engine/api/common/common-args-processors/data-arg-processor/validator-utils/validate-rich-text-field-or-throw.util.ts+++ b/packages/twenty-server/src/engine/api/common/common-args-processors/data-arg-processor/validator-utils/validate-rich-text-field-or-throw.util.ts@@ -2,6 +2,7 @@ import { inspect } from 'util';import { msg } from '@lingui/core/macro';import { isNonEmptyString, isNull } from '@sniptt/guards';+import { isSafeUrl } from 'twenty-shared/utils';import { validateRawJsonFieldOrThrow } from 'src/engine/api/common/common-args-processors/data-arg-processor/validator-utils/validate-raw-json-field-or-throw.util';import { validateTextFieldOrThrow } from 'src/engine/api/common/common-args-processors/data-arg-processor/validator-utils/validate-text-field-or-throw.util';@@ -10,6 +11,24 @@ import {CommonQueryRunnerExceptionCode,} from 'src/engine/api/common/common-query-runners/errors/common-query-runner.exception';+const URL_VALUE_PATTERN = /"(?:url|href)"\s*:\s*"([^"]*)"/gi;++const hasDangerousUrl = (json: string): boolean => {+ URL_VALUE_PATTERN.lastIndex = 0;++ let match;++ while ((match = URL_VALUE_PATTERN.exec(json)) !== null) {+ const url = match[1].trim();++ if (url.length > 0 && !isSafeUrl(url)) {+ return true;+ }+ }++ return false;+};+const validateBlocknoteFieldOrThrow = (value: unknown,fieldName: string,@@ -38,6 +57,16 @@ const validateBlocknoteFieldOrThrow = ();}+ if (hasDangerousUrl(textValue)) {+ throw new CommonQueryRunnerException(+ `Dangerous URL protocol in blocknote content for field "${fieldName}"`,+ CommonQueryRunnerExceptionCode.INVALID_ARGS_DATA,+ {+ userFriendlyMessage: msg`Content contains a URL with a dangerous protocol.`,+ },+ );+ }+return textValue;};diff --git a/packages/twenty-shared/src/utils/index.ts b/packages/twenty-shared/src/utils/index.tsindex 59e7e4b2fbb..1df43b3c7f3 100644--- a/packages/twenty-shared/src/utils/index.ts+++ b/packages/twenty-shared/src/utils/index.ts@@ -193,7 +193,9 @@ export { absoluteUrlSchema } from './url/absoluteUrlSchema';export { buildSignedPath } from './url/buildSignedPath';export { ensureAbsoluteUrl } from './url/ensureAbsoluteUrl';export { getAbsoluteUrlOrThrow } from './url/getAbsoluteUrlOrThrow';+export { getSafeUrl } from './url/getSafeUrl';export { getUrlHostnameOrThrow } from './url/getUrlHostnameOrThrow';+export { isSafeUrl } from './url/isSafeUrl';export { isValidHostname } from './url/isValidHostname';export { isValidUrl } from './url/isValidUrl';export { normalizeUrl } from './url/normalizeUrl';diff --git a/packages/twenty-shared/src/utils/url/getSafeUrl.ts b/packages/twenty-shared/src/utils/url/getSafeUrl.tsnew file mode 100644index 00000000000..e7b5269728a--- /dev/null+++ b/packages/twenty-shared/src/utils/url/getSafeUrl.ts@@ -0,0 +1,17 @@+import { isSafeUrl } from './isSafeUrl';++export const getSafeUrl = (+ url: string | undefined | null,+): string | undefined => {+ if (!url || url.trim().length === 0) {+ return undefined;+ }++ if (isSafeUrl(url)) {+ return url;+ }++ const withScheme = `https://${url}`;++ return isSafeUrl(withScheme) ? withScheme : undefined;+};diff --git a/packages/twenty-shared/src/utils/url/index.ts b/packages/twenty-shared/src/utils/url/index.tsindex 1a8ca833042..8ff633915be 100644--- a/packages/twenty-shared/src/utils/url/index.ts+++ b/packages/twenty-shared/src/utils/url/index.ts@@ -1,4 +1,6 @@export * from './absoluteUrlSchema';+export * from './getSafeUrl';+export * from './isSafeUrl';export * from './ensureAbsoluteUrl';export * from './getAbsoluteUrlOrThrow';export * from './getUrlHostnameOrThrow';diff --git a/packages/twenty-shared/src/utils/url/isSafeUrl.ts b/packages/twenty-shared/src/utils/url/isSafeUrl.tsnew file mode 100644index 00000000000..c2df3e69575--- /dev/null+++ b/packages/twenty-shared/src/utils/url/isSafeUrl.ts@@ -0,0 +1,15 @@+const SAFE_URL_PROTOCOLS = ['http:', 'https:', 'mailto:', 'tel:'];++export const isSafeUrl = (url: string): boolean => {+ if (url.startsWith('/') && !url.startsWith('//')) {+ return true;+ }++ try {+ const parsed = new URL(url);++ return SAFE_URL_PROTOCOLS.includes(parsed.protocol);+ } catch {+ return false;+ }+};