fix: CSP nonce 导致动态 style 全丢(插件样式失效)v3.26.9 / promptlib 1.4.5
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 2m52s

This commit is contained in:
qiqi committed 2026-11-21 22:43:41 +08:00
1 parent a3edc81f55
commit 5f8f4d229f
22 files changed
+135 -43

No files matched your search

+4 -1
View File
@@ -62,8 +62,11 @@
if (styleNodes[id] && styleNodes[id].parentNode) styleNodes[id].parentNode.removeChild(styleNodes[id])
const node = doc.createElement('style')
node.setAttribute('data-plugin', String(id))
// v3.26.8:CSP 带 nonce 时,没有 nonce 的内联 <style> 会被整段丢弃(实测 sheet=null)
try { const n0 = doc.querySelector('style[nonce], link[nonce]'); const nv = n0 ? String((/** @type {any} */ (n0)).nonce || n0.getAttribute('nonce') || '') : ''; if (nv) node.setAttribute('nonce', nv) } catch (e) { /* ignore */ }
node.textContent = String(css)
doc.head.appendChild(node)
// v3.26.7:WKWebView 里动态插入 <head> 的 <style> 可能不生效(sheet=null),统一挂到 body
;(doc.body || doc.head).appendChild(node)
styleNodes[id] = node
} catch (e) { /* 样式失败不影响脚本 */ }
}
+32
View File
@@ -0,0 +1,32 @@
/* runtime-style-nonce.js —— 动态 <style> 的 nonce 兜底(v3.26.9)
*
* 背景:桌面端 CSP 带 nonce;CSP3 下 unsafe-inline 被忽略 ⇒ 没有 nonce 的动态 <style> 会被整段丢弃
*(style.sheet === null)。宿主和插件都用 createElement('style') 注入样式,于是插件样式全丢。
* 这里统一给后来插入的 <style> 补上页面已有的 nonce,并重挂一次让浏览器重新解析。
*/
;(function (global) {
'use strict'
function install () {
try {
const doc = global.document
if (!doc || global.IWB_STYLE_NONCE_DONE) return
global.IWB_STYLE_NONCE_DONE = true
const srcNonce = () => {
try { const n = doc.querySelector('style[nonce], link[nonce]'); return n ? String(n.getAttribute('nonce') || '') : '' } catch (e) { return '' }
}
const fixStyle = (node) => {
try {
if (!node || node.nodeType !== 1 || node.tagName !== 'STYLE') return
if (node.getAttribute('nonce')) return
const nonce = srcNonce()
if (!nonce) return
node.setAttribute('nonce', nonce)
if (node.parentNode) { const p = node.parentNode; p.removeChild(node); p.appendChild(node) }
} catch (e) { /* ignore */ }
}
const mo = new global.MutationObserver((muts) => { for (const m of muts) for (const n of m.addedNodes) fixStyle(n) })
mo.observe(doc.documentElement, { childList: true, subtree: true })
} catch (e) { /* ignore */ }
}
global.IWBRuntimeStyleNonce = { install: install }
})(typeof window !== 'undefined' ? window : globalThis)