The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Enable microphone and camera in custom iframe widgets (#29219)
Raphaël Bosie46c7572f475
diff --git a/packages/twenty-docs/user-guide/dashboards/capabilities/widgets.mdx b/packages/twenty-docs/user-guide/dashboards/capabilities/widgets.mdxindex 8a6f861544f..c2429048135 100644--- a/packages/twenty-docs/user-guide/dashboards/capabilities/widgets.mdx+++ b/packages/twenty-docs/user-guide/dashboards/capabilities/widgets.mdx@@ -90,6 +90,12 @@ Display single key values prominently.### <span style={{ display: 'inline-flex', alignItems: 'center', gap: '8px' }}><ChartIcon icon="frame" />iFrames</span>Embed external tools and content directly in your dashboard.+For embedded phones or video tools, a member with permission to manage security can configure **Settings → General → Security → Embedded website media access**. Add the website's exact HTTPS origin, such as `https://workspace.aircall.io`, and enable **Microphone**, **Camera**, or both. Paths and wildcards are not accepted. Only approve websites you trust.++Reload open Twenty tabs after changing these permissions. Reloading ends active calls and recordings. Each member then selects **Enable microphone**, **Enable camera**, or **Enable microphone and camera** on the embed and approves the browser permission when prompted.++The header indicator shows **Media access enabled** while an embed has access, including when it is hidden. This does not mean the website is currently recording: Twenty cannot inspect microphone or camera activity inside another website. Select the indicator and choose **Disable** to unload the embed and reload it with media access blocked. Enabling access again requires another click.+<Frame><img src="/images/user-guide/dashboard/dashboard-widget-table.png" alt="Table chart"/></Frame>diff --git a/packages/twenty-front/src/modules/front-components/media-session/components/FrontComponentMediaSessionRegistrationEffect.tsx b/packages/twenty-front/src/modules/front-components/media-session/components/FrontComponentMediaSessionRegistrationEffect.tsxindex 7f63e57a060..c330cc14d5e 100644--- a/packages/twenty-front/src/modules/front-components/media-session/components/FrontComponentMediaSessionRegistrationEffect.tsx+++ b/packages/twenty-front/src/modules/front-components/media-session/components/FrontComponentMediaSessionRegistrationEffect.tsx@@ -1,4 +1,5 @@-import { frontComponentMediaSessionsState } from '@/front-components/media-session/states/frontComponentMediaSessionsState';+import { mediaAccessSessionsState } from '@/media-access/states/mediaAccessSessionsState';+import { getMediaAccessOwnerId } from '@/media-access/utils/getMediaAccessOwnerId';import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';import { useEffect, useId } from 'react';import {@@ -23,9 +24,7 @@ export const FrontComponentMediaSessionRegistrationEffect = ({onStop,}: FrontComponentMediaSessionRegistrationEffectProps) => {const id = useId();- const setFrontComponentMediaSessions = useSetAtomState(- frontComponentMediaSessionsState,- );+ const setMediaAccessSessions = useSetAtomState(mediaAccessSessionsState);useEffect(() => {const activeMediaTypes = [@@ -40,20 +39,25 @@ export const FrontComponentMediaSessionRegistrationEffect = ({return;}- setFrontComponentMediaSessions((sessions) => [+ setMediaAccessSessions((sessions) => [...sessions.filter((session) => session.id !== id),{id,- applicationId,- applicationName,- activeMediaTypes,- pendingMediaTypes,+ ownerId: getMediaAccessOwnerId({+ type: 'application',+ id: applicationId,+ }),+ ownerName: applicationName,+ status: isNonEmptyArray(activeMediaTypes) ? 'capturing' : 'pending',+ mediaTypes: isNonEmptyArray(activeMediaTypes)+ ? activeMediaTypes+ : pendingMediaTypes,onStop,},]);return () => {- setFrontComponentMediaSessions((sessions) =>+ setMediaAccessSessions((sessions) =>sessions.filter((session) => session.id !== id),);};@@ -64,7 +68,7 @@ export const FrontComponentMediaSessionRegistrationEffect = ({id,onStop,pendingStartMediaTypes,- setFrontComponentMediaSessions,+ setMediaAccessSessions,]);return null;diff --git a/packages/twenty-front/src/modules/front-components/media-session/components/FrontComponentMediaSessionTooltipRow.tsx b/packages/twenty-front/src/modules/front-components/media-session/components/FrontComponentMediaSessionTooltipRow.tsxdeleted file mode 100644index 2a7b6a3fc01..00000000000--- a/packages/twenty-front/src/modules/front-components/media-session/components/FrontComponentMediaSessionTooltipRow.tsx+++ /dev/null@@ -1,98 +0,0 @@-import { type FrontComponentMediaSessionStatus } from '@/front-components/media-session/types/FrontComponentMediaSessionStatus';-import { styled } from '@linaria/react';-import { t } from '@lingui/core/macro';-import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';-import { IconMicrophone, IconVideo } from 'twenty-ui/icon';-import { Button } from 'twenty-ui/primitives/input';-import { themeCssVariables, useTheme } from 'twenty-ui/theme';--type FrontComponentMediaSessionTooltipRowProps = {- sessions: FrontComponentMediaSessionStatus[];-};--const StyledRow = styled.div`- align-items: center;- display: flex;- gap: ${themeCssVariables.spacing[2]};-`;--const StyledDetails = styled.div`- display: flex;- flex: 1;- flex-direction: column;- gap: ${themeCssVariables.spacing[1]};- min-width: 0;-`;--const StyledApplicationName = styled.span`- font-weight: ${themeCssVariables.font.weight.medium};- overflow-wrap: anywhere;-`;--const StyledMediaType = styled.span`- color: ${themeCssVariables.font.color.secondary};- font-size: ${themeCssVariables.font.size.xs};-`;--export const FrontComponentMediaSessionTooltipRow = ({- sessions,-}: FrontComponentMediaSessionTooltipRowProps) => {- const theme = useTheme();- const firstSession = sessions[0];-- if (!isDefined(firstSession)) {- return null;- }-- const activeMediaTypes = sessions.flatMap(- (session) => session.activeMediaTypes,- );- const isCapturing = isNonEmptyArray(activeMediaTypes);- const mediaTypes = isCapturing- ? activeMediaTypes- : sessions.flatMap((session) => session.pendingMediaTypes);- const usesAudio = mediaTypes.includes('audio');- const usesVideo = mediaTypes.includes('video');- const getMediaLabel = () => {- if (usesAudio && usesVideo) {- return t`Microphone and camera`;- }-- if (usesVideo) {- return t`Camera`;- }-- return t`Microphone`;- };- const { applicationName } = firstSession;- const MediaIcon = usesVideo ? IconVideo : IconMicrophone;- const handleStop = () => {- for (const session of sessions) {- session.onStop();- }- };-- return (- <StyledRow role="listitem">- <MediaIcon size={theme.icon.size.md} aria-hidden />- <StyledDetails>- <StyledApplicationName>{applicationName}</StyledApplicationName>- <StyledMediaType>- {isCapturing ? getMediaLabel() : t`Waiting for permission`}- </StyledMediaType>- </StyledDetails>- <Button- size="sm"- variant="ghost"- aria-label={- isCapturing- ? t`Stop recording for ${applicationName}`- : t`Cancel recording for ${applicationName}`- }- onClick={handleStop}- >- {isCapturing ? t`Stop` : t`Cancel`}- </Button>- </StyledRow>- );-};diff --git a/packages/twenty-front/src/modules/front-components/media-session/states/frontComponentMediaSessionsState.ts b/packages/twenty-front/src/modules/front-components/media-session/states/frontComponentMediaSessionsState.tsdeleted file mode 100644index c188fc68d34..00000000000--- a/packages/twenty-front/src/modules/front-components/media-session/states/frontComponentMediaSessionsState.ts+++ /dev/null@@ -1,9 +0,0 @@-import { type FrontComponentMediaSessionStatus } from '@/front-components/media-session/types/FrontComponentMediaSessionStatus';-import { createAtomState } from '@/ui/utilities/state/jotai/utils/createAtomState';--export const frontComponentMediaSessionsState = createAtomState<- FrontComponentMediaSessionStatus[]->({- key: 'frontComponentMediaSessionsState',- defaultValue: [],-});diff --git a/packages/twenty-front/src/modules/front-components/media-session/types/FrontComponentMediaSessionStatus.ts b/packages/twenty-front/src/modules/front-components/media-session/types/FrontComponentMediaSessionStatus.tsdeleted file mode 100644index 1e696d8a502..00000000000--- a/packages/twenty-front/src/modules/front-components/media-session/types/FrontComponentMediaSessionStatus.ts+++ /dev/null@@ -1,10 +0,0 @@-import { type MediaSessionMediaType } from 'twenty-front-component-renderer';--export type FrontComponentMediaSessionStatus = {- id: string;- applicationId: string;- applicationName: string;- activeMediaTypes: MediaSessionMediaType[];- pendingMediaTypes: MediaSessionMediaType[];- onStop: () => void;-};diff --git a/packages/twenty-front/src/modules/media-access/components/ManagedIframe.tsx b/packages/twenty-front/src/modules/media-access/components/ManagedIframe.tsxnew file mode 100644index 00000000000..a2e9bbece24--- /dev/null+++ b/packages/twenty-front/src/modules/media-access/components/ManagedIframe.tsx@@ -0,0 +1,54 @@+import { ManagedIframeSession } from '@/media-access/components/ManagedIframeSession';+import { type ManagedIframeProps } from '@/media-access/types/ManagedIframeProps';+import { getManagedIframeMediaPermission } from '@/media-access/utils/getManagedIframeMediaPermission';+import { getMediaAccessOwnerId } from '@/media-access/utils/getMediaAccessOwnerId';++export const ManagedIframe = ({+ src,+ srcDoc,+ title,+ className,+ style,+ width,+ height,+ hidden,+ onLoad,+ onError,+ sandbox,+ allow,+ allowFullScreen,+ owner,+ requestedMediaCapabilities,+ iframeMediaPermissions,+}: ManagedIframeProps) => {+ const permission = getManagedIframeMediaPermission({+ src,+ srcDoc,+ requestedMediaCapabilities,+ iframeMediaPermissions,+ hostOrigin: window.location.origin,+ });+ const ownerId = getMediaAccessOwnerId(owner);++ return (+ <ManagedIframeSession+ key={ownerId}+ src={src}+ srcDoc={srcDoc}+ title={title}+ className={className}+ style={style}+ width={width}+ height={height}+ hidden={hidden}+ onLoad={onLoad}+ onError={onError}+ sandbox={sandbox}+ allow={allow}+ allowFullScreen={allowFullScreen}+ ownerId={ownerId}+ ownerName={owner.name}+ permission={permission}+ />+ );+};diff --git a/packages/twenty-front/src/modules/media-access/components/ManagedIframeEnableButton.tsx b/packages/twenty-front/src/modules/media-access/components/ManagedIframeEnableButton.tsxnew file mode 100644index 00000000000..d64d6e23339--- /dev/null+++ b/packages/twenty-front/src/modules/media-access/components/ManagedIframeEnableButton.tsx@@ -0,0 +1,52 @@+import { MANAGED_IFRAME_ENABLE_BUTTON_INSET_PX } from '@/media-access/constants/ManagedIframeEnableButtonInsetPx';+import { autoUpdate, hide, offset, useFloating } from '@floating-ui/react';+import { styled } from '@linaria/react';+import { Button } from 'twenty-ui/primitives/input';+import { themeCssVariables } from 'twenty-ui/theme';++type ManagedIframeEnableButtonProps = {+ anchorElement: Element;+ label: string;+ onClick: () => void;+};++const StyledControls = styled.div`+ background: ${themeCssVariables.background.primary};+ border: 1px solid ${themeCssVariables.border.color.medium};+ border-radius: ${themeCssVariables.border.radius.sm};+ display: flex;+ padding: ${themeCssVariables.spacing[2]};+`;++export const ManagedIframeEnableButton = ({+ anchorElement,+ label,+ onClick,+}: ManagedIframeEnableButtonProps) => {+ const { refs, floatingStyles, middlewareData, isPositioned } = useFloating({+ elements: { reference: anchorElement },+ placement: 'bottom-end',+ middleware: [+ offset(({ rects }) => ({+ mainAxis: -(+ rects.floating.height + MANAGED_IFRAME_ENABLE_BUTTON_INSET_PX+ ),+ alignmentAxis: MANAGED_IFRAME_ENABLE_BUTTON_INSET_PX,+ })),+ hide(),+ ],+ whileElementsMounted: autoUpdate,+ });+ const isHidden = !isPositioned || middlewareData.hide?.referenceHidden;++ return (+ <StyledControls+ ref={refs.setFloating}+ style={{ ...floatingStyles, visibility: isHidden ? 'hidden' : 'visible' }}+ >+ <Button size="sm" variant="outline" onClick={onClick}>+ {label}+ </Button>+ </StyledControls>+ );+};diff --git a/packages/twenty-front/src/modules/media-access/components/ManagedIframeMediaAccessSessionEffect.tsx b/packages/twenty-front/src/modules/media-access/components/ManagedIframeMediaAccessSessionEffect.tsxnew file mode 100644index 00000000000..b470f8fd0b9--- /dev/null+++ b/packages/twenty-front/src/modules/media-access/components/ManagedIframeMediaAccessSessionEffect.tsx@@ -0,0 +1,46 @@+import { mediaAccessSessionsState } from '@/media-access/states/mediaAccessSessionsState';+import { getIframeMediaPermissionMediaTypes } from '@/media-access/utils/getIframeMediaPermissionMediaTypes';+import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';+import { useEffect } from 'react';+import { type IframeMediaPermission } from 'twenty-shared/types';++type ManagedIframeMediaAccessSessionEffectProps = {+ id: string;+ ownerId: string;+ ownerName: string;+ permission: IframeMediaPermission;+ onStop: () => void;+};++export const ManagedIframeMediaAccessSessionEffect = ({+ id,+ ownerId,+ ownerName,+ permission,+ onStop,+}: ManagedIframeMediaAccessSessionEffectProps) => {+ const setMediaAccessSessions = useSetAtomState(mediaAccessSessionsState);++ useEffect(() => {+ setMediaAccessSessions((sessions) => [+ ...sessions.filter((session) => session.id !== id),+ {+ id,+ ownerId,+ ownerName,+ status: 'delegated',+ origin: permission.origin,+ mediaTypes: getIframeMediaPermissionMediaTypes(permission),+ onStop,+ },+ ]);++ return () => {+ setMediaAccessSessions((sessions) =>+ sessions.filter((session) => session.id !== id),+ );+ };+ }, [id, onStop, ownerId, ownerName, permission, setMediaAccessSessions]);++ return null;+};diff --git a/packages/twenty-front/src/modules/media-access/components/ManagedIframeSession.tsx b/packages/twenty-front/src/modules/media-access/components/ManagedIframeSession.tsxnew file mode 100644index 00000000000..eebec5301a8--- /dev/null+++ b/packages/twenty-front/src/modules/media-access/components/ManagedIframeSession.tsx@@ -0,0 +1,124 @@+import { ManagedIframeEnableButton } from '@/media-access/components/ManagedIframeEnableButton';+import { ManagedIframeMediaAccessSessionEffect } from '@/media-access/components/ManagedIframeMediaAccessSessionEffect';+import { type ManagedIframeElementProps } from '@/media-access/types/ManagedIframeElementProps';+import { getDelegatedIframeMediaPermission } from '@/media-access/utils/getDelegatedIframeMediaPermission';+import { getIframeMediaAllow } from '@/media-access/utils/getIframeMediaAllow';+import { t } from '@lingui/core/macro';+import { isNonEmptyString } from '@sniptt/guards';+import { useCallback, useId, useState } from 'react';+import { type IframeMediaPermission } from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';++type ManagedIframeSessionProps = ManagedIframeElementProps & {+ ownerId: string;+ ownerName: string;+ permission: IframeMediaPermission | null;+};++const getEnableLabel = (permission: IframeMediaPermission) => {+ if (permission.microphone && permission.camera) {+ return t`Enable microphone and camera`;+ }++ if (permission.camera) {+ return t`Enable camera`;+ }++ return t`Enable microphone`;+};++export const ManagedIframeSession = ({+ src,+ srcDoc,+ title,+ className,+ style,+ width,+ height,+ hidden,+ onLoad,+ onError,+ sandbox,+ allow,+ allowFullScreen,+ ownerId,+ ownerName,+ permission,+}: ManagedIframeSessionProps) => {+ const mediaAccessSessionId = useId();+ const [iframeElement, setIframeElement] = useState<HTMLIFrameElement | null>(+ null,+ );+ const [activatedPermission, setActivatedPermission] =+ useState<IframeMediaPermission | null>(null);+ const delegatedPermission = getDelegatedIframeMediaPermission({+ activatedPermission,+ permission,+ });+ const isActivated = isDefined(delegatedPermission);++ if (isDefined(activatedPermission) && !isActivated) {+ setActivatedPermission(null);+ }++ const handleDeactivate = useCallback(() => {+ setActivatedPermission(null);+ }, []);+ const handleEnable = () => {+ setActivatedPermission(permission);+ };+ const iframeAllow = getIframeMediaAllow({+ allow,+ permission: delegatedPermission,+ });+ const iframeSandbox =+ isActivated && isDefined(sandbox)+ ? [+ ...new Set([+ ...sandbox.split(/\s+/).filter(isNonEmptyString),+ 'allow-same-origin',+ ]),+ ].join(' ')+ : sandbox;++ return (+ <>+ {isDefined(delegatedPermission) && (+ <ManagedIframeMediaAccessSessionEffect+ id={mediaAccessSessionId}+ ownerId={ownerId}+ ownerName={ownerName}+ permission={delegatedPermission}+ onStop={handleDeactivate}+ />+ )}+ <iframe+ key={isActivated ? 'media-enabled' : 'media-disabled'}+ ref={setIframeElement}+ src={src}+ srcDoc={srcDoc}+ title={title}+ className={className}+ style={style}+ width={width}+ height={height}+ hidden={hidden}+ onLoad={onLoad}+ onError={onError}+ sandbox={iframeSandbox}+ allow={iframeAllow}+ allowFullScreen={allowFullScreen}+ />+ {isDefined(permission) &&+ !isActivated &&+ !hidden &&+ isDefined(iframeElement) && (+ <ManagedIframeEnableButton+ anchorElement={iframeElement}+ label={getEnableLabel(permission)}+ onClick={handleEnable}+ />+ )}+ </>+ );+};diff --git a/packages/twenty-front/src/modules/front-components/media-session/components/FrontComponentMediaSessionIndicator.tsx b/packages/twenty-front/src/modules/media-access/components/MediaAccessIndicator.tsxsimilarity index 61%rename from packages/twenty-front/src/modules/front-components/media-session/components/FrontComponentMediaSessionIndicator.tsxrename to packages/twenty-front/src/modules/media-access/components/MediaAccessIndicator.tsxindex aa5131c0548..eb9909cfbbd 100644--- a/packages/twenty-front/src/modules/front-components/media-session/components/FrontComponentMediaSessionIndicator.tsx+++ b/packages/twenty-front/src/modules/media-access/components/MediaAccessIndicator.tsx@@ -1,5 +1,5 @@-import { FrontComponentMediaSessionTooltipRow } from '@/front-components/media-session/components/FrontComponentMediaSessionTooltipRow';-import { frontComponentMediaSessionsState } from '@/front-components/media-session/states/frontComponentMediaSessionsState';+import { MediaAccessSessionRow } from '@/media-access/components/MediaAccessSessionRow';+import { mediaAccessSessionsState } from '@/media-access/states/mediaAccessSessionsState';import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';import { styled } from '@linaria/react';import { t } from '@lingui/core/macro';@@ -33,22 +33,35 @@ const StyledApplications = styled.div`gap: ${themeCssVariables.spacing[2]};`;-export const FrontComponentMediaSessionIndicator = () => {- const frontComponentMediaSessions = useAtomStateValue(- frontComponentMediaSessionsState,- );+export const MediaAccessIndicator = () => {+ const mediaAccessSessions = useAtomStateValue(mediaAccessSessionsState);- if (!isNonEmptyArray(frontComponentMediaSessions)) {+ if (!isNonEmptyArray(mediaAccessSessions)) {return null;}- const isCapturing = frontComponentMediaSessions.some((session) =>- isNonEmptyArray(session.activeMediaTypes),+ const isCapturing = mediaAccessSessions.some(+ (session) => session.status === 'capturing',+ );+ const hasPendingRequest = mediaAccessSessions.some(+ (session) => session.status === 'pending',);- const title = isCapturing ? t`Apps recording` : t`Recording requests`;- const sessionsByApplication = groupBy(- frontComponentMediaSessions,- 'applicationId',+ const getTitle = () => {+ if (isCapturing) {+ return t`Microphone or camera in use`;+ }++ if (hasPendingRequest) {+ return t`Media access requests`;+ }++ return t`Media access enabled`;+ };+ const title = getTitle();+ const sessionsByGroupKey = groupBy(mediaAccessSessions, (session) =>+ session.status === 'delegated'+ ? `${session.ownerId}:delegated:${session.origin}`+ : session.ownerId,);return (@@ -66,10 +79,10 @@ export const FrontComponentMediaSessionIndicator = () => {<StyledPopup initialFocus={false}><Popover.Title>{title}</Popover.Title><StyledApplications role="list" aria-label={title}>- {Object.entries(sessionsByApplication).map(- ([applicationId, sessions]) => (- <FrontComponentMediaSessionTooltipRow- key={applicationId}+ {Object.entries(sessionsByGroupKey).map(+ ([sessionGroupKey, sessions]) => (+ <MediaAccessSessionRow+ key={sessionGroupKey}sessions={sessions}/>),diff --git a/packages/twenty-front/src/modules/media-access/components/MediaAccessSessionRow.tsx b/packages/twenty-front/src/modules/media-access/components/MediaAccessSessionRow.tsxnew file mode 100644index 00000000000..a13e147b53b--- /dev/null+++ b/packages/twenty-front/src/modules/media-access/components/MediaAccessSessionRow.tsx@@ -0,0 +1,119 @@+import { type MediaAccessSession } from '@/media-access/types/MediaAccessSession';+import { styled } from '@linaria/react';+import { t } from '@lingui/core/macro';+import { isDefined } from 'twenty-shared/utils';+import { IconMicrophone, IconVideo } from 'twenty-ui/icon';+import { Button } from 'twenty-ui/primitives/input';+import { themeCssVariables, useTheme } from 'twenty-ui/theme';++const StyledRow = styled.div`+ align-items: center;+ display: flex;+ gap: ${themeCssVariables.spacing[2]};+`;++const StyledDetails = styled.div`+ display: flex;+ flex: 1;+ flex-direction: column;+ gap: ${themeCssVariables.spacing[1]};+ min-width: 0;+`;++const StyledOwnerName = styled.span`+ font-weight: ${themeCssVariables.font.weight.medium};+ overflow-wrap: anywhere;+`;++const StyledMediaType = styled.span`+ color: ${themeCssVariables.font.color.secondary};+ font-size: ${themeCssVariables.font.size.xs};+ overflow-wrap: anywhere;+`;++export const MediaAccessSessionRow = ({+ sessions,+}: {+ sessions: MediaAccessSession[];+}) => {+ const theme = useTheme();+ const firstSession = sessions[0];++ if (!isDefined(firstSession)) {+ return null;+ }++ const isCapturing = sessions.some(+ (session) => session.status === 'capturing',+ );+ const isDelegated = firstSession.status === 'delegated';+ const mediaTypes = sessions+ .filter((session) => !isCapturing || session.status === 'capturing')+ .flatMap((session) => session.mediaTypes);+ const hasAudioMediaType = mediaTypes.includes('audio');+ const hasVideoMediaType = mediaTypes.includes('video');+ const getMediaLabel = () => {+ if (hasAudioMediaType && hasVideoMediaType) {+ return isDelegated+ ? t`Microphone and camera access enabled`+ : t`Microphone and camera`;+ }++ if (hasVideoMediaType) {+ return isDelegated ? t`Camera access enabled` : t`Camera`;+ }++ return isDelegated ? t`Microphone access enabled` : t`Microphone`;+ };+ const { ownerName, origin } = firstSession;+ const MediaIcon = hasVideoMediaType ? IconVideo : IconMicrophone;+ const handleStop = () => {+ for (const session of sessions) {+ session.onStop();+ }+ };+ const getActionLabels = () => {+ if (isDelegated) {+ return {+ actionLabel: t`Disable`,+ actionAriaLabel: t`Disable media access for ${ownerName}`,+ };+ }++ if (isCapturing) {+ return {+ actionLabel: t`Stop`,+ actionAriaLabel: t`Stop capture for ${ownerName}`,+ };+ }++ return {+ actionLabel: t`Cancel`,+ actionAriaLabel: t`Cancel media request for ${ownerName}`,+ };+ };+ const { actionLabel, actionAriaLabel } = getActionLabels();++ return (+ <StyledRow role="listitem">+ <MediaIcon size={theme.icon.size.md} aria-hidden />+ <StyledDetails>+ <StyledOwnerName>{ownerName}</StyledOwnerName>+ <StyledMediaType>+ {isCapturing || isDelegated+ ? getMediaLabel()+ : t`Waiting for permission`}+ </StyledMediaType>+ {isDelegated && <StyledMediaType>{origin}</StyledMediaType>}+ </StyledDetails>+ <Button+ size="sm"+ variant="ghost"+ aria-label={actionAriaLabel}+ onClick={handleStop}+ >+ {actionLabel}+ </Button>+ </StyledRow>+ );+};diff --git a/packages/twenty-front/src/modules/media-access/components/__stories__/ManagedIframe.stories.tsx b/packages/twenty-front/src/modules/media-access/components/__stories__/ManagedIframe.stories.tsxnew file mode 100644index 00000000000..42cd639523d--- /dev/null+++ b/packages/twenty-front/src/modules/media-access/components/__stories__/ManagedIframe.stories.tsx@@ -0,0 +1,265 @@+import { ManagedIframe } from '@/media-access/components/ManagedIframe';+import { MediaAccessIndicator } from '@/media-access/components/MediaAccessIndicator';+import { mediaAccessSessionsState } from '@/media-access/states/mediaAccessSessionsState';+import { type MediaAccessSession } from '@/media-access/types/MediaAccessSession';+import { getMediaAccessOwnerId } from '@/media-access/utils/getMediaAccessOwnerId';+import { type Meta, type StoryObj } from '@storybook/react-vite';+import { createStore, Provider } from 'jotai';+import { type CSSProperties, useState } from 'react';+import { expect, fn, screen, userEvent, waitFor, within } from 'storybook/test';+import { isDefined } from 'twenty-shared/utils';+import { Button } from 'twenty-ui/primitives/input';+import { ComponentDecorator } from 'twenty-ui/testing';++const meta: Meta<typeof ManagedIframe> = {+ title: 'Modules/MediaAccess/ManagedIframe',+ component: ManagedIframe,+ decorators: [ComponentDecorator],+};++export default meta;++const MICROPHONE_PERMISSION = {+ origin: 'https://example.com',+ microphone: true,+ camera: false,+};++const NATIVE_CAPTURE_SESSION: MediaAccessSession = {+ id: 'recorder-session',+ ownerId: getMediaAccessOwnerId({ type: 'application', id: 'recorder' }),+ ownerName: 'Native recorder',+ status: 'capturing',+ mediaTypes: ['video'],+ onStop: fn(),+};++const CLASS_SIZED_IFRAME_CLASS_NAME = 'managed-iframe-story-class-sized';++const ManagedIframePreview = ({+ hasNativeCapture = false,+ iframeStyle,+ iframeClassName,+}: {+ hasNativeCapture?: boolean;+ iframeStyle?: CSSProperties;+ iframeClassName?: string;+}) => {+ const [isHidden, setIsHidden] = useState(false);+ const [isGranted, setIsGranted] = useState(true);+ const [store] = useState(() => {+ const previewStore = createStore();+ previewStore.set(+ mediaAccessSessionsState.atom,+ hasNativeCapture ? [NATIVE_CAPTURE_SESSION] : [],+ );++ return previewStore;+ });++ return (+ <Provider store={store}>+ <style>{`.${CLASS_SIZED_IFRAME_CLASS_NAME} { border: 0; height: 180px; width: 376px; }`}</style>+ <MediaAccessIndicator />+ <Button onClick={() => setIsHidden(!isHidden)}>+ {isHidden ? 'Show phone' : 'Hide phone'}+ </Button>+ <Button onClick={() => setIsGranted(!isGranted)}>+ {isGranted ? 'Revoke microphone' : 'Grant microphone'}+ </Button>+ <div style={{ width: 500, height: 250 }}>+ <ManagedIframe+ owner={{ type: 'workspace-widget', id: 'phone', name: 'Aircall' }}+ iframeMediaPermissions={isGranted ? [MICROPHONE_PERMISSION] : []}+ requestedMediaCapabilities={['microphone', 'camera']}+ src="https://example.com"+ title="Aircall phone"+ className={iframeClassName}+ width={isDefined(iframeClassName) ? undefined : '100%'}+ height={isDefined(iframeClassName) ? undefined : '100%'}+ hidden={isHidden}+ style={iframeStyle}+ sandbox="allow-scripts allow-forms"+ allow="microphone *; camera *; encrypted-media"+ />+ </div>+ </Provider>+ );+};++export const EnableAndDisable: StoryObj<typeof ManagedIframe> = {+ render: () => <ManagedIframePreview />,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const initialFrame = canvas.getByTitle('Aircall phone');++ await expect(initialFrame).toHaveAttribute(+ 'allow',+ "microphone 'none'; camera 'none'; encrypted-media",+ );+ await expect(+ canvas.queryByRole('button', { name: 'Media access enabled' }),+ ).not.toBeInTheDocument();+ await canvas.findByRole('button', { name: 'Enable microphone' });+ await userEvent.click(canvas.getByRole('button', { name: 'Hide phone' }));+ await expect(initialFrame).not.toBeVisible();+ await expect(+ canvas.queryByRole('button', { name: 'Enable microphone' }),+ ).not.toBeInTheDocument();+ await userEvent.click(canvas.getByRole('button', { name: 'Show phone' }));+ await userEvent.click(+ await canvas.findByRole('button', { name: 'Enable microphone' }),+ );++ const enabledFrame = canvas.getByTitle('Aircall phone');+ await expect(enabledFrame).not.toBe(initialFrame);+ await expect(enabledFrame).toHaveAttribute(+ 'allow',+ "microphone https://example.com; camera 'none'; encrypted-media",+ );+ await userEvent.click(canvas.getByRole('button', { name: 'Hide phone' }));+ await expect(enabledFrame).not.toBeVisible();+ await expect(canvas.getByTitle('Aircall phone')).toBe(enabledFrame);+ await userEvent.click(+ canvas.getByRole('button', { name: 'Media access enabled' }),+ );+ await expect(+ await screen.findByText('Microphone access enabled'),+ ).toBeVisible();+ await expect(screen.getByText('https://example.com')).toBeVisible();+ await userEvent.click(+ screen.getByRole('button', { name: 'Disable media access for Aircall' }),+ );++ await waitFor(() => expect(enabledFrame).not.toBeInTheDocument());+ await expect(+ canvas.queryByRole('button', { name: 'Media access enabled' }),+ ).not.toBeInTheDocument();+ await userEvent.click(canvas.getByRole('button', { name: 'Show phone' }));+ await expect(+ await canvas.findByRole('button', { name: 'Enable microphone' }),+ ).toBeVisible();+ await expect(canvas.getByTitle('Aircall phone')).toHaveAttribute(+ 'allow',+ "microphone 'none'; camera 'none'; encrypted-media",+ );+ },+};++export const RevokedPermission: StoryObj<typeof ManagedIframe> = {+ render: () => <ManagedIframePreview />,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await userEvent.click(+ await canvas.findByRole('button', { name: 'Enable microphone' }),+ );+ const enabledFrame = canvas.getByTitle('Aircall phone');+ await userEvent.click(+ canvas.getByRole('button', { name: 'Revoke microphone' }),+ );++ await waitFor(() => expect(enabledFrame).not.toBeInTheDocument());+ await expect(+ canvas.queryByRole('button', { name: 'Media access enabled' }),+ ).not.toBeInTheDocument();+ await expect(+ canvas.queryByRole('button', { name: 'Enable microphone' }),+ ).not.toBeInTheDocument();+ await userEvent.click(+ canvas.getByRole('button', { name: 'Grant microphone' }),+ );+ await expect(+ await canvas.findByRole('button', { name: 'Enable microphone' }),+ ).toBeVisible();+ await expect(+ canvas.queryByRole('button', { name: 'Media access enabled' }),+ ).not.toBeInTheDocument();+ await expect(canvas.getByTitle('Aircall phone')).toHaveAttribute(+ 'allow',+ "microphone 'none'; camera 'none'; encrypted-media",+ );+ },+};++export const NativeCaptureAndExternalAccess: StoryObj<typeof ManagedIframe> = {+ render: () => <ManagedIframePreview hasNativeCapture />,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await userEvent.click(+ await canvas.findByRole('button', { name: 'Enable microphone' }),+ );+ await userEvent.click(+ canvas.getByRole('button', { name: 'Microphone or camera in use' }),+ );++ const sessions = await screen.findByRole('list', {+ name: 'Microphone or camera in use',+ });+ await expect(within(sessions).getAllByRole('listitem')).toHaveLength(2);+ await expect(within(sessions).getByText('Camera')).toBeVisible();+ await expect(+ within(sessions).getByText('Microphone access enabled'),+ ).toBeVisible();+ await userEvent.click(+ within(sessions).getByRole('button', {+ name: 'Disable media access for Aircall',+ }),+ );++ await waitFor(() =>+ expect(within(sessions).getAllByRole('listitem')).toHaveLength(1),+ );+ await expect(+ within(sessions).getByRole('button', {+ name: 'Stop capture for Native recorder',+ }),+ ).toBeVisible();+ },+};++export const FixedSize: StoryObj<typeof ManagedIframe> = {+ render: () => (+ <ManagedIframePreview+ iframeStyle={{ width: 360, height: 180, border: 0 }}+ />+ ),+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const initialFrame = canvas.getByTitle('Aircall phone');++ await expect(initialFrame.getBoundingClientRect().width).toBe(360);+ await expect(initialFrame.getBoundingClientRect().height).toBe(180);+ await expect(+ initialFrame.parentElement?.getBoundingClientRect().width,+ ).toBe(500);+ await userEvent.click(+ await canvas.findByRole('button', { name: 'Enable microphone' }),+ );++ const enabledFrame = canvas.getByTitle('Aircall phone');+ await expect(enabledFrame).not.toBe(initialFrame);+ await expect(enabledFrame.getBoundingClientRect().width).toBe(360);+ await expect(enabledFrame.getBoundingClientRect().height).toBe(180);+ },+};++export const ClassSized: StoryObj<typeof ManagedIframe> = {+ render: () => (+ <ManagedIframePreview iframeClassName={CLASS_SIZED_IFRAME_CLASS_NAME} />+ ),+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const initialFrame = canvas.getByTitle('Aircall phone');++ await expect(initialFrame.getBoundingClientRect().width).toBe(376);+ await expect(initialFrame.getBoundingClientRect().height).toBe(180);+ await userEvent.click(+ await canvas.findByRole('button', { name: 'Enable microphone' }),+ );++ const enabledFrame = canvas.getByTitle('Aircall phone');+ await expect(enabledFrame).not.toBe(initialFrame);+ await expect(enabledFrame.getBoundingClientRect().width).toBe(376);+ await expect(enabledFrame.getBoundingClientRect().height).toBe(180);+ },+};diff --git a/packages/twenty-front/src/modules/front-components/media-session/components/__stories__/FrontComponentMediaSessionIndicator.stories.tsx b/packages/twenty-front/src/modules/media-access/components/__stories__/MediaAccessIndicator.stories.tsxsimilarity index 63%rename from packages/twenty-front/src/modules/front-components/media-session/components/__stories__/FrontComponentMediaSessionIndicator.stories.tsxrename to packages/twenty-front/src/modules/media-access/components/__stories__/MediaAccessIndicator.stories.tsxindex 5b3e2a2f2ac..97e90401fab 100644--- a/packages/twenty-front/src/modules/front-components/media-session/components/__stories__/FrontComponentMediaSessionIndicator.stories.tsx+++ b/packages/twenty-front/src/modules/media-access/components/__stories__/MediaAccessIndicator.stories.tsx@@ -1,16 +1,16 @@-import { FrontComponentMediaSessionIndicator } from '@/front-components/media-session/components/FrontComponentMediaSessionIndicator';-import { frontComponentMediaSessionsState } from '@/front-components/media-session/states/frontComponentMediaSessionsState';+import { MediaAccessIndicator } from '@/media-access/components/MediaAccessIndicator';+import { mediaAccessSessionsState } from '@/media-access/states/mediaAccessSessionsState';import { type Meta, type StoryObj } from '@storybook/react-vite';-import { type FrontComponentMediaSessionStatus } from '@/front-components/media-session/types/FrontComponentMediaSessionStatus';+import { type MediaAccessSession } from '@/media-access/types/MediaAccessSession';import { createStore, Provider } from 'jotai';import { useState } from 'react';import { expect, fn, screen, userEvent, waitFor, within } from 'storybook/test';import { isDefined } from 'twenty-shared/utils';import { ComponentDecorator } from 'twenty-ui/testing';-const meta: Meta<typeof FrontComponentMediaSessionIndicator> = {- title: 'Modules/FrontComponents/FrontComponentMediaSessionIndicator',- component: FrontComponentMediaSessionIndicator,+const meta: Meta<typeof MediaAccessIndicator> = {+ title: 'Modules/MediaAccess/MediaAccessIndicator',+ component: MediaAccessIndicator,decorators: [ComponentDecorator],};@@ -24,13 +24,13 @@ const MediaSessionIndicatorPreview = ({const [store] = useState(() => {const previewStore = createStore();- previewStore.set(frontComponentMediaSessionsState.atom, [+ previewStore.set(mediaAccessSessionsState.atom, [{id: 'recorder',- applicationId: 'recorder',- applicationName: 'Call recorder',- activeMediaTypes: isPending ? [] : ['audio', 'video'],- pendingMediaTypes: isPending ? ['audio', 'video'] : [],+ ownerId: 'recorder',+ ownerName: 'Call recorder',+ status: isPending ? 'pending' : 'capturing',+ mediaTypes: ['audio', 'video'],onStop: fn(),},]);@@ -40,14 +40,12 @@ const MediaSessionIndicatorPreview = ({return (<Provider store={store}>- <FrontComponentMediaSessionIndicator />+ <MediaAccessIndicator /></Provider>);};-export const CircularIndicators: StoryObj<- typeof FrontComponentMediaSessionIndicator-> = {+export const CircularIndicators: StoryObj<typeof MediaAccessIndicator> = {render: () => (<><MediaSessionIndicatorPreview isPending={false} />@@ -57,7 +55,10 @@ export const CircularIndicators: StoryObj<play: async ({ canvasElement }) => {const canvas = within(canvasElement);- for (const name of ['Apps recording', 'Recording requests']) {+ for (const name of [+ 'Microphone or camera in use',+ 'Media access requests',+ ]) {const trigger = canvas.getByRole('button', { name });const dot = trigger.querySelector('span[aria-hidden]:empty');@@ -82,19 +83,19 @@ export const CircularIndicators: StoryObj<const StoredSessionsIndicator = ({sessions,}: {- sessions: FrontComponentMediaSessionStatus[];+ sessions: MediaAccessSession[];}) => {const [store] = useState(() => {const previewStore = createStore();- previewStore.set(frontComponentMediaSessionsState.atom, sessions);+ previewStore.set(mediaAccessSessionsState.atom, sessions);return previewStore;});return (<Provider store={store}>- <FrontComponentMediaSessionIndicator />+ <MediaAccessIndicator /></Provider>);};@@ -103,16 +104,16 @@ const stopRecorderAudio = fn();const stopRecorderVideo = fn();const stopCameraApp = fn();-const recorderSession: FrontComponentMediaSessionStatus = {+const recorderSession: MediaAccessSession = {id: 'recorder-audio',- applicationId: 'recorder',- applicationName: 'Recorder',- activeMediaTypes: ['audio'],- pendingMediaTypes: [],+ ownerId: 'recorder',+ ownerName: 'Recorder',+ status: 'capturing',+ mediaTypes: ['audio'],onStop: fn(),};-export const Hidden: StoryObj<typeof FrontComponentMediaSessionIndicator> = {+export const Hidden: StoryObj<typeof MediaAccessIndicator> = {render: () => <StoredSessionsIndicator sessions={[]} />,play: async ({ canvasElement }) => {await expect(@@ -121,9 +122,7 @@ export const Hidden: StoryObj<typeof FrontComponentMediaSessionIndicator> = {},};-export const OneRowPerApplication: StoryObj<- typeof FrontComponentMediaSessionIndicator-> = {+export const OneRowPerApplication: StoryObj<typeof MediaAccessIndicator> = {render: () => (<StoredSessionsIndicatorsessions={[@@ -131,15 +130,15 @@ export const OneRowPerApplication: StoryObj<{...recorderSession,id: 'recorder-video',- activeMediaTypes: ['video'],+ mediaTypes: ['video'],onStop: stopRecorderVideo,},{...recorderSession,id: 'camera-session',- applicationId: 'camera-app',- applicationName: 'Camera app',- activeMediaTypes: ['video'],+ ownerId: 'camera-app',+ ownerName: 'Camera app',+ mediaTypes: ['video'],onStop: stopCameraApp,},]}@@ -151,11 +150,11 @@ export const OneRowPerApplication: StoryObj<await expect(canvas.queryByText('Recorder')).not.toBeInTheDocument();await userEvent.click(- canvas.getByRole('button', { name: 'Apps recording' }),+ canvas.getByRole('button', { name: 'Microphone or camera in use' }),);const applications = await screen.findByRole('list', {- name: 'Apps recording',+ name: 'Microphone or camera in use',});await waitFor(() => expect(applications).toBeVisible());const applicationsCanvas = within(applications);@@ -169,7 +168,7 @@ export const OneRowPerApplication: StoryObj<await expect(applicationsCanvas.getByText('Camera')).toBeVisible();await userEvent.click(- screen.getByRole('button', { name: 'Stop recording for Recorder' }),+ screen.getByRole('button', { name: 'Stop capture for Recorder' }),);await expect(stopRecorderAudio).toHaveBeenCalledTimes(1);@@ -178,16 +177,14 @@ export const OneRowPerApplication: StoryObj<},};-export const PendingRequest: StoryObj<- typeof FrontComponentMediaSessionIndicator-> = {+export const PendingRequest: StoryObj<typeof MediaAccessIndicator> = {render: () => (<StoredSessionsIndicatorsessions={[{...recorderSession,- activeMediaTypes: [],- pendingMediaTypes: ['audio'],+ status: 'pending',+ mediaTypes: ['audio'],},]}/>@@ -196,33 +193,31 @@ export const PendingRequest: StoryObj<const canvas = within(canvasElement);await expect(- canvas.queryByRole('button', { name: 'Apps recording' }),+ canvas.queryByRole('button', { name: 'Microphone or camera in use' }),).not.toBeInTheDocument();await userEvent.click(- canvas.getByRole('button', { name: 'Recording requests' }),+ canvas.getByRole('button', { name: 'Media access requests' }),);await waitFor(async () => {await expect(screen.getByText('Waiting for permission')).toBeVisible();});await expect(- screen.getByRole('button', { name: 'Cancel recording for Recorder' }),+ screen.getByRole('button', { name: 'Cancel media request for Recorder' }),).toBeVisible();},};-export const ClosesWithEscape: StoryObj<- typeof FrontComponentMediaSessionIndicator-> = {+export const ClosesWithEscape: StoryObj<typeof MediaAccessIndicator> = {render: () => <StoredSessionsIndicator sessions={[recorderSession]} />,play: async ({ canvasElement }) => {const canvas = within(canvasElement);await userEvent.click(- canvas.getByRole('button', { name: 'Apps recording' }),+ canvas.getByRole('button', { name: 'Microphone or camera in use' }),);- await screen.findByRole('list', { name: 'Apps recording' });+ await screen.findByRole('list', { name: 'Microphone or camera in use' });await userEvent.keyboard('{Escape}');await waitFor(async () => {diff --git a/packages/twenty-front/src/modules/front-components/media-session/components/__stories__/FrontComponentMediaSessionTooltipRow.stories.tsx b/packages/twenty-front/src/modules/media-access/components/__stories__/MediaAccessSessionRow.stories.tsxsimilarity index 54%rename from packages/twenty-front/src/modules/front-components/media-session/components/__stories__/FrontComponentMediaSessionTooltipRow.stories.tsxrename to packages/twenty-front/src/modules/media-access/components/__stories__/MediaAccessSessionRow.stories.tsxindex 73aad49ac1e..93fb3e02714 100644--- a/packages/twenty-front/src/modules/front-components/media-session/components/__stories__/FrontComponentMediaSessionTooltipRow.stories.tsx+++ b/packages/twenty-front/src/modules/media-access/components/__stories__/MediaAccessSessionRow.stories.tsx@@ -1,27 +1,27 @@-import { FrontComponentMediaSessionTooltipRow } from '@/front-components/media-session/components/FrontComponentMediaSessionTooltipRow';-import { type FrontComponentMediaSessionStatus } from '@/front-components/media-session/types/FrontComponentMediaSessionStatus';+import { MediaAccessSessionRow } from '@/media-access/components/MediaAccessSessionRow';+import { type MediaAccessSession } from '@/media-access/types/MediaAccessSession';import { type Meta, type StoryObj } from '@storybook/react-vite';import { expect, fn, userEvent, within } from 'storybook/test';import { ComponentDecorator } from 'twenty-ui/testing';-const meta: Meta<typeof FrontComponentMediaSessionTooltipRow> = {- title: 'Modules/FrontComponents/FrontComponentMediaSessionTooltipRow',- component: FrontComponentMediaSessionTooltipRow,+const meta: Meta<typeof MediaAccessSessionRow> = {+ title: 'Modules/MediaAccess/MediaAccessSessionRow',+ component: MediaAccessSessionRow,decorators: [ComponentDecorator],};export default meta;-type Story = StoryObj<typeof FrontComponentMediaSessionTooltipRow>;+type Story = StoryObj<typeof MediaAccessSessionRow>;const buildSession = (- overrides: Partial<FrontComponentMediaSessionStatus>,-): FrontComponentMediaSessionStatus => ({+ overrides: Partial<MediaAccessSession>,+): MediaAccessSession => ({id: 'recorder-session',- applicationId: 'recorder',- applicationName: 'Recorder',- activeMediaTypes: [],- pendingMediaTypes: [],+ ownerId: 'recorder',+ ownerName: 'Recorder',+ status: 'capturing',+ mediaTypes: [],onStop: fn(),...overrides,});@@ -29,14 +29,14 @@ const buildSession = (export const CapturedMediaTypes: Story = {render: () => (<div role="list">- <FrontComponentMediaSessionTooltipRow- sessions={[buildSession({ activeMediaTypes: ['audio'] })]}+ <MediaAccessSessionRow+ sessions={[buildSession({ mediaTypes: ['audio'] })]}/>- <FrontComponentMediaSessionTooltipRow- sessions={[buildSession({ activeMediaTypes: ['video'] })]}+ <MediaAccessSessionRow+ sessions={[buildSession({ mediaTypes: ['video'] })]}/>- <FrontComponentMediaSessionTooltipRow- sessions={[buildSession({ activeMediaTypes: ['audio', 'video'] })]}+ <MediaAccessSessionRow+ sessions={[buildSession({ mediaTypes: ['audio', 'video'] })]}/></div>),@@ -47,7 +47,7 @@ export const CapturedMediaTypes: Story = {await expect(canvas.getByText('Camera')).toBeVisible();await expect(canvas.getByText('Microphone and camera')).toBeVisible();await expect(- canvas.getAllByRole('button', { name: 'Stop recording for Recorder' }),+ canvas.getAllByRole('button', { name: 'Stop capture for Recorder' }),).toHaveLength(3);},};@@ -55,8 +55,10 @@ export const CapturedMediaTypes: Story = {export const WaitingForPermission: Story = {render: () => (<div role="list">- <FrontComponentMediaSessionTooltipRow- sessions={[buildSession({ pendingMediaTypes: ['audio', 'video'] })]}+ <MediaAccessSessionRow+ sessions={[+ buildSession({ status: 'pending', mediaTypes: ['audio', 'video'] }),+ ]}/></div>),@@ -65,7 +67,7 @@ export const WaitingForPermission: Story = {await expect(canvas.getByText('Waiting for permission')).toBeVisible();await expect(- canvas.getByRole('button', { name: 'Cancel recording for Recorder' }),+ canvas.getByRole('button', { name: 'Cancel media request for Recorder' }),).toBeVisible();},};@@ -76,15 +78,15 @@ const stopVideoCapture = fn();export const StopsEverySessionOfTheApplication: Story = {render: () => (<div role="list">- <FrontComponentMediaSessionTooltipRow+ <MediaAccessSessionRowsessions={[buildSession({- activeMediaTypes: ['audio'],+ mediaTypes: ['audio'],onStop: stopAudioCapture,}),buildSession({id: 'recorder-video',- activeMediaTypes: ['video'],+ mediaTypes: ['video'],onStop: stopVideoCapture,}),]}@@ -97,7 +99,7 @@ export const StopsEverySessionOfTheApplication: Story = {await expect(canvas.getByText('Microphone and camera')).toBeVisible();await userEvent.click(- canvas.getByRole('button', { name: 'Stop recording for Recorder' }),+ canvas.getByRole('button', { name: 'Stop capture for Recorder' }),);await expect(stopAudioCapture).toHaveBeenCalledTimes(1);diff --git a/packages/twenty-front/src/modules/media-access/constants/ManagedIframeEnableButtonInsetPx.ts b/packages/twenty-front/src/modules/media-access/constants/ManagedIframeEnableButtonInsetPx.tsnew file mode 100644index 00000000000..993b7e5a08c--- /dev/null+++ b/packages/twenty-front/src/modules/media-access/constants/ManagedIframeEnableButtonInsetPx.ts@@ -0,0 +1 @@+export const MANAGED_IFRAME_ENABLE_BUTTON_INSET_PX = 8;diff --git a/packages/twenty-front/src/modules/media-access/hooks/useWorkspaceIframeMediaPermissions.ts b/packages/twenty-front/src/modules/media-access/hooks/useWorkspaceIframeMediaPermissions.tsnew file mode 100644index 00000000000..3544c1c8c30--- /dev/null+++ b/packages/twenty-front/src/modules/media-access/hooks/useWorkspaceIframeMediaPermissions.ts@@ -0,0 +1,11 @@+import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';+import { limitToDocumentIframeMediaPermissions } from '@/media-access/utils/limitToDocumentIframeMediaPermissions';+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';++export const useWorkspaceIframeMediaPermissions = () => {+ const currentWorkspace = useAtomStateValue(currentWorkspaceState);++ return limitToDocumentIframeMediaPermissions(+ currentWorkspace?.iframeMediaPermissions ?? [],+ );+};diff --git a/packages/twenty-front/src/modules/media-access/states/mediaAccessSessionsState.ts b/packages/twenty-front/src/modules/media-access/states/mediaAccessSessionsState.tsnew file mode 100644index 00000000000..1e6fe6405d2--- /dev/null+++ b/packages/twenty-front/src/modules/media-access/states/mediaAccessSessionsState.ts@@ -0,0 +1,7 @@+import { type MediaAccessSession } from '@/media-access/types/MediaAccessSession';+import { createAtomState } from '@/ui/utilities/state/jotai/utils/createAtomState';++export const mediaAccessSessionsState = createAtomState<MediaAccessSession[]>({+ key: 'mediaAccessSessionsState',+ defaultValue: [],+});diff --git a/packages/twenty-front/src/modules/media-access/types/ManagedIframeElementProps.ts b/packages/twenty-front/src/modules/media-access/types/ManagedIframeElementProps.tsnew file mode 100644index 00000000000..2dc5dc979e3--- /dev/null+++ b/packages/twenty-front/src/modules/media-access/types/ManagedIframeElementProps.ts@@ -0,0 +1,18 @@+import { type IframeHTMLAttributes } from 'react';++export type ManagedIframeElementProps = Pick<+ IframeHTMLAttributes<HTMLIFrameElement>,+ | 'src'+ | 'srcDoc'+ | 'title'+ | 'className'+ | 'style'+ | 'width'+ | 'height'+ | 'hidden'+ | 'onLoad'+ | 'onError'+ | 'sandbox'+ | 'allow'+ | 'allowFullScreen'+>;diff --git a/packages/twenty-front/src/modules/media-access/types/ManagedIframeProps.ts b/packages/twenty-front/src/modules/media-access/types/ManagedIframeProps.tsnew file mode 100644index 00000000000..89e815b9f0a--- /dev/null+++ b/packages/twenty-front/src/modules/media-access/types/ManagedIframeProps.ts@@ -0,0 +1,10 @@+import { type ManagedIframeElementProps } from '@/media-access/types/ManagedIframeElementProps';+import { type MediaAccessOwner } from '@/media-access/types/MediaAccessOwner';+import { type MediaCapability } from '@/media-access/types/MediaCapability';+import { type IframeMediaPermission } from 'twenty-shared/types';++export type ManagedIframeProps = ManagedIframeElementProps & {+ owner: MediaAccessOwner;+ requestedMediaCapabilities?: readonly MediaCapability[];+ iframeMediaPermissions: readonly IframeMediaPermission[];+};diff --git a/packages/twenty-front/src/modules/media-access/types/MediaAccessOwner.ts b/packages/twenty-front/src/modules/media-access/types/MediaAccessOwner.tsnew file mode 100644index 00000000000..8afe2eed5b2--- /dev/null+++ b/packages/twenty-front/src/modules/media-access/types/MediaAccessOwner.ts@@ -0,0 +1,5 @@+export type MediaAccessOwner = {+ type: 'workspace-widget' | 'application';+ id: string;+ name: string;+};diff --git a/packages/twenty-front/src/modules/media-access/types/MediaAccessSession.ts b/packages/twenty-front/src/modules/media-access/types/MediaAccessSession.tsnew file mode 100644index 00000000000..68e99098d68--- /dev/null+++ b/packages/twenty-front/src/modules/media-access/types/MediaAccessSession.ts@@ -0,0 +1,11 @@+import { type MediaSessionMediaType } from 'twenty-front-component-renderer';++export type MediaAccessSession = {+ id: string;+ ownerId: string;+ ownerName: string;+ status: 'pending' | 'capturing' | 'delegated';+ mediaTypes: MediaSessionMediaType[];+ origin?: string;+ onStop: () => void;+};diff --git a/packages/twenty-front/src/modules/media-access/types/MediaCapability.ts b/packages/twenty-front/src/modules/media-access/types/MediaCapability.tsnew file mode 100644index 00000000000..d3e7f1c3b06--- /dev/null+++ b/packages/twenty-front/src/modules/media-access/types/MediaCapability.ts@@ -0,0 +1,3 @@+import { type MEDIA_CAPABILITIES } from 'twenty-shared/constants';++export type MediaCapability = (typeof MEDIA_CAPABILITIES)[number];diff --git a/packages/twenty-front/src/modules/media-access/utils/__tests__/getDelegatedIframeMediaPermission.test.ts b/packages/twenty-front/src/modules/media-access/utils/__tests__/getDelegatedIframeMediaPermission.test.tsnew file mode 100644index 00000000000..ca15ceb0dc6--- /dev/null+++ b/packages/twenty-front/src/modules/media-access/utils/__tests__/getDelegatedIframeMediaPermission.test.ts@@ -0,0 +1,36 @@+import { getDelegatedIframeMediaPermission } from '@/media-access/utils/getDelegatedIframeMediaPermission';++const ACTIVATED_PERMISSION = {+ origin: 'https://phone.example.com',+ microphone: true,+ camera: false,+};++describe('getDelegatedIframeMediaPermission', () => {+ it('returns null before the user enables media access', () => {+ expect(+ getDelegatedIframeMediaPermission({+ activatedPermission: null,+ permission: ACTIVATED_PERMISSION,+ }),+ ).toBeNull();+ });++ it('keeps the activated permission while it is still granted', () => {+ expect(+ getDelegatedIframeMediaPermission({+ activatedPermission: ACTIVATED_PERMISSION,+ permission: { ...ACTIVATED_PERMISSION, camera: true },+ }),+ ).toBe(ACTIVATED_PERMISSION);+ });++ it('drops the activated permission once it is revoked', () => {+ expect(+ getDelegatedIframeMediaPermission({+ activatedPermission: ACTIVATED_PERMISSION,+ permission: null,+ }),+ ).toBeNull();+ });+});diff --git a/packages/twenty-front/src/modules/media-access/utils/__tests__/getDocumentIframeMediaPermissions.test.ts b/packages/twenty-front/src/modules/media-access/utils/__tests__/getDocumentIframeMediaPermissions.test.tsnew file mode 100644index 00000000000..2f031381710--- /dev/null+++ b/packages/twenty-front/src/modules/media-access/utils/__tests__/getDocumentIframeMediaPermissions.test.ts@@ -0,0 +1,53 @@+import { getDocumentIframeMediaPermissions } from '@/media-access/utils/getDocumentIframeMediaPermissions';+import { IFRAME_MEDIA_PERMISSIONS_BOOTSTRAP_ELEMENT_ID } from 'twenty-shared/constants';++const appendBootstrapElement = (content: string) => {+ const element = document.createElement('script');++ element.id = IFRAME_MEDIA_PERMISSIONS_BOOTSTRAP_ELEMENT_ID;+ element.type = 'application/json';+ element.textContent = content;+ document.head.append(element);+};++describe('getDocumentIframeMediaPermissions', () => {+ afterEach(() => {+ document+ .getElementById(IFRAME_MEDIA_PERMISSIONS_BOOTSTRAP_ELEMENT_ID)+ ?.remove();+ });++ it('returns undefined when the document was not served with a media policy', () => {+ expect(getDocumentIframeMediaPermissions()).toBeUndefined();+ });++ it('returns the valid permissions served with the document', () => {+ appendBootstrapElement(+ JSON.stringify([+ {+ origin: 'https://phone.example.com',+ microphone: true,+ camera: false,+ },+ {+ origin: 'https://video.example.com',+ microphone: 'yes',+ camera: true,+ },+ ]),+ );++ expect(getDocumentIframeMediaPermissions()).toEqual([+ { origin: 'https://phone.example.com', microphone: true, camera: false },+ ]);+ });++ it.each(['not json', '{}'])(+ 'denies every origin when the served policy is malformed: %s',+ (content) => {+ appendBootstrapElement(content);++ expect(getDocumentIframeMediaPermissions()).toEqual([]);+ },+ );+});diff --git a/packages/twenty-front/src/modules/media-access/utils/__tests__/getIframeMediaAllow.test.ts b/packages/twenty-front/src/modules/media-access/utils/__tests__/getIframeMediaAllow.test.tsnew file mode 100644index 00000000000..dac8ad8f8dc--- /dev/null+++ b/packages/twenty-front/src/modules/media-access/utils/__tests__/getIframeMediaAllow.test.ts@@ -0,0 +1,102 @@+import { getIframeMediaAllow } from '@/media-access/utils/getIframeMediaAllow';++describe('getIframeMediaAllow', () => {+ it.each([undefined, ''])(+ 'denies media by default for the allow value %p',+ (allow) => {+ expect(getIframeMediaAllow({ allow })).toBe(+ "microphone 'none'; camera 'none'",+ );+ },+ );++ it('removes every media directive while preserving unrelated permissions', () => {+ expect(+ getIframeMediaAllow({+ allow: " MICROPHONE *; Camera; microphone 'src'; fullscreen; autoplay ",+ permission: null,+ }),+ ).toBe("microphone 'none'; camera 'none'; fullscreen; autoplay");+ });++ it.each([+ 'camera:*',+ 'camera*',+ 'cameras *',+ 'Microphone:*',+ 'microphones *',+ ])(+ 'removes the prefixed media directive %s that WebKit also parses as a media feature',+ (mediaDirective) => {+ expect(+ getIframeMediaAllow({+ allow: `${mediaDirective}; autoplay`,+ permission: null,+ }),+ ).toBe("microphone 'none'; camera 'none'; autoplay");+ },+ );++ it('places the enforced media directives before every guest directive so the first declaration wins', () => {+ expect(+ getIframeMediaAllow({+ allow: 'autoplay; fullscreen',+ permission: {+ origin: 'https://phone.example.com',+ microphone: true,+ camera: false,+ },+ }).split('; '),+ ).toEqual([+ 'microphone https://phone.example.com',+ "camera 'none'",+ 'autoplay',+ 'fullscreen',+ ]);+ });++ it.each([+ {+ microphone: true,+ camera: false,+ expected: "microphone https://phone.example.com; camera 'none'",+ },+ {+ microphone: false,+ camera: true,+ expected: "microphone 'none'; camera https://phone.example.com",+ },+ {+ microphone: true,+ camera: true,+ expected:+ 'microphone https://phone.example.com; camera https://phone.example.com',+ },+ ])(+ 'serializes exact origins independently for microphone=$microphone and camera=$camera',+ ({ microphone, camera, expected }) => {+ expect(+ getIframeMediaAllow({+ allow: 'camera *; microphone https://other.example.com',+ permission: {+ origin: 'https://PHONE.example.com:443/',+ microphone,+ camera,+ },+ }),+ ).toBe(expected);+ },+ );++ it.each(['http://phone.example.com', 'https://phone.example.com; camera *'])(+ 'denies both capabilities when the supplied origin is invalid: %s',+ (origin) => {+ expect(+ getIframeMediaAllow({+ allow: 'microphone *; camera *',+ permission: { origin, microphone: true, camera: true },+ }),+ ).toBe("microphone 'none'; camera 'none'");+ },+ );+});diff --git a/packages/twenty-front/src/modules/media-access/utils/__tests__/getManagedIframeMediaPermission.test.ts b/packages/twenty-front/src/modules/media-access/utils/__tests__/getManagedIframeMediaPermission.test.tsnew file mode 100644index 00000000000..bc8b339e332--- /dev/null+++ b/packages/twenty-front/src/modules/media-access/utils/__tests__/getManagedIframeMediaPermission.test.ts@@ -0,0 +1,76 @@+import { type ManagedIframeProps } from '@/media-access/types/ManagedIframeProps';+import { getManagedIframeMediaPermission } from '@/media-access/utils/getManagedIframeMediaPermission';++const TRUSTED_ORIGIN = 'https://phone.example.com';+const DEFAULT_INPUT = {+ src: `${TRUSTED_ORIGIN}/dialer`,+ requestedMediaCapabilities: ['microphone', 'camera'],+ iframeMediaPermissions: [+ { origin: TRUSTED_ORIGIN, microphone: true, camera: false },+ ],+ hostOrigin: 'https://workspace.twenty.com',+} satisfies Pick<+ ManagedIframeProps,+ 'src' | 'requestedMediaCapabilities' | 'iframeMediaPermissions'+> & { hostOrigin: string };++describe('getManagedIframeMediaPermission', () => {+ it('intersects requested capabilities and the exact workspace origin grant', () => {+ expect(getManagedIframeMediaPermission(DEFAULT_INPUT)).toEqual({+ origin: TRUSTED_ORIGIN,+ microphone: true,+ camera: false,+ });+ });++ it('returns no permission when no requested capability is approved for the origin', () => {+ expect(+ getManagedIframeMediaPermission({+ ...DEFAULT_INPUT,+ requestedMediaCapabilities: ['camera'],+ }),+ ).toBeNull();+ });++ it.each([+ 'http://phone.example.com',+ 'https://untrusted.example.com',+ 'https://phone.example.com.attacker.example',+ 'https://subdomain.phone.example.com',+ 'https://phone.example.com:444',+ 'https://user:[email protected]',+ 'https://workspace.twenty.com',+ 'blob:https://phone.example.com/stream',+ 'data:text/html,hello',+ 'about:blank',+ '/dialer',+ ])('does not delegate media to %s', (src) => {+ expect(+ getManagedIframeMediaPermission({ ...DEFAULT_INPUT, src }),+ ).toBeNull();+ });++ it('rejects srcDoc even when src is an approved HTTPS URL', () => {+ expect(+ getManagedIframeMediaPermission({ ...DEFAULT_INPUT, srcDoc: '' }),+ ).toBeNull();+ });++ it('rejects the host origin even when it has a workspace grant', () => {+ expect(+ getManagedIframeMediaPermission({+ ...DEFAULT_INPUT,+ hostOrigin: TRUSTED_ORIGIN,+ }),+ ).toBeNull();+ });++ it('does not delegate capabilities that the embed did not request', () => {+ expect(+ getManagedIframeMediaPermission({+ ...DEFAULT_INPUT,+ requestedMediaCapabilities: undefined,+ }),+ ).toBeNull();+ });+});diff --git a/packages/twenty-front/src/modules/media-access/utils/__tests__/intersectIframeMediaPermissions.test.ts b/packages/twenty-front/src/modules/media-access/utils/__tests__/intersectIframeMediaPermissions.test.tsnew file mode 100644index 00000000000..b3fe7274bf2--- /dev/null+++ b/packages/twenty-front/src/modules/media-access/utils/__tests__/intersectIframeMediaPermissions.test.ts@@ -0,0 +1,46 @@+import { intersectIframeMediaPermissions } from '@/media-access/utils/intersectIframeMediaPermissions';++const PHONE_ORIGIN = 'https://phone.example.com';+const VIDEO_ORIGIN = 'https://video.example.com';++describe('intersectIframeMediaPermissions', () => {+ it('drops origins missing from the allowed permissions', () => {+ expect(+ intersectIframeMediaPermissions({+ permissions: [+ { origin: PHONE_ORIGIN, microphone: true, camera: false },+ { origin: VIDEO_ORIGIN, microphone: true, camera: true },+ ],+ allowedPermissions: [+ { origin: PHONE_ORIGIN, microphone: true, camera: false },+ ],+ }),+ ).toEqual([{ origin: PHONE_ORIGIN, microphone: true, camera: false }]);+ });++ it('keeps only the capabilities both sides grant', () => {+ expect(+ intersectIframeMediaPermissions({+ permissions: [+ { origin: VIDEO_ORIGIN, microphone: true, camera: false },+ ],+ allowedPermissions: [+ { origin: VIDEO_ORIGIN, microphone: true, camera: true },+ ],+ }),+ ).toEqual([{ origin: VIDEO_ORIGIN, microphone: true, camera: false }]);+ });++ it('drops origins left without any capability', () => {+ expect(+ intersectIframeMediaPermissions({+ permissions: [+ { origin: VIDEO_ORIGIN, microphone: false, camera: true },+ ],+ allowedPermissions: [+ { origin: VIDEO_ORIGIN, microphone: true, camera: false },+ ],+ }),+ ).toEqual([]);+ });+});diff --git a/packages/twenty-front/src/modules/media-access/utils/__tests__/isIframeMediaPermissionCovered.test.ts b/packages/twenty-front/src/modules/media-access/utils/__tests__/isIframeMediaPermissionCovered.test.tsnew file mode 100644index 00000000000..ad139de8421--- /dev/null+++ b/packages/twenty-front/src/modules/media-access/utils/__tests__/isIframeMediaPermissionCovered.test.ts@@ -0,0 +1,38 @@+import { isIframeMediaPermissionCovered } from '@/media-access/utils/isIframeMediaPermissionCovered';++const ORIGIN = 'https://phone.example.com';++describe('isIframeMediaPermissionCovered', () => {+ it('stays covered when the covering permission widens', () => {+ expect(+ isIframeMediaPermissionCovered({+ permission: { origin: ORIGIN, microphone: true, camera: false },+ coveringPermission: { origin: ORIGIN, microphone: true, camera: true },+ }),+ ).toBe(true);+ });++ it('is no longer covered when a delegated capability is revoked', () => {+ expect(+ isIframeMediaPermissionCovered({+ permission: { origin: ORIGIN, microphone: true, camera: true },+ coveringPermission: { origin: ORIGIN, microphone: true, camera: false },+ }),+ ).toBe(false);+ });++ it.each([+ null,+ { origin: 'https://other.example.com', microphone: true, camera: true },+ ])(+ 'is not covered by a missing or different-origin permission %o',+ (coveringPermission) => {+ expect(+ isIframeMediaPermissionCovered({+ permission: { origin: ORIGIN, microphone: true, camera: false },+ coveringPermission,+ }),+ ).toBe(false);+ },+ );+});diff --git a/packages/twenty-front/src/modules/media-access/utils/__tests__/limitToDocumentIframeMediaPermissions.test.ts b/packages/twenty-front/src/modules/media-access/utils/__tests__/limitToDocumentIframeMediaPermissions.test.tsnew file mode 100644index 00000000000..6f54b36c5fa--- /dev/null+++ b/packages/twenty-front/src/modules/media-access/utils/__tests__/limitToDocumentIframeMediaPermissions.test.ts@@ -0,0 +1,37 @@+import { limitToDocumentIframeMediaPermissions } from '@/media-access/utils/limitToDocumentIframeMediaPermissions';+import { IFRAME_MEDIA_PERMISSIONS_BOOTSTRAP_ELEMENT_ID } from 'twenty-shared/constants';++const PHONE_ORIGIN = 'https://phone.example.com';+const VIDEO_ORIGIN = 'https://video.example.com';++const PERMISSIONS = [+ { origin: PHONE_ORIGIN, microphone: true, camera: false },+ { origin: VIDEO_ORIGIN, microphone: true, camera: true },+];++describe('limitToDocumentIframeMediaPermissions', () => {+ afterEach(() => {+ document+ .getElementById(IFRAME_MEDIA_PERMISSIONS_BOOTSTRAP_ELEMENT_ID)+ ?.remove();+ });++ it('keeps the permissions when the document was not served with a media policy', () => {+ expect(limitToDocumentIframeMediaPermissions(PERMISSIONS)).toEqual(+ PERMISSIONS,+ );+ });++ it('ignores origins approved after the document was served', () => {+ const element = document.createElement('script');++ element.id = IFRAME_MEDIA_PERMISSIONS_BOOTSTRAP_ELEMENT_ID;+ element.type = 'application/json';+ element.textContent = JSON.stringify([PERMISSIONS[0]]);+ document.head.append(element);++ expect(limitToDocumentIframeMediaPermissions(PERMISSIONS)).toEqual([+ PERMISSIONS[0],+ ]);+ });+});diff --git a/packages/twenty-front/src/modules/media-access/utils/__tests__/restrictIframeMediaPermission.test.ts b/packages/twenty-front/src/modules/media-access/utils/__tests__/restrictIframeMediaPermission.test.tsnew file mode 100644index 00000000000..28a96d1e813--- /dev/null+++ b/packages/twenty-front/src/modules/media-access/utils/__tests__/restrictIframeMediaPermission.test.ts@@ -0,0 +1,36 @@+import { restrictIframeMediaPermission } from '@/media-access/utils/restrictIframeMediaPermission';++const PERMISSION = {+ origin: 'https://phone.example.com',+ microphone: true,+ camera: true,+};++describe('restrictIframeMediaPermission', () => {+ it('keeps only the capabilities the application holds', () => {+ expect(+ restrictIframeMediaPermission({+ permission: PERMISSION,+ capabilities: ['camera'],+ }),+ ).toEqual({ origin: PERMISSION.origin, microphone: false, camera: true });+ });++ it('returns no permission when the application holds none of the capabilities', () => {+ expect(+ restrictIframeMediaPermission({+ permission: PERMISSION,+ capabilities: [],+ }),+ ).toBeNull();+ });++ it('returns no permission when the origin is not approved', () => {+ expect(+ restrictIframeMediaPermission({+ permission: null,+ capabilities: ['microphone', 'camera'],+ }),+ ).toBeNull();+ });+});diff --git a/packages/twenty-front/src/modules/media-access/utils/getDelegatedIframeMediaPermission.ts b/packages/twenty-front/src/modules/media-access/utils/getDelegatedIframeMediaPermission.tsnew file mode 100644index 00000000000..f2a4b9ceb75--- /dev/null+++ b/packages/twenty-front/src/modules/media-access/utils/getDelegatedIframeMediaPermission.ts@@ -0,0 +1,22 @@+import { isIframeMediaPermissionCovered } from '@/media-access/utils/isIframeMediaPermissionCovered';+import { type IframeMediaPermission } from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';++export const getDelegatedIframeMediaPermission = ({+ activatedPermission,+ permission,+}: {+ activatedPermission: IframeMediaPermission | null;+ permission: IframeMediaPermission | null;+}): IframeMediaPermission | null => {+ if (!isDefined(activatedPermission)) {+ return null;+ }++ return isIframeMediaPermissionCovered({+ permission: activatedPermission,+ coveringPermission: permission,+ })+ ? activatedPermission+ : null;+};diff --git a/packages/twenty-front/src/modules/media-access/utils/getDocumentIframeMediaPermissions.ts b/packages/twenty-front/src/modules/media-access/utils/getDocumentIframeMediaPermissions.tsnew file mode 100644index 00000000000..0e7ed59f785--- /dev/null+++ b/packages/twenty-front/src/modules/media-access/utils/getDocumentIframeMediaPermissions.ts@@ -0,0 +1,40 @@+import { isArray, isBoolean, isObject, isString } from '@sniptt/guards';+import { IFRAME_MEDIA_PERMISSIONS_BOOTSTRAP_ELEMENT_ID } from 'twenty-shared/constants';+import { type IframeMediaPermission } from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';+import { logError } from '~/utils/logError';++const isIframeMediaPermission = (+ value: unknown,+): value is IframeMediaPermission =>+ isObject(value) &&+ 'origin' in value &&+ isString(value.origin) &&+ 'microphone' in value &&+ isBoolean(value.microphone) &&+ 'camera' in value &&+ isBoolean(value.camera);++export const getDocumentIframeMediaPermissions = ():+ | IframeMediaPermission[]+ | undefined => {+ const element = document.getElementById(+ IFRAME_MEDIA_PERMISSIONS_BOOTSTRAP_ELEMENT_ID,+ );++ if (!isDefined(element)) {+ return undefined;+ }++ try {+ const permissions: unknown = JSON.parse(element.textContent ?? 'null');++ return isArray(permissions)+ ? permissions.filter(isIframeMediaPermission)+ : [];+ } catch (error) {+ logError(error);++ return [];+ }+};diff --git a/packages/twenty-front/src/modules/media-access/utils/getIframeMediaAllow.ts b/packages/twenty-front/src/modules/media-access/utils/getIframeMediaAllow.tsnew file mode 100644index 00000000000..9b644b22d9b--- /dev/null+++ b/packages/twenty-front/src/modules/media-access/utils/getIframeMediaAllow.ts@@ -0,0 +1,35 @@+import { isNonEmptyString } from '@sniptt/guards';+import { type IframeMediaPermission } from 'twenty-shared/types';+import { isDefined, normalizeIframeOrigin } from 'twenty-shared/utils';++const MEDIA_DIRECTIVE_PREFIX_PATTERN = /^(?:microphone|camera)/i;++export const getIframeMediaAllow = ({+ allow,+ permission,+}: {+ allow?: string;+ permission?: IframeMediaPermission | null;+}): string => {+ const otherDirectives = (allow ?? '')+ .split(';')+ .map((directive) => directive.trim())+ .filter(+ (directive) =>+ isNonEmptyString(directive) &&+ !MEDIA_DIRECTIVE_PREFIX_PATTERN.test(directive),+ );+ const origin = isDefined(permission)+ ? normalizeIframeOrigin(permission.origin, { isHttpsOnly: true })+ : undefined;+ const microphoneOrigin =+ isDefined(origin) && permission?.microphone ? origin : "'none'";+ const cameraOrigin =+ isDefined(origin) && permission?.camera ? origin : "'none'";++ return [+ `microphone ${microphoneOrigin}`,+ `camera ${cameraOrigin}`,+ ...otherDirectives,+ ].join('; ');+};diff --git a/packages/twenty-front/src/modules/media-access/utils/getIframeMediaPermissionMediaTypes.ts b/packages/twenty-front/src/modules/media-access/utils/getIframeMediaPermissionMediaTypes.tsnew file mode 100644index 00000000000..b6631a1f5f2--- /dev/null+++ b/packages/twenty-front/src/modules/media-access/utils/getIframeMediaPermissionMediaTypes.ts@@ -0,0 +1,9 @@+import { type MediaSessionMediaType } from 'twenty-front-component-renderer';+import { type IframeMediaPermission } from 'twenty-shared/types';++export const getIframeMediaPermissionMediaTypes = (+ permission: Pick<IframeMediaPermission, 'microphone' | 'camera'>,+): MediaSessionMediaType[] => [+ ...(permission.microphone ? (['audio'] as const) : []),+ ...(permission.camera ? (['video'] as const) : []),+];diff --git a/packages/twenty-front/src/modules/media-access/utils/getManagedIframeMediaPermission.ts b/packages/twenty-front/src/modules/media-access/utils/getManagedIframeMediaPermission.tsnew file mode 100644index 00000000000..dfc8c28907f--- /dev/null+++ b/packages/twenty-front/src/modules/media-access/utils/getManagedIframeMediaPermission.ts@@ -0,0 +1,49 @@+import { type ManagedIframeProps } from '@/media-access/types/ManagedIframeProps';+import { restrictIframeMediaPermission } from '@/media-access/utils/restrictIframeMediaPermission';+import { isNonEmptyString } from '@sniptt/guards';+import { type IframeMediaPermission } from 'twenty-shared/types';+import {+ getUrlSafely,+ isDefined,+ normalizeIframeOrigin,+} from 'twenty-shared/utils';++export const getManagedIframeMediaPermission = ({+ src,+ srcDoc,+ requestedMediaCapabilities = [],+ iframeMediaPermissions,+ hostOrigin,+}: Pick<+ ManagedIframeProps,+ 'src' | 'srcDoc' | 'requestedMediaCapabilities' | 'iframeMediaPermissions'+> & { hostOrigin: string }): IframeMediaPermission | null => {+ if (!isNonEmptyString(src) || isDefined(srcDoc)) {+ return null;+ }++ const sourceUrl = getUrlSafely(src);++ if (!isDefined(sourceUrl)) {+ return null;+ }++ const origin = normalizeIframeOrigin(sourceUrl.origin, { isHttpsOnly: true });++ if (+ sourceUrl.protocol !== 'https:' ||+ !isDefined(origin) ||+ origin === hostOrigin ||+ isNonEmptyString(sourceUrl.username) ||+ isNonEmptyString(sourceUrl.password)+ ) {+ return null;+ }++ return restrictIframeMediaPermission({+ permission:+ iframeMediaPermissions.find((candidate) => candidate.origin === origin) ??+ null,+ capabilities: requestedMediaCapabilities,+ });+};diff --git a/packages/twenty-front/src/modules/media-access/utils/getMediaAccessOwnerId.ts b/packages/twenty-front/src/modules/media-access/utils/getMediaAccessOwnerId.tsnew file mode 100644index 00000000000..346f6189f56--- /dev/null+++ b/packages/twenty-front/src/modules/media-access/utils/getMediaAccessOwnerId.ts@@ -0,0 +1,6 @@+import { type MediaAccessOwner } from '@/media-access/types/MediaAccessOwner';++export const getMediaAccessOwnerId = ({+ type,+ id,+}: Pick<MediaAccessOwner, 'type' | 'id'>) => `${type}:${id}`;diff --git a/packages/twenty-front/src/modules/media-access/utils/intersectIframeMediaPermissions.ts b/packages/twenty-front/src/modules/media-access/utils/intersectIframeMediaPermissions.tsnew file mode 100644index 00000000000..5067ab95840--- /dev/null+++ b/packages/twenty-front/src/modules/media-access/utils/intersectIframeMediaPermissions.ts@@ -0,0 +1,26 @@+import { type IframeMediaPermission } from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';++export const intersectIframeMediaPermissions = ({+ permissions,+ allowedPermissions,+}: {+ permissions: readonly IframeMediaPermission[];+ allowedPermissions: readonly IframeMediaPermission[];+}): IframeMediaPermission[] =>+ permissions.flatMap((permission) => {+ const allowedPermission = allowedPermissions.find(+ (candidate) => candidate.origin === permission.origin,+ );++ if (!isDefined(allowedPermission)) {+ return [];+ }++ const microphone = permission.microphone && allowedPermission.microphone;+ const camera = permission.camera && allowedPermission.camera;++ return microphone || camera+ ? [{ origin: permission.origin, microphone, camera }]+ : [];+ });diff --git a/packages/twenty-front/src/modules/media-access/utils/isIframeMediaPermissionCovered.ts b/packages/twenty-front/src/modules/media-access/utils/isIframeMediaPermissionCovered.tsnew file mode 100644index 00000000000..5d151986644--- /dev/null+++ b/packages/twenty-front/src/modules/media-access/utils/isIframeMediaPermissionCovered.ts@@ -0,0 +1,14 @@+import { type IframeMediaPermission } from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';++export const isIframeMediaPermissionCovered = ({+ permission,+ coveringPermission,+}: {+ permission: IframeMediaPermission;+ coveringPermission: IframeMediaPermission | null;+}): boolean =>+ isDefined(coveringPermission) &&+ coveringPermission.origin === permission.origin &&+ (!permission.microphone || coveringPermission.microphone) &&+ (!permission.camera || coveringPermission.camera);diff --git a/packages/twenty-front/src/modules/media-access/utils/limitToDocumentIframeMediaPermissions.ts b/packages/twenty-front/src/modules/media-access/utils/limitToDocumentIframeMediaPermissions.tsnew file mode 100644index 00000000000..0f2884b2cf9--- /dev/null+++ b/packages/twenty-front/src/modules/media-access/utils/limitToDocumentIframeMediaPermissions.ts@@ -0,0 +1,17 @@+import { getDocumentIframeMediaPermissions } from '@/media-access/utils/getDocumentIframeMediaPermissions';+import { intersectIframeMediaPermissions } from '@/media-access/utils/intersectIframeMediaPermissions';+import { type IframeMediaPermission } from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';++export const limitToDocumentIframeMediaPermissions = (+ permissions: readonly IframeMediaPermission[],+): readonly IframeMediaPermission[] => {+ const documentPermissions = getDocumentIframeMediaPermissions();++ return isDefined(documentPermissions)+ ? intersectIframeMediaPermissions({+ permissions,+ allowedPermissions: documentPermissions,+ })+ : permissions;+};diff --git a/packages/twenty-front/src/modules/media-access/utils/restrictIframeMediaPermission.ts b/packages/twenty-front/src/modules/media-access/utils/restrictIframeMediaPermission.tsnew file mode 100644index 00000000000..8097cd0ea73--- /dev/null+++ b/packages/twenty-front/src/modules/media-access/utils/restrictIframeMediaPermission.ts@@ -0,0 +1,25 @@+import { type MediaCapability } from '@/media-access/types/MediaCapability';+import { type IframeMediaPermission } from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';++export const restrictIframeMediaPermission = ({+ permission,+ capabilities,+}: {+ permission: IframeMediaPermission | null;+ capabilities: readonly MediaCapability[];+}): IframeMediaPermission | null => {+ if (!isDefined(permission)) {+ return null;+ }++ const microphone =+ permission.microphone && capabilities.includes('microphone');+ const camera = permission.camera && capabilities.includes('camera');++ if (!microphone && !camera) {+ return null;+ }++ return { origin: permission.origin, microphone, camera };+};diff --git a/packages/twenty-front/src/modules/navigation/components/NavigationDrawerHeader.tsx b/packages/twenty-front/src/modules/navigation/components/NavigationDrawerHeader.tsxindex 04b794ba766..28c96093e30 100644--- a/packages/twenty-front/src/modules/navigation/components/NavigationDrawerHeader.tsx+++ b/packages/twenty-front/src/modules/navigation/components/NavigationDrawerHeader.tsx@@ -1,4 +1,4 @@-import { FrontComponentMediaSessionIndicator } from '@/front-components/media-session/components/FrontComponentMediaSessionIndicator';+import { MediaAccessIndicator } from '@/media-access/components/MediaAccessIndicator';import { APP_HEADER_HEIGHT } from '@/ui/layout/constants/AppHeaderHeight';import { styled } from '@linaria/react';import { t } from '@lingui/core/macro';@@ -77,7 +77,7 @@ export const NavigationDrawerHeader = () => {</StyledWorkspaceDropdownContainer>{isExpanded && (<StyledRightActions>- <FrontComponentMediaSessionIndicator />+ <MediaAccessIndicator />{searchButton}<NavigationDrawerCollapseButtondirection="left"@@ -88,7 +88,7 @@ export const NavigationDrawerHeader = () => {</StyledHeaderRow>{!isExpanded && !isMobile && (<StyledCollapsedSearch>- <FrontComponentMediaSessionIndicator />+ <MediaAccessIndicator />{searchButton}</StyledCollapsedSearch>)}diff --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 e9e1e91d429..5c46445af21 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@@ -1,9 +1,13 @@+import { ManagedIframe } from '@/media-access/components/ManagedIframe';+import { useWorkspaceIframeMediaPermissions } from '@/media-access/hooks/useWorkspaceIframeMediaPermissions';+import { useGetIsMetadataItemCustom } from '@/object-metadata/hooks/useGetIsMetadataItemCustom';import { useIsPageLayoutInEditMode } from '@/page-layout/hooks/useIsPageLayoutInEditMode';import { type PageLayoutWidget } from '@/page-layout/types/PageLayoutWidget';import { PageLayoutWidgetNoDataDisplay } from '@/page-layout/widgets/components/PageLayoutWidgetNoDataDisplay';import { WidgetSkeletonLoader } from '@/page-layout/widgets/components/WidgetSkeletonLoader';import { styled } from '@linaria/react';import { useState } from 'react';+import { MEDIA_CAPABILITIES } from 'twenty-shared/constants';import { getSafeUrl, isDefined, isHttpUrl } from 'twenty-shared/utils';import { doNotTranslate } from 'twenty-shared/i18n';import { themeCssVariables } from 'twenty-ui/theme';@@ -21,7 +25,7 @@ const StyledContainer = styled.div<{ $isEditMode: boolean }>`width: 100%;`;-const StyledIframe = styled.iframe<{ $isEditMode: boolean }>`+const StyledIframe = styled(ManagedIframe)<{ $isEditMode: boolean }>`border: none;flex: 1;height: 100%;@@ -52,12 +56,15 @@ const StyledErrorContainer = styled.div`text-align: center;`;-export type IframeWidgetProps = {+type IframeWidgetProps = {widget: PageLayoutWidget;};export const IframeWidget = ({ widget }: IframeWidgetProps) => {const isPageLayoutInEditMode = useIsPageLayoutInEditMode();+ const iframeMediaPermissions = useWorkspaceIframeMediaPermissions();+ const getIsMetadataItemCustom = useGetIsMetadataItemCustom();+ const isWorkspaceWidget = getIsMetadataItemCustom(widget);const configuration = widget.configuration;@@ -104,6 +111,9 @@ export const IframeWidget = ({ widget }: IframeWidgetProps) => {)}<StyledIframe$isEditMode={isPageLayoutInEditMode}+ owner={{ type: 'workspace-widget', id: widget.id, name: title }}+ iframeMediaPermissions={iframeMediaPermissions}+ requestedMediaCapabilities={isWorkspaceWidget ? MEDIA_CAPABILITIES : []}src={safeUrl}title={title}onLoad={handleIframeLoad}diff --git a/packages/twenty-front/src/modules/ui/layout/page/components/PageHeader.tsx b/packages/twenty-front/src/modules/ui/layout/page/components/PageHeader.tsxindex 2bbf317b85f..4db774e1b24 100644--- a/packages/twenty-front/src/modules/ui/layout/page/components/PageHeader.tsx+++ b/packages/twenty-front/src/modules/ui/layout/page/components/PageHeader.tsx@@ -2,7 +2,7 @@ import { styled } from '@linaria/react';import { t } from '@lingui/core/macro';import { type ReactNode } from 'react';-import { FrontComponentMediaSessionIndicator } from '@/front-components/media-session/components/FrontComponentMediaSessionIndicator';+import { MediaAccessIndicator } from '@/media-access/components/MediaAccessIndicator';import { NavigationDrawerCollapseButton } from '@/ui/navigation/navigation-drawer/components/NavigationDrawerCollapseButton';import { useIsSettingsPage } from '@/navigation/hooks/useIsSettingsPage';@@ -143,7 +143,7 @@ export const PageHeader = ({data-click-outside-id={PAGE_ACTION_CONTAINER_CLICK_OUTSIDE_ID}>{children}- {isMobile && <FrontComponentMediaSessionIndicator />}+ {isMobile && <MediaAccessIndicator />}</StyledPageActionContainer></StyledTopBarContainer></AnimatePresence>diff --git a/packages/twenty-oxlint-rules/rules/no-twenty-ui-override.exemptions.ts b/packages/twenty-oxlint-rules/rules/no-twenty-ui-override.exemptions.tsindex 4762a54390f..707a7de05de 100644--- a/packages/twenty-oxlint-rules/rules/no-twenty-ui-override.exemptions.ts+++ b/packages/twenty-oxlint-rules/rules/no-twenty-ui-override.exemptions.ts@@ -26,7 +26,7 @@ export const TWENTY_UI_OVERRIDE_EXEMPTIONS = [},{filePath:- 'packages/twenty-front/src/modules/front-components/media-session/components/FrontComponentMediaSessionIndicator.tsx',+ 'packages/twenty-front/src/modules/media-access/components/MediaAccessIndicator.tsx',reason: 'Popover.Popup sized and spaced for the recording sessions list',},{