145 lines
5.8 KiB
TypeScript
145 lines
5.8 KiB
TypeScript
import React, { useEffect, useRef, useState } from 'react'
|
|
import { getPluginMessageBundle, localeDir, parseAppError, t } from '../i18n'
|
|
import { Locale, PanelContribution } from '../types'
|
|
import { Button } from '../ui/controls'
|
|
import { api } from '../wails'
|
|
import { locText } from './SchemaForm'
|
|
|
|
interface Props {
|
|
locale: Locale
|
|
panel: PanelContribution
|
|
assetToken: string
|
|
appearance: 'light' | 'dark'
|
|
}
|
|
|
|
/**
|
|
* Sandboxed L4 iframe panel with strict bridge verification (§4.2, §7.3):
|
|
* - `sandbox="allow-scripts"` (no allow-same-origin, no top-navigation)
|
|
* - Only responds to postMessage where `event.source === iframe.contentWindow`
|
|
* - Routes all Host API calls through Go `PanelBridgeCall` for permission & rate checks
|
|
* - Syncs theme tokens into iframe and provides error placeholder + retry.
|
|
*/
|
|
const RE_SAFE_TOKEN = /^[a-f0-9]+$/
|
|
const RE_SAFE_PLUGIN_ID = /^[a-z0-9][a-z0-9._-]*$/
|
|
const RE_SAFE_ENTRY_SEG = /^[a-zA-Z0-9._@ -]+$/
|
|
|
|
function buildSafePanelSrc(assetToken: string, pluginId: string | undefined, entry: string | undefined): string | null {
|
|
if (!assetToken || !RE_SAFE_TOKEN.test(assetToken)) return null
|
|
if (!pluginId || !RE_SAFE_PLUGIN_ID.test(pluginId) || pluginId.includes('..')) return null
|
|
const raw = (entry || 'index.html').trim().replace(/^\/+/, '')
|
|
if (!raw || raw.includes('\\') || raw.includes('?') || raw.includes('#') || /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(raw)) {
|
|
return null
|
|
}
|
|
const segs = raw.split('/')
|
|
for (const seg of segs) {
|
|
if (!seg || seg === '.' || seg === '..' || !RE_SAFE_ENTRY_SEG.test(seg)) return null
|
|
}
|
|
return `/plugin-assets/${encodeURIComponent(assetToken)}/${encodeURIComponent(pluginId)}/${segs.map(encodeURIComponent).join('/')}`
|
|
}
|
|
|
|
export const PluginPanelFrame: React.FC<Props> = ({ locale, panel, assetToken, appearance }) => {
|
|
const iframeRef = useRef<HTMLIFrameElement>(null)
|
|
const localeRef = useRef<Locale>(locale)
|
|
localeRef.current = locale
|
|
const [failed, setFailed] = useState(false)
|
|
const [nonce, setNonce] = useState(0)
|
|
|
|
const src = buildSafePanelSrc(assetToken, panel.pluginId, panel.entry)
|
|
|
|
const syncTheme = () => {
|
|
const win = iframeRef.current?.contentWindow
|
|
if (!win) return
|
|
const cs = getComputedStyle(document.documentElement)
|
|
const tokens: Record<string, string> = {}
|
|
for (const k of ['--surface-0', '--surface-1', '--text', '--text-2', '--border', '--accent', '--font-sans']) {
|
|
tokens[k] = cs.getPropertyValue(k).trim()
|
|
}
|
|
const dir = localeDir(locale)
|
|
const messages = getPluginMessageBundle(panel.pluginId ?? '', locale)
|
|
// bridgeApi 1.0 events (bridgeContract.ts).
|
|
win.postMessage({ type: 'reims:event', event: 'theme.changed', data: { appearance, tokens } }, '*')
|
|
win.postMessage({ type: 'reims:event', event: 'locale.changed', data: { locale, dir, messages } }, '*')
|
|
// Pre-1.0 message types, kept for panels written before the bridge contract.
|
|
win.postMessage({ type: 'reims:theme', appearance, locale, dir, tokens, messages }, '*')
|
|
win.postMessage({ type: 'reims:i18n', locale, dir, messages }, '*')
|
|
}
|
|
|
|
useEffect(() => {
|
|
syncTheme()
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [appearance, locale])
|
|
|
|
useEffect(() => {
|
|
if (!src) return
|
|
let cancelled = false
|
|
|
|
const onMessage = async (e: MessageEvent) => {
|
|
const win = iframeRef.current?.contentWindow
|
|
// Strict origin + window identity check for sandbox="allow-scripts" opaque origin (§7.3).
|
|
if (!win || e.source !== win || e.origin !== 'null') return
|
|
const msg = e.data
|
|
if (!msg || typeof msg !== 'object' || msg.type !== 'reims:rpc' || typeof msg.id !== 'string' || typeof msg.method !== 'string') return
|
|
const rawParams = msg.params
|
|
const params: Record<string, unknown> =
|
|
rawParams && typeof rawParams === 'object' && !Array.isArray(rawParams)
|
|
? (rawParams as Record<string, unknown>)
|
|
: {}
|
|
try {
|
|
if (msg.method === 'i18n.getBundle') {
|
|
const curLocale = localeRef.current
|
|
const bundle = {
|
|
locale: curLocale,
|
|
dir: localeDir(curLocale),
|
|
messages: getPluginMessageBundle(panel.pluginId ?? '', curLocale),
|
|
}
|
|
win.postMessage({ type: 'reims:rpc-result', id: msg.id, ok: true, result: bundle }, '*')
|
|
return
|
|
}
|
|
const result = await api.PanelBridgeCall(panel.pluginId ?? '', msg.method, params)
|
|
if (cancelled || iframeRef.current?.contentWindow !== win) return
|
|
win.postMessage({ type: 'reims:rpc-result', id: msg.id, ok: true, result }, '*')
|
|
} catch (err) {
|
|
if (cancelled || iframeRef.current?.contentWindow !== win) return
|
|
win.postMessage({ type: 'reims:rpc-result', id: msg.id, ok: false, error: parseAppError(err).summary || 'RPC failed' }, '*')
|
|
}
|
|
}
|
|
|
|
window.addEventListener('message', onMessage)
|
|
return () => {
|
|
cancelled = true
|
|
window.removeEventListener('message', onMessage)
|
|
}
|
|
}, [panel.pluginId, nonce, src])
|
|
|
|
if (failed || !src) {
|
|
return (
|
|
<div className="plugin-panel-error">
|
|
<span>{t(locale, 'panelLoadFailed')}</span>
|
|
{src && (
|
|
<Button onClick={() => { setFailed(false); setNonce((n) => n + 1) }}>
|
|
{t(locale, 'installersRetry')}
|
|
</Button>
|
|
)}
|
|
</div>
|
|
)
|
|
}
|
|
|
|
return (
|
|
<div className="plugin-panel-wrap rg-p-plugin-view" data-plugin={panel.pluginId}>
|
|
<div className="plugin-panel-head">{locText(panel.title, locale, panel.id)}</div>
|
|
<iframe
|
|
key={nonce}
|
|
ref={iframeRef}
|
|
className="plugin-panel-frame"
|
|
title={locText(panel.title, locale, panel.id)}
|
|
src={src}
|
|
sandbox="allow-scripts"
|
|
referrerPolicy="no-referrer"
|
|
style={{ height: Math.max(120, Math.min(480, panel.height || 220)) }}
|
|
onLoad={syncTheme}
|
|
onError={() => setFailed(true)}
|
|
/>
|
|
</div>
|
|
)
|
|
}
|