Beautiful Open-Source Form Builder
Add SDK bridge messaging functionality for iframe communication (#1134)
Chirag Chhatralaaed5a031795d
diff --git a/client/lib/sdk/sdkBridgeMessaging.js b/client/lib/sdk/sdkBridgeMessaging.jsnew file mode 100644index 000000000..871f26430--- /dev/null+++ b/client/lib/sdk/sdkBridgeMessaging.js@@ -0,0 +1,152 @@+export const MSG_PREFIX = 'opnform:'+export const WILDCARD_ORIGIN = '*'++export function resolveInitialTrustedOrigin(isIframe) {+ if (!isIframe || typeof window === 'undefined') return null++ try {+ const params = new URLSearchParams(window.location.search)+ const parentOrigin = params.get('_sdkParentOrigin')+ if (parentOrigin) {+ return new URL(decodeURIComponent(parentOrigin), window.location.href).origin+ }+ } catch { /* ignore */ }++ try {+ if (window.location.ancestorOrigins?.length) {+ return window.location.ancestorOrigins[window.location.ancestorOrigins.length - 1]+ }+ } catch { /* ignore */ }++ try {+ if (document.referrer) {+ return new URL(document.referrer).origin+ }+ } catch { /* ignore */ }++ return null+}++export function readSdkTokenFromUrl() {+ if (typeof window === 'undefined') return null++ try {+ const params = new URLSearchParams(window.location.search)+ return params.get('_sdkToken') || null+ } catch {+ return null+ }+}++/**+ * Creates postMessage security handlers for the iframe SDK bridge.+ */+export function createSdkBridgeMessageHandler(options) {+ const {+ isIframe,+ getFormSlug,+ initialSdkToken = null,+ initialTrustedOrigin = null,+ postToParent,+ onCommand,+ } = options++ let trustedOrigin = initialTrustedOrigin+ let sdkToken = initialSdkToken++ function getPostTargetOrigin() {+ return trustedOrigin || WILDCARD_ORIGIN+ }++ function validateAndLockParentOrigin(event, claimedParentOrigin) {+ if (!isIframe || event.source !== window.parent) {+ return false+ }++ if (claimedParentOrigin && claimedParentOrigin !== event.origin) {+ return false+ }++ if (!trustedOrigin && event.origin) {+ trustedOrigin = event.origin+ } else if (trustedOrigin && event.origin !== trustedOrigin) {+ return false+ }++ return true+ }++ function sendResponse(requestId, success, data = null, error = null) {+ postToParent({+ type: MSG_PREFIX + 'response',+ formSlug: getFormSlug(),+ requestId,+ success,+ data,+ error,+ }, getPostTargetOrigin())+ }++ function sendHandshakeAck(success) {+ postToParent({+ type: MSG_PREFIX + 'handshake-ack',+ formSlug: getFormSlug(),+ success,+ }, getPostTargetOrigin())+ }++ function handleHandshake(message, event) {+ if (message.formSlug !== getFormSlug()) return+ if (!validateAndLockParentOrigin(event, message.parentOrigin)) return++ const incomingToken = message._sdkToken+ if (!incomingToken || typeof incomingToken !== 'string') return++ if (sdkToken && sdkToken !== incomingToken) {+ sendHandshakeAck(false)+ return+ }++ sdkToken = sdkToken || incomingToken+ sendHandshakeAck(true)+ }++ function onMessage(event) {+ if (isIframe) {+ if (event.source !== window.parent) return+ } else if (event.source !== window) {+ return+ }++ const data = event.data+ if (!data || typeof data !== 'object') return++ if (data.type === MSG_PREFIX + 'handshake') {+ if (isIframe) {+ handleHandshake(data, event)+ }+ return+ }++ if (data.type === MSG_PREFIX + 'command') {+ if (isIframe && !validateAndLockParentOrigin(event)) {+ return+ }++ if (isIframe && (!sdkToken || data._sdkToken !== sdkToken)) {+ sendResponse(data.requestId, false, null, 'Invalid SDK token')+ return+ }++ onCommand(data)+ }+ }++ return {+ onMessage,+ sendResponse,+ getTrustedOrigin: () => trustedOrigin,+ getSdkToken: () => sdkToken,+ getPostTargetOrigin,+ }+}diff --git a/client/lib/sdk/useSdkBridge.js b/client/lib/sdk/useSdkBridge.jsindex 732794f17..2b8cca9a4 100644--- a/client/lib/sdk/useSdkBridge.js+++ b/client/lib/sdk/useSdkBridge.js@@ -7,9 +7,13 @@import { watch, toValue, onMounted, onUnmounted, toRaw, isRef, unref } from 'vue'import { useIsIframe } from '~/composables/useIsIframe'import { handleDarkMode } from '~/lib/forms/public-page'--const MSG_PREFIX = 'opnform:'-const POST_MESSAGE_TARGET = '*'+import {+ MSG_PREFIX,+ WILDCARD_ORIGIN,+ createSdkBridgeMessageHandler,+ readSdkTokenFromUrl,+ resolveInitialTrustedOrigin,+} from '~/lib/sdk/sdkBridgeMessaging'// Event typesconst EVENTS = {@@ -688,9 +692,14 @@ export function useSdkBridge(options) {const isIframe = useIsIframe()let messageHandler = null- function postMessageSafe(target, message) {+ const initialSdkToken = typeof window !== 'undefined' ? readSdkTokenFromUrl() : null+ const initialTrustedOrigin = typeof window !== 'undefined'+ ? resolveInitialTrustedOrigin(isIframe)+ : null++ function postMessageSafe(target, message, origin) {try {- target.postMessage(message, POST_MESSAGE_TARGET)+ target.postMessage(message, origin || WILDCARD_ORIGIN)} catch (error) {if (error?.name !== 'DataCloneError') {console.error('[OpnForm SDK Bridge] postMessage failed:', error)@@ -703,9 +712,9 @@ export function useSdkBridge(options) {if (!cloneableMessage) returnif (isIframe) {- postMessageSafe(window.parent, cloneableMessage)+ postMessageSafe(window.parent, cloneableMessage, bridgeMessaging.getPostTargetOrigin())}- postMessageSafe(window, cloneableMessage)+ postMessageSafe(window, cloneableMessage, window.location.origin)}/**@@ -746,23 +755,18 @@ export function useSdkBridge(options) {function sendResponse(requestId, success, data = null, error = null) {if (!import.meta.client) return- const config = toValue(formConfig)- const message = {- type: MSG_PREFIX + 'response',- formSlug: config?.slug,- requestId: requestId,- success: success,- data: toPlainObject(data),- error: toPlainObject(error)- }-- emitMessage(message)+ bridgeMessaging.sendResponse(+ requestId,+ success,+ toPlainObject(data),+ toPlainObject(error),+ )}/*** Handle incoming command from parent*/- function handleCommand(message) {+ function handleCommand(message, respond = sendResponse) {const { command, payload, requestId } = messageconst config = toValue(formConfig)@@ -857,8 +861,8 @@ export function useSdkBridge(options) {case 'submit':if (formManager?.submit) {formManager.submit()- .then(() => sendResponse(requestId, true, { success: true }))- .catch((err) => sendResponse(requestId, false, null, err?.message || 'Submit failed'))+ .then(() => respond(requestId, true, { success: true }))+ .catch((err) => respond(requestId, false, null, err?.message || 'Submit failed'))return}break@@ -894,31 +898,31 @@ export function useSdkBridge(options) {}if (result !== null) {- sendResponse(requestId, result.success !== false, result)+ respond(requestId, result.success !== false, result)}} catch (e) {console.error('[OpnForm SDK Bridge] Command error:', e)- sendResponse(requestId, false, null, e.message)+ respond(requestId, false, null, e.message)}}+ const bridgeMessaging = createSdkBridgeMessageHandler({+ isIframe,+ getFormSlug: () => toValue(formConfig)?.slug,+ initialSdkToken,+ initialTrustedOrigin,+ postToParent: (message, origin) => {+ if (!import.meta.client || !isIframe) return+ postMessageSafe(window.parent, message, origin)+ },+ onCommand: handleCommand,+ })+/*** Handle incoming messages*/function onMessage(event) {- if (isIframe) {- if (event.source !== window.parent) return- } else if (event.source !== window) {- return- }-- const data = event.data- if (!data || typeof data !== 'object') return-- // Handle SDK commands- if (data.type === MSG_PREFIX + 'command') {- handleCommand(data)- }+ bridgeMessaging.onMessage(event)}/**diff --git a/client/public/widgets/opnform-sdk.js b/client/public/widgets/opnform-sdk.jsindex f36bd40f0..955b8f024 100644--- a/client/public/widgets/opnform-sdk.js+++ b/client/public/widgets/opnform-sdk.js@@ -38,6 +38,13 @@RESIZE: 'resize'}+ function generateSdkToken() {+ if (global.crypto?.randomUUID) {+ return global.crypto.randomUUID()+ }+ return `${Date.now()}-${Math.random().toString(36).slice(2)}`+ }+function getIframeOrigin(iframe) {try {if (!iframe?.src) return null@@ -47,6 +54,15 @@}}+ function getIframeSdkToken(iframe) {+ try {+ if (!iframe?.src) return null+ return new URL(iframe.src, window.location.href).searchParams.get('_sdkToken')+ } catch (e) {+ return null+ }+ }+/*** Simple EventEmitter implementation*/@@ -111,12 +127,13 @@* Form Instance - represents a single embedded form*/class FormInstance extends EventEmitter {- constructor(iframe, slug, sdk) {+ constructor(iframe, slug, sdk, sdkToken = null) {super()this.iframe = iframethis.slug = slugthis.id = iframe.id || slugthis._sdk = sdk+ this._sdkToken = sdkToken || getIframeSdkToken(iframe) || generateSdkToken()this._ready = falsethis._pendingRequests = {}this._requestId = 0@@ -127,34 +144,130 @@this._popupOpen = falsethis._resizeInitialized = falsethis._targetOrigin = getIframeOrigin(iframe) || '*'+ this._handshakeComplete = false+ this._handshakePromise = null+ this._handshakeResolve = null+ this._handshakeReject = null+ this._handshakeRetryTimer = null}isReady() { return this._ready }+ _sendHandshake() {+ if (!this.iframe?.contentWindow || !this._sdkToken) return++ this.iframe.contentWindow.postMessage({+ type: MSG_PREFIX + 'handshake',+ formSlug: this.slug,+ _sdkToken: this._sdkToken,+ parentOrigin: window.location.origin,+ }, this._targetOrigin)+ }++ _createHandshakePromise() {+ return new Promise((resolve, reject) => {+ this._handshakeResolve = resolve+ this._handshakeReject = reject+ this._sendHandshake()++ this._handshakeRetryTimer = setInterval(() => {+ if (this._handshakeComplete) return+ this._sendHandshake()+ }, 250)++ setTimeout(() => {+ if (this._handshakeComplete) return++ if (this._handshakeRetryTimer) {+ clearInterval(this._handshakeRetryTimer)+ this._handshakeRetryTimer = null+ }++ this._handshakePromise = null+ this._handshakeResolve = null+ if (this._handshakeReject) {+ this._handshakeReject(new Error('SDK handshake timeout'))+ this._handshakeReject = null+ }+ }, 3000)+ })+ }++ _startHandshake() {+ this._handshakePromise = this._createHandshakePromise()+ this._handshakePromise.catch(() => {})++ if (this.iframe.contentWindow) {+ this._sendHandshake()+ } else {+ this.iframe.addEventListener('load', () => this._sendHandshake())+ }+ }++ _ensureHandshake() {+ if (this._handshakeComplete) {+ return Promise.resolve()+ }++ if (!this._handshakePromise) {+ this._handshakePromise = this._createHandshakePromise()+ }++ return this._handshakePromise+ }++ _handleHandshakeAck(message) {+ if (this._handshakeRetryTimer) {+ clearInterval(this._handshakeRetryTimer)+ this._handshakeRetryTimer = null+ }++ if (message.success === false) {+ this._handshakePromise = null+ this._handshakeResolve = null+ if (this._handshakeReject) {+ this._handshakeReject(new Error('SDK handshake rejected'))+ this._handshakeReject = null+ }+ return+ }++ this._handshakeComplete = true++ if (this._handshakeResolve) {+ this._handshakeResolve()+ this._handshakeResolve = null+ this._handshakeReject = null+ }+ }+_sendCommand(command, payload = {}) {if (!this.iframe || !this.iframe.contentWindow) {console.warn('[OpnForm SDK] Cannot send command - iframe not available')return Promise.reject(new Error('Iframe not available'))}- const requestId = ++this._requestId- const message = {- type: MSG_PREFIX + 'command',- command: command,- formSlug: this.slug,- requestId: requestId,- payload: payload- }+ return this._ensureHandshake().then(() => {+ const requestId = ++this._requestId+ const message = {+ type: MSG_PREFIX + 'command',+ command: command,+ formSlug: this.slug,+ requestId: requestId,+ payload: payload,+ _sdkToken: this._sdkToken,+ }- return new Promise((resolve, reject) => {- this._pendingRequests[requestId] = { resolve, reject }- setTimeout(() => {- if (this._pendingRequests[requestId]) {- delete this._pendingRequests[requestId]- reject(new Error('Command timeout'))- }- }, 5000)- this.iframe.contentWindow.postMessage(message, this._targetOrigin)+ return new Promise((resolve, reject) => {+ this._pendingRequests[requestId] = { resolve, reject }+ setTimeout(() => {+ if (this._pendingRequests[requestId]) {+ delete this._pendingRequests[requestId]+ reject(new Error('Command timeout'))+ }+ }, 5000)+ this.iframe.contentWindow.postMessage(message, this._targetOrigin)+ })})}@@ -312,14 +425,16 @@})}- _registerForm(iframe, slug) {- const instance = new FormInstance(iframe, slug, this)+ _registerForm(iframe, slug, sdkToken = null) {+ const instance = new FormInstance(iframe, slug, this, sdkToken)this._forms[slug] = instanceif (iframe.id && iframe.id !== slug) {this._forms[iframe.id] = instance}+ instance._startHandshake()+// Auto-initialize resize if enabledif (this._options.autoResize !== false) {// Wait for iframe to be ready@@ -356,6 +471,8 @@this._handleEvent(data, form)} else if (messageType === 'response') {this._handleResponse(data, form)+ } else if (messageType === 'handshake-ack') {+ form._handleHandshakeAck(data)}}}@@ -475,14 +592,20 @@iframe.style.height = height === 'auto' ? '600px' : heightlet url = `/forms/${slug}`+ const sdkToken = generateSdkToken()+ const query = new URLSearchParams({+ _sdkToken: sdkToken,+ _sdkParentOrigin: window.location.origin,+ })if (darkMode !== undefined) {- url += `?darkMode=${darkMode}`+ query.set('darkMode', String(darkMode))}+ url += `?${query.toString()}`iframe.src = urlcontainerEl.appendChild(iframe)- const form = this._registerForm(iframe, slug)+ const form = this._registerForm(iframe, slug, sdkToken)if (onSubmit) {form.on(EVENTS.SUBMIT, onSubmit)diff --git a/client/public/widgets/opnform-sdk.min.js b/client/public/widgets/opnform-sdk.min.jsindex f36bd40f0..955b8f024 100644--- a/client/public/widgets/opnform-sdk.min.js+++ b/client/public/widgets/opnform-sdk.min.js@@ -38,6 +38,13 @@RESIZE: 'resize'}+ function generateSdkToken() {+ if (global.crypto?.randomUUID) {+ return global.crypto.randomUUID()+ }+ return `${Date.now()}-${Math.random().toString(36).slice(2)}`+ }+function getIframeOrigin(iframe) {try {if (!iframe?.src) return null@@ -47,6 +54,15 @@}}+ function getIframeSdkToken(iframe) {+ try {+ if (!iframe?.src) return null+ return new URL(iframe.src, window.location.href).searchParams.get('_sdkToken')+ } catch (e) {+ return null+ }+ }+/*** Simple EventEmitter implementation*/@@ -111,12 +127,13 @@* Form Instance - represents a single embedded form*/class FormInstance extends EventEmitter {- constructor(iframe, slug, sdk) {+ constructor(iframe, slug, sdk, sdkToken = null) {super()this.iframe = iframethis.slug = slugthis.id = iframe.id || slugthis._sdk = sdk+ this._sdkToken = sdkToken || getIframeSdkToken(iframe) || generateSdkToken()this._ready = falsethis._pendingRequests = {}this._requestId = 0@@ -127,34 +144,130 @@this._popupOpen = falsethis._resizeInitialized = falsethis._targetOrigin = getIframeOrigin(iframe) || '*'+ this._handshakeComplete = false+ this._handshakePromise = null+ this._handshakeResolve = null+ this._handshakeReject = null+ this._handshakeRetryTimer = null}isReady() { return this._ready }+ _sendHandshake() {+ if (!this.iframe?.contentWindow || !this._sdkToken) return++ this.iframe.contentWindow.postMessage({+ type: MSG_PREFIX + 'handshake',+ formSlug: this.slug,+ _sdkToken: this._sdkToken,+ parentOrigin: window.location.origin,+ }, this._targetOrigin)+ }++ _createHandshakePromise() {+ return new Promise((resolve, reject) => {+ this._handshakeResolve = resolve+ this._handshakeReject = reject+ this._sendHandshake()++ this._handshakeRetryTimer = setInterval(() => {+ if (this._handshakeComplete) return+ this._sendHandshake()+ }, 250)++ setTimeout(() => {+ if (this._handshakeComplete) return++ if (this._handshakeRetryTimer) {+ clearInterval(this._handshakeRetryTimer)+ this._handshakeRetryTimer = null+ }++ this._handshakePromise = null+ this._handshakeResolve = null+ if (this._handshakeReject) {+ this._handshakeReject(new Error('SDK handshake timeout'))+ this._handshakeReject = null+ }+ }, 3000)+ })+ }++ _startHandshake() {+ this._handshakePromise = this._createHandshakePromise()+ this._handshakePromise.catch(() => {})++ if (this.iframe.contentWindow) {+ this._sendHandshake()+ } else {+ this.iframe.addEventListener('load', () => this._sendHandshake())+ }+ }++ _ensureHandshake() {+ if (this._handshakeComplete) {+ return Promise.resolve()+ }++ if (!this._handshakePromise) {+ this._handshakePromise = this._createHandshakePromise()+ }++ return this._handshakePromise+ }++ _handleHandshakeAck(message) {+ if (this._handshakeRetryTimer) {+ clearInterval(this._handshakeRetryTimer)+ this._handshakeRetryTimer = null+ }++ if (message.success === false) {+ this._handshakePromise = null+ this._handshakeResolve = null+ if (this._handshakeReject) {+ this._handshakeReject(new Error('SDK handshake rejected'))+ this._handshakeReject = null+ }+ return+ }++ this._handshakeComplete = true++ if (this._handshakeResolve) {+ this._handshakeResolve()+ this._handshakeResolve = null+ this._handshakeReject = null+ }+ }+_sendCommand(command, payload = {}) {if (!this.iframe || !this.iframe.contentWindow) {console.warn('[OpnForm SDK] Cannot send command - iframe not available')return Promise.reject(new Error('Iframe not available'))}- const requestId = ++this._requestId- const message = {- type: MSG_PREFIX + 'command',- command: command,- formSlug: this.slug,- requestId: requestId,- payload: payload- }+ return this._ensureHandshake().then(() => {+ const requestId = ++this._requestId+ const message = {+ type: MSG_PREFIX + 'command',+ command: command,+ formSlug: this.slug,+ requestId: requestId,+ payload: payload,+ _sdkToken: this._sdkToken,+ }- return new Promise((resolve, reject) => {- this._pendingRequests[requestId] = { resolve, reject }- setTimeout(() => {- if (this._pendingRequests[requestId]) {- delete this._pendingRequests[requestId]- reject(new Error('Command timeout'))- }- }, 5000)- this.iframe.contentWindow.postMessage(message, this._targetOrigin)+ return new Promise((resolve, reject) => {+ this._pendingRequests[requestId] = { resolve, reject }+ setTimeout(() => {+ if (this._pendingRequests[requestId]) {+ delete this._pendingRequests[requestId]+ reject(new Error('Command timeout'))+ }+ }, 5000)+ this.iframe.contentWindow.postMessage(message, this._targetOrigin)+ })})}@@ -312,14 +425,16 @@})}- _registerForm(iframe, slug) {- const instance = new FormInstance(iframe, slug, this)+ _registerForm(iframe, slug, sdkToken = null) {+ const instance = new FormInstance(iframe, slug, this, sdkToken)this._forms[slug] = instanceif (iframe.id && iframe.id !== slug) {this._forms[iframe.id] = instance}+ instance._startHandshake()+// Auto-initialize resize if enabledif (this._options.autoResize !== false) {// Wait for iframe to be ready@@ -356,6 +471,8 @@this._handleEvent(data, form)} else if (messageType === 'response') {this._handleResponse(data, form)+ } else if (messageType === 'handshake-ack') {+ form._handleHandshakeAck(data)}}}@@ -475,14 +592,20 @@iframe.style.height = height === 'auto' ? '600px' : heightlet url = `/forms/${slug}`+ const sdkToken = generateSdkToken()+ const query = new URLSearchParams({+ _sdkToken: sdkToken,+ _sdkParentOrigin: window.location.origin,+ })if (darkMode !== undefined) {- url += `?darkMode=${darkMode}`+ query.set('darkMode', String(darkMode))}+ url += `?${query.toString()}`iframe.src = urlcontainerEl.appendChild(iframe)- const form = this._registerForm(iframe, slug)+ const form = this._registerForm(iframe, slug, sdkToken)if (onSubmit) {form.on(EVENTS.SUBMIT, onSubmit)diff --git a/client/test/unit/opnform-sdk-postmessage.test.ts b/client/test/unit/opnform-sdk-postmessage.test.tsindex bc9244c7c..376d51947 100644--- a/client/test/unit/opnform-sdk-postmessage.test.ts+++ b/client/test/unit/opnform-sdk-postmessage.test.ts@@ -5,6 +5,46 @@ import { JSDOM } from 'jsdom'const sdkSource = readFileSync(resolve(__dirname, '../../public/widgets/opnform-sdk.js'), 'utf8')+function getIframeOrigin(window: Window, iframe: HTMLIFrameElement) {+ return new URL(iframe.src, window.location.href).origin+}++function mockIframePostMessage(window: Window, iframe: HTMLIFrameElement) {+ const iframeOrigin = getIframeOrigin(window, iframe)++ vi.spyOn(iframe.contentWindow!, 'postMessage').mockImplementation((message: {+ type?: string+ formSlug?: string+ requestId?: number+ }) => {+ if (message?.type === 'opnform:command') {+ window.dispatchEvent(new window.MessageEvent('message', {+ data: {+ type: 'opnform:response',+ formSlug: message.formSlug,+ requestId: message.requestId,+ success: true,+ data: { success: true },+ },+ origin: iframeOrigin,+ source: iframe.contentWindow,+ }))+ }+ })+}++function simulateHandshakeAck(window: Window, iframe: HTMLIFrameElement, formSlug = 'demo') {+ window.dispatchEvent(new window.MessageEvent('message', {+ data: {+ type: 'opnform:handshake-ack',+ formSlug,+ success: true,+ },+ origin: getIframeOrigin(window, iframe),+ source: iframe.contentWindow,+ }))+}+function createSdkWindow() {const dom = new JSDOM('<!doctype html><html><body><iframe id="demo" src="https://forms.example.test/forms/demo"></iframe></body></html>',@@ -17,9 +57,10 @@ function createSdkWindow() {dom.window.eval(sdkSource)const iframe = dom.window.document.getElementById('demo') as HTMLIFrameElement- vi.spyOn(iframe.contentWindow!, 'postMessage').mockImplementation(() => {})+ mockIframePostMessage(dom.window, iframe)dom.window.opnform._forms = {}dom.window.opnform.init({ autoResize: false, preventRedirect: true })+ simulateHandshakeAck(dom.window, iframe)return { window: dom.window, iframe }}@@ -67,19 +108,136 @@ describe('OpnForm public SDK postMessage security', () => {expect(form.getData()).toEqual({ trusted: true })})- it('sends commands to the iframe origin instead of a wildcard target', () => {+ it('sends commands to the iframe origin instead of a wildcard target', async () => {const { window, iframe } = createSdkWindow()const form = window.opnform.get('demo')- form.setField('email', '[email protected]')+ await form.setField('email', '[email protected]')expect(iframe.contentWindow!.postMessage).toHaveBeenCalledWith(expect.objectContaining({type: 'opnform:command',command: 'setField',formSlug: 'demo',+ _sdkToken: expect.any(String),}),'https://forms.example.test',)})++ it('sends a handshake when discovering an existing iframe', () => {+ const dom = new JSDOM(+ '<!doctype html><html><body><iframe id="demo" src="https://forms.example.test/forms/demo"></iframe></body></html>',+ {+ url: 'https://embedder.example.test/',+ runScripts: 'outside-only',+ },+ )++ dom.window.eval(sdkSource)+ const iframe = dom.window.document.getElementById('demo') as HTMLIFrameElement++ vi.spyOn(iframe.contentWindow!, 'postMessage').mockImplementation(() => {})+ dom.window.opnform._forms = {}+ dom.window.opnform.init({ autoResize: false, preventRedirect: true })++ expect(iframe.contentWindow!.postMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ type: 'opnform:handshake',+ formSlug: 'demo',+ _sdkToken: expect.any(String),+ parentOrigin: 'https://embedder.example.test',+ }),+ 'https://forms.example.test',+ )+ })++ it('does not create an unhandled rejection when passive handshake times out', async () => {+ vi.useFakeTimers()++ try {+ const dom = new JSDOM(+ '<!doctype html><html><body><iframe id="demo" src="https://forms.example.test/forms/demo"></iframe></body></html>',+ {+ url: 'https://embedder.example.test/',+ runScripts: 'outside-only',+ },+ )++ dom.window.eval(sdkSource)+ const iframe = dom.window.document.getElementById('demo') as HTMLIFrameElement++ vi.spyOn(iframe.contentWindow!, 'postMessage').mockImplementation(() => {})+ dom.window.opnform._forms = {}+ dom.window.opnform.init({ autoResize: false, preventRedirect: true })++ await vi.advanceTimersByTimeAsync(3000)++ expect(iframe.contentWindow!.postMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ type: 'opnform:handshake',+ formSlug: 'demo',+ }),+ 'https://forms.example.test',+ )+ } finally {+ vi.useRealTimers()+ }+ })++ it('includes the SDK token when creating a form iframe', async () => {+ const dom = new JSDOM('<!doctype html><html><body><div id="container"></div></body></html>', {+ url: 'https://embedder.example.test/',+ runScripts: 'outside-only',+ })++ dom.window.eval(sdkSource)+ dom.window.opnform.init({ autoResize: false })++ const form = dom.window.opnform.create('demo', { container: '#container' })+ const iframe = dom.window.document.querySelector('iframe') as HTMLIFrameElement++ expect(iframe.src).toContain('_sdkToken=')+ expect(iframe.src).toContain('_sdkParentOrigin=')++ mockIframePostMessage(dom.window, iframe)+ simulateHandshakeAck(dom.window, iframe)+ await form.setField('email', '[email protected]')++ expect(iframe.contentWindow!.postMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ type: 'opnform:command',+ _sdkToken: expect.any(String),+ }),+ 'https://embedder.example.test',+ )+ })++ it('rejects commands when handshake times out without ack', async () => {+ vi.useFakeTimers()++ const dom = new JSDOM(+ '<!doctype html><html><body><iframe id="demo" src="https://forms.example.test/forms/demo"></iframe></body></html>',+ {+ url: 'https://embedder.example.test/',+ runScripts: 'outside-only',+ },+ )++ dom.window.eval(sdkSource)+ const iframe = dom.window.document.getElementById('demo') as HTMLIFrameElement++ vi.spyOn(iframe.contentWindow!, 'postMessage').mockImplementation(() => {})+ dom.window.opnform._forms = {}+ dom.window.opnform.init({ autoResize: false, preventRedirect: true })++ const form = dom.window.opnform.get('demo')+ const commandPromise = form.setField('email', '[email protected]')+ const assertion = expect(commandPromise).rejects.toThrow('SDK handshake timeout')++ await vi.advanceTimersByTimeAsync(3000)+ await assertion++ vi.useRealTimers()+ })})diff --git a/client/test/unit/use-sdk-bridge-postmessage.test.ts b/client/test/unit/use-sdk-bridge-postmessage.test.tsnew file mode 100644index 000000000..8b0131db2--- /dev/null+++ b/client/test/unit/use-sdk-bridge-postmessage.test.ts@@ -0,0 +1,219 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { JSDOM } from 'jsdom'+import {+ MSG_PREFIX,+ createSdkBridgeMessageHandler,+ readSdkTokenFromUrl,+ resolveInitialTrustedOrigin,+} from '../../lib/sdk/sdkBridgeMessaging.js'++const FORM_SLUG = 'demo'+const PARENT_ORIGIN = 'https://embedder.example.test'+const FORM_ORIGIN = 'https://forms.example.test'++function installIframeWindow(dom: JSDOM, search = '') {+ const { window } = dom+ const mockParent = {+ postMessage: vi.fn(),+ }++ Object.defineProperty(window, 'parent', {+ configurable: true,+ value: mockParent,+ })++ return { window, mockParent }+}++function createBridgeHarness(dom: JSDOM, options: {+ initialSdkToken?: string | null+ initialTrustedOrigin?: string | null+ onCommand?: ReturnType<typeof vi.fn>+} = {}) {+ const { window, mockParent } = installIframeWindow(dom)+ const parentMessages: Array<{ message: unknown, origin: string }> = []+ const onCommand = options.onCommand || vi.fn()++ mockParent.postMessage.mockImplementation((message: unknown, origin: string) => {+ parentMessages.push({ message, origin })+ })++ const bridge = createSdkBridgeMessageHandler({+ isIframe: true,+ getFormSlug: () => FORM_SLUG,+ initialSdkToken: options.initialSdkToken ?? null,+ initialTrustedOrigin: options.initialTrustedOrigin ?? null,+ postToParent: (message, origin) => {+ mockParent.postMessage(message, origin)+ },+ onCommand,+ })++ function dispatchMessage(data: Record<string, unknown>, overrides: {+ origin?: string+ source?: Window | { postMessage: ReturnType<typeof vi.fn> }+ } = {}) {+ bridge.onMessage(new window.MessageEvent('message', {+ data,+ origin: overrides.origin ?? PARENT_ORIGIN,+ source: (overrides.source ?? mockParent) as MessageEventSource,+ }))+ }++ return { window, mockParent, bridge, onCommand, parentMessages, dispatchMessage }+}++describe('SDK bridge messaging security', () => {+ let dom: JSDOM++ beforeEach(() => {+ dom = new JSDOM('<!doctype html><html><body></body></html>', {+ url: `${FORM_ORIGIN}/forms/${FORM_SLUG}`,+ })+ vi.stubGlobal('window', dom.window)+ vi.stubGlobal('document', dom.window.document)+ })++ afterEach(() => {+ vi.restoreAllMocks()+ })++ it('accepts handshake, locks origin, and sends handshake-ack', () => {+ const { bridge, parentMessages, dispatchMessage } = createBridgeHarness(dom)++ dispatchMessage({+ type: `${MSG_PREFIX}handshake`,+ formSlug: FORM_SLUG,+ _sdkToken: 'bridge-token',+ parentOrigin: PARENT_ORIGIN,+ })++ expect(bridge.getSdkToken()).toBe('bridge-token')+ expect(bridge.getTrustedOrigin()).toBe(PARENT_ORIGIN)+ expect(parentMessages).toContainEqual({+ message: {+ type: `${MSG_PREFIX}handshake-ack`,+ formSlug: FORM_SLUG,+ success: true,+ },+ origin: PARENT_ORIGIN,+ })+ })++ it('rejects handshake when parentOrigin does not match event origin', () => {+ const { bridge, parentMessages, dispatchMessage } = createBridgeHarness(dom)++ dispatchMessage({+ type: `${MSG_PREFIX}handshake`,+ formSlug: FORM_SLUG,+ _sdkToken: 'bridge-token',+ parentOrigin: 'https://attacker.example.test',+ })++ expect(bridge.getSdkToken()).toBeNull()+ expect(parentMessages).toHaveLength(0)+ })++ it('rejects commands without a registered SDK token', () => {+ const { onCommand, parentMessages, dispatchMessage } = createBridgeHarness(dom)++ dispatchMessage({+ type: `${MSG_PREFIX}command`,+ command: 'setField',+ formSlug: FORM_SLUG,+ requestId: 1,+ payload: { fieldId: 'email', value: '[email protected]' },+ _sdkToken: 'wrong-token',+ })++ expect(onCommand).not.toHaveBeenCalled()+ expect(parentMessages).toContainEqual({+ message: expect.objectContaining({+ type: `${MSG_PREFIX}response`,+ success: false,+ error: 'Invalid SDK token',+ requestId: 1,+ }),+ origin: PARENT_ORIGIN,+ })+ })++ it('rejects commands when token does not match the registered token', () => {+ const { onCommand, parentMessages, dispatchMessage } = createBridgeHarness(dom, {+ initialSdkToken: 'registered-token',+ initialTrustedOrigin: PARENT_ORIGIN,+ })++ dispatchMessage({+ type: `${MSG_PREFIX}command`,+ command: 'setField',+ formSlug: FORM_SLUG,+ requestId: 2,+ payload: { fieldId: 'email', value: '[email protected]' },+ _sdkToken: 'wrong-token',+ })++ expect(onCommand).not.toHaveBeenCalled()+ expect(parentMessages).toContainEqual({+ message: expect.objectContaining({+ success: false,+ error: 'Invalid SDK token',+ }),+ origin: PARENT_ORIGIN,+ })+ })++ it('rejects commands from an unexpected parent origin after origin lock', () => {+ const { onCommand, dispatchMessage } = createBridgeHarness(dom, {+ initialSdkToken: 'registered-token',+ initialTrustedOrigin: PARENT_ORIGIN,+ })++ dispatchMessage({+ type: `${MSG_PREFIX}command`,+ command: 'setField',+ formSlug: FORM_SLUG,+ requestId: 3,+ payload: { fieldId: 'email', value: '[email protected]' },+ _sdkToken: 'registered-token',+ }, {+ origin: 'https://attacker.example.test',+ })++ expect(onCommand).not.toHaveBeenCalled()+ })++ it('accepts commands after handshake with matching token', () => {+ const { onCommand, dispatchMessage } = createBridgeHarness(dom)++ dispatchMessage({+ type: `${MSG_PREFIX}handshake`,+ formSlug: FORM_SLUG,+ _sdkToken: 'bridge-token',+ parentOrigin: PARENT_ORIGIN,+ })++ dispatchMessage({+ type: `${MSG_PREFIX}command`,+ command: 'setField',+ formSlug: FORM_SLUG,+ requestId: 4,+ payload: { fieldId: 'email', value: '[email protected]' },+ _sdkToken: 'bridge-token',+ })++ expect(onCommand).toHaveBeenCalledTimes(1)+ })++ it('reads SDK token and parent origin from iframe URL params', () => {+ const urlDom = new JSDOM('<!doctype html><html><body></body></html>', {+ url: `${FORM_ORIGIN}/forms/${FORM_SLUG}?_sdkToken=url-token&_sdkParentOrigin=${encodeURIComponent(PARENT_ORIGIN)}`,+ })++ vi.stubGlobal('window', urlDom.window)+ vi.stubGlobal('document', urlDom.window.document)++ expect(readSdkTokenFromUrl()).toBe('url-token')+ expect(resolveInitialTrustedOrigin(true)).toBe(PARENT_ORIGIN)+ })+})