紀錄工作經驗、相關知識,解決技術相關問題。

Javascript, 資訊相關

Window.postMessage 跨來源通訊資安地雷:來源驗證與 targetOrigin 避坑要點

Window.postMessage 跨來源通訊資安地雷:來源驗證與 targetOrigin 避坑要點 特色圖片

在瀏覽器同源政策的嚴密保護下,兩個不同來源的視窗(例如主站與其內嵌的第三方金流或驗證 iframe)預設無法互相讀取對方的 DOM 與變數。要在不同來源的視窗之間交換資料,HTML 標準提供了 Window.postMessage() API(WHATWG 規範中的 Cross-document messaging)。

一、 postMessage 的基本工作流程

跨視窗通訊必須包含兩個角色:發送方 (Sender) 與 監聽接收方 (Receiver)。

1.1 發送訊息 (Sending Message)

// 獲取內嵌 iframe 的 window 參考
const iframeWindow = document.getElementById('payment-frame').contentWindow;

// ❌ 極度危險:使用萬用字元 '*' 作為 targetOrigin,若該視窗已被導向其他網站,資料會照樣送給對方!
// iframeWindow.postMessage({ token: 'secret-123' }, '*');

// 🟢 安全實務:嚴格指定目標接收者的合法網域
iframeWindow.postMessage(
  { action: 'PAY_SUBMIT', amount: 1500 },
  'https://trusted-payment-gateway.com'
);

targetOrigin 與接收視窗當下文件的來源不符時,瀏覽器會直接丟棄這則訊息,發送端不會收到任何例外;只有 '*' 會略過這項比對。


二、 結構化物件傳遞與 Structured Clone Algorithm 注意事項

當開發者透過 postMessage 傳遞複雜的結構化物件(如巢狀 Object、Array、Map、Set 等)時,資料並非透過簡單的字串化(如 JSON.stringify)處理,而是由瀏覽器底層的 Structured Clone Algorithm 進行深拷貝(Deep Clone)。

2.1 Structured Clone Algorithm 核心優勢與傳遞限制

Structured Clone 相比傳統 JSON 序列化的一大突破在於:它支援循環引用(Circular References)、RegExp、Blob、File、ArrayBuffer 等特殊型別。然而,它在實際生產環境中仍有嚴格的限制與效能盲點:

  1. 不支援函式 (Functions):無法傳遞 Function 或 Method,若物件中包含函式會直接拋出 DataCloneError 例外錯誤。
  2. 原型鏈遺失 (Prototype Loss):被序列化並傳遞的物件在抵達接收端後,其原型鏈(Prototype Chain)會消失,變為純粹的普通物件(Plain Object),原先綁定的類別方法或原型屬性將無法使用。
  3. 效能消耗 (Performance Overhead):當傳遞體積龐大的大型陣列或二進位資料(如 ArrayBuffer)時,深拷貝會佔用大量記憶體與 CPU 運算資源。建議搭配 Transferable Objects(如傳遞 ArrayBuffer 的同時轉移所有權)來優化效能。

2.2 結構化物件傳遞範例與防錯寫法

// 🟢 發送包含 ArrayBuffer 的高效能資料傳遞
const buffer = new ArrayBuffer(1024 * 1024); // 1MB 記憶體緩衝區
iframeWindow.postMessage(
  { type: 'TRANSFER_DATA', payload: buffer },
  'https://trusted-payment-gateway.com',
  [buffer] // 透過 Transferable Objects 轉移擁有權,避免記憶體雙重拷貝
);
console.log(buffer.byteLength); // 0:擁有權已轉移,發送端不能再使用這個 buffer
Structured Clone 傳遞結果:含函式的物件拋出 DataCloneError、class 實例在接收端變成原型為 Object.prototype 的普通物件、循環引用與 Map/Set/RegExp/Date 都能傳遞,轉移後的 ArrayBuffer 在發送端 byteLength 變成 0

主站(http://127.0.0.1:4321)對金流 iframe(http://localhost:4322)傳送各種資料的結果,Headless Chrome 156、Windows 11 執行畫面。


三、 接收方驗證:不可妥協的資安三部曲

接收方在收到 message 事件時,必須第一時間驗證來源網域:

window.addEventListener('message', (event) => {
  // 1. 嚴格比對來源網域 (Origin Verification)
  if (event.origin !== 'https://trusted-payment-gateway.com') {
    console.warn('拒絕未授權來源的 postMessage 請求:', event.origin);
    return; // 立即阻斷!
  }

  // 2. 驗證資料型別與結構 (Data Validation)
  const data = event.data;
  if (!data || data.type !== 'PAYMENT_SUCCESS') {
    return;
  }

  // 3. 處理合法業務邏輯
  console.log('金流授權成功,交易編號:', data.transactionId);
});
targetOrigin 與 event.origin 驗證結果:targetOrigin 相符時 iframe 收到訊息、不符時 iframe 沒收到且發送端無例外、設為星號時照樣送達;金流 iframe 回傳的成功訊息被接受,其他來源 iframe 冒充的成功訊息因 event.origin 不符被拒絕

主站嵌入金流 iframe(http://localhost:4322)與另一個來源的 iframe(http://127.0.0.1:4323),套用上方接收端程式碼的結果,Headless Chrome 156、Windows 11 執行畫面。


總結

  1. 發送時指定具體網域:已知接收方的來源時,不要將 targetOrigin 設為 *,含機密資料的訊息更不能用。
  2. 接收時必查 origin:永遠不要跳過 event.origin 驗證。
  3. 留意物件序列化限制:傳遞結構化物件時注意 Structured Clone Algorithm 不支援函式且會遺失原型鏈。
  4. 防範 DOM 注入:收到的數據在寫入畫面時,切勿直接丟給 innerHTML,改用 textContent。

參考資料與延伸閱讀

發佈留言