diff --git a/lib/experimental/media/docs/client-side-media-docs.md b/lib/experimental/media/docs/client-side-media-docs.md index 49a290a9172a86..fafc0e34817675 100644 --- a/lib/experimental/media/docs/client-side-media-docs.md +++ b/lib/experimental/media/docs/client-side-media-docs.md @@ -1,12 +1,57 @@ # Technical Documentation +## Browser Compatibility + +Client-side media processing requires the following browser capabilities: + +| Feature | Required | Purpose | +|---------|----------|---------| +| WebAssembly | Yes | Runs the wasm-vips image processing library | +| SharedArrayBuffer | Yes | Enables multi-threaded WASM execution | +| Cross-origin isolation | Yes | Required for SharedArrayBuffer in modern browsers | +| CSP `blob:` workers | Yes | The WASM worker is loaded via a blob URL | + +### Browser Support Matrix + +| Browser | Minimum Version | Notes | +|---------|-----------------|-------| +| Chrome | 92+ | Full support | +| Firefox | 79+ | Full support except embed previews | +| Safari | 15.2+ | Requires `require-corp` instead of `credentialless` | +| Edge | 92+ | Full support | + +### Automatic Fallback + +When client-side media processing is unavailable, the system automatically falls back to server-side processing. This fallback is transparent to users and requires no action. A message is logged to the browser console indicating the reason for the fallback. + +The fallback occurs when any of the following conditions are detected: +- WebAssembly is not supported in the browser +- SharedArrayBuffer is not available +- Cross-origin isolation is not enabled (missing required headers) +- The site's Content Security Policy (CSP) blocks blob URL workers + ## Cross-origin isolation / `SharedArrayBuffer` -WASM-based image optimization requires `SharedArrayBuffer` support, which in turn requires [cross-origin isolation](https://web.dev/articles/cross-origin-isolation-guide). To implement this, the editor uses the following headers: -- `Cross-Origin-Opener-Policy: same-origin` -- `Cross-Origin-Embedder-Policy: credentialless` (or `require-corp` for safari) +WASM-based image optimization requires `SharedArrayBuffer` support, which in turn requires [cross-origin isolation](https://web.dev/articles/cross-origin-isolation-guide). + +Once the page is served with these headers, `SharedArrayBuffer` will be available in the browser, and WASM-based image optimization will work as expected. However, all embedded resources (e.g., images, iframes, scripts) must also be served with appropriate CORS headers (or iframe with `iframe-credentialless` for supporting browsers) to ensure cross-origin isolation is maintained. For third party embeds (for example a YouTube video), the plugin uses [iframe `credentialless` attribute](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/IFrame_credentialless) to help with this. For browsers that do not support this attribute, embeds will show an information pane instead of a live preview. + +### Troubleshooting + +If client-side media processing is not working, check the browser console for messages. Common issues include: + +1. **"SharedArrayBuffer is not available"**: The server is not sending the required cross-origin isolation headers. +2. **"Cross-origin isolation is not enabled"**: The headers are present but cross-origin isolation is not active. This can happen if: + - Third-party resources are blocking isolation + - Headers are being stripped by a proxy or CDN + - The page is being served over HTTP instead of HTTPS + +3. **"WebAssembly is not supported"**: The browser does not support WebAssembly. This is rare in modern browsers but can occur in older versions or restricted environments. -Once the page is served with these headers, `SharedArrayBuffer` will be available in the browser, and WASM-based image optimization will work as expected. However, all embedded resources (e.g., images, iframes, scripts) must also be served with appropriate CORS headers to ensure cross-origin isolation is maintained. For third party embeds (for example a YouTube video), the plugin uses [iframe `credentialless` attribute](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/IFrame_credentialless) to help with this. For browsers that do not support this attribute, embeds will show an information pane instead of a live preview. +4. **"Content Security Policy (CSP) does not allow blob: workers"**: A security plugin or server configuration is setting a `worker-src` CSP directive that does not include `blob:`. The WASM image processing worker is loaded via a blob URL, which requires CSP to permit it. To resolve this: + - Add `blob:` to the `worker-src` directive in the site's CSP header (e.g., `worker-src 'self' blob:`) + - If using a security plugin (e.g., WP Cerber, Wordfence, or similar), check its CSP settings and add `blob:` to the allowed worker sources + - If the CSP header is set at the server level (e.g., in `.htaccess`, Nginx config, or a CDN), update it there -Check out [this tracking issue](https://github.com/swissspidy/media-experiments/issues/294) for more details and further resources. +Check out [this tracking issue](https://github.com/WordPress/gutenberg/issues/74464) for more details and further resources. diff --git a/packages/block-editor/src/components/provider/index.js b/packages/block-editor/src/components/provider/index.js index a6591ef2676122..0252671f4d9c30 100644 --- a/packages/block-editor/src/components/provider/index.js +++ b/packages/block-editor/src/components/provider/index.js @@ -7,6 +7,7 @@ import { SlotFillProvider } from '@wordpress/components'; import { MediaUploadProvider, store as uploadStore, + detectClientSideMediaSupport, } from '@wordpress/upload-media'; /** @@ -24,6 +25,64 @@ import useMediaUploadSettings from './use-media-upload-settings'; const noop = () => {}; +/** + * Flag to track if we've already logged the fallback message. + */ +let hasLoggedFallback = false; + +/** + * Cached result of whether client-side media processing should be enabled. + * This is computed once per session for efficiency and stability. + */ +let isClientSideMediaEnabledCache = null; + +/** + * Checks if client-side media processing should be enabled. + * + * Returns true only if: + * 1. The experimental media processing flag is enabled + * 2. The browser supports WebAssembly, SharedArrayBuffer, cross-origin isolation, and CSP allows blob workers + * + * The result is cached for the session to ensure stability during React renders. + * + * @return {boolean} Whether client-side media processing should be enabled. + */ +function shouldEnableClientSideMediaProcessing() { + // Return cached result if available. + if ( isClientSideMediaEnabledCache !== null ) { + return isClientSideMediaEnabledCache; + } + + // Check if experimental flag is enabled first. + if ( ! window.__experimentalMediaProcessing ) { + isClientSideMediaEnabledCache = false; + return false; + } + + // Safety check in case the import is unavailable. + if ( typeof detectClientSideMediaSupport !== 'function' ) { + isClientSideMediaEnabledCache = false; + return false; + } + + const detection = detectClientSideMediaSupport(); + if ( ! detection || ! detection.supported ) { + // Only log once per session to avoid console spam. + if ( ! hasLoggedFallback ) { + // eslint-disable-next-line no-console + console.info( + `Client-side media processing unavailable: ${ detection.reason }. Using server-side processing.` + ); + hasLoggedFallback = true; + } + isClientSideMediaEnabledCache = false; + return false; + } + + isClientSideMediaEnabledCache = true; + return true; +} + /** * Upload a media file when the file upload button is activated * or when adding a file to the editor via drag & drop. @@ -71,11 +130,11 @@ export const ExperimentalBlockEditorProvider = withRegistryProvider( const mediaUploadSettings = useMediaUploadSettings( _settings ); + const isClientSideMediaEnabled = + shouldEnableClientSideMediaProcessing(); + const settings = useMemo( () => { - if ( - window.__experimentalMediaProcessing && - _settings?.mediaUpload - ) { + if ( isClientSideMediaEnabled && _settings?.mediaUpload ) { // Create a new object so that the original props.settings.mediaUpload is not modified. return { ..._settings, @@ -83,7 +142,7 @@ export const ExperimentalBlockEditorProvider = withRegistryProvider( }; } return _settings; - }, [ _settings, registry ] ); + }, [ _settings, registry, isClientSideMediaEnabled ] ); const { __experimentalUpdateSettings } = unlock( useDispatch( blockEditorStore ) @@ -115,7 +174,7 @@ export const ExperimentalBlockEditorProvider = withRegistryProvider( ); - if ( window.__experimentalMediaProcessing ) { + if ( isClientSideMediaEnabled ) { return ( { + const originalWebAssembly = global.WebAssembly; + const originalSharedArrayBuffer = global.SharedArrayBuffer; + const originalWorker = global.Worker; + const originalCreateObjectURL = global.URL.createObjectURL; + const originalRevokeObjectURL = global.URL.revokeObjectURL; + + beforeEach( () => { + // Clear the cache before each test. + clearFeatureDetectionCache(); + + // By default, provide a mock Worker that does not throw (CSP allows blob workers). + global.Worker = class MockWorker { + terminate() {} + } as unknown as typeof Worker; + + // jsdom does not implement URL.createObjectURL/revokeObjectURL. + global.URL.createObjectURL = jest.fn( + () => 'blob:http://localhost/test' + ); + global.URL.revokeObjectURL = jest.fn(); + } ); + + afterEach( () => { + // Restore original values. + global.WebAssembly = originalWebAssembly; + global.SharedArrayBuffer = originalSharedArrayBuffer; + global.Worker = originalWorker; + global.URL.createObjectURL = originalCreateObjectURL; + global.URL.revokeObjectURL = originalRevokeObjectURL; + } ); + + describe( 'detectClientSideMediaSupport', () => { + it( 'returns supported when all features are available', () => { + // Ensure all features are available. + global.WebAssembly = originalWebAssembly; + global.SharedArrayBuffer = originalSharedArrayBuffer; + + const result = detectClientSideMediaSupport(); + + expect( result.supported ).toBe( true ); + expect( result.reason ).toBeUndefined(); + } ); + + it( 'returns not supported when WebAssembly is unavailable', () => { + // @ts-ignore - Intentionally setting WebAssembly to undefined for testing. + global.WebAssembly = undefined; + + const result = detectClientSideMediaSupport(); + + expect( result.supported ).toBe( false ); + expect( result.reason ).toBe( + 'WebAssembly is not supported in this browser' + ); + } ); + + it( 'returns not supported when SharedArrayBuffer is unavailable', () => { + global.WebAssembly = originalWebAssembly; + // @ts-ignore - Intentionally setting SharedArrayBuffer to undefined for testing. + global.SharedArrayBuffer = undefined; + + const result = detectClientSideMediaSupport(); + + expect( result.supported ).toBe( false ); + expect( result.reason ).toContain( 'SharedArrayBuffer' ); + } ); + + it( 'returns not supported when CSP blocks blob workers', () => { + global.WebAssembly = originalWebAssembly; + global.SharedArrayBuffer = originalSharedArrayBuffer; + + // Simulate CSP blocking blob URL workers by throwing a SecurityError. + global.Worker = class ThrowingWorker { + constructor() { + throw new DOMException( + "Refused to create a worker from 'blob:...' because it violates the Content Security Policy directive: \"worker-src 'self'\".", + 'SecurityError' + ); + } + } as unknown as typeof Worker; + + const result = detectClientSideMediaSupport(); + + expect( result.supported ).toBe( false ); + expect( result.reason ).toContain( 'Content Security Policy' ); + expect( result.reason ).toContain( 'worker-src' ); + } ); + + it( 'caches the result', () => { + global.WebAssembly = originalWebAssembly; + global.SharedArrayBuffer = originalSharedArrayBuffer; + + const result1 = detectClientSideMediaSupport(); + expect( result1.supported ).toBe( true ); + + // Now set WebAssembly to undefined - cached result should still be returned. + // @ts-ignore - Intentionally setting WebAssembly to undefined for testing. + global.WebAssembly = undefined; + + const result2 = detectClientSideMediaSupport(); + expect( result2.supported ).toBe( true ); + expect( result2 ).toBe( result1 ); // Same object reference. + } ); + } ); + + describe( 'isClientSideMediaSupported', () => { + it( 'returns true when all features are available', () => { + global.WebAssembly = originalWebAssembly; + global.SharedArrayBuffer = originalSharedArrayBuffer; + + expect( isClientSideMediaSupported() ).toBe( true ); + } ); + + it( 'returns false when features are unavailable', () => { + // @ts-ignore - Intentionally setting WebAssembly to undefined for testing. + global.WebAssembly = undefined; + + expect( isClientSideMediaSupported() ).toBe( false ); + } ); + } ); + + describe( 'clearFeatureDetectionCache', () => { + it( 'clears the cached result', () => { + global.WebAssembly = originalWebAssembly; + global.SharedArrayBuffer = originalSharedArrayBuffer; + + const result1 = detectClientSideMediaSupport(); + expect( result1.supported ).toBe( true ); + + // Clear cache and set WebAssembly to undefined. + clearFeatureDetectionCache(); + // @ts-ignore - Intentionally setting WebAssembly to undefined for testing. + global.WebAssembly = undefined; + + const result2 = detectClientSideMediaSupport(); + expect( result2.supported ).toBe( false ); + } ); + } ); +} );