Merge PR #98: fix(plugin): unify market compatibility, persist external themes, and harden ui:script approval
fix(plugin): unify market compatibility, persist external themes, and harden ui:script approval
This commit is contained in:
30 files changed
+1925
-279
No files matched your search
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "fixes",
|
||||
"order": 0,
|
||||
"authors": ["Dnyo666"],
|
||||
"zh": "修复插件市场平台与引擎兼容校验不一致、外部主题在重启或升级后丢失、安全模式或 CLI 停用无关插件误清空当前主题,以及隐藏对话框阻断快捷键和审批弹窗在小窗口被裁切的问题。 [#93](https://github.com/Nwflower/Reims-Go/issues/93)",
|
||||
"en": "Fix mismatched plugin market platform and engine compatibility checks, external theme loss across restarts and upgrades, unrelated safe-mode or CLI disables clearing the active theme, hidden dialogs blocking shortcuts, and approval modal list clipping on compact windows. [#93](https://github.com/Nwflower/Reims-Go/issues/93)"
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "security",
|
||||
"order": 0,
|
||||
"authors": ["Dnyo666"],
|
||||
"zh": "为 `ui:script` 交互主题补齐脚本 SHA-256 哈希锚定与高危审批详情(从 `v0.2.11` 升级后已启用的 `ui:script` 主题首次启动需重新确认一次),并为插件市场下载加固直连防 HTTPS 降级、体积硬上限、慢流超时、版本路径校验及陈旧缓存信任降级一致性。 [#93](https://github.com/Nwflower/Reims-Go/issues/93)",
|
||||
"en": "Enforce script SHA-256 hash pinning and full high-risk approval disclosure for `ui:script` interactive themes (existing `v0.2.11` `ui:script` themes require one-time re-approval on first startup), and harden plugin market downloads with direct HTTPS-only redirects, hard size caps, stall timeouts, version path validation, and stale-cache trust parity. [#93](https://github.com/Nwflower/Reims-Go/issues/93)"
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"test": "node --test --test-concurrency=2 scripts/test-i18n.mjs scripts/test-keymap.mjs scripts/test-tasks.mjs scripts/test-macos-boundary.mjs scripts/test-no-empty-catch.mjs",
|
||||
"test": "node --test --test-concurrency=2 scripts/test-i18n.mjs scripts/test-keymap.mjs scripts/test-plugins.mjs scripts/test-tasks.mjs scripts/test-macos-boundary.mjs scripts/test-no-empty-catch.mjs",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"bundle": "vite build && node scripts/check-ui-contract.mjs",
|
||||
"build": "tsc --noEmit && pnpm run bundle",
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import test from 'node:test'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { loadTestModule } from './load-test-module.mjs'
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
||||
const appCSSPath = path.resolve(__dirname, '../src/styles/app.css')
|
||||
|
||||
const { hasVisibleDialog, isDialogElementVisible } = await loadTestModule(`export * from './lib/dialogState'`)
|
||||
const { resolvePluginApprovalNotice } = await loadTestModule(`export { resolvePluginApprovalNotice } from './components/PluginParts'`)
|
||||
|
||||
function fakeDialog({
|
||||
display = 'block',
|
||||
visibility = 'visible',
|
||||
ariaHidden = null,
|
||||
hidden = false,
|
||||
inert = false,
|
||||
dataState = null,
|
||||
parentElement = null,
|
||||
} = {}) {
|
||||
const el = {
|
||||
parentElement,
|
||||
getAttribute(name) {
|
||||
if (name === 'aria-hidden') return ariaHidden
|
||||
if (name === 'hidden') return hidden ? '' : null
|
||||
if (name === 'inert') return inert ? '' : null
|
||||
if (name === 'data-state') return dataState
|
||||
return null
|
||||
},
|
||||
closest() {
|
||||
return null
|
||||
},
|
||||
}
|
||||
return { el, style: { display, visibility } }
|
||||
}
|
||||
|
||||
test('hidden dialog elements (including ancestor display:none, inert, and closed state) do not block shortcuts', () => {
|
||||
const hiddenDisplay = fakeDialog({ display: 'none' })
|
||||
const hiddenVis = fakeDialog({ visibility: 'hidden' })
|
||||
const hiddenCollapse = fakeDialog({ visibility: 'collapse' })
|
||||
const hiddenAttr = fakeDialog({ hidden: true })
|
||||
const hiddenInert = fakeDialog({ inert: true })
|
||||
const hiddenAria = fakeDialog({ ariaHidden: 'true' })
|
||||
const closedState = fakeDialog({ dataState: 'closed' })
|
||||
const hiddenParent = fakeDialog({ display: 'none' })
|
||||
const childOfHiddenParent = fakeDialog({ parentElement: hiddenParent.el })
|
||||
const visibleParent = fakeDialog({ display: 'block' })
|
||||
const visible = fakeDialog({ parentElement: visibleParent.el })
|
||||
|
||||
const styles = new Map([
|
||||
[hiddenDisplay.el, hiddenDisplay.style],
|
||||
[hiddenVis.el, hiddenVis.style],
|
||||
[hiddenCollapse.el, hiddenCollapse.style],
|
||||
[hiddenAttr.el, hiddenAttr.style],
|
||||
[hiddenInert.el, hiddenInert.style],
|
||||
[hiddenAria.el, hiddenAria.style],
|
||||
[closedState.el, closedState.style],
|
||||
[hiddenParent.el, hiddenParent.style],
|
||||
[childOfHiddenParent.el, childOfHiddenParent.style],
|
||||
[visibleParent.el, visibleParent.style],
|
||||
[visible.el, visible.style],
|
||||
])
|
||||
const getStyle = (node) => styles.get(node) ?? { display: 'block', visibility: 'visible' }
|
||||
|
||||
for (const hiddenCase of [
|
||||
hiddenDisplay,
|
||||
hiddenVis,
|
||||
hiddenCollapse,
|
||||
hiddenAttr,
|
||||
hiddenInert,
|
||||
hiddenAria,
|
||||
closedState,
|
||||
childOfHiddenParent,
|
||||
]) {
|
||||
assert.equal(isDialogElementVisible(hiddenCase.el, getStyle), false)
|
||||
}
|
||||
assert.equal(isDialogElementVisible(visible.el, getStyle), true)
|
||||
|
||||
assert.equal(
|
||||
hasVisibleDialog(
|
||||
{ querySelectorAll: () => [hiddenDisplay.el, hiddenVis.el, childOfHiddenParent.el, closedState.el] },
|
||||
getStyle,
|
||||
),
|
||||
false,
|
||||
)
|
||||
assert.equal(
|
||||
hasVisibleDialog({ querySelectorAll: () => [childOfHiddenParent.el, visible.el] }, getStyle),
|
||||
true,
|
||||
)
|
||||
})
|
||||
|
||||
test('L1 ui:script plugins receive accurate, style-compliant warning instead of L3 sidecar copy', () => {
|
||||
const uiScriptPlugin = {
|
||||
tier: 'L1',
|
||||
permissions: [{ name: 'ui:script', level: 'high' }],
|
||||
}
|
||||
const zhNotice = resolvePluginApprovalNotice(uiScriptPlugin, null, 'zh-CN')
|
||||
const enNotice = resolvePluginApprovalNotice(uiScriptPlugin, null, 'en-US')
|
||||
assert.ok(zhNotice.includes('ui:script'), `expected ui:script zh notice, got: ${zhNotice}`)
|
||||
assert.ok(!zhNotice.includes('L3 Sidecar'), `L1 ui:script must not show L3 Sidecar warning: ${zhNotice}`)
|
||||
assert.ok(!zhNotice.includes('请'), `zh notice should follow design guidelines (no 请): ${zhNotice}`)
|
||||
assert.ok(enNotice.includes('ui:script'), `expected ui:script en notice, got: ${enNotice}`)
|
||||
assert.ok(!enNotice.includes('L3 Sidecar'), `L1 ui:script must not show L3 Sidecar warning: ${enNotice}`)
|
||||
assert.ok(!enNotice.endsWith('.'), `en notice should not end with a trailing period: ${enNotice}`)
|
||||
|
||||
const l3Plugin = { tier: 'L3', permissions: [{ name: 'driver:vm', level: 'high' }] }
|
||||
const l3Notice = resolvePluginApprovalNotice(l3Plugin, null, 'en-US')
|
||||
assert.ok(l3Notice.includes('L3 Sidecar'), `expected L3 Sidecar warning, got: ${l3Notice}`)
|
||||
|
||||
const plainTheme = { tier: 'L1', permissions: [] }
|
||||
assert.equal(resolvePluginApprovalNotice(plainTheme, null, 'en-US'), '')
|
||||
})
|
||||
|
||||
test('dialog body children and plugin scan lists disable flex shrinking so tall modals scroll instead of clipping', () => {
|
||||
const css = fs.readFileSync(appCSSPath, 'utf8')
|
||||
assert.match(css, /\.dialog-body\s*>\s*\*\s*\{[^}]*flex-shrink\s*:\s*0/)
|
||||
assert.match(css, /\.plugin-scan-section\s*>\s*\.list\s*\{[^}]*flex-shrink\s*:\s*0/)
|
||||
})
|
||||
@@ -18,6 +18,7 @@ import { LogLine, appendLog } from './lib/logs'
|
||||
import { macOSMajor } from './macos/macosRelease'
|
||||
import { currentTask, finishedTaskTTL, isActiveInstallerTask, pruneFinishedTasks, upsertTask } from './lib/tasks'
|
||||
import { applyActiveLocaleFonts, applyActiveTheme, disposeActiveThemeAndLocaleFonts, emitThemeEvent, notifyInteractiveThemeState, type UIStateSnapshot } from './lib/themeEngine'
|
||||
import { hasVisibleDialog } from './lib/dialogState'
|
||||
import { latestVMStatsWithDriver, refreshSubscribedVMStats, refreshVMStatsWithDriver } from './lib/vmStats'
|
||||
import { vmRefKey } from './lib/vmRef'
|
||||
import { ActiveThemePayload, AppState, AppUpdateInfo, CachedInstaller, CreateOpts, Locale, PluginUIContributions, Task, VMDetail } from './types'
|
||||
@@ -506,7 +507,7 @@ export const App: React.FC = () => {
|
||||
el.dataset.sidebarCollapsed = String(!sidebarOpen)
|
||||
el.dataset.safeMode = String(!!state?.safe_mode)
|
||||
notifyInteractiveThemeState(uiStateRef.current)
|
||||
}, [currentView, effectiveState, isBusyAny, hasAnyError, sidebarOpen, state?.safe_mode, locale, dir, theme])
|
||||
}, [currentView, effectiveState, isBusyAny, hasAnyError, sidebarOpen, state?.safe_mode, locale, dir, theme, reducedMotion])
|
||||
|
||||
// UI SDK event stream (ui-contract UI_CONTRACT_SDK_EVENTS). emitThemeEvent is
|
||||
// a no-op unless an interactive theme is loaded; payloads carry no paths.
|
||||
@@ -939,7 +940,7 @@ export const App: React.FC = () => {
|
||||
shortcutRef.current = (e: KeyboardEvent) => {
|
||||
if (!e.ctrlKey || e.altKey || e.metaKey) return
|
||||
if (appDialogOpen) return
|
||||
if (document.querySelector('[role="dialog"], [role="alertdialog"]')) return
|
||||
if (hasVisibleDialog()) return
|
||||
const k = e.key.toLowerCase()
|
||||
if (k === 'n') { e.preventDefault(); openWizard() }
|
||||
else if (k === ',' && detail && effectiveState !== 'suspended' && effectiveState !== 'suspending' && effectiveState !== 'resuming') { e.preventDefault(); setShowSettings(true) }
|
||||
|
||||
@@ -2,11 +2,11 @@ import { AlertTriangle, Check, Download, ShieldAlert } from 'lucide-react'
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import '../i18n/domains/plugins.gen'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { Locale, MarketBrowseResult, MarketCatalogItem, PluginInfo } from '../types'
|
||||
import { Locale, MarketBrowseResult, MarketCatalogItem, PluginInfo, ScanReport } from '../types'
|
||||
import { Button, Tip } from '../ui/controls'
|
||||
import { Modal } from '../ui/dialog'
|
||||
import { api, events, MarketInstallProgress } from '../wails'
|
||||
import { PluginAppIcon, PluginSearchInput, PluginTrustBadge, RiskList } from './PluginParts'
|
||||
import { PluginAppIcon, PluginApprovalBody, PluginSearchInput, PluginTrustBadge, RiskList } from './PluginParts'
|
||||
import { locText } from './SchemaForm'
|
||||
import { WordmarkLoader } from './WordmarkLoader'
|
||||
|
||||
@@ -57,12 +57,16 @@ export const PluginMarket: React.FC<Props> = ({
|
||||
const [visible, setVisible] = useState(PAGE_SIZE)
|
||||
const [progress, setProgress] = useState<ProgressMap>({})
|
||||
const [prompt, setPrompt] = useState<PluginInfo | null>(null)
|
||||
const [promptReport, setPromptReport] = useState<ScanReport | null>(null)
|
||||
const [promptChecked, setPromptChecked] = useState(false)
|
||||
const [enabling, setEnabling] = useState(false)
|
||||
|
||||
const seq = useRef(0)
|
||||
const synced = useRef(false)
|
||||
const sentinel = useRef<HTMLDivElement>(null)
|
||||
const installingRef = useRef<Set<string>>(new Set())
|
||||
const promptTargetIDRef = useRef('')
|
||||
const promptQueueRef = useRef<PluginInfo[]>([])
|
||||
const params = useRef({ query, kind })
|
||||
params.current = { query, kind }
|
||||
|
||||
@@ -158,19 +162,57 @@ export const PluginMarket: React.FC<Props> = ({
|
||||
return () => io.disconnect()
|
||||
}, [hasMore, visible, items.length])
|
||||
|
||||
const openPrompt = (info: PluginInfo) => {
|
||||
promptTargetIDRef.current = info.id
|
||||
setPromptChecked(false)
|
||||
setPromptReport(null)
|
||||
setPrompt(info)
|
||||
if (info.needs_approval) {
|
||||
void api.ScanInstalledPlugin(info.id)
|
||||
.then((rep) => {
|
||||
if (promptTargetIDRef.current === info.id) setPromptReport(rep)
|
||||
})
|
||||
.catch((e) => console.warn('[market] ScanInstalledPlugin failed:', info.id, e))
|
||||
}
|
||||
}
|
||||
|
||||
const advancePrompt = () => {
|
||||
const next = promptQueueRef.current.shift()
|
||||
if (next) {
|
||||
openPrompt(next)
|
||||
return
|
||||
}
|
||||
promptTargetIDRef.current = ''
|
||||
setPrompt(null)
|
||||
setPromptReport(null)
|
||||
}
|
||||
|
||||
const closePrompt = () => {
|
||||
if (enabling) return
|
||||
advancePrompt()
|
||||
}
|
||||
|
||||
const install = async (item: MarketCatalogItem) => {
|
||||
const id = item.entry.id
|
||||
if (installingRef.current.has(id)) return
|
||||
installingRef.current.add(id)
|
||||
setProgress((prev) => ({ ...prev, [id]: { id, phase: 'download', done: 0, total: item.entry.size_bytes ?? 0 } }))
|
||||
try {
|
||||
const info = await api.InstallMarketPlugin(id, false)
|
||||
await onChanged({})
|
||||
if (info && !info.enabled) {
|
||||
setPromptChecked(false)
|
||||
setPrompt(info)
|
||||
if (promptTargetIDRef.current) {
|
||||
if (promptTargetIDRef.current !== info.id && !promptQueueRef.current.some((p) => p.id === info.id)) {
|
||||
promptQueueRef.current.push(info)
|
||||
}
|
||||
} else {
|
||||
openPrompt(info)
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
onError(tr('pluginFailMarketInstall'), e)
|
||||
} finally {
|
||||
installingRef.current.delete(id)
|
||||
setProgress((prev) => {
|
||||
const next = { ...prev }
|
||||
delete next[id]
|
||||
@@ -185,7 +227,7 @@ export const PluginMarket: React.FC<Props> = ({
|
||||
try {
|
||||
const target = prompt
|
||||
await api.EnablePlugin(target.id, target.needs_approval)
|
||||
setPrompt(null)
|
||||
advancePrompt()
|
||||
await onChanged({ enabled: target })
|
||||
} catch (e) {
|
||||
onError(tr('pluginFailEnable'), e)
|
||||
@@ -349,10 +391,19 @@ export const PluginMarket: React.FC<Props> = ({
|
||||
title={tr('pluginEnablePromptTitle', { name: locText(prompt.name, locale, prompt.id) })}
|
||||
subtitle={`${prompt.publisher || tr('pluginTrustCommunity')} · v${prompt.version}`}
|
||||
closeLabel={tr('close')}
|
||||
onClose={() => { if (!enabling) setPrompt(null) }}
|
||||
dismissable={!enabling}
|
||||
onClose={closePrompt}
|
||||
>
|
||||
<div className="dialog-body">
|
||||
{(prompt.risks?.length ?? 0) > 0 ? (
|
||||
{prompt.needs_approval ? (
|
||||
<>
|
||||
<PluginApprovalBody locale={locale} plugin={prompt} report={promptReport} />
|
||||
<label className="choice">
|
||||
<input type="checkbox" checked={promptChecked} onChange={(e) => setPromptChecked(e.target.checked)} />
|
||||
<span>{tr('pluginApproveCheckbox')}</span>
|
||||
</label>
|
||||
</>
|
||||
) : (prompt.risks?.length ?? 0) > 0 ? (
|
||||
<>
|
||||
<p className="plugin-enable-lead">{tr('pluginEnablePromptBody')}</p>
|
||||
<RiskList locale={locale} risks={prompt.risks} />
|
||||
@@ -360,23 +411,17 @@ export const PluginMarket: React.FC<Props> = ({
|
||||
) : (
|
||||
<p className="plugin-enable-lead">{tr('pluginEnablePromptNoRisk')}</p>
|
||||
)}
|
||||
{prompt.needs_approval && (
|
||||
<label className="choice">
|
||||
<input type="checkbox" checked={promptChecked} onChange={(e) => setPromptChecked(e.target.checked)} />
|
||||
<span>{tr('pluginApproveCheckbox')}</span>
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<span />
|
||||
<span className="hstack">
|
||||
<Button variant="ghost" disabled={enabling} onClick={() => setPrompt(null)}>{tr('pluginEnableLater')}</Button>
|
||||
<Button variant="ghost" disabled={enabling} onClick={closePrompt}>{tr('pluginEnableLater')}</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
disabled={enabling || !!safeMode || (prompt.needs_approval && !promptChecked)}
|
||||
onClick={() => void enablePrompted()}
|
||||
>
|
||||
{tr('pluginEnableNow')}
|
||||
{tr(prompt.needs_approval ? 'pluginApproveConfirm' : 'pluginEnableNow')}
|
||||
</Button>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
@@ -1,15 +1,32 @@
|
||||
import {
|
||||
Activity, BadgeCheck, Binary, Clipboard, Code2, Files, Globe,
|
||||
Keyboard, Monitor, PanelsTopLeft, Search, ShieldCheck, Users,
|
||||
Keyboard, Monitor, PanelsTopLeft, Search, ShieldAlert, ShieldCheck, Users,
|
||||
} from 'lucide-react'
|
||||
import React from 'react'
|
||||
import '../i18n/domains/plugins.gen'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { Locale } from '../types'
|
||||
import { I18nKey, locText, t } from '../i18n'
|
||||
import { Locale, PluginInfo, ScanReport } from '../types'
|
||||
import { Tip } from '../ui/controls'
|
||||
|
||||
export { PluginAppIcon, resolvePluginVisual, type PluginVisual, type PluginVisualSource } from './PluginAppIcon'
|
||||
|
||||
/** Selects the accurate high-risk warning notice for a plugin (L3 native vs ui:script). */
|
||||
export function resolvePluginApprovalNotice(
|
||||
plugin: Pick<PluginInfo, 'tier' | 'permissions'>,
|
||||
report: Pick<ScanReport, 'native_exec_notice'> | null | undefined,
|
||||
locale: Locale,
|
||||
): string {
|
||||
if (plugin.tier === 'L3') {
|
||||
return report?.native_exec_notice
|
||||
? locText(report.native_exec_notice, locale, t(locale, 'pluginApproveL3Warn'))
|
||||
: t(locale, 'pluginApproveL3Warn')
|
||||
}
|
||||
if ((plugin.permissions ?? []).some((p) => p.name === 'ui:script')) {
|
||||
return t(locale, 'pluginApproveUIScriptWarn')
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
/** Publisher + trust-tier mark shared by Installed rows and Market cards. */
|
||||
export const PluginTrustBadge: React.FC<{
|
||||
locale: Locale
|
||||
@@ -80,3 +97,86 @@ export const RiskList: React.FC<{ locale: Locale; risks?: string[] }> = ({ local
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
|
||||
/** High-risk approval disclosure shared by Installed approval and Market enable flows. */
|
||||
export const PluginApprovalBody: React.FC<{
|
||||
locale: Locale
|
||||
plugin: PluginInfo
|
||||
report?: ScanReport | null
|
||||
}> = ({ locale, plugin, report }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const warnText = resolvePluginApprovalNotice(plugin, report, locale)
|
||||
return (
|
||||
<>
|
||||
{warnText && (
|
||||
<div className="notice notice-warn">
|
||||
<span className="notice-main">
|
||||
<ShieldAlert size={15} className="notice-icon" aria-hidden="true" />
|
||||
<span>{warnText}</span>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<RiskList locale={locale} risks={plugin.risks} />
|
||||
<div className="list">
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('pluginPublisherLicense')}</div>
|
||||
<div className="row-sub">{plugin.publisher || '—'} · {plugin.license || '—'}</div>
|
||||
</div>
|
||||
</div>
|
||||
{plugin.entry_path && (
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('pluginEntryPath')}</div>
|
||||
<div className="row-sub mono selectable">{plugin.entry_path}</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{plugin.entry_hash && (
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">SHA-256</div>
|
||||
<div className="row-sub mono selectable">{plugin.entry_hash}</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('pluginRequestedPerms')}</div>
|
||||
<div className="row-sub mono">
|
||||
{(plugin.permissions ?? []).length > 0
|
||||
? (plugin.permissions ?? []).map((p) => `${p.name} (${p.level})`).join(', ')
|
||||
: '—'}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{(report?.capabilities?.length ?? 0) > 0 && (
|
||||
<div className="plugin-scan-section">
|
||||
<div className="plugin-scan-section-title">{tr('pluginScanCapabilitiesSection')}</div>
|
||||
<div className="list">
|
||||
{report!.capabilities!.map((c) => (
|
||||
<div className="row" key={c.id}>
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
<span className={`badge rg-p-badge${c.level === 'high' ? ' badge-warn' : ''}`}>{c.level.toUpperCase()}</span>
|
||||
<span>{locText(c.title, locale, c.id)}</span>
|
||||
</div>
|
||||
<div className="row-sub">{locText(c.summary, locale, '')}</div>
|
||||
{(c.examples?.length ?? 0) > 0 && (
|
||||
<div className="plugin-scan-examples mono">
|
||||
{c.examples!.map((ex, i) => <div key={i}>· {ex}</div>)}
|
||||
{(c.extra_count ?? 0) > 0 && (
|
||||
<div className="muted">· {tr('pluginScanMoreItems', { count: c.extra_count! })}</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import {
|
||||
AlertTriangle, CheckCircle2, FolderOpen, PackagePlus, Palette,
|
||||
RefreshCw, Settings2, Shield, ShieldAlert, Sparkles, Terminal, Trash2,
|
||||
} from 'lucide-react'
|
||||
import React, { useEffect, useMemo, useState } from 'react'
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import '../i18n/domains/plugins.gen'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
@@ -15,7 +15,7 @@ import { PopupSelect, Segmented, Switch } from '../ui/settings'
|
||||
import { api } from '../wails'
|
||||
import { PluginMarket } from './PluginMarket'
|
||||
import { PluginPanelFrame } from './PluginPanelFrame'
|
||||
import { PluginAppIcon, PluginSearchInput, PluginTrustBadge, RiskList } from './PluginParts'
|
||||
import { PluginAppIcon, PluginApprovalBody, PluginSearchInput, PluginTrustBadge } from './PluginParts'
|
||||
import { SchemaForm, locText } from './SchemaForm'
|
||||
|
||||
// Search only earns its space once the list is long enough to scan.
|
||||
@@ -57,6 +57,7 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
const [approveTarget, setApproveTarget] = useState<PluginInfo | null>(null)
|
||||
const [approveReport, setApproveReport] = useState<ScanReport | null>(null)
|
||||
const [approveChecked, setApproveChecked] = useState(false)
|
||||
const approveTargetIDRef = useRef('')
|
||||
const [settingsTarget, setSettingsTarget] = useState<PluginInfo | null>(null)
|
||||
const [settingsValues, setSettingsValues] = useState<Record<string, unknown>>({})
|
||||
const [logTarget, setLogTarget] = useState<{ id: string; text: string } | null>(null)
|
||||
@@ -93,8 +94,10 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
setPlugins(list ?? [])
|
||||
setContribs(ui)
|
||||
setActiveTheme(th)
|
||||
return { ui, th }
|
||||
} catch (e) {
|
||||
onError(tr('pluginFailLoad'), e)
|
||||
return null
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
@@ -116,13 +119,34 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
if (tags.length > 0 && !tags.includes(locale)) onLocaleSwitch?.(tags[0])
|
||||
}
|
||||
|
||||
// Enabling a theme plugin from the market switches to its first theme only
|
||||
// while the user is still on the built-in default theme.
|
||||
const adoptPluginTheme = async (
|
||||
p: PluginInfo,
|
||||
ui: PluginUIContributions | null | undefined,
|
||||
currentTheme: ActiveThemePayload | null | undefined,
|
||||
) => {
|
||||
if (safeMode) return
|
||||
const curID = currentTheme?.theme_id ?? ''
|
||||
if (curID && curID !== 'builtin.theme.default') return
|
||||
const matched = (ui?.themes ?? []).find((th) => th.pluginId === p.id)
|
||||
if (!matched) return
|
||||
try {
|
||||
await api.SetActiveTheme(matched.id, '')
|
||||
setActiveTheme(await api.GetActiveTheme())
|
||||
} catch (e) {
|
||||
onError(tr('pluginFailSwitchTheme'), e)
|
||||
}
|
||||
}
|
||||
|
||||
const onMarketChanged = async ({ enabled }: { enabled?: PluginInfo }) => {
|
||||
await reload()
|
||||
onRefresh()
|
||||
const latest = await reload()
|
||||
if (enabled) {
|
||||
onThemeChanged?.()
|
||||
await adoptPluginTheme(enabled, latest?.ui, latest?.th)
|
||||
adoptPluginLocale(enabled)
|
||||
}
|
||||
onRefresh()
|
||||
onThemeChanged?.()
|
||||
}
|
||||
|
||||
useEffect(() => { void reload() }, [safeMode])
|
||||
@@ -136,10 +160,15 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
return
|
||||
}
|
||||
if (enable && p.needs_approval) {
|
||||
approveTargetIDRef.current = p.id
|
||||
setApproveChecked(false)
|
||||
setApproveReport(null)
|
||||
setApproveTarget(p)
|
||||
void api.ScanInstalledPlugin(p.id).then(setApproveReport).catch((e) => console.warn('[plugins] ScanInstalledPlugin failed:', p.id, e))
|
||||
void api.ScanInstalledPlugin(p.id)
|
||||
.then((rep) => {
|
||||
if (approveTargetIDRef.current === p.id) setApproveReport(rep)
|
||||
})
|
||||
.catch((e) => console.warn('[plugins] ScanInstalledPlugin failed:', p.id, e))
|
||||
return
|
||||
}
|
||||
setBusyID(p.id)
|
||||
@@ -157,11 +186,16 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
}
|
||||
}
|
||||
|
||||
const closeApprove = () => {
|
||||
approveTargetIDRef.current = ''
|
||||
setApproveTarget(null)
|
||||
setApproveReport(null)
|
||||
}
|
||||
|
||||
const confirmApprove = async () => {
|
||||
if (!approveTarget || !approveChecked) return
|
||||
const target = approveTarget
|
||||
setApproveTarget(null)
|
||||
setApproveReport(null)
|
||||
closeApprove()
|
||||
setBusyID(target.id)
|
||||
try {
|
||||
await api.EnablePlugin(target.id, true)
|
||||
@@ -803,46 +837,10 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
title={tr('pluginApproveTitle')}
|
||||
subtitle={locText(approveTarget.name, locale, approveTarget.id)}
|
||||
closeLabel={tr('close')}
|
||||
onClose={() => { setApproveTarget(null); setApproveReport(null) }}
|
||||
onClose={closeApprove}
|
||||
>
|
||||
<div className="dialog-body">
|
||||
{(approveTarget.tier === 'L3' || (approveTarget.permissions ?? []).some((p) => p.name === 'ui:script')) && (
|
||||
<div className="notice notice-warn">
|
||||
<span className="notice-main">
|
||||
<ShieldAlert size={15} className="notice-icon" aria-hidden="true" />
|
||||
<span>{approveReport?.native_exec_notice ? locText(approveReport.native_exec_notice, locale, tr('pluginApproveL3Warn')) : tr('pluginApproveL3Warn')}</span>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<RiskList locale={locale} risks={approveTarget.risks} />
|
||||
<div className="list">
|
||||
<div className="row"><div className="row-main"><div className="row-title">{tr('pluginPublisherLicense')}</div><div className="row-sub">{approveTarget.publisher || '—'} · {approveTarget.license || '—'}</div></div></div>
|
||||
{approveTarget.entry_path && (
|
||||
<div className="row"><div className="row-main"><div className="row-title">{tr('pluginEntryPath')}</div><div className="row-sub mono selectable">{approveTarget.entry_path}</div></div></div>
|
||||
)}
|
||||
{approveTarget.entry_hash && (
|
||||
<div className="row"><div className="row-main"><div className="row-title">SHA-256</div><div className="row-sub mono selectable">{approveTarget.entry_hash}</div></div></div>
|
||||
)}
|
||||
<div className="row"><div className="row-main"><div className="row-title">{tr('pluginRequestedPerms')}</div><div className="row-sub mono">{(approveTarget.permissions ?? []).length > 0 ? (approveTarget.permissions ?? []).map((p) => `${p.name} (${p.level})`).join(', ') : '—'}</div></div></div>
|
||||
</div>
|
||||
{(approveReport?.capabilities?.length ?? 0) > 0 && (
|
||||
<div className="plugin-scan-section">
|
||||
<div className="plugin-scan-section-title">{tr('pluginScanCapabilitiesSection')}</div>
|
||||
<div className="list">
|
||||
{approveReport!.capabilities!.map((c) => (
|
||||
<div className="row" key={c.id}>
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
<span className={`badge rg-p-badge${c.level === 'high' ? ' badge-warn' : ''}`}>{c.level.toUpperCase()}</span>
|
||||
<span>{locText(c.title, locale, c.id)}</span>
|
||||
</div>
|
||||
<div className="row-sub">{locText(c.summary, locale, '')}</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<PluginApprovalBody locale={locale} plugin={approveTarget} report={approveReport} />
|
||||
<label className="choice">
|
||||
<input type="checkbox" checked={approveChecked} onChange={(e) => setApproveChecked(e.target.checked)} />
|
||||
<span>{tr('pluginApproveCheckbox')}</span>
|
||||
@@ -851,7 +849,7 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
<div className="dialog-foot">
|
||||
<span />
|
||||
<span className="hstack">
|
||||
<Button variant="ghost" onClick={() => { setApproveTarget(null); setApproveReport(null) }}>{tr('cancel')}</Button>
|
||||
<Button variant="ghost" onClick={closeApprove}>{tr('cancel')}</Button>
|
||||
<Button variant="primary" disabled={!approveChecked} onClick={() => void confirmApprove()}>
|
||||
{tr('pluginApproveConfirm')}
|
||||
</Button>
|
||||
|
||||
@@ -3,6 +3,7 @@ import { AppWindow, Camera, CopyPlus, Cpu, Download, FolderOpen, Info, Maximize2
|
||||
import React, { useRef } from 'react'
|
||||
import { I18nKey, localeDir, t } from '../i18n'
|
||||
import { Locale, VMListItem } from '../types'
|
||||
import { hasVisibleDialog } from '../lib/dialogState'
|
||||
import { vmRefKey } from '../lib/vmRef'
|
||||
import { IconButton, StatusShape, Tip, statusKind } from '../ui/controls'
|
||||
import { VersionArt } from '../macos/VersionArt'
|
||||
@@ -162,7 +163,7 @@ export const Sidebar: React.FC<Props> = ({
|
||||
onCloseAutoFocus={(e) => {
|
||||
if (
|
||||
ctxOpenedByPointerRef.current
|
||||
|| document.querySelector('[role="dialog"], [role="alertdialog"]')
|
||||
|| hasVisibleDialog()
|
||||
) {
|
||||
e.preventDefault()
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import * as Menu from '@radix-ui/react-dropdown-menu'
|
||||
import { Check, PanelLeft } from 'lucide-react'
|
||||
import React, { useRef, useState } from 'react'
|
||||
import { I18nKey, localeDir, t } from '../i18n'
|
||||
import { hasVisibleDialog } from '../lib/dialogState'
|
||||
import { useVMStats } from '../lib/vmStats'
|
||||
import { Locale } from '../types'
|
||||
import { Tip } from '../ui/controls'
|
||||
@@ -178,7 +179,7 @@ export const TitleMenus: React.FC<Props> = ({
|
||||
openRef.current !== null
|
||||
|| openedByPointerRef.current
|
||||
|| pointerClosedRef.current
|
||||
|| document.querySelector('[role="dialog"], [role="alertdialog"]')
|
||||
|| hasVisibleDialog()
|
||||
) {
|
||||
e.preventDefault()
|
||||
}
|
||||
|
||||
@@ -48,6 +48,7 @@ import {
|
||||
controllerLabel, formatBytes, formatDiskUsage, formatMemory, formatUptime, graphicsLabel,
|
||||
parseMemoryGB, pendingChangeText, resolveGuestLang, sshCommand,
|
||||
} from '../lib/format'
|
||||
import { hasVisibleDialog } from '../lib/dialogState'
|
||||
import { useVMStats } from '../lib/vmStats'
|
||||
import { DiskSnapshot, HostReport, Locale, PendingChange, PluginUIContributions, VMDetail, VMThumbnail } from '../types'
|
||||
import { api } from '../wails'
|
||||
@@ -563,7 +564,7 @@ export const VMPage: React.FC<Props> = ({
|
||||
if (
|
||||
moreOpenedByPointer.current
|
||||
|| morePointerClosed.current
|
||||
|| document.querySelector('[role="dialog"], [role="alertdialog"]')
|
||||
|| hasVisibleDialog()
|
||||
) {
|
||||
e.preventDefault()
|
||||
}
|
||||
@@ -1150,7 +1151,7 @@ export const VMPage: React.FC<Props> = ({
|
||||
if (
|
||||
sshOpenedByPointer.current
|
||||
|| sshPointerClosed.current
|
||||
|| document.querySelector('[role="dialog"], [role="alertdialog"]')
|
||||
|| hasVisibleDialog()
|
||||
) {
|
||||
e.preventDefault()
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ export const pluginsZh: Record<string, string> = {
|
||||
"pluginApproveConfirm": "确认启用",
|
||||
"pluginApproveL3Warn": "此插件为原生可执行程序(L3 Sidecar),能够以当前 Windows 账户身份执行任意操作",
|
||||
"pluginApproveTitle": "高危权限确认",
|
||||
"pluginApproveUIScriptWarn": "此插件包含交互界面脚本(ui:script),会在主窗口界面中运行并可访问页面内容,启用前务必核对来源与脚本 SHA-256",
|
||||
"pluginBuiltinSection": "内置插件",
|
||||
"pluginColorSchemes": "配色方案",
|
||||
"pluginColorSchemesHint": "修改种子色派生整套界面色阶",
|
||||
@@ -133,6 +134,7 @@ export const pluginsEn: Record<string, string> = {
|
||||
"pluginApproveConfirm": "Confirm enable",
|
||||
"pluginApproveL3Warn": "This plugin runs native code (L3 Sidecar) and can perform arbitrary actions as your Windows user",
|
||||
"pluginApproveTitle": "Approve high-risk permissions",
|
||||
"pluginApproveUIScriptWarn": "This plugin runs an interactive script (ui:script) inside the main window with full access to the interface; verify its source and SHA-256 before enabling",
|
||||
"pluginBuiltinSection": "Built-in plugins",
|
||||
"pluginColorSchemes": "Color schemes",
|
||||
"pluginColorSchemesHint": "Seed colors derive the full surface, text, and accent ramp",
|
||||
|
||||
@@ -651,6 +651,7 @@ export type I18nKey =
|
||||
| "pluginApproveConfirm"
|
||||
| "pluginApproveL3Warn"
|
||||
| "pluginApproveTitle"
|
||||
| "pluginApproveUIScriptWarn"
|
||||
| "pluginBuiltinSection"
|
||||
| "pluginColorSchemes"
|
||||
| "pluginColorSchemesHint"
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
// Pure UI helper for checking whether any modal dialog is actually visible.
|
||||
// Hidden pre-mounted dialog elements (display:none on self or ancestor,
|
||||
// visibility:hidden/collapse, [hidden], [inert], aria-hidden="true",
|
||||
// data-state="closed") must not block global shortcuts or menu focus return.
|
||||
|
||||
export interface DialogLikeElement {
|
||||
getAttribute(name: string): string | null
|
||||
closest?(selector: string): unknown
|
||||
parentElement?: DialogLikeElement | null
|
||||
}
|
||||
|
||||
export interface ComputedVisibility {
|
||||
display: string
|
||||
visibility: string
|
||||
}
|
||||
|
||||
export function isDialogElementVisible(
|
||||
el: DialogLikeElement,
|
||||
getStyle: (node: DialogLikeElement) => ComputedVisibility,
|
||||
): boolean {
|
||||
if (el.getAttribute('data-state') === 'closed') return false
|
||||
const selfStyle = getStyle(el)
|
||||
if (selfStyle.visibility === 'hidden' || selfStyle.visibility === 'collapse') return false
|
||||
|
||||
let cur: DialogLikeElement | null = el
|
||||
while (cur) {
|
||||
if (
|
||||
cur.getAttribute('hidden') !== null
|
||||
|| cur.getAttribute('inert') !== null
|
||||
|| cur.getAttribute('aria-hidden') === 'true'
|
||||
) {
|
||||
return false
|
||||
}
|
||||
const style = cur === el ? selfStyle : getStyle(cur)
|
||||
if (style.display === 'none') return false
|
||||
cur = cur.parentElement ?? null
|
||||
}
|
||||
|
||||
if (!el.parentElement && el.closest?.('[hidden], [inert], [aria-hidden="true"]')) return false
|
||||
return true
|
||||
}
|
||||
|
||||
export function hasVisibleDialog(
|
||||
root: Pick<Document, 'querySelectorAll'> = document,
|
||||
getStyle: (node: DialogLikeElement) => ComputedVisibility = (node) => window.getComputedStyle(node as Element),
|
||||
): boolean {
|
||||
const nodes = root.querySelectorAll('[role="dialog"], [role="alertdialog"]')
|
||||
for (let i = 0; i < nodes.length; i++) {
|
||||
if (isDialogElementVisible(nodes[i], getStyle)) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -584,7 +584,8 @@ export async function applyActiveTheme(
|
||||
activeUIScriptNotifier = notifyThemeSDKState
|
||||
activeUIScriptEventSink = emitThemeSDKEvent
|
||||
activeUIScriptURL = nextScriptURL
|
||||
} catch {
|
||||
} catch (e) {
|
||||
console.warn('[theme] mount interactive theme script failed:', nextScriptURL, e)
|
||||
if (gen === applyGeneration) {
|
||||
// Fall back to the scriptless style/token theme.
|
||||
activeUIScriptCleanup = null
|
||||
|
||||
@@ -941,6 +941,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
.dialog-title { font-size: var(--fs-16); font-weight: var(--fw-strong); letter-spacing: -0.01em; text-wrap: balance; }
|
||||
.dialog-desc { font-size: var(--fs-13); color: var(--text-2); margin-top: 2px; overflow-wrap: anywhere; }
|
||||
.dialog-body { padding: 20px 22px; overflow-y: auto; overscroll-behavior: contain; flex: 1; display: flex; flex-direction: column; gap: var(--sp-4); }
|
||||
.dialog-body > * { flex-shrink: 0; }
|
||||
.dialog-foot { flex-shrink: 0; display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: var(--sp-2); padding: 12px 22px; border-top: 1px solid var(--border); }
|
||||
.dialog.sm .dialog-body { padding: 22px 22px 14px; gap: var(--sp-3); }
|
||||
.dialog.sm .dialog-foot { border-top: none; justify-content: flex-end; padding-top: 0; padding-bottom: 20px; }
|
||||
@@ -1915,6 +1916,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
}
|
||||
.plugin-risk.is-high .plugin-risk-icon { background: var(--warn-soft); color: var(--warn-text); }
|
||||
.plugin-scan-section { display: flex; flex-direction: column; gap: 6px; }
|
||||
.plugin-scan-section > .list { flex-shrink: 0; }
|
||||
.plugin-scan-section-title { font-size: var(--fs-12); font-weight: var(--fw-strong); color: var(--text-2); }
|
||||
.plugin-scan-section-title.is-danger { color: var(--danger-text); }
|
||||
.plugin-scan-examples { margin-top: 4px; font-size: var(--fs-11); color: var(--text-2); display: flex; flex-direction: column; gap: 2px; }
|
||||
|
||||
+96
-29
@@ -16,6 +16,7 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/downloader"
|
||||
@@ -104,55 +105,89 @@ func ExpectedSum(ctx context.Context, client *http.Client, sumsURL, name string)
|
||||
return "", fmt.Errorf("%s has no entry for %s", SumsAsset, name)
|
||||
}
|
||||
|
||||
// ResumeOptions configures security and streaming safeguards for a resumable download.
|
||||
type ResumeOptions struct {
|
||||
// BypassDownloader skips any registered downloader plugin and always uses
|
||||
// the caller-supplied http.Client (preserving custom CheckRedirect and proxy rules).
|
||||
BypassDownloader bool
|
||||
// MaxBytes caps total downloaded bytes on disk (<= 0 disables the cap).
|
||||
MaxBytes int64
|
||||
// StallTimeout aborts the download when no bytes arrive for this duration
|
||||
// (<= 0 disables per-read stall detection).
|
||||
StallTimeout time.Duration
|
||||
}
|
||||
|
||||
// Resume downloads url to final, continuing a "<final>.part" left by an earlier
|
||||
// attempt, and keeps the result only when its SHA-256 is want. A final file
|
||||
// that already matches is returned without downloading. size is the expected
|
||||
// length (0 when unknown) and only feeds progress.
|
||||
func Resume(ctx context.Context, client *http.Client, url, final string, size int64, want string, onProgress Progress) (string, error) {
|
||||
return resumeWithOptions(ctx, client, url, final, size, want, onProgress, ResumeOptions{})
|
||||
}
|
||||
|
||||
// ResumeDirect behaves like Resume, always using client directly (never
|
||||
// delegating to activeDownloader plugins) and enforcing opts.MaxBytes and
|
||||
// opts.StallTimeout.
|
||||
func ResumeDirect(ctx context.Context, client *http.Client, url, final string, size int64, want string, onProgress Progress, opts ResumeOptions) (string, error) {
|
||||
opts.BypassDownloader = true
|
||||
return resumeWithOptions(ctx, client, url, final, size, want, onProgress, opts)
|
||||
}
|
||||
|
||||
func resumeWithOptions(ctx context.Context, client *http.Client, url, final string, size int64, want string, onProgress Progress, opts ResumeOptions) (string, error) {
|
||||
if onProgress == nil {
|
||||
onProgress = func(int64, int64) {}
|
||||
}
|
||||
name := filepath.Base(final)
|
||||
if got, err := FileSHA256(final); err == nil && strings.EqualFold(got, want) {
|
||||
onProgress(size, size)
|
||||
return final, nil
|
||||
if st, err := os.Stat(final); err == nil && (opts.MaxBytes <= 0 || st.Size() <= opts.MaxBytes) {
|
||||
if got, herr := FileSHA256(final); herr == nil && strings.EqualFold(got, want) {
|
||||
onProgress(size, size)
|
||||
return final, nil
|
||||
}
|
||||
}
|
||||
part := final + ".part"
|
||||
|
||||
// Try the active downloader plugin first (fail-open to single-stream below).
|
||||
if prov := activeDownloader(); prov != nil {
|
||||
err := prov.Download(ctx, downloader.Request{
|
||||
URL: url,
|
||||
DestPath: part,
|
||||
ExpectedSize: size,
|
||||
ExpectedSHA256: want,
|
||||
Resume: true,
|
||||
}, func(p downloader.Progress) {
|
||||
onProgress(p.Done, p.Total)
|
||||
})
|
||||
if err == nil {
|
||||
if got, herr := FileSHA256(part); herr == nil && strings.EqualFold(got, want) {
|
||||
if rerr := os.Rename(part, final); rerr != nil {
|
||||
return "", rerr
|
||||
// Try the active downloader plugin first unless bypassed for security-sensitive paths.
|
||||
if !opts.BypassDownloader {
|
||||
if prov := activeDownloader(); prov != nil {
|
||||
err := prov.Download(ctx, downloader.Request{
|
||||
URL: url,
|
||||
DestPath: part,
|
||||
ExpectedSize: size,
|
||||
ExpectedSHA256: want,
|
||||
Resume: true,
|
||||
}, func(p downloader.Progress) {
|
||||
onProgress(p.Done, p.Total)
|
||||
})
|
||||
if err == nil {
|
||||
if got, herr := FileSHA256(part); herr == nil && strings.EqualFold(got, want) {
|
||||
if rerr := os.Rename(part, final); rerr != nil {
|
||||
return "", rerr
|
||||
}
|
||||
return final, nil
|
||||
}
|
||||
return final, nil
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return "", ctx.Err()
|
||||
}
|
||||
// Clean up any partial multi-range file before single-stream fallback so
|
||||
// sequential append doesn't concatenate onto sparse holes.
|
||||
_ = os.Remove(part)
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return "", ctx.Err()
|
||||
}
|
||||
// Clean up any partial multi-range file before single-stream fallback so
|
||||
// sequential append doesn't concatenate onto sparse holes.
|
||||
_ = os.Remove(part)
|
||||
}
|
||||
|
||||
for attempt := 0; ; attempt++ {
|
||||
var have int64
|
||||
if st, err := os.Stat(part); err == nil {
|
||||
have = st.Size()
|
||||
if opts.MaxBytes > 0 && st.Size() > opts.MaxBytes {
|
||||
_ = os.Remove(part)
|
||||
} else {
|
||||
have = st.Size()
|
||||
}
|
||||
}
|
||||
req, err := NewRequest(ctx, url)
|
||||
reqCtx, cancelReq := context.WithCancel(ctx)
|
||||
req, err := NewRequest(reqCtx, url)
|
||||
if err != nil {
|
||||
cancelReq()
|
||||
return "", err
|
||||
}
|
||||
if have > 0 {
|
||||
@@ -160,6 +195,7 @@ func Resume(ctx context.Context, client *http.Client, url, final string, size in
|
||||
}
|
||||
resp, err := clientOr(client).Do(req)
|
||||
if err != nil {
|
||||
cancelReq()
|
||||
return "", fmt.Errorf("download %s: %w", name, err)
|
||||
}
|
||||
|
||||
@@ -172,6 +208,7 @@ func Resume(ctx context.Context, client *http.Client, url, final string, size in
|
||||
flags |= os.O_TRUNC
|
||||
case http.StatusRequestedRangeNotSatisfiable:
|
||||
resp.Body.Close()
|
||||
cancelReq()
|
||||
os.Remove(part)
|
||||
if attempt > 0 {
|
||||
return "", fmt.Errorf("download %s: HTTP 416", name)
|
||||
@@ -179,14 +216,22 @@ func Resume(ctx context.Context, client *http.Client, url, final string, size in
|
||||
continue
|
||||
default:
|
||||
resp.Body.Close()
|
||||
cancelReq()
|
||||
return "", fmt.Errorf("download %s: HTTP %d", name, resp.StatusCode)
|
||||
}
|
||||
if opts.MaxBytes > 0 && resp.ContentLength > 0 && have+resp.ContentLength > opts.MaxBytes {
|
||||
resp.Body.Close()
|
||||
cancelReq()
|
||||
_ = os.Remove(part)
|
||||
return "", fmt.Errorf("download %s: content length %d exceeds %d byte limit", name, have+resp.ContentLength, opts.MaxBytes)
|
||||
}
|
||||
total := size
|
||||
if total <= 0 && resp.ContentLength > 0 {
|
||||
total = have + resp.ContentLength
|
||||
}
|
||||
err = copyBody(resp.Body, part, flags, have, total, name, onProgress)
|
||||
err = copyBody(resp.Body, cancelReq, part, flags, have, total, opts.MaxBytes, opts.StallTimeout, name, onProgress)
|
||||
resp.Body.Close()
|
||||
cancelReq()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -207,11 +252,22 @@ func Resume(ctx context.Context, client *http.Client, url, final string, size in
|
||||
return final, nil
|
||||
}
|
||||
|
||||
func copyBody(body io.Reader, part string, flags int, have, total int64, name string, onProgress Progress) error {
|
||||
func copyBody(body io.Reader, cancelReq context.CancelFunc, part string, flags int, have, total, maxBytes int64, stallTimeout time.Duration, name string, onProgress Progress) error {
|
||||
f, err := os.OpenFile(part, flags, 0o644)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var (
|
||||
stalled atomic.Bool
|
||||
timer *time.Timer
|
||||
)
|
||||
if stallTimeout > 0 && cancelReq != nil {
|
||||
timer = time.AfterFunc(stallTimeout, func() {
|
||||
stalled.Store(true)
|
||||
cancelReq()
|
||||
})
|
||||
defer timer.Stop()
|
||||
}
|
||||
done := have
|
||||
onProgress(done, total)
|
||||
buf := make([]byte, 256*1024)
|
||||
@@ -219,6 +275,14 @@ func copyBody(body io.Reader, part string, flags int, have, total int64, name st
|
||||
for {
|
||||
n, rerr := body.Read(buf)
|
||||
if n > 0 {
|
||||
if timer != nil {
|
||||
timer.Reset(stallTimeout)
|
||||
}
|
||||
if maxBytes > 0 && done+int64(n) > maxBytes {
|
||||
f.Close()
|
||||
_ = os.Remove(part)
|
||||
return fmt.Errorf("download %s: exceeds %d byte limit", name, maxBytes)
|
||||
}
|
||||
if _, werr := f.Write(buf[:n]); werr != nil {
|
||||
f.Close()
|
||||
return werr
|
||||
@@ -234,6 +298,9 @@ func copyBody(body io.Reader, part string, flags int, have, total int64, name st
|
||||
}
|
||||
if rerr != nil {
|
||||
f.Close()
|
||||
if stalled.Load() {
|
||||
return fmt.Errorf("download %s: stalled for %s", name, stallTimeout)
|
||||
}
|
||||
return fmt.Errorf("download %s: %w", name, rerr) // .part kept for resume
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,8 +10,11 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/downloader"
|
||||
)
|
||||
|
||||
func sum(b []byte) string {
|
||||
@@ -95,3 +98,91 @@ func TestResumeDiscardsMismatch(t *testing.T) {
|
||||
}
|
||||
|
||||
var timeZero = time.Time{}
|
||||
|
||||
type spyDownloader struct {
|
||||
called atomic.Int32
|
||||
}
|
||||
|
||||
func (s *spyDownloader) ID() string { return "test.spy" }
|
||||
|
||||
func (s *spyDownloader) Download(_ context.Context, _ downloader.Request, _ func(downloader.Progress)) error {
|
||||
s.called.Add(1)
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestResumeDirectBypassesDownloaderAndEnforcesMaxBytesAndStall(t *testing.T) {
|
||||
spy := &spyDownloader{}
|
||||
SetDefaultDownloader(func() downloader.Provider { return spy })
|
||||
t.Cleanup(func() { SetDefaultDownloader(nil) })
|
||||
|
||||
// 1. Streaming response with unknown declared size (size=0) exceeding MaxBytes must abort early and delete .part.
|
||||
bigBody := []byte(strings.Repeat("x", 4096))
|
||||
stallRelease := make(chan struct{})
|
||||
t.Cleanup(func() { close(stallRelease) })
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/chunked-big":
|
||||
fl, _ := w.(http.Flusher)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
for i := 0; i < len(bigBody); i += 64 {
|
||||
_, _ = w.Write(bigBody[i : i+64])
|
||||
if fl != nil {
|
||||
fl.Flush()
|
||||
}
|
||||
}
|
||||
case "/content-length-big":
|
||||
w.Header().Set("Content-Length", "4096")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write(bigBody)
|
||||
case "/stall":
|
||||
fl, _ := w.(http.Flusher)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte("partial"))
|
||||
if fl != nil {
|
||||
fl.Flush()
|
||||
}
|
||||
select {
|
||||
case <-stallRelease:
|
||||
case <-r.Context().Done():
|
||||
}
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
dir := t.TempDir()
|
||||
chunkedFinal := filepath.Join(dir, "chunked.zip")
|
||||
if _, err := ResumeDirect(context.Background(), srv.Client(), srv.URL+"/chunked-big", chunkedFinal, 0, sum(bigBody), nil, ResumeOptions{
|
||||
MaxBytes: 256,
|
||||
}); err == nil || !strings.Contains(err.Error(), "exceeds 256 byte limit") {
|
||||
t.Fatalf("expected MaxBytes error on chunked body, got: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(chunkedFinal + ".part"); !os.IsNotExist(err) {
|
||||
t.Fatal("oversized .part must be deleted")
|
||||
}
|
||||
|
||||
clFinal := filepath.Join(dir, "cl.zip")
|
||||
if _, err := ResumeDirect(context.Background(), srv.Client(), srv.URL+"/content-length-big", clFinal, 0, sum(bigBody), nil, ResumeOptions{
|
||||
MaxBytes: 256,
|
||||
}); err == nil || !strings.Contains(err.Error(), "exceeds 256 byte limit") {
|
||||
t.Fatalf("expected Content-Length MaxBytes error, got: %v", err)
|
||||
}
|
||||
|
||||
// 2. Stalled stream aborts within StallTimeout instead of hanging indefinitely.
|
||||
stallFinal := filepath.Join(dir, "stall.zip")
|
||||
started := time.Now()
|
||||
if _, err := ResumeDirect(context.Background(), srv.Client(), srv.URL+"/stall", stallFinal, 0, sum([]byte("x")), nil, ResumeOptions{
|
||||
MaxBytes: 4096,
|
||||
StallTimeout: 150 * time.Millisecond,
|
||||
}); err == nil || !strings.Contains(err.Error(), "stalled") {
|
||||
t.Fatalf("expected stall timeout error, got: %v", err)
|
||||
}
|
||||
if elapsed := time.Since(started); elapsed > 2*time.Second {
|
||||
t.Fatalf("stall timeout took too long: %s", elapsed)
|
||||
}
|
||||
|
||||
if spy.called.Load() != 0 {
|
||||
t.Fatalf("ResumeDirect must bypass activeDownloader, got %d calls", spy.called.Load())
|
||||
}
|
||||
}
|
||||
+94
-43
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
@@ -96,6 +97,7 @@ func NewManager(opts ManagerOptions) (*Manager, error) {
|
||||
clear(m.l10nCache)
|
||||
m.l10nGen++
|
||||
m.mu.Unlock()
|
||||
m.SyncActiveTheme()
|
||||
})
|
||||
m.assets = NewAssetServer(func(pluginID string) (string, bool) {
|
||||
m.mu.RLock()
|
||||
@@ -169,7 +171,6 @@ func (m *Manager) LoadExternal() error {
|
||||
st := m.state
|
||||
safe := m.safeMode
|
||||
var devMode bool
|
||||
var activeThemeID string
|
||||
type extEntry struct {
|
||||
id string
|
||||
rec PluginRecord
|
||||
@@ -177,7 +178,6 @@ func (m *Manager) LoadExternal() error {
|
||||
var entries []extEntry
|
||||
if st != nil {
|
||||
devMode = st.DeveloperMode
|
||||
activeThemeID = st.ActiveThemeID
|
||||
for id, rec := range st.Plugins {
|
||||
if rec == nil || rec.Source == SourceBuiltin || rec.Source == SourceBundled {
|
||||
continue
|
||||
@@ -226,10 +226,9 @@ func (m *Manager) LoadExternal() error {
|
||||
m.opts.Logger("plugin", fmt.Sprintf("skipped external plugin %s: %v", id, err))
|
||||
}
|
||||
}
|
||||
// Restore active theme unless in safe mode (§5.1: safe mode always reverts to builtin theme).
|
||||
if !safe && activeThemeID != "" {
|
||||
_ = m.registry.SetActiveTheme(activeThemeID)
|
||||
}
|
||||
// Restore built-in active themes immediately; external themes are restored
|
||||
// by SyncActiveTheme once Registry.Reconcile activates their plugins.
|
||||
m.SyncActiveTheme()
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -259,22 +258,9 @@ func (m *Manager) registerExternalDir(dir string, rec *PluginRecord, safeMode bo
|
||||
trust = TrustDev
|
||||
}
|
||||
|
||||
entryRel := man.Entry.Sidecar
|
||||
if entryRel == "" {
|
||||
entryRel = man.Entry.UIScript
|
||||
}
|
||||
if entryRel == "" {
|
||||
entryRel = man.Entry.Script
|
||||
}
|
||||
entryAbs := ""
|
||||
entryHash := ""
|
||||
if entryRel != "" {
|
||||
full, err := safeJoin(dir, entryRel)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid plugin entry path %q: %w", entryRel, err)
|
||||
}
|
||||
entryAbs = full
|
||||
entryHash, _ = fileSHA256Hex(full)
|
||||
_, entryAbs, entryHash, err := resolveManifestEntry(man, dir, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
needsApproval := computeNeedsApproval(man, trust, rec.ApprovedPermissions, rec.ApprovedEntryHash, entryHash)
|
||||
@@ -308,7 +294,7 @@ func (m *Manager) registerExternalDir(dir string, rec *PluginRecord, safeMode bo
|
||||
|
||||
// computeNeedsApproval applies the same gate to every installed package,
|
||||
// official ones included: trust labels a plugin, it does not waive review.
|
||||
// Only dev links skip the L3 hash check, since their code changes on every build.
|
||||
// Only dev links skip entry hash pinning, since their code changes on every build.
|
||||
func computeNeedsApproval(m Manifest, trust TrustLevel, approvedPerms []string, approvedHash, currentHash string) bool {
|
||||
approvedSet := make(map[string]bool, len(approvedPerms))
|
||||
for _, p := range approvedPerms {
|
||||
@@ -320,8 +306,9 @@ func computeNeedsApproval(m Manifest, trust TrustLevel, approvedPerms []string,
|
||||
return true
|
||||
}
|
||||
}
|
||||
// An L3 sidecar requires explicit approval of its exact binary hash (§7.2).
|
||||
if trust != TrustDev && m.InferTier(false) == TierL3 {
|
||||
// L3 sidecars and interactive UI scripts require explicit approval of their
|
||||
// exact entry hash so upgrades modifying executable code pause for re-review (§7.2).
|
||||
if trust != TrustDev && (m.InferTier(false) == TierL3 || len(collectUIScriptPaths(m)) > 0) {
|
||||
if currentHash == "" || approvedHash != currentHash {
|
||||
return true
|
||||
}
|
||||
@@ -544,6 +531,7 @@ func (m *Manager) InstallArchiveWithSource(ctx context.Context, archivePath stri
|
||||
return nil, err
|
||||
}
|
||||
m.registry.Reconcile(ctx)
|
||||
m.SyncActiveTheme()
|
||||
info, _ := m.registry.Info(installed.Manifest.ID)
|
||||
return &info, nil
|
||||
}
|
||||
@@ -597,6 +585,7 @@ func (m *Manager) LinkDev(ctx context.Context, dir string) (*PluginInfo, error)
|
||||
return nil, err
|
||||
}
|
||||
m.registry.Reconcile(ctx)
|
||||
m.SyncActiveTheme()
|
||||
info, _ := m.registry.Info(man.ID)
|
||||
return &info, nil
|
||||
}
|
||||
@@ -660,18 +649,50 @@ func (m *Manager) Enable(ctx context.Context, id string, approveHighRisk bool) e
|
||||
m.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
m.SyncActiveTheme()
|
||||
m.mu.Lock()
|
||||
err := m.store.Save(m.state)
|
||||
m.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
|
||||
// SyncActiveTheme applies the persisted active theme ID in state.json to the
|
||||
// Registry whenever the theme has been registered and the manager is not in
|
||||
// safe mode (§5.1). Safe to call repeatedly after startup, upgrade, or re-enable.
|
||||
func (m *Manager) SyncActiveTheme() {
|
||||
if m.safeMode {
|
||||
return
|
||||
}
|
||||
m.mu.RLock()
|
||||
activeID := ""
|
||||
if m.state != nil {
|
||||
activeID = m.state.ActiveThemeID
|
||||
}
|
||||
m.mu.RUnlock()
|
||||
if activeID == "" || activeID == "builtin.theme.default" {
|
||||
return
|
||||
}
|
||||
if cur := m.registry.ActiveTheme(); cur != nil && cur.ID == activeID {
|
||||
return
|
||||
}
|
||||
_ = m.registry.SetActiveTheme(activeID)
|
||||
}
|
||||
|
||||
// Disable turns off a plugin (if not in use) and persists the state.
|
||||
func (m *Manager) Disable(ctx context.Context, id string) error {
|
||||
m.mu.RLock()
|
||||
activeThemeID := ""
|
||||
activeThemePluginID := ""
|
||||
if m.state != nil {
|
||||
activeThemeID = m.state.ActiveThemeID
|
||||
activeThemePluginID = m.state.ActiveThemePluginID
|
||||
}
|
||||
m.mu.RUnlock()
|
||||
ownsActiveTheme := activeThemeID != "" && ((activeThemePluginID != "" && activeThemePluginID == id) || m.registry.PluginOwnsTheme(id, activeThemeID))
|
||||
|
||||
if err := m.registry.SetDesired(ctx, id, false); err != nil {
|
||||
return err
|
||||
}
|
||||
activeThemeNil := m.registry.ActiveTheme() == nil
|
||||
m.mu.Lock()
|
||||
if m.state == nil {
|
||||
m.mu.Unlock()
|
||||
@@ -684,9 +705,11 @@ func (m *Manager) Disable(ctx context.Context, id string) error {
|
||||
}
|
||||
rec.Enabled = false
|
||||
rec.UpdatedAt = time.Now()
|
||||
if m.state.ActiveThemeID != "" && activeThemeNil {
|
||||
if ownsActiveTheme && m.state.ActiveThemeID == activeThemeID {
|
||||
// If disabling the active theme's plugin, fall back to builtin default theme (§5.1).
|
||||
m.state.ActiveThemeID = ""
|
||||
m.state.ActiveThemePluginID = ""
|
||||
m.state.ActiveSchemeID = ""
|
||||
}
|
||||
err := m.store.Save(m.state)
|
||||
m.mu.Unlock()
|
||||
@@ -694,14 +717,25 @@ func (m *Manager) Disable(ctx context.Context, id string) error {
|
||||
}
|
||||
|
||||
// MarkBootComplete clears the plugin startup crash sentinel after Reconcile
|
||||
// has activated plugins cleanly.
|
||||
// has activated plugins cleanly and ensures any persisted active theme is restored.
|
||||
func (m *Manager) MarkBootComplete() {
|
||||
m.SyncActiveTheme()
|
||||
EndStartupInit(m.layout.Root)
|
||||
}
|
||||
|
||||
// Remove uninstalls a removable external plugin (refusing builtins/bundled or in-use plugins).
|
||||
// Also allows removing orphaned/failed records present only in state.json.
|
||||
func (m *Manager) Remove(ctx context.Context, id string, purgeData bool) error {
|
||||
m.mu.RLock()
|
||||
activeThemeID := ""
|
||||
activeThemePluginID := ""
|
||||
if m.state != nil {
|
||||
activeThemeID = m.state.ActiveThemeID
|
||||
activeThemePluginID = m.state.ActiveThemePluginID
|
||||
}
|
||||
m.mu.RUnlock()
|
||||
ownsActiveTheme := activeThemeID != "" && ((activeThemePluginID != "" && activeThemePluginID == id) || m.registry.PluginOwnsTheme(id, activeThemeID))
|
||||
|
||||
if info, ok := m.registry.Info(id); ok {
|
||||
if !info.Removable {
|
||||
return fmt.Errorf("plugin %q is built-in or bundled and cannot be uninstalled (disable it instead)", id)
|
||||
@@ -716,6 +750,9 @@ func (m *Manager) Remove(ctx context.Context, id string, purgeData bool) error {
|
||||
if !existsInState {
|
||||
return fmt.Errorf("plugin %q not found", id)
|
||||
}
|
||||
if activeThemeID != "" && activeThemePluginID == "" && m.registry.ThemeOwner(activeThemeID) == "" && (activeThemeID == id || strings.HasPrefix(activeThemeID, id+".")) {
|
||||
ownsActiveTheme = true
|
||||
}
|
||||
}
|
||||
m.mu.Lock()
|
||||
if m.state == nil {
|
||||
@@ -724,6 +761,11 @@ func (m *Manager) Remove(ctx context.Context, id string, purgeData bool) error {
|
||||
}
|
||||
delete(m.state.Plugins, id)
|
||||
delete(m.installDirs, id)
|
||||
if ownsActiveTheme && m.state.ActiveThemeID == activeThemeID {
|
||||
m.state.ActiveThemeID = ""
|
||||
m.state.ActiveThemePluginID = ""
|
||||
m.state.ActiveSchemeID = ""
|
||||
}
|
||||
err := m.store.Save(m.state)
|
||||
m.mu.Unlock()
|
||||
if err != nil {
|
||||
@@ -962,12 +1004,17 @@ func (m *Manager) SetActiveTheme(themeID, schemeID string) error {
|
||||
if err := m.registry.SetActiveTheme(themeID); err != nil {
|
||||
return err
|
||||
}
|
||||
activePluginID := ""
|
||||
if th := m.registry.ActiveTheme(); th != nil && th.ID == themeID {
|
||||
activePluginID = th.PluginID
|
||||
}
|
||||
m.mu.Lock()
|
||||
if m.state == nil {
|
||||
m.mu.Unlock()
|
||||
return m.stateNotLoadedErr()
|
||||
}
|
||||
m.state.ActiveThemeID = themeID
|
||||
m.state.ActiveThemePluginID = activePluginID
|
||||
m.state.ActiveSchemeID = schemeID
|
||||
err := m.store.Save(m.state)
|
||||
m.mu.Unlock()
|
||||
@@ -1088,7 +1135,22 @@ func (m *Manager) ActiveThemePayload() ActiveThemePayload {
|
||||
}
|
||||
// Enforce §5.1 trust boundary: ui:script requires declared and approved permission.
|
||||
if hasPerm && approved {
|
||||
payload.UIScriptURL = m.assets.AssetURL(th.PluginID, th.UIScript)
|
||||
scriptURL := m.assets.AssetURL(th.PluginID, th.UIScript)
|
||||
q := url.Values{}
|
||||
if info.Version != "" {
|
||||
q.Set("v", info.Version)
|
||||
}
|
||||
if info.EntryHash != "" {
|
||||
h := info.EntryHash
|
||||
if len(h) > 12 {
|
||||
h = h[:12]
|
||||
}
|
||||
q.Set("h", h)
|
||||
}
|
||||
if enc := q.Encode(); enc != "" {
|
||||
scriptURL += "?" + enc
|
||||
}
|
||||
payload.UIScriptURL = scriptURL
|
||||
payload.UIScriptTrust = info.Trust
|
||||
}
|
||||
}
|
||||
@@ -1960,20 +2022,9 @@ func LoadStaticLocalePacks(dataRoot string) map[i18n.Locale]i18n.PluginCatalog {
|
||||
if c.rec.Source == SourceDevLink {
|
||||
trust = TrustDev
|
||||
}
|
||||
entryRel := man.Entry.Sidecar
|
||||
if entryRel == "" {
|
||||
entryRel = man.Entry.UIScript
|
||||
}
|
||||
if entryRel == "" {
|
||||
entryRel = man.Entry.Script
|
||||
}
|
||||
entryHash := ""
|
||||
if entryRel != "" {
|
||||
full, err := safeJoin(c.dir, entryRel)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
entryHash, _ = fileSHA256Hex(full)
|
||||
_, _, entryHash, err := resolveManifestEntry(man, c.dir, false)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if computeNeedsApproval(man, trust, c.rec.ApprovedPermissions, c.rec.ApprovedEntryHash, entryHash) {
|
||||
continue
|
||||
|
||||
+136
-57
@@ -12,13 +12,13 @@ import (
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/fetch"
|
||||
"github.com/Nwflower/reims-go/internal/netproxy"
|
||||
)
|
||||
|
||||
//go:embed market_fallback.json
|
||||
@@ -38,8 +38,9 @@ const (
|
||||
// primary GitHub raw endpoint is unreachable or blocked.
|
||||
DefaultMarketMirrorURL = "https://cdn.jsdelivr.net/gh/reims-go/plugins@dist/index.json"
|
||||
|
||||
defaultMarketCacheTTL = 10 * time.Minute
|
||||
maxMarketIndexBytes = 4 << 20 // 4 MiB ceiling for lightweight index.json
|
||||
defaultMarketCacheTTL = 10 * time.Minute
|
||||
defaultMarketStallTimeout = 45 * time.Second
|
||||
maxMarketIndexBytes = 4 << 20 // 4 MiB ceiling for lightweight index.json
|
||||
)
|
||||
|
||||
// MarketEntry describes one plugin published in the remote/embedded market index (§9).
|
||||
@@ -165,6 +166,7 @@ type MarketClientOptions struct {
|
||||
HTTPClient *http.Client
|
||||
DownloadClient *http.Client
|
||||
CacheTTL time.Duration
|
||||
DownloadStallTimeout time.Duration
|
||||
AllowInsecureLocalhost bool
|
||||
// FirstParty marks URLs as the project's own index, whose trust levels
|
||||
// carry over to installs. The built-in default URLs always are.
|
||||
@@ -180,6 +182,7 @@ type MarketClient struct {
|
||||
httpClient *http.Client
|
||||
downloadClient *http.Client
|
||||
cacheTTL time.Duration
|
||||
downloadStallTimeout time.Duration
|
||||
allowInsecureLocalhost bool
|
||||
firstParty bool
|
||||
|
||||
@@ -187,8 +190,13 @@ type MarketClient struct {
|
||||
memIndex *MarketIndex
|
||||
memLoaded time.Time
|
||||
// memFetched is true when memIndex came over the network in this
|
||||
// session, not from the disk cache.
|
||||
// session and is not stale.
|
||||
memFetched bool
|
||||
// memStale is true after the most recent remote fetch failed in this session.
|
||||
memStale bool
|
||||
memFetchErr error
|
||||
|
||||
diskCacheMu sync.Mutex
|
||||
}
|
||||
|
||||
// DefaultMarketURLs resolves market index URL(s) from REIMS_GO_PLUGIN_MARKET_URL
|
||||
@@ -223,13 +231,30 @@ func NewMarketClient(opts MarketClientOptions) *MarketClient {
|
||||
if ttl <= 0 {
|
||||
ttl = defaultMarketCacheTTL
|
||||
}
|
||||
stallTimeout := opts.DownloadStallTimeout
|
||||
if stallTimeout <= 0 {
|
||||
stallTimeout = defaultMarketStallTimeout
|
||||
}
|
||||
checkRedirect := func(req *http.Request, via []*http.Request) error {
|
||||
if len(via) >= 10 {
|
||||
return errors.New("stopped after 10 redirects")
|
||||
}
|
||||
return validateMarketURL(req.URL.String(), opts.AllowInsecureLocalhost)
|
||||
}
|
||||
hc := opts.HTTPClient
|
||||
if hc == nil {
|
||||
hc = &http.Client{Timeout: 20 * time.Second}
|
||||
hc = &http.Client{
|
||||
Transport: netproxy.NewTransport(),
|
||||
Timeout: 20 * time.Second,
|
||||
CheckRedirect: checkRedirect,
|
||||
}
|
||||
}
|
||||
dc := opts.DownloadClient
|
||||
if dc == nil {
|
||||
dc = &http.Client{Timeout: 5 * time.Minute}
|
||||
dc = &http.Client{
|
||||
Transport: netproxy.NewTransport(),
|
||||
CheckRedirect: checkRedirect,
|
||||
}
|
||||
}
|
||||
return &MarketClient{
|
||||
layout: opts.Layout,
|
||||
@@ -238,6 +263,7 @@ func NewMarketClient(opts MarketClientOptions) *MarketClient {
|
||||
httpClient: hc,
|
||||
downloadClient: dc,
|
||||
cacheTTL: ttl,
|
||||
downloadStallTimeout: stallTimeout,
|
||||
allowInsecureLocalhost: opts.AllowInsecureLocalhost,
|
||||
firstParty: opts.FirstParty || isDefaultMarketURLs(urls),
|
||||
}
|
||||
@@ -248,7 +274,7 @@ func NewMarketClient(opts MarketClientOptions) *MarketClient {
|
||||
func (c *MarketClient) LoadIndex(ctx context.Context, forceRefresh bool) (idx MarketIndex, source string, stale bool, fetchErr error) {
|
||||
if !forceRefresh {
|
||||
c.mu.RLock()
|
||||
if c.memIndex != nil && time.Since(c.memLoaded) < c.cacheTTL {
|
||||
if c.memIndex != nil && !c.memStale && time.Since(c.memLoaded) < c.cacheTTL {
|
||||
cp := cloneMarketIndex(*c.memIndex)
|
||||
c.mu.RUnlock()
|
||||
return cp, "cache", false, nil
|
||||
@@ -258,7 +284,7 @@ func (c *MarketClient) LoadIndex(ctx context.Context, forceRefresh bool) (idx Ma
|
||||
|
||||
if len(c.urls) == 0 {
|
||||
if disk, err := c.readDiskCache(); err == nil {
|
||||
c.storeMem(disk, false)
|
||||
c.storeMem(disk, false, false, nil)
|
||||
return disk, "cache", false, nil
|
||||
}
|
||||
return cloneMarketIndex(EmbeddedFallbackMarketIndex), "fallback", false, nil
|
||||
@@ -268,7 +294,7 @@ func (c *MarketClient) LoadIndex(ctx context.Context, forceRefresh bool) (idx Ma
|
||||
for _, u := range c.urls {
|
||||
fetched, err := c.fetchRemoteIndex(ctx, u)
|
||||
if err == nil {
|
||||
c.storeMem(fetched, true)
|
||||
c.storeMem(fetched, true, false, nil)
|
||||
_ = c.writeDiskCache(fetched)
|
||||
return fetched, "remote", false, nil
|
||||
}
|
||||
@@ -277,16 +303,22 @@ func (c *MarketClient) LoadIndex(ctx context.Context, forceRefresh bool) (idx Ma
|
||||
fetchErr = errors.New(strings.Join(errs, "; "))
|
||||
|
||||
// Remote failed: fall back gracefully without overwriting valid caches.
|
||||
c.mu.RLock()
|
||||
// Clear memFetched and memLoaded so stale data never vouches for trust
|
||||
// and subsequent non-forced Browse/Install calls retry immediately once online.
|
||||
c.mu.Lock()
|
||||
c.memStale = true
|
||||
c.memFetched = false
|
||||
c.memFetchErr = fetchErr
|
||||
c.memLoaded = time.Time{}
|
||||
if c.memIndex != nil {
|
||||
cp := cloneMarketIndex(*c.memIndex)
|
||||
c.mu.RUnlock()
|
||||
c.mu.Unlock()
|
||||
return cp, "cache", true, fetchErr
|
||||
}
|
||||
c.mu.RUnlock()
|
||||
c.mu.Unlock()
|
||||
|
||||
if disk, err := c.readDiskCache(); err == nil {
|
||||
c.storeMem(disk, false)
|
||||
c.storeMem(disk, false, true, fetchErr)
|
||||
return disk, "cache", true, fetchErr
|
||||
}
|
||||
return cloneMarketIndex(EmbeddedFallbackMarketIndex), "fallback", true, fetchErr
|
||||
@@ -296,12 +328,21 @@ func (c *MarketClient) LoadIndex(ctx context.Context, forceRefresh bool) (idx Ma
|
||||
// fallback without touching the network, so the GUI can paint at once and
|
||||
// revalidate in the background.
|
||||
func (c *MarketClient) CachedIndex() (idx MarketIndex, source string) {
|
||||
idx, source, _, _ = c.cachedSnapshot()
|
||||
return idx, source
|
||||
}
|
||||
|
||||
func (c *MarketClient) cachedSnapshot() (idx MarketIndex, source string, stale bool, fetchErr error) {
|
||||
c.mu.RLock()
|
||||
if c.memIndex != nil {
|
||||
cp := cloneMarketIndex(*c.memIndex)
|
||||
st := c.memStale
|
||||
fe := c.memFetchErr
|
||||
c.mu.RUnlock()
|
||||
return cp, "cache"
|
||||
return cp, "cache", st, fe
|
||||
}
|
||||
st := c.memStale
|
||||
fe := c.memFetchErr
|
||||
c.mu.RUnlock()
|
||||
if disk, err := c.readDiskCache(); err == nil {
|
||||
c.mu.Lock()
|
||||
@@ -312,26 +353,28 @@ func (c *MarketClient) CachedIndex() (idx MarketIndex, source string) {
|
||||
// Not fetched in this session: leave memLoaded zero so the next
|
||||
// Browse still goes to the network.
|
||||
}
|
||||
st = c.memStale
|
||||
fe = c.memFetchErr
|
||||
c.mu.Unlock()
|
||||
return disk, "cache"
|
||||
return disk, "cache", st, fe
|
||||
}
|
||||
return cloneMarketIndex(EmbeddedFallbackMarketIndex), "fallback"
|
||||
return cloneMarketIndex(EmbeddedFallbackMarketIndex), "fallback", st, fe
|
||||
}
|
||||
|
||||
// Peek is Browse over CachedIndex: no network I/O.
|
||||
func (c *MarketClient) Peek(installed []PluginInfo, opts MarketBrowseOptions) MarketBrowseResult {
|
||||
idx, source := c.CachedIndex()
|
||||
return c.browseIndex(idx, source, false, nil, installed, opts)
|
||||
idx, source, stale, fetchErr := c.cachedSnapshot()
|
||||
return c.browseIndex(idx, source, stale, fetchErr, installed, opts, c.vouches(source, stale))
|
||||
}
|
||||
|
||||
// Browse filters the market index and annotates compatibility, local install
|
||||
// state, available updates, and soft-withdrawal advisories.
|
||||
func (c *MarketClient) Browse(ctx context.Context, installed []PluginInfo, opts MarketBrowseOptions) MarketBrowseResult {
|
||||
idx, source, stale, fetchErr := c.LoadIndex(ctx, opts.ForceRefresh)
|
||||
return c.browseIndex(idx, source, stale, fetchErr, installed, opts)
|
||||
return c.browseIndex(idx, source, stale, fetchErr, installed, opts, c.vouches(source, stale))
|
||||
}
|
||||
|
||||
func (c *MarketClient) browseIndex(idx MarketIndex, source string, stale bool, fetchErr error, installed []PluginInfo, opts MarketBrowseOptions) MarketBrowseResult {
|
||||
func (c *MarketClient) browseIndex(idx MarketIndex, source string, stale bool, fetchErr error, installed []PluginInfo, opts MarketBrowseOptions, vouched bool) MarketBrowseResult {
|
||||
res := MarketBrowseResult{
|
||||
Source: source,
|
||||
Stale: stale,
|
||||
@@ -375,9 +418,9 @@ func (c *MarketClient) browseIndex(idx MarketIndex, source string, stale bool, f
|
||||
if kindFilter != "" && !strings.EqualFold(entry.Kind, kindFilter) {
|
||||
continue
|
||||
}
|
||||
if !c.firstParty && entry.Trust != TrustCommunity {
|
||||
// A third-party index can't vouch for anything, so show the
|
||||
// trust its packages will actually install with.
|
||||
if !vouched && entry.Trust != TrustCommunity {
|
||||
// An index that cannot vouch (third-party or stale cache) must show
|
||||
// the trust its packages will actually install with.
|
||||
entry.Trust = TrustCommunity
|
||||
}
|
||||
compat, incompatReason := CheckMarketCompatibility(entry, c.hostVersion)
|
||||
@@ -484,7 +527,17 @@ func (c *MarketClient) InstallFromMarket(ctx context.Context, mgr *Manager, plug
|
||||
return nil, fmt.Errorf("plugin %s@%s is incompatible with this host: %s", entry.ID, entry.Version, reason)
|
||||
}
|
||||
|
||||
// Validate SHA-256 and download URL before touching the network.
|
||||
// Validate version, archive size, SHA-256, and download URL before touching the network or disk.
|
||||
if entry.Version == "" || strings.TrimSpace(entry.Version) != entry.Version ||
|
||||
strings.ContainsAny(entry.Version, `/\`) || strings.Contains(entry.Version, "..") {
|
||||
return nil, fmt.Errorf("market entry %s has invalid version %q", entry.ID, entry.Version)
|
||||
}
|
||||
if _, err := ParseSemVer(entry.Version); err != nil {
|
||||
return nil, fmt.Errorf("market entry %s has invalid version %q: %w", entry.ID, entry.Version, err)
|
||||
}
|
||||
if entry.SizeBytes < 0 || entry.SizeBytes > maxPluginArchiveBytes {
|
||||
return nil, fmt.Errorf("market entry %s@%s declares invalid archive size %d", entry.ID, entry.Version, entry.SizeBytes)
|
||||
}
|
||||
wantSum := strings.ToLower(strings.TrimSpace(entry.SHA256))
|
||||
if len(wantSum) != 64 {
|
||||
return nil, fmt.Errorf("market entry %s@%s is missing a valid 64-char SHA-256 checksum", entry.ID, entry.Version)
|
||||
@@ -500,7 +553,10 @@ func (c *MarketClient) InstallFromMarket(ctx context.Context, mgr *Manager, plug
|
||||
return nil, err
|
||||
}
|
||||
archiveName := fmt.Sprintf("market-%s-%s.zip", entry.ID, entry.Version)
|
||||
archivePath := filepath.Join(c.layout.TmpDir(), archiveName)
|
||||
archivePath, err := safeJoin(c.layout.TmpDir(), archiveName)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid market archive path for %s@%s: %w", entry.ID, entry.Version, err)
|
||||
}
|
||||
defer func() {
|
||||
_ = os.Remove(archivePath)
|
||||
_ = os.Remove(archivePath + ".part")
|
||||
@@ -509,7 +565,15 @@ func (c *MarketClient) InstallFromMarket(ctx context.Context, mgr *Manager, plug
|
||||
if opts.OnPhase != nil {
|
||||
opts.OnPhase(MarketPhaseDownload)
|
||||
}
|
||||
if _, err := fetch.Resume(ctx, c.downloadClient, entry.DownloadURL, archivePath, entry.SizeBytes, wantSum, opts.OnProgress); err != nil {
|
||||
maxBytes := maxPluginArchiveBytes
|
||||
if entry.SizeBytes > 0 && entry.SizeBytes < maxBytes {
|
||||
maxBytes = entry.SizeBytes
|
||||
}
|
||||
if _, err := fetch.ResumeDirect(ctx, c.downloadClient, entry.DownloadURL, archivePath, entry.SizeBytes, wantSum, opts.OnProgress, fetch.ResumeOptions{
|
||||
BypassDownloader: true,
|
||||
MaxBytes: maxBytes,
|
||||
StallTimeout: c.downloadStallTimeout,
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if opts.OnPhase != nil {
|
||||
@@ -528,29 +592,7 @@ func (c *MarketClient) InstallFromMarket(ctx context.Context, mgr *Manager, plug
|
||||
|
||||
// CheckMarketCompatibility verifies platform and engines constraints before downloading.
|
||||
func CheckMarketCompatibility(entry MarketEntry, hostVersion string) (bool, string) {
|
||||
if len(entry.Platforms) > 0 {
|
||||
cur := runtime.GOOS + "/" + runtime.GOARCH
|
||||
matched := false
|
||||
for _, p := range entry.Platforms {
|
||||
if p == cur || p == "*" {
|
||||
matched = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !matched {
|
||||
return false, fmt.Sprintf("platform %s not supported (requires %s)", cur, strings.Join(entry.Platforms, ", "))
|
||||
}
|
||||
}
|
||||
if entry.Engines.PluginAPI != "" && !MatchesRange(PluginAPIVersion, entry.Engines.PluginAPI) {
|
||||
return false, fmt.Sprintf("requires pluginApi %s (host has %s)", entry.Engines.PluginAPI, PluginAPIVersion)
|
||||
}
|
||||
if entry.Engines.UIAPI != "" && !MatchesRange(UIAPIVersion, entry.Engines.UIAPI) {
|
||||
return false, fmt.Sprintf("requires uiApi %s (host has %s)", entry.Engines.UIAPI, UIAPIVersion)
|
||||
}
|
||||
if hostVersion != "" && entry.Engines.ReimsGo != "" && !MatchesRange(hostVersion, entry.Engines.ReimsGo) {
|
||||
return false, fmt.Sprintf("requires reims-go %s (host has %s)", entry.Engines.ReimsGo, hostVersion)
|
||||
}
|
||||
return true, ""
|
||||
return checkHostCompatibility(entry.Platforms, entry.Engines, hostVersion)
|
||||
}
|
||||
|
||||
func (c *MarketClient) fetchRemoteIndex(ctx context.Context, rawURL string) (MarketIndex, error) {
|
||||
@@ -590,6 +632,10 @@ func (c *MarketClient) fetchRemoteIndex(ctx context.Context, rawURL string) (Mar
|
||||
}
|
||||
|
||||
func (c *MarketClient) validateDownloadURL(rawURL string) error {
|
||||
return validateMarketURL(rawURL, c.allowInsecureLocalhost)
|
||||
}
|
||||
|
||||
func validateMarketURL(rawURL string, allowInsecureLocalhost bool) error {
|
||||
u, err := url.Parse(strings.TrimSpace(rawURL))
|
||||
if err != nil || u.Host == "" {
|
||||
return errors.New("malformed URL")
|
||||
@@ -598,7 +644,7 @@ func (c *MarketClient) validateDownloadURL(rawURL string) error {
|
||||
case "https":
|
||||
return nil
|
||||
case "http":
|
||||
if c.allowInsecureLocalhost {
|
||||
if allowInsecureLocalhost {
|
||||
host := strings.ToLower(u.Hostname())
|
||||
if host == "127.0.0.1" || host == "localhost" || host == "::1" {
|
||||
return nil
|
||||
@@ -610,12 +656,18 @@ func (c *MarketClient) validateDownloadURL(rawURL string) error {
|
||||
}
|
||||
}
|
||||
|
||||
func (c *MarketClient) storeMem(idx MarketIndex, fetched bool) {
|
||||
func (c *MarketClient) storeMem(idx MarketIndex, fetched, stale bool, fetchErr error) {
|
||||
cp := cloneMarketIndex(idx)
|
||||
c.mu.Lock()
|
||||
c.memIndex = &cp
|
||||
c.memLoaded = time.Now()
|
||||
c.memFetched = fetched
|
||||
if stale {
|
||||
c.memLoaded = time.Time{}
|
||||
} else {
|
||||
c.memLoaded = time.Now()
|
||||
}
|
||||
c.memFetched = fetched && !stale
|
||||
c.memStale = stale
|
||||
c.memFetchErr = fetchErr
|
||||
c.mu.Unlock()
|
||||
}
|
||||
|
||||
@@ -644,19 +696,36 @@ func (c *MarketClient) writeDiskCache(idx MarketIndex) error {
|
||||
if c.layout.Root == "" {
|
||||
return nil
|
||||
}
|
||||
c.diskCacheMu.Lock()
|
||||
defer c.diskCacheMu.Unlock()
|
||||
cachePath := c.layout.IndexCachePath()
|
||||
if err := os.MkdirAll(filepath.Dir(cachePath), 0o755); err != nil {
|
||||
dir := filepath.Dir(cachePath)
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
raw, err := json.MarshalIndent(idx, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmp := cachePath + ".tmp"
|
||||
if err := os.WriteFile(tmp, raw, 0o644); err != nil {
|
||||
tmpFile, err := os.CreateTemp(dir, "index-cache-*.tmp")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmp, cachePath)
|
||||
tmpPath := tmpFile.Name()
|
||||
if _, err := tmpFile.Write(raw); err != nil {
|
||||
_ = tmpFile.Close()
|
||||
_ = os.Remove(tmpPath)
|
||||
return err
|
||||
}
|
||||
if err := tmpFile.Close(); err != nil {
|
||||
_ = os.Remove(tmpPath)
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(tmpPath, cachePath); err != nil {
|
||||
_ = os.Remove(tmpPath)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func selectChannelEntries(entries []MarketEntry, includeAlpha bool) map[string]MarketEntry {
|
||||
@@ -702,6 +771,16 @@ func marketEntryMatchesQuery(e MarketEntry, q string) bool {
|
||||
strings.Contains(strings.ToLower(e.Description.EnUS), q) {
|
||||
return true
|
||||
}
|
||||
for _, v := range e.Name.Extra {
|
||||
if strings.Contains(strings.ToLower(v), q) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
for _, v := range e.Description.Extra {
|
||||
if strings.Contains(strings.ToLower(v), q) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
for _, tag := range e.Tags {
|
||||
if strings.Contains(strings.ToLower(tag), q) {
|
||||
return true
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/downloader"
|
||||
"github.com/Nwflower/reims-go/internal/fetch"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
)
|
||||
@@ -272,3 +273,231 @@ func TestMarketBrowseAndInstallGates(t *testing.T) {
|
||||
t.Fatalf("unexpected installed info: %+v", info)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckMarketCompatibilityUnified(t *testing.T) {
|
||||
base := plugin.MarketEntry{
|
||||
ID: "community.theme.compat",
|
||||
Version: "1.0.0",
|
||||
Engines: plugin.Engines{PluginAPI: "^1.0.0", UIAPI: "^2.0.0", BridgeAPI: "^1.0.0", ReimsGo: ">=0.2.10"},
|
||||
}
|
||||
for _, plats := range [][]string{nil, {"*"}, {"any"}, {"ANY"}, {"windows-x64", "linux-x64", "darwin-arm64", "darwin-x64"}, {"windows/amd64", "linux/amd64", "darwin/arm64", "darwin/amd64"}} {
|
||||
e := base
|
||||
e.Platforms = plats
|
||||
if ok, reason := plugin.CheckMarketCompatibility(e, "0.2.11"); !ok {
|
||||
t.Fatalf("platforms=%v expected compatible, got: %s", plats, reason)
|
||||
}
|
||||
}
|
||||
// Dev host builds skip engines.reims-go just like ValidateManifest.
|
||||
if ok, reason := plugin.CheckMarketCompatibility(base, "dev"); !ok {
|
||||
t.Fatalf("dev host expected compatible, got: %s", reason)
|
||||
}
|
||||
// Unsupported platform rejected.
|
||||
badPlat := base
|
||||
badPlat.Platforms = []string{"solaris-sparc"}
|
||||
if ok, _ := plugin.CheckMarketCompatibility(badPlat, "0.2.11"); ok {
|
||||
t.Fatal("expected unsupported platform to be incompatible")
|
||||
}
|
||||
// Incompatible bridgeApi rejected before download.
|
||||
badBridge := base
|
||||
badBridge.Engines.BridgeAPI = "^9.0.0"
|
||||
if ok, reason := plugin.CheckMarketCompatibility(badBridge, "0.2.11"); ok || !strings.Contains(reason, "bridgeApi") {
|
||||
t.Fatalf("expected bridgeApi incompatibility, got ok=%v reason=%q", ok, reason)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMarketSecurityGatesSearchExtraAndConcurrentCache(t *testing.T) {
|
||||
var srvURL string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/index.json":
|
||||
idx := plugin.MarketIndex{
|
||||
Schema: 1,
|
||||
UpdatedAt: "2026-12-02T00:00:00Z",
|
||||
Plugins: []plugin.MarketEntry{
|
||||
{
|
||||
ID: "evil.theme.traversal",
|
||||
Version: "../../escape",
|
||||
Channel: "stable",
|
||||
Kind: "theme",
|
||||
Trust: plugin.TrustCommunity,
|
||||
Name: plugin.LocalizedText{EnUS: "Traversal"},
|
||||
DownloadURL: srvURL + "/pkg.zip",
|
||||
SHA256: strings.Repeat("a", 64),
|
||||
},
|
||||
{
|
||||
ID: "evil.theme.spacesver",
|
||||
Version: " 1.0.0 ",
|
||||
Channel: "stable",
|
||||
Kind: "theme",
|
||||
Trust: plugin.TrustCommunity,
|
||||
Name: plugin.LocalizedText{EnUS: "Spaces Version"},
|
||||
DownloadURL: srvURL + "/pkg.zip",
|
||||
SHA256: strings.Repeat("a", 64),
|
||||
},
|
||||
{
|
||||
ID: "evil.theme.oversize-body",
|
||||
Version: "1.0.0",
|
||||
Channel: "stable",
|
||||
Kind: "theme",
|
||||
Trust: plugin.TrustCommunity,
|
||||
Name: plugin.LocalizedText{EnUS: "Oversize Body"},
|
||||
DownloadURL: srvURL + "/oversize.zip",
|
||||
SHA256: strings.Repeat("e", 64),
|
||||
SizeBytes: 64,
|
||||
},
|
||||
{
|
||||
ID: "evil.theme.stall",
|
||||
Version: "1.0.0",
|
||||
Channel: "stable",
|
||||
Kind: "theme",
|
||||
Trust: plugin.TrustCommunity,
|
||||
Name: plugin.LocalizedText{EnUS: "Stall"},
|
||||
DownloadURL: srvURL + "/stall.zip",
|
||||
SHA256: strings.Repeat("f", 64),
|
||||
SizeBytes: 0,
|
||||
},
|
||||
{
|
||||
ID: "evil.theme.huge",
|
||||
Version: "1.0.0",
|
||||
Channel: "stable",
|
||||
Kind: "theme",
|
||||
Trust: plugin.TrustCommunity,
|
||||
Name: plugin.LocalizedText{EnUS: "Huge"},
|
||||
DownloadURL: srvURL + "/pkg.zip",
|
||||
SHA256: strings.Repeat("b", 64),
|
||||
SizeBytes: 1 << 30,
|
||||
},
|
||||
{
|
||||
ID: "evil.theme.downgrade",
|
||||
Version: "1.0.0",
|
||||
Channel: "stable",
|
||||
Kind: "theme",
|
||||
Trust: plugin.TrustCommunity,
|
||||
Name: plugin.LocalizedText{EnUS: "Downgrade"},
|
||||
DownloadURL: srvURL + "/redirect-http",
|
||||
SHA256: strings.Repeat("c", 64),
|
||||
},
|
||||
{
|
||||
ID: "community.locale.ja",
|
||||
Version: "1.0.0",
|
||||
Channel: "stable",
|
||||
Kind: "locale",
|
||||
Trust: plugin.TrustCommunity,
|
||||
Name: plugin.LocalizedText{
|
||||
EnUS: "Japanese Pack",
|
||||
Extra: map[string]string{"ja-JP": "日本語パック"},
|
||||
},
|
||||
Description: plugin.LocalizedText{
|
||||
EnUS: "UI translation",
|
||||
Extra: map[string]string{"ko-KR": "한국어 설명"},
|
||||
},
|
||||
DownloadURL: srvURL + "/pkg.zip",
|
||||
SHA256: strings.Repeat("d", 64),
|
||||
},
|
||||
},
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(idx)
|
||||
case "/redirect-http":
|
||||
http.Redirect(w, r, "http://example.com/downgraded.zip", http.StatusFound)
|
||||
case "/oversize.zip":
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(strings.Repeat("Z", 1024)))
|
||||
case "/stall.zip":
|
||||
fl, _ := w.(http.Flusher)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte("slow"))
|
||||
if fl != nil {
|
||||
fl.Flush()
|
||||
}
|
||||
<-r.Context().Done()
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
srvURL = srv.URL
|
||||
|
||||
mgr, err := plugin.NewManager(plugin.ManagerOptions{DataRoot: t.TempDir(), HostVersion: "0.2.11"})
|
||||
if err != nil {
|
||||
t.Fatalf("NewManager: %v", err)
|
||||
}
|
||||
defer mgr.Close()
|
||||
|
||||
mc := plugin.NewMarketClient(plugin.MarketClientOptions{
|
||||
Layout: mgr.Layout(),
|
||||
HostVersion: "0.2.11",
|
||||
URLs: []string{srvURL + "/index.json"},
|
||||
DownloadStallTimeout: 150 * time.Millisecond,
|
||||
AllowInsecureLocalhost: true,
|
||||
})
|
||||
|
||||
// Register default ParallelDownloader (matching desktop app startup) to
|
||||
// prove market downloads bypass it and still enforce CheckRedirect & MaxBytes.
|
||||
parallel := downloader.NewParallelDownloader(func() downloader.ParallelOptions {
|
||||
return downloader.ParallelOptions{ID: "builtin.downloader.parallel", Connections: 2, ProxyMode: "direct"}
|
||||
})
|
||||
fetch.SetDefaultDownloader(func() downloader.Provider { return parallel })
|
||||
t.Cleanup(func() { fetch.SetDefaultDownloader(nil) })
|
||||
|
||||
// 1. Path traversal or surrounding whitespace in entry.Version must be rejected.
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "evil.theme.traversal", plugin.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "invalid version") {
|
||||
t.Fatalf("expected invalid version error for traversal, got: %v", err)
|
||||
}
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "evil.theme.spacesver", plugin.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "invalid version") {
|
||||
t.Fatalf("expected invalid version error for whitespace version, got: %v", err)
|
||||
}
|
||||
|
||||
// 2. Oversized declared SizeBytes and oversized actual stream must both be rejected.
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "evil.theme.huge", plugin.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "invalid archive size") {
|
||||
t.Fatalf("expected invalid archive size error, got: %v", err)
|
||||
}
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "evil.theme.oversize-body", plugin.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "exceeds 64 byte limit") {
|
||||
t.Fatalf("expected actual stream byte limit error, got: %v", err)
|
||||
}
|
||||
|
||||
// 3. Stalled market stream aborts via DownloadStallTimeout.
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "evil.theme.stall", plugin.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "stalled") {
|
||||
t.Fatalf("expected stalled error, got: %v", err)
|
||||
}
|
||||
|
||||
// 4. Redirect to non-localhost plain HTTP must still be blocked even with ParallelDownloader active.
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "evil.theme.downgrade", plugin.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "only HTTPS") {
|
||||
t.Fatalf("expected HTTPS-only redirect refusal with active ParallelDownloader, got: %v", err)
|
||||
}
|
||||
|
||||
// 4. Market search matches localized Name.Extra and Description.Extra.
|
||||
resName := mc.Browse(context.Background(), nil, plugin.MarketBrowseOptions{Query: "日本語"})
|
||||
if len(resName.Items) != 1 || resName.Items[0].Entry.ID != "community.locale.ja" {
|
||||
t.Fatalf("expected Name.Extra search match, got %+v", resName.Items)
|
||||
}
|
||||
resDesc := mc.Browse(context.Background(), nil, plugin.MarketBrowseOptions{Query: "한국어"})
|
||||
if len(resDesc.Items) != 1 || resDesc.Items[0].Entry.ID != "community.locale.ja" {
|
||||
t.Fatalf("expected Description.Extra search match, got %+v", resDesc.Items)
|
||||
}
|
||||
|
||||
// 5. Concurrent force refreshes writing disk cache must not race or corrupt cache JSON.
|
||||
done := make(chan error, 8)
|
||||
for i := 0; i < 8; i++ {
|
||||
go func() {
|
||||
_, src, stale, ferr := mc.LoadIndex(context.Background(), true)
|
||||
if ferr != nil || src != "remote" || stale {
|
||||
done <- ferr
|
||||
return
|
||||
}
|
||||
done <- nil
|
||||
}()
|
||||
}
|
||||
for i := 0; i < 8; i++ {
|
||||
if err := <-done; err != nil {
|
||||
t.Fatalf("concurrent LoadIndex error: %v", err)
|
||||
}
|
||||
}
|
||||
raw, err := os.ReadFile(mgr.Layout().IndexCachePath())
|
||||
if err != nil {
|
||||
t.Fatalf("read disk cache: %v", err)
|
||||
}
|
||||
var cached plugin.MarketIndex
|
||||
if err := json.Unmarshal(raw, &cached); err != nil || len(cached.Plugins) != 7 {
|
||||
t.Fatalf("corrupted disk cache after concurrent writes: err=%v len=%d", err, len(cached.Plugins))
|
||||
}
|
||||
}
|
||||
+226
-57
@@ -140,6 +140,9 @@ func ValidateManifest(m Manifest, hostVersion string, isBuiltinOrBundled bool) e
|
||||
if !isBuiltinOrBundled && strings.HasPrefix(m.ID, "builtin.") {
|
||||
return fmt.Errorf("plugin id %q uses reserved builtin. namespace", m.ID)
|
||||
}
|
||||
if m.Version == "" || strings.TrimSpace(m.Version) != m.Version {
|
||||
return fmt.Errorf("invalid plugin version %q: must not contain surrounding whitespace", m.Version)
|
||||
}
|
||||
if _, err := ParseSemVer(m.Version); err != nil {
|
||||
return fmt.Errorf("invalid plugin version %q: %w", m.Version, err)
|
||||
}
|
||||
@@ -152,33 +155,8 @@ func ValidateManifest(m Manifest, hostVersion string, isBuiltinOrBundled bool) e
|
||||
if bad := ForbiddenPermissions(m.Permissions); len(bad) > 0 {
|
||||
return fmt.Errorf("plugin requests forbidden or unknown permissions: %s", strings.Join(bad, ", "))
|
||||
}
|
||||
if reqAPI := strings.TrimSpace(m.Engines.PluginAPI); reqAPI != "" {
|
||||
if !MatchesRange(PluginAPIVersion, reqAPI) {
|
||||
return fmt.Errorf("incompatible pluginApi: plugin requires %s, host provides %s", reqAPI, PluginAPIVersion)
|
||||
}
|
||||
}
|
||||
if reqUI := strings.TrimSpace(m.Engines.UIAPI); reqUI != "" {
|
||||
if !MatchesRange(UIAPIVersion, reqUI) {
|
||||
return fmt.Errorf("incompatible uiApi: plugin requires %s, host provides %s", reqUI, UIAPIVersion)
|
||||
}
|
||||
}
|
||||
if reqHost := strings.TrimSpace(m.Engines.ReimsGo); reqHost != "" && hostVersion != "" && hostVersion != "dev" {
|
||||
if !MatchesRange(hostVersion, reqHost) {
|
||||
return fmt.Errorf("incompatible reims-go version: plugin requires %s, host is %s", reqHost, hostVersion)
|
||||
}
|
||||
}
|
||||
if len(m.Platforms) > 0 {
|
||||
curPlat := currentPlatformTag()
|
||||
matched := false
|
||||
for _, p := range m.Platforms {
|
||||
if strings.EqualFold(p, curPlat) || p == "*" || strings.EqualFold(p, "any") {
|
||||
matched = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !matched {
|
||||
return fmt.Errorf("plugin does not support platform %s (supported: %s)", curPlat, strings.Join(m.Platforms, ", "))
|
||||
}
|
||||
if compat, reason := checkHostCompatibility(m.Platforms, m.Engines, hostVersion); !compat {
|
||||
return errors.New(reason)
|
||||
}
|
||||
if len(m.Contributes.Runtimes) > 0 {
|
||||
if m.Provenance == nil || strings.TrimSpace(m.Provenance.SourcePackage) == "" || strings.TrimSpace(m.License) == "" {
|
||||
@@ -623,25 +601,10 @@ func InstallArchive(layout PluginsLayout, archivePath string, opts PackageInstal
|
||||
trust = opts.IndexTrust
|
||||
}
|
||||
|
||||
// Validate entry file existence and compute entry hash for high-risk display.
|
||||
entryRel := m.Entry.Sidecar
|
||||
if entryRel == "" {
|
||||
entryRel = m.Entry.UIScript
|
||||
}
|
||||
if entryRel == "" {
|
||||
entryRel = m.Entry.Script
|
||||
}
|
||||
var entryHash string
|
||||
if entryRel != "" {
|
||||
entryFull, err := safeJoin(stageDir, entryRel)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid entry path %q: %w", entryRel, err)
|
||||
}
|
||||
h, err := fileSHA256Hex(entryFull)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("entry file %q missing: %w", entryRel, err)
|
||||
}
|
||||
entryHash = h
|
||||
// Validate entry file(s) existence and compute entry hash for high-risk display and approval pinning.
|
||||
entryRel, _, entryHash, err := resolveManifestEntry(m, stageDir, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := validateDiskContributions(m, stageDir); err != nil {
|
||||
@@ -720,9 +683,194 @@ var (
|
||||
reCSSVar = regexp.MustCompile(`var\(\s*(--[a-zA-Z0-9_-]+)`)
|
||||
)
|
||||
|
||||
// matchesCurrentPlatform reports whether platforms includes the current host
|
||||
// platform (accepting both "windows-x64" and "windows/amd64" forms as well as
|
||||
// "*" and "any", case-insensitively). An empty slice matches all platforms.
|
||||
func matchesCurrentPlatform(platforms []string) bool {
|
||||
if len(platforms) == 0 {
|
||||
return true
|
||||
}
|
||||
curTag := currentPlatformTag()
|
||||
curPair := runtime.GOOS + "/" + runtime.GOARCH
|
||||
for _, p := range platforms {
|
||||
p = strings.TrimSpace(p)
|
||||
if p == "*" || strings.EqualFold(p, "any") || strings.EqualFold(p, curTag) || strings.EqualFold(p, curPair) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// checkHostCompatibility is the shared platform and engines gate used by both
|
||||
// market pre-download checks and manifest installation validation.
|
||||
func checkHostCompatibility(platforms []string, engines Engines, hostVersion string) (bool, string) {
|
||||
if !matchesCurrentPlatform(platforms) {
|
||||
return false, fmt.Sprintf("platform %s not supported (requires %s)", currentPlatformTag(), strings.Join(platforms, ", "))
|
||||
}
|
||||
if reqAPI := strings.TrimSpace(engines.PluginAPI); reqAPI != "" && !MatchesRange(PluginAPIVersion, reqAPI) {
|
||||
return false, fmt.Sprintf("incompatible pluginApi: requires %s (host has %s)", reqAPI, PluginAPIVersion)
|
||||
}
|
||||
if reqUI := strings.TrimSpace(engines.UIAPI); reqUI != "" && !MatchesRange(UIAPIVersion, reqUI) {
|
||||
return false, fmt.Sprintf("incompatible uiApi: requires %s (host has %s)", reqUI, UIAPIVersion)
|
||||
}
|
||||
if reqBridge := strings.TrimSpace(engines.BridgeAPI); reqBridge != "" && !MatchesRange(BridgeAPIVersion, reqBridge) {
|
||||
return false, fmt.Sprintf("incompatible bridgeApi: requires %s (host has %s)", reqBridge, BridgeAPIVersion)
|
||||
}
|
||||
if reqHost := strings.TrimSpace(engines.ReimsGo); reqHost != "" && hostVersion != "" && hostVersion != "dev" && !MatchesRange(hostVersion, reqHost) {
|
||||
return false, fmt.Sprintf("incompatible reims-go: requires %s (host has %s)", reqHost, hostVersion)
|
||||
}
|
||||
return true, ""
|
||||
}
|
||||
|
||||
// collectApprovalEntryPaths returns the primary executable/script entry path
|
||||
// (preserving Sidecar first for L3 activation) and all deduplicated executable
|
||||
// or UI script entry paths that must be covered by approval hash pinning.
|
||||
func collectApprovalEntryPaths(m Manifest) (primary string, all []string) {
|
||||
seen := map[string]bool{}
|
||||
add := func(rel string) {
|
||||
rel = normalizeRel(rel)
|
||||
if rel == "" || seen[rel] {
|
||||
return
|
||||
}
|
||||
seen[rel] = true
|
||||
if primary == "" {
|
||||
primary = rel
|
||||
}
|
||||
all = append(all, rel)
|
||||
}
|
||||
add(m.Entry.Sidecar)
|
||||
add(m.Entry.Script)
|
||||
for _, p := range collectUIScriptPaths(m) {
|
||||
add(p)
|
||||
}
|
||||
return primary, all
|
||||
}
|
||||
|
||||
// resolveManifestEntry resolves the primary entry file path and computes the
|
||||
// approval SHA-256 digest covering all executable / UI script entries.
|
||||
// For a single entry file, the digest is the raw file SHA-256 (matching L3
|
||||
// sidecar hashes and sha256sum output). For multiple entries, it computes a
|
||||
// deterministic composite SHA-256 over sorted "<rel>:<hex>\n" lines.
|
||||
func resolveManifestEntry(m Manifest, rootDir string, requireFiles bool) (primaryRel, primaryAbs, entryHash string, err error) {
|
||||
primaryRel, allRels := collectApprovalEntryPaths(m)
|
||||
if len(allRels) == 0 {
|
||||
return "", "", "", nil
|
||||
}
|
||||
primaryAbs, err = safeJoin(rootDir, primaryRel)
|
||||
if err != nil {
|
||||
return "", "", "", fmt.Errorf("invalid entry path %q: %w", primaryRel, err)
|
||||
}
|
||||
if len(allRels) == 1 {
|
||||
h, hErr := fileSHA256Hex(primaryAbs)
|
||||
if hErr != nil {
|
||||
if requireFiles {
|
||||
return "", "", "", fmt.Errorf("entry file %q missing: %w", primaryRel, hErr)
|
||||
}
|
||||
return primaryRel, primaryAbs, "", nil
|
||||
}
|
||||
return primaryRel, primaryAbs, h, nil
|
||||
}
|
||||
sorted := append([]string(nil), allRels...)
|
||||
sort.Strings(sorted)
|
||||
agg := sha256.New()
|
||||
for _, rel := range sorted {
|
||||
full, jErr := safeJoin(rootDir, rel)
|
||||
if jErr != nil {
|
||||
return "", "", "", fmt.Errorf("invalid entry path %q: %w", rel, jErr)
|
||||
}
|
||||
h, hErr := fileSHA256Hex(full)
|
||||
if hErr != nil {
|
||||
if requireFiles {
|
||||
return "", "", "", fmt.Errorf("entry file %q missing: %w", rel, hErr)
|
||||
}
|
||||
return primaryRel, primaryAbs, "", nil
|
||||
}
|
||||
_, _ = fmt.Fprintf(agg, "%s:%s\n", rel, h)
|
||||
}
|
||||
return primaryRel, primaryAbs, hex.EncodeToString(agg.Sum(nil)), nil
|
||||
}
|
||||
|
||||
// stripCSSNonCode replaces CSS comments, quoted strings, and url(...) arguments
|
||||
// with spaces so contract selector/variable regexes never match inside comments
|
||||
// or asset filenames (such as /* studio.js */ or url(assets/bg.png)).
|
||||
func stripCSSNonCode(css string) string {
|
||||
var b strings.Builder
|
||||
b.Grow(len(css))
|
||||
n := len(css)
|
||||
i := 0
|
||||
|
||||
skipComment := func() bool {
|
||||
if i+1 >= n || css[i] != '/' || css[i+1] != '*' {
|
||||
return false
|
||||
}
|
||||
end := strings.Index(css[i+2:], "*/")
|
||||
if end < 0 {
|
||||
i = n
|
||||
return true
|
||||
}
|
||||
i += 2 + end + 2
|
||||
return true
|
||||
}
|
||||
|
||||
skipQuoted := func() bool {
|
||||
if i >= n || (css[i] != '"' && css[i] != '\'') {
|
||||
return false
|
||||
}
|
||||
q := css[i]
|
||||
i++
|
||||
for i < n {
|
||||
if css[i] == '\\' && i+1 < n {
|
||||
if css[i+1] == '\r' && i+2 < n && css[i+2] == '\n' {
|
||||
i += 3
|
||||
continue
|
||||
}
|
||||
i += 2
|
||||
continue
|
||||
}
|
||||
if css[i] == q || css[i] == '\n' || css[i] == '\r' {
|
||||
i++
|
||||
break
|
||||
}
|
||||
i++
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
for i < n {
|
||||
if skipComment() || skipQuoted() {
|
||||
b.WriteByte(' ')
|
||||
continue
|
||||
}
|
||||
// url(...) function (case-insensitive, not part of a longer identifier)
|
||||
if i+4 <= n && strings.EqualFold(css[i:i+4], "url(") && (i == 0 || !isCSSIdentChar(css[i-1])) {
|
||||
b.WriteString("url()")
|
||||
i += 4
|
||||
for i < n {
|
||||
if skipComment() || skipQuoted() {
|
||||
continue
|
||||
}
|
||||
if css[i] == '\\' && i+1 < n {
|
||||
i += 2
|
||||
continue
|
||||
}
|
||||
if css[i] == ')' {
|
||||
i++
|
||||
break
|
||||
}
|
||||
i++
|
||||
}
|
||||
continue
|
||||
}
|
||||
b.WriteByte(css[i])
|
||||
i++
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// CheckCSSAgainstContract verifies that a theme stylesheet only references
|
||||
// contract part classes (`rg-p-*`) and contract design tokens (§5.1).
|
||||
func CheckCSSAgainstContract(css string, contract UIContract) []string {
|
||||
cleaned := stripCSSNonCode(css)
|
||||
partSet := make(map[string]bool, len(contract.Parts))
|
||||
for _, p := range contract.Parts {
|
||||
partSet[p] = true
|
||||
@@ -737,7 +885,7 @@ func CheckCSSAgainstContract(css string, contract UIContract) []string {
|
||||
}
|
||||
var issues []string
|
||||
seen := map[string]bool{}
|
||||
for _, m := range reCSSClass.FindAllStringSubmatch(css, -1) {
|
||||
for _, m := range reCSSClass.FindAllStringSubmatch(cleaned, -1) {
|
||||
cls := m[1]
|
||||
if !partSet[cls] && !seen["cls:"+cls] {
|
||||
seen["cls:"+cls] = true
|
||||
@@ -748,7 +896,7 @@ func CheckCSSAgainstContract(css string, contract UIContract) []string {
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, m := range reCSSVar.FindAllStringSubmatch(css, -1) {
|
||||
for _, m := range reCSSVar.FindAllStringSubmatch(cleaned, -1) {
|
||||
v := m[1]
|
||||
if !tokenSet[v] && !strings.HasPrefix(v, "--theme-") && !seen["var:"+v] {
|
||||
seen["var:"+v] = true
|
||||
@@ -759,6 +907,8 @@ func CheckCSSAgainstContract(css string, contract UIContract) []string {
|
||||
return issues
|
||||
}
|
||||
|
||||
const maxPluginArchiveBytes = int64(512 << 20)
|
||||
|
||||
func extractPluginZip(archivePath, destDir string) error {
|
||||
r, err := zip.OpenReader(archivePath)
|
||||
if err != nil {
|
||||
@@ -768,7 +918,7 @@ func extractPluginZip(archivePath, destDir string) error {
|
||||
const (
|
||||
maxZipFiles = 2048
|
||||
maxZipFileBytes = int64(256 << 20)
|
||||
maxZipTotalBytes = int64(512 << 20)
|
||||
maxZipTotalBytes = maxPluginArchiveBytes
|
||||
)
|
||||
if len(r.File) > maxZipFiles {
|
||||
return fmt.Errorf("plugin zip exceeds maximum file count (%d)", maxZipFiles)
|
||||
@@ -848,17 +998,36 @@ func checkMarketRedlines(root string) error {
|
||||
|
||||
func verifyDirSHA256Sums(root string, sumsRaw []byte) error {
|
||||
expected := make(map[string]string)
|
||||
for _, line := range strings.Split(string(sumsRaw), "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" || strings.HasPrefix(line, "#") {
|
||||
for _, rawLine := range strings.Split(string(sumsRaw), "\n") {
|
||||
line := strings.TrimRight(rawLine, "\r")
|
||||
trimmed := strings.TrimLeft(line, " \t")
|
||||
if trimmed == "" || strings.HasPrefix(trimmed, "#") {
|
||||
continue
|
||||
}
|
||||
fields := strings.Fields(line)
|
||||
if len(fields) < 2 {
|
||||
return fmt.Errorf("malformed SHA256SUMS line: %q", line)
|
||||
if len(trimmed) < 66 {
|
||||
return fmt.Errorf("malformed SHA256SUMS line: %q", strings.TrimSpace(line))
|
||||
}
|
||||
rel := filepath.ToSlash(strings.TrimPrefix(fields[1], "./"))
|
||||
expected[rel] = strings.ToLower(fields[0])
|
||||
hashHex := strings.ToLower(trimmed[:64])
|
||||
if _, err := hex.DecodeString(hashHex); err != nil {
|
||||
return fmt.Errorf("malformed SHA256SUMS line: %q", strings.TrimSpace(line))
|
||||
}
|
||||
rest := trimmed[64:]
|
||||
switch {
|
||||
case strings.HasPrefix(rest, " "), strings.HasPrefix(rest, " *"):
|
||||
rest = rest[2:]
|
||||
case strings.HasPrefix(rest, " "), strings.HasPrefix(rest, "\t"):
|
||||
rest = rest[1:]
|
||||
default:
|
||||
return fmt.Errorf("malformed SHA256SUMS line: %q", strings.TrimSpace(line))
|
||||
}
|
||||
if rest == "" || strings.ContainsRune(rest, '\\') {
|
||||
return fmt.Errorf("malformed SHA256SUMS line: %q", strings.TrimSpace(line))
|
||||
}
|
||||
rel := strings.TrimPrefix(rest, "./")
|
||||
if _, dup := expected[rel]; dup {
|
||||
return fmt.Errorf("duplicate SHA256SUMS entry: %s", rel)
|
||||
}
|
||||
expected[rel] = hashHex
|
||||
}
|
||||
if len(expected) == 0 {
|
||||
return errors.New("SHA256SUMS is empty")
|
||||
|
||||
@@ -804,6 +804,47 @@ func (r *Registry) Themes() []ThemeContribution {
|
||||
return out
|
||||
}
|
||||
|
||||
// PluginOwnsTheme reports whether pluginID declares or currently registers
|
||||
// themeID. Works even when external plugins are not activated (e.g. safe mode).
|
||||
func (r *Registry) PluginOwnsTheme(pluginID, themeID string) bool {
|
||||
if pluginID == "" || themeID == "" {
|
||||
return false
|
||||
}
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
if th, ok := r.themes[themeID]; ok && th.PluginID == pluginID {
|
||||
return true
|
||||
}
|
||||
if e, ok := r.entries[pluginID]; ok {
|
||||
for _, th := range e.def.Manifest.Contributes.Themes {
|
||||
if th.ID == themeID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ThemeOwner returns the plugin ID that registers or declares themeID, or "".
|
||||
func (r *Registry) ThemeOwner(themeID string) string {
|
||||
if themeID == "" {
|
||||
return ""
|
||||
}
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
if th, ok := r.themes[themeID]; ok && th.PluginID != "" {
|
||||
return th.PluginID
|
||||
}
|
||||
for pid, e := range r.entries {
|
||||
for _, th := range e.def.Manifest.Contributes.Themes {
|
||||
if th.ID == themeID {
|
||||
return pid
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (r *Registry) RegisterUIScript(sc *Scope, us UIScriptContribution) {
|
||||
if us.ID == "" {
|
||||
return
|
||||
|
||||
@@ -518,7 +518,8 @@ func ScanDirectory(dir, hostVersion string, opts ScanOptions) ScanReport {
|
||||
EnUS: "This plugin ships a native executable (L3 Sidecar) that runs with full current Windows user privileges. Static scanning verifies manifest integrity and hashes only and cannot prove native binary safety; verify publisher provenance and SHA-256 before enabling.",
|
||||
}
|
||||
}
|
||||
rep.NeedsApproval = computeNeedsApproval(m, rep.Trust, nil, "", firstDeclaredExecHash(rep.Executables))
|
||||
_, _, entryHash, _ := resolveManifestEntry(m, dir, false)
|
||||
rep.NeedsApproval = computeNeedsApproval(m, rep.Trust, nil, "", entryHash)
|
||||
|
||||
finalizeScanReport(&rep)
|
||||
return rep
|
||||
@@ -852,7 +853,10 @@ func describePermission(perm string) (LocalizedText, LocalizedText) {
|
||||
switch perm {
|
||||
case "ui:script":
|
||||
return LocalizedText{ZhCN: "运行交互主题脚本", EnUS: "Run interactive theme script"},
|
||||
LocalizedText{ZhCN: "在受限主题沙盒中执行前端脚本以呈现动态主题效果。", EnUS: "Executes frontend script inside the theme sandbox for interactive visuals."}
|
||||
LocalizedText{
|
||||
ZhCN: "在主窗口前端环境中运行交互脚本并访问界面 DOM(非隔离沙盒),启用前务必核对来源与脚本哈希。",
|
||||
EnUS: "Runs frontend JavaScript in the main window with DOM access (not an isolated sandbox); verify publisher and script hash before enabling.",
|
||||
}
|
||||
case "driver:vm":
|
||||
return LocalizedText{ZhCN: "提供虚拟机客体驱动", EnUS: "Provide VM guest driver"},
|
||||
LocalizedText{ZhCN: "创建、配置并驱动新的虚拟机客体类型。", EnUS: "Creates, configures, and drives guest virtual machine lifecycles."}
|
||||
@@ -984,15 +988,6 @@ func isRedlineTextExt(ext string) bool {
|
||||
}
|
||||
}
|
||||
|
||||
func firstDeclaredExecHash(execs []ExecutableFile) string {
|
||||
for _, e := range execs {
|
||||
if e.Declared && e.SHA256 != "" {
|
||||
return e.SHA256
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func maxInt(a, b int) int {
|
||||
if a > b {
|
||||
return a
|
||||
|
||||
@@ -243,3 +243,109 @@ func TestScanArchiveSignedOfficialTrust(t *testing.T) {
|
||||
t.Fatalf("expected official passing report, got passed=%v trust=%s hard=%+v", rep.Passed, rep.Trust, rep.HardFindings)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckCSSAgainstContractIgnoresCommentsStringsAndURLs(t *testing.T) {
|
||||
contract := plugin.UIContract{
|
||||
UIAPI: "1.0.0",
|
||||
Parts: []string{"rg-p-shell"},
|
||||
Tokens: []string{"--surface-sidebar"},
|
||||
}
|
||||
cleanCSS := `
|
||||
/* layer.background handled by studio.js — var(--not-a-real-token) */
|
||||
.rg-p-shell {
|
||||
background-color: var(--surface-sidebar);
|
||||
background-image: url(assets/bg.png);
|
||||
}
|
||||
.rg-p-shell::after {
|
||||
content: "v1.0.beta\\\r\n.continued-string-class";
|
||||
background: url("assets/overlay.webp");
|
||||
}
|
||||
`
|
||||
if issues := plugin.CheckCSSAgainstContract(cleanCSS, contract); len(issues) != 0 {
|
||||
t.Fatalf("expected no issues on clean CSS with comments/urls/strings, got: %v", issues)
|
||||
}
|
||||
dirtyCSS := cleanCSS + "\n.non-contract-class { color: var(--unknown-token); }\n"
|
||||
issues := plugin.CheckCSSAgainstContract(dirtyCSS, contract)
|
||||
if len(issues) != 2 {
|
||||
t.Fatalf("expected 2 issues on real violations, got: %v", issues)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSHA256SumsRejectsDuplicateAndBackslashAndManifestRejectsPaddedVersion(t *testing.T) {
|
||||
// ValidateManifest rejects surrounding whitespace in version.
|
||||
if err := plugin.ValidateManifest(plugin.Manifest{
|
||||
Schema: 1,
|
||||
ID: "test.theme.ver",
|
||||
Version: " 1.0.0 ",
|
||||
Name: plugin.LocalizedText{EnUS: "Ver"},
|
||||
}, "0.2.11", false); err == nil {
|
||||
t.Fatal("expected whitespace-padded manifest version to be rejected")
|
||||
}
|
||||
|
||||
// Duplicate SHA256SUMS lines and backslash separators must be rejected.
|
||||
dir := t.TempDir()
|
||||
man, _ := json.Marshal(plugin.Manifest{
|
||||
Schema: 1,
|
||||
ID: "test.theme.sums",
|
||||
Version: "1.0.0",
|
||||
Name: plugin.LocalizedText{EnUS: "Sums"},
|
||||
})
|
||||
_ = os.WriteFile(filepath.Join(dir, "plugin.json"), man, 0o644)
|
||||
h := sha256HexBytes(man)
|
||||
|
||||
_ = os.WriteFile(filepath.Join(dir, "SHA256SUMS"), []byte(h+" plugin.json\n"+h+" plugin.json\n"), 0o644)
|
||||
if rep := plugin.ScanDirectory(dir, "0.2.11", plugin.ScanOptions{RequireChecksums: true}); !rep.HardBlocked {
|
||||
t.Fatal("expected duplicate SHA256SUMS entry to be hard-blocked")
|
||||
}
|
||||
|
||||
_ = os.WriteFile(filepath.Join(dir, "SHA256SUMS"), []byte(h+" sub\\plugin.json\n"), 0o644)
|
||||
if rep := plugin.ScanDirectory(dir, "0.2.11", plugin.ScanOptions{RequireChecksums: true}); !rep.HardBlocked {
|
||||
t.Fatal("expected backslash path in SHA256SUMS to be hard-blocked")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSHA256SumsSupportsFilenamesWithSpacesAndTruthfulUIScriptCopy(t *testing.T) {
|
||||
man, _ := json.Marshal(plugin.Manifest{
|
||||
Schema: 1,
|
||||
ID: "test.theme.spaces",
|
||||
Version: "1.0.0",
|
||||
Name: plugin.LocalizedText{ZhCN: "空格资源主题", EnUS: "Spaced Asset Theme"},
|
||||
Publisher: "tester",
|
||||
License: "MIT",
|
||||
Permissions: []string{"ui:script"},
|
||||
Contributes: plugin.Contributes{
|
||||
Themes: []plugin.ThemeContribution{{
|
||||
ID: "test.theme.spaces",
|
||||
Name: plugin.LocalizedText{EnUS: "Spaced"},
|
||||
Stylesheet: "theme.css",
|
||||
UIScript: "studio.js",
|
||||
}},
|
||||
},
|
||||
})
|
||||
zipPath := makePluginZip(t, map[string][]byte{
|
||||
"plugin.json": man,
|
||||
"theme.css": []byte(".rg-p-shell { background-image: url(\"assets/my wallpaper.png\"); }"),
|
||||
"studio.js": []byte("sdk.on('view.changed', () => {});"),
|
||||
"assets/my wallpaper.png": []byte("png-bytes"),
|
||||
}, nil, false)
|
||||
|
||||
rep, err := plugin.ScanArchive(zipPath, t.TempDir(), "0.2.11", plugin.ScanOptions{RequireChecksums: true})
|
||||
if err != nil {
|
||||
t.Fatalf("ScanArchive: %v", err)
|
||||
}
|
||||
if rep.HardBlocked || !rep.Passed {
|
||||
t.Fatalf("expected spaced asset package to pass checksum & scan, hard=%+v", rep.HardFindings)
|
||||
}
|
||||
var uiScriptCap *plugin.CapabilityItem
|
||||
for i := range rep.Capabilities {
|
||||
if rep.Capabilities[i].ID == "ui:script" {
|
||||
uiScriptCap = &rep.Capabilities[i]
|
||||
}
|
||||
}
|
||||
if uiScriptCap == nil {
|
||||
t.Fatalf("expected ui:script capability item, got %+v", rep.Capabilities)
|
||||
}
|
||||
if strings.Contains(uiScriptCap.Summary.ZhCN, "受限主题沙盒") || strings.Contains(uiScriptCap.Summary.EnUS, "inside the theme sandbox") {
|
||||
t.Fatalf("ui:script copy must not falsely claim theme sandbox: %+v", uiScriptCap.Summary)
|
||||
}
|
||||
}
|
||||
@@ -47,12 +47,13 @@ type CustomThemeScheme struct {
|
||||
|
||||
// StateFile is the authoritative persisted plugin state at `<DataRoot>/plugins/state.json`.
|
||||
type StateFile struct {
|
||||
Schema int `json:"schema"`
|
||||
DeveloperMode bool `json:"developer_mode,omitempty"`
|
||||
ActiveThemeID string `json:"active_theme_id,omitempty"`
|
||||
ActiveSchemeID string `json:"active_scheme_id,omitempty"`
|
||||
CustomSchemes []CustomThemeScheme `json:"custom_schemes,omitempty"`
|
||||
Plugins map[string]*PluginRecord `json:"plugins"`
|
||||
Schema int `json:"schema"`
|
||||
DeveloperMode bool `json:"developer_mode,omitempty"`
|
||||
ActiveThemeID string `json:"active_theme_id,omitempty"`
|
||||
ActiveThemePluginID string `json:"active_theme_plugin_id,omitempty"`
|
||||
ActiveSchemeID string `json:"active_scheme_id,omitempty"`
|
||||
CustomSchemes []CustomThemeScheme `json:"custom_schemes,omitempty"`
|
||||
Plugins map[string]*PluginRecord `json:"plugins"`
|
||||
}
|
||||
|
||||
// StateStore safely reads and atomically writes state.json with .bak fallback.
|
||||
|
||||
@@ -0,0 +1,423 @@
|
||||
package plugin_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
)
|
||||
|
||||
func sha256HexBytes(b []byte) string {
|
||||
sum := sha256.Sum256(b)
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func TestExternalThemePersistsAcrossRestartAndUpgrade(t *testing.T) {
|
||||
dataRoot := t.TempDir()
|
||||
ctx := context.Background()
|
||||
|
||||
buildThemeZip := func(ver, css string) string {
|
||||
man, _ := json.Marshal(plugin.Manifest{
|
||||
Schema: 1,
|
||||
ID: "test.theme.persist",
|
||||
Version: ver,
|
||||
Name: plugin.LocalizedText{EnUS: "Persist Theme"},
|
||||
Publisher: "tester",
|
||||
License: "MIT",
|
||||
Engines: plugin.Engines{PluginAPI: "^1.0.0", UIAPI: "^2.0.0"},
|
||||
Platforms: []string{"any"},
|
||||
Contributes: plugin.Contributes{
|
||||
Themes: []plugin.ThemeContribution{{
|
||||
ID: "test.theme.persist",
|
||||
Name: plugin.LocalizedText{EnUS: "Persist Theme"},
|
||||
Stylesheet: "theme.css",
|
||||
}},
|
||||
},
|
||||
})
|
||||
return makePluginZip(t, map[string][]byte{
|
||||
"plugin.json": man,
|
||||
"theme.css": []byte(css),
|
||||
}, nil, false)
|
||||
}
|
||||
|
||||
openMgr := func(safe bool) *plugin.Manager {
|
||||
mgr, err := plugin.NewManager(plugin.ManagerOptions{
|
||||
DataRoot: dataRoot,
|
||||
HostVersion: "0.2.11",
|
||||
SafeMode: safe,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewManager: %v", err)
|
||||
}
|
||||
if err := mgr.LoadExternal(); err != nil {
|
||||
t.Fatalf("LoadExternal: %v", err)
|
||||
}
|
||||
mgr.Registry().Reconcile(ctx)
|
||||
mgr.MarkBootComplete()
|
||||
return mgr
|
||||
}
|
||||
|
||||
mgr1 := openMgr(false)
|
||||
v1Zip := buildThemeZip("1.0.1", ".rg-p-sidebar { background: #112233; }")
|
||||
if _, err := mgr1.InstallLocalArchive(ctx, v1Zip, plugin.PackageInstallOptions{}); err != nil {
|
||||
t.Fatalf("install v1: %v", err)
|
||||
}
|
||||
if err := mgr1.Enable(ctx, "test.theme.persist", false); err != nil {
|
||||
t.Fatalf("enable v1: %v", err)
|
||||
}
|
||||
if err := mgr1.SetActiveTheme("test.theme.persist", "ocean"); err != nil {
|
||||
t.Fatalf("SetActiveTheme: %v", err)
|
||||
}
|
||||
if got := mgr1.ActiveThemePayload(); got.ThemeID != "test.theme.persist" || got.ActiveScheme != "ocean" {
|
||||
t.Fatalf("active theme before restart = %+v", got)
|
||||
}
|
||||
mgr1.Close()
|
||||
|
||||
// 1. Restart: external theme and active scheme must persist after LoadExternal + Reconcile.
|
||||
mgr2 := openMgr(false)
|
||||
defer mgr2.Close()
|
||||
afterRestart := mgr2.ActiveThemePayload()
|
||||
if afterRestart.ThemeID != "test.theme.persist" || afterRestart.ActiveScheme != "ocean" || !strings.Contains(afterRestart.CSS, "#112233") {
|
||||
t.Fatalf("active theme lost across restart: %+v", afterRestart)
|
||||
}
|
||||
|
||||
// 2. Upgrade (no new high-risk permissions): active theme must survive and pick up v1.0.2 CSS.
|
||||
v2Zip := buildThemeZip("1.0.2", ".rg-p-sidebar { background: #445566; }")
|
||||
if _, err := mgr2.InstallLocalArchive(ctx, v2Zip, plugin.PackageInstallOptions{}); err != nil {
|
||||
t.Fatalf("upgrade v2: %v", err)
|
||||
}
|
||||
afterUpgrade := mgr2.ActiveThemePayload()
|
||||
if afterUpgrade.ThemeID != "test.theme.persist" || !strings.Contains(afterUpgrade.CSS, "#445566") {
|
||||
t.Fatalf("active theme lost or stale after upgrade: %+v", afterUpgrade)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInteractiveThemeUIScriptHashPinningAndUpgradeReapproval(t *testing.T) {
|
||||
dataRoot := t.TempDir()
|
||||
ctx := context.Background()
|
||||
|
||||
buildInteractiveZip := func(ver string, script []byte) string {
|
||||
man, _ := json.Marshal(plugin.Manifest{
|
||||
Schema: 1,
|
||||
ID: "test.theme.studio",
|
||||
Version: ver,
|
||||
Name: plugin.LocalizedText{EnUS: "Studio Theme"},
|
||||
Publisher: "tester",
|
||||
License: "MIT",
|
||||
Engines: plugin.Engines{PluginAPI: "^1.0.0", UIAPI: "^2.0.0"},
|
||||
Platforms: []string{"any"},
|
||||
Permissions: []string{"ui:script"},
|
||||
Contributes: plugin.Contributes{
|
||||
Themes: []plugin.ThemeContribution{{
|
||||
ID: "test.theme.studio",
|
||||
Name: plugin.LocalizedText{EnUS: "Studio Theme"},
|
||||
Stylesheet: "theme.css",
|
||||
UIScript: "studio.js",
|
||||
}},
|
||||
},
|
||||
})
|
||||
return makePluginZip(t, map[string][]byte{
|
||||
"plugin.json": man,
|
||||
"theme.css": []byte(".rg-p-shell { color: var(--text-primary); }"),
|
||||
"studio.js": script,
|
||||
}, nil, false)
|
||||
}
|
||||
|
||||
scriptV1 := []byte("sdk.on('view.changed', () => {}); // v1\n")
|
||||
scriptV2 := []byte("sdk.on('view.changed', () => {}); // v2 modified\n")
|
||||
hashV1 := sha256HexBytes(scriptV1)
|
||||
hashV2 := sha256HexBytes(scriptV2)
|
||||
|
||||
mgr1, err := plugin.NewManager(plugin.ManagerOptions{DataRoot: dataRoot, HostVersion: "0.2.11"})
|
||||
if err != nil {
|
||||
t.Fatalf("NewManager: %v", err)
|
||||
}
|
||||
if err := mgr1.LoadExternal(); err != nil {
|
||||
t.Fatalf("LoadExternal: %v", err)
|
||||
}
|
||||
mgr1.Registry().Reconcile(ctx)
|
||||
mgr1.MarkBootComplete()
|
||||
|
||||
info1, err := mgr1.InstallLocalArchive(ctx, buildInteractiveZip("1.0.1", scriptV1), plugin.PackageInstallOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("install v1: %v", err)
|
||||
}
|
||||
if info1.EntryPath == "" || info1.EntryHash != hashV1 || !info1.NeedsApproval {
|
||||
t.Fatalf("v1 entry metadata wrong: path=%q hash=%q (want %q) needsApproval=%v", info1.EntryPath, info1.EntryHash, hashV1, info1.NeedsApproval)
|
||||
}
|
||||
if err := mgr1.Enable(ctx, "test.theme.studio", false); err == nil {
|
||||
t.Fatal("enabling ui:script plugin without explicit approval succeeded")
|
||||
}
|
||||
if err := mgr1.Enable(ctx, "test.theme.studio", true); err != nil {
|
||||
t.Fatalf("enable v1 with approval: %v", err)
|
||||
}
|
||||
if err := mgr1.SetActiveTheme("test.theme.studio", ""); err != nil {
|
||||
t.Fatalf("SetActiveTheme: %v", err)
|
||||
}
|
||||
p1 := mgr1.ActiveThemePayload()
|
||||
if p1.ThemeID != "test.theme.studio" || !strings.Contains(p1.UIScriptURL, "v=1.0.1") || !strings.Contains(p1.UIScriptURL, "h="+hashV1[:12]) {
|
||||
t.Fatalf("unexpected v1 active payload: %+v", p1)
|
||||
}
|
||||
mgr1.Close()
|
||||
|
||||
// Restart with unchanged script stays approved and active.
|
||||
mgr2, err := plugin.NewManager(plugin.ManagerOptions{DataRoot: dataRoot, HostVersion: "0.2.11"})
|
||||
if err != nil {
|
||||
t.Fatalf("NewManager restart: %v", err)
|
||||
}
|
||||
defer mgr2.Close()
|
||||
if err := mgr2.LoadExternal(); err != nil {
|
||||
t.Fatalf("LoadExternal restart: %v", err)
|
||||
}
|
||||
mgr2.Registry().Reconcile(ctx)
|
||||
mgr2.MarkBootComplete()
|
||||
pRestart := mgr2.ActiveThemePayload()
|
||||
if pRestart.ThemeID != "test.theme.studio" || pRestart.UIScriptURL == "" {
|
||||
t.Fatalf("interactive theme lost on restart: %+v", pRestart)
|
||||
}
|
||||
|
||||
// Upgrade with modified studio.js MUST pause for re-approval and fall back safely.
|
||||
info2, err := mgr2.InstallLocalArchive(ctx, buildInteractiveZip("1.0.2", scriptV2), plugin.PackageInstallOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("upgrade v2: %v", err)
|
||||
}
|
||||
if !info2.NeedsApproval || info2.Enabled || info2.EntryHash != hashV2 {
|
||||
t.Fatalf("modified uiScript upgrade must require re-approval: enabled=%v needsApproval=%v hash=%q want=%q",
|
||||
info2.Enabled, info2.NeedsApproval, info2.EntryHash, hashV2)
|
||||
}
|
||||
if pPaused := mgr2.ActiveThemePayload(); pPaused.ThemeID != "builtin.theme.default" || pPaused.UIScriptURL != "" {
|
||||
t.Fatalf("paused interactive theme should fall back to default: %+v", pPaused)
|
||||
}
|
||||
|
||||
// Re-approving v1.0.2 restores the active theme and busts the script URL cache.
|
||||
if err := mgr2.Enable(ctx, "test.theme.studio", true); err != nil {
|
||||
t.Fatalf("re-approve v2: %v", err)
|
||||
}
|
||||
p2 := mgr2.ActiveThemePayload()
|
||||
if p2.ThemeID != "test.theme.studio" || !strings.Contains(p2.UIScriptURL, "v=1.0.2") || !strings.Contains(p2.UIScriptURL, "h="+hashV2[:12]) {
|
||||
t.Fatalf("re-approved interactive theme not restored or URL not cache-busted: %+v", p2)
|
||||
}
|
||||
if p2.UIScriptURL == p1.UIScriptURL {
|
||||
t.Fatalf("expected updated UIScriptURL after script change, both were %q", p2.UIScriptURL)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDisableAndRemoveActiveThemeSemantics(t *testing.T) {
|
||||
dataRoot := t.TempDir()
|
||||
ctx := context.Background()
|
||||
|
||||
themeMan, _ := json.Marshal(plugin.Manifest{
|
||||
Schema: 1,
|
||||
ID: "test.theme.pack",
|
||||
Version: "1.0.0",
|
||||
Name: plugin.LocalizedText{EnUS: "Theme Pack"},
|
||||
Publisher: "tester",
|
||||
License: "MIT",
|
||||
Contributes: plugin.Contributes{
|
||||
Themes: []plugin.ThemeContribution{{
|
||||
ID: "test.theme.pack.dark",
|
||||
Name: plugin.LocalizedText{EnUS: "Dark"},
|
||||
Stylesheet: "theme.css",
|
||||
}},
|
||||
},
|
||||
})
|
||||
themeZip := makePluginZip(t, map[string][]byte{
|
||||
"plugin.json": themeMan,
|
||||
"theme.css": []byte(".rg-p-sidebar { background: #101010; }"),
|
||||
}, nil, false)
|
||||
|
||||
otherMan, _ := json.Marshal(plugin.Manifest{
|
||||
Schema: 1,
|
||||
ID: "test.other.noop",
|
||||
Version: "1.0.0",
|
||||
Name: plugin.LocalizedText{EnUS: "Other Plugin"},
|
||||
Publisher: "tester",
|
||||
License: "MIT",
|
||||
})
|
||||
otherZip := makePluginZip(t, map[string][]byte{"plugin.json": otherMan}, nil, false)
|
||||
|
||||
openMgr := func(safe bool) *plugin.Manager {
|
||||
mgr, err := plugin.NewManager(plugin.ManagerOptions{
|
||||
DataRoot: dataRoot,
|
||||
HostVersion: "0.2.11",
|
||||
SafeMode: safe,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewManager(safe=%v): %v", safe, err)
|
||||
}
|
||||
if err := mgr.LoadExternal(); err != nil {
|
||||
t.Fatalf("LoadExternal(safe=%v): %v", safe, err)
|
||||
}
|
||||
mgr.Registry().Reconcile(ctx)
|
||||
mgr.MarkBootComplete()
|
||||
return mgr
|
||||
}
|
||||
|
||||
mgr := openMgr(false)
|
||||
if _, err := mgr.InstallLocalArchive(ctx, themeZip, plugin.PackageInstallOptions{}); err != nil {
|
||||
t.Fatalf("install theme: %v", err)
|
||||
}
|
||||
if _, err := mgr.InstallLocalArchive(ctx, otherZip, plugin.PackageInstallOptions{}); err != nil {
|
||||
t.Fatalf("install other: %v", err)
|
||||
}
|
||||
if err := mgr.Enable(ctx, "test.theme.pack", false); err != nil {
|
||||
t.Fatalf("enable theme: %v", err)
|
||||
}
|
||||
if err := mgr.Enable(ctx, "test.other.noop", false); err != nil {
|
||||
t.Fatalf("enable other: %v", err)
|
||||
}
|
||||
if err := mgr.SetActiveTheme("test.theme.pack.dark", "warm"); err != nil {
|
||||
t.Fatalf("SetActiveTheme: %v", err)
|
||||
}
|
||||
mgr.Close()
|
||||
|
||||
// 1. Disabling an unrelated plugin in safeMode (as CLI does) MUST NOT wipe ActiveThemeID.
|
||||
safeMgr := openMgr(true)
|
||||
if err := safeMgr.Disable(ctx, "test.other.noop"); err != nil {
|
||||
t.Fatalf("safe Disable unrelated: %v", err)
|
||||
}
|
||||
safeMgr.Close()
|
||||
|
||||
st, err := plugin.NewStateStore(plugin.NewPluginsLayout(dataRoot).Root).Load()
|
||||
if err != nil {
|
||||
t.Fatalf("load state: %v", err)
|
||||
}
|
||||
if st.ActiveThemeID != "test.theme.pack.dark" || st.ActiveSchemeID != "warm" {
|
||||
t.Fatalf("disabling unrelated plugin in safeMode wiped active theme: theme=%q scheme=%q", st.ActiveThemeID, st.ActiveSchemeID)
|
||||
}
|
||||
|
||||
// 2. Disabling the theme plugin in safeMode clears BOTH ActiveThemeID and ActiveSchemeID.
|
||||
safeMgr2 := openMgr(true)
|
||||
if err := safeMgr2.Disable(ctx, "test.theme.pack"); err != nil {
|
||||
t.Fatalf("safe Disable theme: %v", err)
|
||||
}
|
||||
safeMgr2.Close()
|
||||
|
||||
st, err = plugin.NewStateStore(plugin.NewPluginsLayout(dataRoot).Root).Load()
|
||||
if err != nil {
|
||||
t.Fatalf("load state after disable: %v", err)
|
||||
}
|
||||
if st.ActiveThemeID != "" || st.ActiveSchemeID != "" {
|
||||
t.Fatalf("disabling active theme plugin left stale state: theme=%q scheme=%q", st.ActiveThemeID, st.ActiveSchemeID)
|
||||
}
|
||||
|
||||
// 3. Removing the active theme plugin clears BOTH ActiveThemeID and ActiveSchemeID.
|
||||
mgr3 := openMgr(false)
|
||||
defer mgr3.Close()
|
||||
if err := mgr3.Enable(ctx, "test.theme.pack", false); err != nil {
|
||||
t.Fatalf("re-enable theme: %v", err)
|
||||
}
|
||||
if err := mgr3.SetActiveTheme("test.theme.pack.dark", "warm"); err != nil {
|
||||
t.Fatalf("re-activate theme: %v", err)
|
||||
}
|
||||
if err := mgr3.Remove(ctx, "test.theme.pack", true); err != nil {
|
||||
t.Fatalf("remove theme: %v", err)
|
||||
}
|
||||
st, err = plugin.NewStateStore(plugin.NewPluginsLayout(dataRoot).Root).Load()
|
||||
if err != nil {
|
||||
t.Fatalf("load state after remove: %v", err)
|
||||
}
|
||||
if st.ActiveThemeID != "" || st.ActiveThemePluginID != "" || st.ActiveSchemeID != "" {
|
||||
t.Fatalf("removing active theme plugin left stale state: theme=%q plugin=%q scheme=%q", st.ActiveThemeID, st.ActiveThemePluginID, st.ActiveSchemeID)
|
||||
}
|
||||
|
||||
// 4. Removing an orphaned theme plugin (whose themeID != pluginID and whose
|
||||
// package directory vanished on disk) must still clear active theme state.
|
||||
if _, err := mgr3.InstallLocalArchive(ctx, themeZip, plugin.PackageInstallOptions{}); err != nil {
|
||||
t.Fatalf("re-install theme: %v", err)
|
||||
}
|
||||
if err := mgr3.Enable(ctx, "test.theme.pack", false); err != nil {
|
||||
t.Fatalf("re-enable theme for orphan test: %v", err)
|
||||
}
|
||||
if err := mgr3.SetActiveTheme("test.theme.pack.dark", "midnight"); err != nil {
|
||||
t.Fatalf("activate theme for orphan test: %v", err)
|
||||
}
|
||||
mgr3.Close()
|
||||
|
||||
// Delete package files to turn test.theme.pack into an orphaned state.json record.
|
||||
if err := os.RemoveAll(filepath.Join(plugin.NewPluginsLayout(dataRoot).PkgsDir(), "test.theme.pack")); err != nil {
|
||||
t.Fatalf("remove pkg dir: %v", err)
|
||||
}
|
||||
orphanMgr := openMgr(true)
|
||||
defer orphanMgr.Close()
|
||||
if err := orphanMgr.Remove(ctx, "test.theme.pack", true); err != nil {
|
||||
t.Fatalf("remove orphaned theme plugin: %v", err)
|
||||
}
|
||||
st, err = plugin.NewStateStore(plugin.NewPluginsLayout(dataRoot).Root).Load()
|
||||
if err != nil {
|
||||
t.Fatalf("load state after orphan remove: %v", err)
|
||||
}
|
||||
if st.ActiveThemeID != "" || st.ActiveThemePluginID != "" || st.ActiveSchemeID != "" {
|
||||
t.Fatalf("removing orphaned theme plugin left stale state: theme=%q plugin=%q scheme=%q", st.ActiveThemeID, st.ActiveThemePluginID, st.ActiveSchemeID)
|
||||
}
|
||||
|
||||
// 5. Removing an orphaned legacy plugin whose ID happens to be a prefix of
|
||||
// another live plugin's active theme ID MUST NOT clear that live theme.
|
||||
prefixMan, _ := json.Marshal(plugin.Manifest{
|
||||
Schema: 1,
|
||||
ID: "test.theme.pack.dark",
|
||||
Version: "1.0.0",
|
||||
Name: plugin.LocalizedText{EnUS: "Live Dark Theme"},
|
||||
Publisher: "tester",
|
||||
License: "MIT",
|
||||
Contributes: plugin.Contributes{
|
||||
Themes: []plugin.ThemeContribution{{
|
||||
ID: "test.theme.pack.dark",
|
||||
Name: plugin.LocalizedText{EnUS: "Live Dark"},
|
||||
Stylesheet: "theme.css",
|
||||
}},
|
||||
},
|
||||
})
|
||||
liveDarkZip := makePluginZip(t, map[string][]byte{
|
||||
"plugin.json": prefixMan,
|
||||
"theme.css": []byte(".rg-p-sidebar { background: #181818; }"),
|
||||
}, nil, false)
|
||||
orphanMgr.Close()
|
||||
|
||||
mgr5 := openMgr(false)
|
||||
if _, err := mgr5.InstallLocalArchive(ctx, liveDarkZip, plugin.PackageInstallOptions{}); err != nil {
|
||||
t.Fatalf("install live dark theme: %v", err)
|
||||
}
|
||||
if err := mgr5.Enable(ctx, "test.theme.pack.dark", false); err != nil {
|
||||
t.Fatalf("enable live dark theme: %v", err)
|
||||
}
|
||||
if err := mgr5.SetActiveTheme("test.theme.pack.dark", "carbon"); err != nil {
|
||||
t.Fatalf("activate live dark theme: %v", err)
|
||||
}
|
||||
mgr5.Close()
|
||||
|
||||
// Inject a legacy state.json (no active_theme_plugin_id) with an orphaned prefix plugin "test.theme.pack".
|
||||
store := plugin.NewStateStore(plugin.NewPluginsLayout(dataRoot).Root)
|
||||
st, err = store.Load()
|
||||
if err != nil {
|
||||
t.Fatalf("load state for prefix collision test: %v", err)
|
||||
}
|
||||
st.ActiveThemePluginID = ""
|
||||
st.Plugins["test.theme.pack"] = &plugin.PluginRecord{
|
||||
ID: "test.theme.pack",
|
||||
Version: "1.0.0",
|
||||
Source: plugin.SourceLocal,
|
||||
}
|
||||
if err := store.Save(st); err != nil {
|
||||
t.Fatalf("save legacy state: %v", err)
|
||||
}
|
||||
|
||||
mgr6 := openMgr(true)
|
||||
defer mgr6.Close()
|
||||
if err := mgr6.Remove(ctx, "test.theme.pack", true); err != nil {
|
||||
t.Fatalf("remove orphaned prefix plugin: %v", err)
|
||||
}
|
||||
st, err = store.Load()
|
||||
if err != nil {
|
||||
t.Fatalf("reload state after prefix orphan remove: %v", err)
|
||||
}
|
||||
if st.ActiveThemeID != "test.theme.pack.dark" || st.ActiveSchemeID != "carbon" {
|
||||
t.Fatalf("removing unrelated orphaned prefix plugin wiped live theme: theme=%q scheme=%q", st.ActiveThemeID, st.ActiveSchemeID)
|
||||
}
|
||||
}
|
||||
@@ -115,17 +115,70 @@ func TestStaleIndexDoesNotVouch(t *testing.T) {
|
||||
URLs: []string{srv.URL + "/index.json"}, CacheTTL: time.Minute,
|
||||
AllowInsecureLocalhost: true, FirstParty: true,
|
||||
}
|
||||
// Seed the disk cache, then point a fresh client at a dead index URL: the
|
||||
// package still downloads, but only the stale cache lists it.
|
||||
// Seed the disk cache, then test cold disk-cache Peek and post-failure
|
||||
// stale consistency: neither cold disk cache nor a failed refresh may ever
|
||||
// claim official trust or silently rebound to fresh within the cache TTL.
|
||||
plugin.NewMarketClient(opts).Browse(context.Background(), nil, plugin.MarketBrowseOptions{})
|
||||
opts.URLs = []string{srv.URL + "/missing-index.json"}
|
||||
info, err := plugin.NewMarketClient(opts).InstallFromMarket(context.Background(), mgr, id, plugin.MarketInstallOptions{})
|
||||
staleClient := plugin.NewMarketClient(opts)
|
||||
|
||||
// Cold disk cache Peek (before network fetch in this session) must not vouch.
|
||||
if coldPeek := staleClient.Peek(nil, plugin.MarketBrowseOptions{}); len(coldPeek.Items) != 1 || coldPeek.Items[0].Entry.Trust != plugin.TrustCommunity {
|
||||
t.Fatalf("cold disk-cache Peek must show community trust, got items=%+v", coldPeek.Items)
|
||||
}
|
||||
|
||||
browse := staleClient.Browse(context.Background(), nil, plugin.MarketBrowseOptions{})
|
||||
if !browse.Stale || browse.FetchError == "" || len(browse.Items) != 1 || browse.Items[0].Entry.Trust != plugin.TrustCommunity {
|
||||
t.Fatalf("stale browse must show community trust, got stale=%v err=%q items=%+v", browse.Stale, browse.FetchError, browse.Items)
|
||||
}
|
||||
// Follow-up non-forced Browse within TTL (e.g. search/category filter) must stay stale + community.
|
||||
followUp := staleClient.Browse(context.Background(), nil, plugin.MarketBrowseOptions{Query: id})
|
||||
if !followUp.Stale || followUp.FetchError == "" || len(followUp.Items) != 1 || followUp.Items[0].Entry.Trust != plugin.TrustCommunity {
|
||||
t.Fatalf("follow-up Browse after failure must stay stale/community, got stale=%v err=%q items=%+v", followUp.Stale, followUp.FetchError, followUp.Items)
|
||||
}
|
||||
if peek := staleClient.Peek(nil, plugin.MarketBrowseOptions{}); !peek.Stale || len(peek.Items) != 1 || peek.Items[0].Entry.Trust != plugin.TrustCommunity {
|
||||
t.Fatalf("peek after stale browse must keep community trust, got stale=%v items=%+v", peek.Stale, peek.Items)
|
||||
}
|
||||
info, err := staleClient.InstallFromMarket(context.Background(), mgr, id, plugin.MarketInstallOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("install: %v", err)
|
||||
}
|
||||
if info.Trust != plugin.TrustCommunity {
|
||||
t.Fatalf("install from stale cache trust = %q, want community", info.Trust)
|
||||
}
|
||||
|
||||
// Online success followed by a failed force-refresh must also stay stale/community on subsequent Browse.
|
||||
var failRemote bool
|
||||
var switchSrv *httptest.Server
|
||||
_, indexFn := marketFixture(t, id, plugin.TrustOfficial, nil)
|
||||
switchSrv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if failRemote {
|
||||
http.Error(w, "down", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(indexFn())
|
||||
}))
|
||||
t.Cleanup(switchSrv.Close)
|
||||
liveClient := plugin.NewMarketClient(plugin.MarketClientOptions{
|
||||
Layout: mgr.Layout(), HostVersion: "0.2.10",
|
||||
URLs: []string{switchSrv.URL + "/index.json"}, CacheTTL: time.Minute,
|
||||
AllowInsecureLocalhost: true, FirstParty: true,
|
||||
})
|
||||
if okRes := liveClient.Browse(context.Background(), nil, plugin.MarketBrowseOptions{}); okRes.Stale || okRes.Items[0].Entry.Trust != plugin.TrustOfficial {
|
||||
t.Fatalf("initial live browse want official/fresh, got stale=%v trust=%q", okRes.Stale, okRes.Items[0].Entry.Trust)
|
||||
}
|
||||
failRemote = true
|
||||
if failRes := liveClient.Browse(context.Background(), nil, plugin.MarketBrowseOptions{ForceRefresh: true}); !failRes.Stale || failRes.Items[0].Entry.Trust != plugin.TrustCommunity {
|
||||
t.Fatalf("failed force-refresh want stale/community, got stale=%v trust=%q", failRes.Stale, failRes.Items[0].Entry.Trust)
|
||||
}
|
||||
if afterFail := liveClient.Browse(context.Background(), nil, plugin.MarketBrowseOptions{}); !afterFail.Stale || afterFail.Items[0].Entry.Trust != plugin.TrustCommunity {
|
||||
t.Fatalf("non-forced Browse after failed refresh rebounded: stale=%v trust=%q", afterFail.Stale, afterFail.Items[0].Entry.Trust)
|
||||
}
|
||||
// Once remote recovers, the next non-forced Browse must retry and restore official trust immediately.
|
||||
failRemote = false
|
||||
if recovered := liveClient.Browse(context.Background(), nil, plugin.MarketBrowseOptions{}); recovered.Stale || recovered.Source != "remote" || recovered.Items[0].Entry.Trust != plugin.TrustOfficial {
|
||||
t.Fatalf("non-forced Browse after recovery stayed stale: source=%q stale=%v trust=%q", recovered.Source, recovered.Stale, recovered.Items[0].Entry.Trust)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOfficialPluginsStillNeedApproval(t *testing.T) {
|
||||
|
||||
@@ -47,6 +47,7 @@
|
||||
"pluginPanelsSection": "Plugin panels",
|
||||
"pluginApproveTitle": "Approve high-risk permissions",
|
||||
"pluginApproveL3Warn": "This plugin runs native code (L3 Sidecar) and can perform arbitrary actions as your Windows user",
|
||||
"pluginApproveUIScriptWarn": "This plugin runs an interactive script (ui:script) inside the main window with full access to the interface; verify its source and SHA-256 before enabling",
|
||||
"pluginPublisherLicense": "Publisher / License",
|
||||
"pluginEntryPath": "Entry path",
|
||||
"pluginRequestedPerms": "Requested permissions",
|
||||
|
||||
@@ -47,6 +47,7 @@
|
||||
"pluginPanelsSection": "插件面板",
|
||||
"pluginApproveTitle": "高危权限确认",
|
||||
"pluginApproveL3Warn": "此插件为原生可执行程序(L3 Sidecar),能够以当前 Windows 账户身份执行任意操作",
|
||||
"pluginApproveUIScriptWarn": "此插件包含交互界面脚本(ui:script),会在主窗口界面中运行并可访问页面内容,启用前务必核对来源与脚本 SHA-256",
|
||||
"pluginPublisherLicense": "发布者 / 许可",
|
||||
"pluginEntryPath": "入口路径",
|
||||
"pluginRequestedPerms": "请求权限",
|
||||
|
||||
Reference in new issue
Block a user