Compare commits
7
Commits
dev
..
v0.2.15-arm.2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d8c9abc3df | ||
|
|
ea6390e8ca | ||
|
|
44905aaa17 | ||
|
|
92573ce550 | ||
|
|
1d15e41482 | ||
|
|
c08ddd7b48 | ||
|
|
9006e6d9a7 |
No files matched your search
@@ -0,0 +1,115 @@
|
||||
name: Windows CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: reims-windows-ci-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
REIMS_CI_WORKSPACE: D:/RgCI/${{ github.run_id }}-${{ github.run_attempt }}
|
||||
GOCACHE: D:/RgCI/${{ github.run_id }}-${{ github.run_attempt }}/.debug/cache/go-build
|
||||
|
||||
jobs:
|
||||
verify:
|
||||
runs-on: reims-windows-x64
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- name: Check out the triggering commit
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$PSNativeCommandUseErrorActionPreference = $true
|
||||
if (Test-Path -LiteralPath $env:REIMS_CI_WORKSPACE) { throw 'The CI checkout directory already exists' }
|
||||
New-Item -ItemType Directory -Path $env:REIMS_CI_WORKSPACE -Force | Out-Null
|
||||
Set-Location -LiteralPath $env:REIMS_CI_WORKSPACE
|
||||
git init .
|
||||
git remote add origin "$env:GITHUB_SERVER_URL/$env:GITHUB_REPOSITORY.git"
|
||||
git fetch --depth=1 origin $env:GITHUB_SHA
|
||||
git checkout --detach FETCH_HEAD
|
||||
if ((git rev-parse HEAD) -ne $env:GITHUB_SHA) { throw 'Unexpected checkout commit' }
|
||||
|
||||
- name: Verify installed build tools
|
||||
working-directory: ${{ env.REIMS_CI_WORKSPACE }}
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$PSNativeCommandUseErrorActionPreference = $true
|
||||
git --version
|
||||
go version
|
||||
node --version
|
||||
pnpm --version
|
||||
|
||||
- name: Verify CHANGELOG.md matches current version
|
||||
working-directory: ${{ env.REIMS_CI_WORKSPACE }}
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
node scripts/changelog.mjs check
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Changelog validation failed' }
|
||||
$verFile = Get-Content -Raw -LiteralPath 'internal/version/version.go'
|
||||
if ($verFile -notmatch 'var\s+Version\s*=\s*"(v[^"]+)"') {
|
||||
throw 'Could not parse Version from internal/version/version.go'
|
||||
}
|
||||
$ver = $Matches[1]
|
||||
New-Item -ItemType Directory -Force -Path .debug/runs/ci | Out-Null
|
||||
$tmp = Join-Path $PWD ".debug/runs/ci/release-notes-$ver.md"
|
||||
& ./scripts/build-release-notes.ps1 -Tag $ver -OutFile $tmp
|
||||
"REIMS_APP_VERSION=$ver" >> $env:GITHUB_ENV
|
||||
Write-Host "PASS CHANGELOG.md contains valid release notes for $ver ($((Get-Item -LiteralPath $tmp).Length) bytes)"
|
||||
|
||||
- name: Workspace hygiene
|
||||
working-directory: ${{ env.REIMS_CI_WORKSPACE }}
|
||||
shell: pwsh
|
||||
run: node scripts/debug/check.mjs
|
||||
|
||||
- name: Install frontend dependencies
|
||||
working-directory: ${{ env.REIMS_CI_WORKSPACE }}
|
||||
shell: pwsh
|
||||
run: pnpm --dir frontend install --frozen-lockfile
|
||||
|
||||
- name: CI tests
|
||||
working-directory: ${{ env.REIMS_CI_WORKSPACE }}
|
||||
shell: pwsh
|
||||
run: node scripts/test.mjs ci
|
||||
|
||||
- name: Bundle frontend
|
||||
working-directory: ${{ env.REIMS_CI_WORKSPACE }}
|
||||
shell: pwsh
|
||||
run: pnpm --dir frontend bundle
|
||||
|
||||
- name: Build reims-go.exe (window + command-line mode)
|
||||
working-directory: ${{ env.REIMS_CI_WORKSPACE }}
|
||||
shell: pwsh
|
||||
run: |
|
||||
$env:GOTMPDIR = (Resolve-Path .debug/runs/ci).Path
|
||||
$exe = '.debug/runs/ci/reims-go.exe'
|
||||
go vet -tags desktop,production .
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Go desktop vet failed' }
|
||||
go build -trimpath -tags desktop,production -ldflags "-H windowsgui" -o $exe .
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Go desktop build failed' }
|
||||
./scripts/check-release-artifact.ps1 -Executable $exe -Version $env:REIMS_APP_VERSION
|
||||
|
||||
- name: WebView2 first-launch smoke
|
||||
working-directory: ${{ env.REIMS_CI_WORKSPACE }}
|
||||
timeout-minutes: 3
|
||||
run: node scripts/test.mjs webview2 .debug/runs/ci/reims-go.exe
|
||||
|
||||
- name: Remove the CI checkout
|
||||
if: always()
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if (!(Test-Path -LiteralPath $env:REIMS_CI_WORKSPACE)) { return }
|
||||
$checkout = Get-Item -LiteralPath $env:REIMS_CI_WORKSPACE
|
||||
$parent = Get-Item -LiteralPath 'D:/RgCI'
|
||||
if ($checkout.Parent.FullName -ne $parent.FullName -or
|
||||
$checkout.Name -notmatch '^[0-9]+-[0-9]+$' -or
|
||||
($checkout.Attributes -band [IO.FileAttributes]::ReparsePoint) -or
|
||||
($parent.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
|
||||
throw 'Refusing to remove an unexpected CI checkout path'
|
||||
}
|
||||
Remove-Item -LiteralPath $checkout.FullName -Recurse -Force
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "new",
|
||||
"order": 0,
|
||||
"authors": ["yxc0915"],
|
||||
"zh": "支持在 Windows x86-64 上使用 Stambha 实验运行时启动 ARM macOS。导入配套运行时后,可从已有的启动介质和虚拟磁盘创建虚拟机。",
|
||||
"en": "Run ARM macOS on Windows x86-64 with the Stambha preview runtime. Import the matching runtime to create a VM from existing boot media and a virtual disk."
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
# 运行 ARM macOS 实验版
|
||||
|
||||
ARM 实验运行时通过 QEMU/WHPX 和 Stambha 在 Windows x86-64 上运行 ARM macOS。使用同一预览配套的 Reims-Go 客户端和 `stambha-hosted` 运行时包。运行时可以和现有 Intel macOS 运行时共存。
|
||||
|
||||
## 准备
|
||||
|
||||
- Windows x86-64 主机,启用 Windows 虚拟机监控程序平台(WHPX),安装支持 Vulkan 的显卡驱动。
|
||||
- 一套你自己的 Stambha 启动介质和与之匹配的 ARM macOS 虚拟磁盘。启动目录至少包含 `EFI/stela/stela.cfg`,其中的磁盘分区标识须与虚拟磁盘一致。从目录启动时,客户端在 VM 的独立引导目录中放入运行时自带的 Stambha EFI。
|
||||
- 为每台运行中的虚拟机准备独立可写副本或 QCOW2 写入层。来宾写入保存在该磁盘文件中。运行时包内提供启动程序、固件和显卡组件,系统文件由用户自行准备。
|
||||
|
||||
macOS 27.2.1 的实验配置使用 8 个 vCPU 和 16 GiB 内存。首次登录后,系统索引和缓存初始化会影响交互速度。
|
||||
|
||||
## 启动
|
||||
|
||||
在运行时页面导入 ARM64 预览包。它以 `stambha-hosted` 类型单独安装。Intel 虚拟机继续绑定选中的 x86-64 运行时,ARM 虚拟机自动使用已安装且兼容的 ARM64 运行时。
|
||||
|
||||
新建虚拟机时选择「macOS ARM64(预览)」。可从 Apple 下载 macOS 27.2.1 恢复镜像,下载支持暂停和续传,文件保存到数据目录的 `images/arm64`,完成后核对 SHA-256。本预览需要先将 IPSW 制作成 Stambha 启动介质。填写准备好的启动目录及对应的可写磁盘路径后即可创建和启动。GPU 加速窗口由运行时打开。
|
||||
|
||||
也可在 PowerShell 中操作。将示例路径替换成自己的文件位置。
|
||||
|
||||
```powershell
|
||||
.\reims-go.exe runtime install .\reims-stambha-runtime-win-x64-stambha-arm64-preview.2.tar.zst
|
||||
.\reims-go.exe vm create --driver builtin.driver.stambha --boot-volume .\arm-boot --disk .\arm-system.qcow2 --cpus 8 --memory 16G arm-macos
|
||||
.\reims-go.exe vm start --driver builtin.driver.stambha arm-macos
|
||||
.\reims-go.exe vm stop --driver builtin.driver.stambha arm-macos
|
||||
```
|
||||
|
||||
如果配置使用原始安装介质,可以用 `--usb-image` 指定文件。原始介质须预先包含与托管 Reims vGPU 相容的 Stambha EFI。首次从 IPSW 制作 ARM 安装介质仍是独立流程。
|
||||
|
||||
日常关机请在 macOS 的苹果菜单中选择「关机」。客户端的停止操作会向来宾发送电源按键事件。若来宾没有退出,可回到桌面完成关机。只在来宾无响应时使用强制停止。
|
||||
@@ -13,7 +13,7 @@ import { VMPage } from './components/VMPage'
|
||||
import { buildFallbackChain, I18nKey, localeDir, locText, parseAppError, resolveActiveLocale, setPluginLocales, t } from './i18n'
|
||||
import { defaultGuestLang, recommendedMemoryGB } from './lib/format'
|
||||
import { initialWizardResolution } from './lib/displayResolution'
|
||||
import { isMacOSDriver, liveVMInfo, splitEndpoints, vmFeatures } from './lib/endpoints'
|
||||
import { hasStambhaRuntime, isMacOSDriver, liveVMInfo, splitEndpoints, vmFeatures } from './lib/endpoints'
|
||||
import { resolveFullscreenHotkey } from './lib/fullscreenHotkey'
|
||||
import { LogLine, appendLog, createLogLine } from './lib/logs'
|
||||
import { macOSMajor } from './macos/macosRelease'
|
||||
@@ -488,7 +488,8 @@ export const App: React.FC = () => {
|
||||
const pending = selectedVM ? (state?.pending_changes[vmRefKey(selectedVM)] ?? []) : []
|
||||
const fixedModeSupported = state?.active_runtime?.manifest.capabilities?.some((c) => c.trim().toLowerCase() === 'display-fixed-mode') ?? false
|
||||
const diskCacheSupported = state?.active_runtime?.manifest.capabilities?.some((c) => c.trim().toLowerCase() === 'win32-native-aio') ?? false
|
||||
const hostReady = !!state && state.host.whpx === 'ready' && !!state.active_runtime
|
||||
const stambhaAvailable = hasStambhaRuntime(state?.runtimes)
|
||||
const hostReady = !!state && state.host.whpx === 'ready' && (!!state.active_runtime || stambhaAvailable)
|
||||
const canSuspend = state?.can_suspend ?? false
|
||||
const fullscreenHotkey = state?.config.fullscreen_hotkey_enabled
|
||||
? resolveFullscreenHotkey(state.config.fullscreen_hotkey)
|
||||
@@ -595,7 +596,7 @@ export const App: React.FC = () => {
|
||||
try {
|
||||
const s = await api.GetState()
|
||||
setState(s)
|
||||
setSetupStage(s?.active_runtime ? null : 'runtime')
|
||||
setSetupStage(s?.active_runtime || hasStambhaRuntime(s?.runtimes) ? null : 'runtime')
|
||||
} catch (e) {
|
||||
console.warn('[app] GetState after setup failed:', e)
|
||||
fail(tr('failGeneric'), e)
|
||||
@@ -937,7 +938,7 @@ export const App: React.FC = () => {
|
||||
}
|
||||
|
||||
const openWizard = () => {
|
||||
if (!state?.active_runtime) {
|
||||
if (!state?.active_runtime && !stambhaAvailable) {
|
||||
setSelected(HOST_ID)
|
||||
toasts.push({ kind: 'error', title: tr('noRuntimeAlert') })
|
||||
return
|
||||
|
||||
@@ -5,6 +5,7 @@ import { ElevationDialog } from './ElevationDialog'
|
||||
import { CloneDialog } from './CloneDialog'
|
||||
import { SendTextDialog } from './SendTextDialog'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { hasStambhaRuntime, STAMBHA_DRIVER_ID } from '../lib/endpoints'
|
||||
import { latestVMStats } from '../lib/vmStats'
|
||||
import { vmRefKey } from '../lib/vmRef'
|
||||
import type { PluginViewRoute } from '../lib/pluginViewRouter'
|
||||
@@ -111,6 +112,7 @@ export const AppDialogs: React.FC<AppDialogsProps> = (props) => {
|
||||
host={state.host}
|
||||
fixedModeSupported={fixedModeSupported}
|
||||
captureSupported={state.runtime_capture_supported}
|
||||
initialDriverID={!state.active_runtime && hasStambhaRuntime(state.runtimes) ? STAMBHA_DRIVER_ID : undefined}
|
||||
tasks={tasks}
|
||||
draft={wizardDraft}
|
||||
onClose={onCloseWizard}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Check, ChevronRight, CircleAlert, CircleCheck, CloudDownload, Copy, Disc3, HardDrive, LucideIcon, Package } from 'lucide-react'
|
||||
import React, { Suspense, lazy, useEffect, useMemo, useState } from 'react'
|
||||
import { useNetworkPlan } from '../lib/useNetworkPlan'
|
||||
import { STAMBHA_DRIVER_ID } from '../lib/endpoints'
|
||||
import { NpcapDependency } from './NpcapDependency'
|
||||
import { NetworkErrorNotice } from './NetworkErrorNotice'
|
||||
import type { ParsedAppError } from '../i18n'
|
||||
@@ -66,6 +67,7 @@ interface Props {
|
||||
host: HostReport
|
||||
fixedModeSupported?: boolean
|
||||
captureSupported?: boolean
|
||||
initialDriverID?: string
|
||||
tasks?: Task[]
|
||||
draft?: WizardDraft | null
|
||||
onClose: () => void
|
||||
@@ -93,7 +95,7 @@ const SOURCES: { mode: 'offline' | 'apple' | 'installer' | 'disk'; icon: LucideI
|
||||
{ mode: 'disk', icon: HardDrive, title: 'srcDiskTitle', sub: 'srcDiskSub' },
|
||||
]
|
||||
|
||||
export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported = false, captureSupported = false, tasks = [], draft, onClose, onSubmit }) => {
|
||||
export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported = false, captureSupported = false, initialDriverID = BUILTIN_MACOS_DRIVER, tasks = [], draft, onClose, onSubmit }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const [step, setStep] = useState(draft?.step ?? 1)
|
||||
// Once the user has reached the review step, keep validating so step markers stay current.
|
||||
@@ -103,7 +105,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
const [issues, setIssues] = useState<ValidationIssue[]>([])
|
||||
const [cmdPreview, setCmdPreview] = useState('')
|
||||
const [drivers, setDrivers] = useState<DriverSummary[]>([])
|
||||
const [driverID, setDriverID] = useState(BUILTIN_MACOS_DRIVER)
|
||||
const [driverID, setDriverID] = useState(initialDriverID)
|
||||
const [driverOpts, setDriverOpts] = useState<Record<string, unknown>>({})
|
||||
const [driverCreating, setDriverCreating] = useState(false)
|
||||
const [dependencyBusy, setDependencyBusy] = useState(false)
|
||||
@@ -115,12 +117,13 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
api.ListDrivers().then((list) => { if (live) setDrivers(list ?? []) }).catch((e) => console.warn('[wizard] ListDrivers failed:', e))
|
||||
return () => { live = false }
|
||||
}, [])
|
||||
const armImageTask = [...tasks].reverse().find((task) => task.installer_kind === 'arm-ipsw')
|
||||
const activeDriver = drivers.find((d) => d.id === driverID)
|
||||
const isCustomDriver = driverID !== BUILTIN_MACOS_DRIVER && !!activeDriver
|
||||
|
||||
const defaultGraphics = host.recommended_gpu ? 'reims-vgpu' : 'vmware-svga'
|
||||
const [opts, setOpts] = useState<CreateOpts>(draft?.opts ?? {
|
||||
name: 'macos-tahoe',
|
||||
name: initialDriverID === STAMBHA_DRIVER_ID ? 'macos-arm64' : 'macos-tahoe',
|
||||
dir: '',
|
||||
// 离线安装默认关闭网络,减少恢复环境依赖;用户仍可在第 4 步改为 NAT 或桥接。
|
||||
source_mode: 'offline',
|
||||
@@ -294,7 +297,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
|
||||
return (
|
||||
<Modal className="wizard-dialog" title={tr('wizardTitle')} closeLabel={tr('close')} onClose={onClose}>
|
||||
<nav className="wizard-steps" aria-label={tr('wizardTitle')}>
|
||||
{driverID !== STAMBHA_DRIVER_ID && <nav className="wizard-steps" aria-label={tr('wizardTitle')}>
|
||||
{steps.map((key, idx) => {
|
||||
const n = idx + 1
|
||||
const bad = issueSteps.has(n) && n !== REVIEW_STEP
|
||||
@@ -312,7 +315,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</nav>
|
||||
</nav>}
|
||||
|
||||
<div className="dialog-body">
|
||||
{err && <div className="notice notice-error">{err}</div>}
|
||||
@@ -332,7 +335,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
value: d.id,
|
||||
label: locText(d.name, locale, d.id),
|
||||
}))}
|
||||
onChange={(id) => { setDriverID(id); setErr('') }}
|
||||
onChange={(id) => { setDriverID(id); setDriverOpts({}); setErr('') }}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
@@ -346,6 +349,19 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
control={<input className="input rg-p-input" value={opts.name} onChange={(e) => set({ name: e.target.value })} />}
|
||||
/>
|
||||
</SetGroup>
|
||||
{driverID === STAMBHA_DRIVER_ID && (
|
||||
<SetGroup title={tr('armRestoreGroup')}>
|
||||
<SetRow title={tr('armRestoreVersion')} desc={tr('armRestoreMediaHint')} control={
|
||||
<Button busy={armImageTask?.status === 'running'} onClick={() => {
|
||||
setErr('')
|
||||
void api.DownloadARMImage().catch((e) => setErr(parseAppError(e).summary))
|
||||
}}>{tr('armRestoreDownload')}</Button>
|
||||
} />
|
||||
{armImageTask?.status === 'done' && armImageTask.result && (
|
||||
<SetRow title={tr('armRestoreDownloaded')} desc={<span className="mono path-text">{armImageTask.result}</span>} />
|
||||
)}
|
||||
</SetGroup>
|
||||
)}
|
||||
{activeDriver.create_schema && (
|
||||
<Suspense fallback={null}>
|
||||
<SchemaForm
|
||||
@@ -353,6 +369,12 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
schema={activeDriver.create_schema}
|
||||
values={driverOpts}
|
||||
onChange={setDriverOpts}
|
||||
pathFields={driverID === STAMBHA_DRIVER_ID ? {
|
||||
boot_volume: true,
|
||||
raw_disk: '*.qcow2;*.raw;*.img',
|
||||
usb_image: '*.raw;*.img;*.bin',
|
||||
} : undefined}
|
||||
onPickError={(e) => setErr(parseAppError(e).summary)}
|
||||
/>
|
||||
</Suspense>
|
||||
)}
|
||||
@@ -792,7 +814,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
await api.CreateVMWithDriver({
|
||||
driver_id: driverID,
|
||||
name: opts.name.trim(),
|
||||
dir: opts.dir,
|
||||
dir: driverID === STAMBHA_DRIVER_ID ? '' : opts.dir,
|
||||
options: driverOpts,
|
||||
})
|
||||
onClose()
|
||||
|
||||
@@ -5,6 +5,7 @@ import '../i18n/domains/wizard.gen'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { formatBytes, gpuCompatHint, gpuKey, gpuMetaLine, sameGPU } from '../lib/format'
|
||||
import { describeHostWHPX } from '../lib/hypervisor'
|
||||
import { hasStambhaRuntime, STAMBHA_RUNTIME_KIND } from '../lib/endpoints'
|
||||
import { AppState, Locale, StorageBreakdown, Task } from '../types'
|
||||
import { Button, IconButton } from '../ui/controls'
|
||||
import { Switch } from '../ui/settings'
|
||||
@@ -111,7 +112,7 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{(state.vms?.length ?? 0) === 0 && host.whpx === 'ready' && !!state.active_runtime && onNewVM && (
|
||||
{(state.vms?.length ?? 0) === 0 && host.whpx === 'ready' && (!!state.active_runtime || hasStambhaRuntime(runtimes)) && onNewVM && (
|
||||
<section className="welcome-card">
|
||||
<h1>{tr('welcomeTitle')}</h1>
|
||||
<p>{tr('welcomeSub')}</p>
|
||||
@@ -228,43 +229,51 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
|
||||
<Switch label={tr('qemuASLR')} checked={!!config.qemu_aslr} disabled={savingASLR} onChange={setQEMUASLR} />
|
||||
</div>
|
||||
</div>
|
||||
{(runtimes ?? []).filter((rt) => !rt.active).map((rt) => (
|
||||
<div className="row" key={rt.commit}>
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
<span className="mono">{rt.commit}</span>
|
||||
{latestRuntimeCommit && sameRuntimeId(rt.commit, latestRuntimeCommit) && (
|
||||
<span className="badge rg-p-badge badge-ok">{tr('runtimeLatestBadge')}</span>
|
||||
{(runtimes ?? []).filter((rt) => !rt.active).map((rt) => {
|
||||
const stambha = rt.kind === STAMBHA_RUNTIME_KIND
|
||||
const ref = stambha ? STAMBHA_RUNTIME_KIND + '/' + rt.commit : rt.commit
|
||||
return (
|
||||
<div className="row" key={ref}>
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
<span className="mono">{stambha ? rt.manifest.name || rt.commit : rt.commit}</span>
|
||||
{(stambha || !rt.kind || rt.kind === 'reims-vgpu') &&
|
||||
<span className="badge rg-p-badge">{tr(stambha ? 'armRuntimeLabel' : 'x86RuntimeLabel')}</span>}
|
||||
{!stambha && latestRuntimeCommit && sameRuntimeId(rt.commit, latestRuntimeCommit) && (
|
||||
<span className="badge rg-p-badge badge-ok">{tr('runtimeLatestBadge')}</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="row-sub">{rt.manifest.qemu_version?.replace(/^QEMU emulator version\s*/i, 'QEMU ')}</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
{confirmDelete === ref ? (
|
||||
<>
|
||||
<Button variant="ghost" disabled={removing === ref} onClick={() => setConfirmDelete('')}>
|
||||
{tr('cancel')}
|
||||
</Button>
|
||||
<Button variant="danger" busy={removing === ref} onClick={() => removeRuntime(ref)}>
|
||||
{tr('runtimeDeleteConfirm')}
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{!stambha && (
|
||||
<Button disabled={removing === ref} onClick={guard(() => api.UseRuntime(rt.commit))}>
|
||||
{tr('activate')}
|
||||
</Button>
|
||||
)}
|
||||
<IconButton
|
||||
label={tr('runtimeDelete')}
|
||||
icon={<Trash size={15} />}
|
||||
disabled={removing !== ''}
|
||||
onClick={() => setConfirmDelete(ref)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="row-sub">{rt.manifest.qemu_version.replace(/^QEMU emulator version\s*/i, 'QEMU ')}</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
{confirmDelete === rt.commit ? (
|
||||
<>
|
||||
<Button variant="ghost" disabled={removing === rt.commit} onClick={() => setConfirmDelete('')}>
|
||||
{tr('cancel')}
|
||||
</Button>
|
||||
<Button variant="danger" busy={removing === rt.commit} onClick={() => removeRuntime(rt.commit)}>
|
||||
{tr('runtimeDeleteConfirm')}
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Button disabled={removing === rt.commit} onClick={guard(() => api.UseRuntime(rt.commit))}>
|
||||
{tr('activate')}
|
||||
</Button>
|
||||
<IconButton
|
||||
label={tr('runtimeDelete')}
|
||||
icon={<Trash size={15} />}
|
||||
disabled={removing !== ''}
|
||||
onClick={() => setConfirmDelete(rt.commit)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@ import '../i18n/domains/settings.gen'
|
||||
import { locText, t } from '../i18n'
|
||||
import { Locale, SettingProperty, SettingsSchema } from '../types'
|
||||
import { NumberField, PopupSelect, Segmented, SetGroup, SetRow, Switch } from '../ui/settings'
|
||||
import { Button } from '../ui/controls'
|
||||
import { api } from '../wails'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
@@ -13,6 +15,8 @@ interface Props {
|
||||
groupFilter?: string
|
||||
onChange: (next: Record<string, unknown>, patch: Record<string, unknown>) => void
|
||||
hideGroupHeader?: boolean
|
||||
pathFields?: Readonly<Record<string, string | true>>
|
||||
onPickError?: (error: unknown) => void
|
||||
}
|
||||
|
||||
const SECRET_MASK = '••••••••'
|
||||
@@ -20,7 +24,7 @@ const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype'])
|
||||
|
||||
/** Lazy-loaded JSON Schema form renderer supporting x-secret, x-effect, and x-scope. */
|
||||
export const SchemaForm: React.FC<Props> = ({
|
||||
locale, schema, values, scopeFilter, groupFilter, onChange, hideGroupHeader,
|
||||
locale, schema, values, scopeFilter, groupFilter, onChange, hideGroupHeader, pathFields, onPickError,
|
||||
}) => {
|
||||
const propsMap = schema.properties ?? {}
|
||||
const keys = (schema['x-order'] && schema['x-order'].length > 0
|
||||
@@ -134,6 +138,29 @@ export const SchemaForm: React.FC<Props> = ({
|
||||
)
|
||||
}
|
||||
|
||||
const pathField = pathFields?.[k]
|
||||
if (pathField !== undefined) {
|
||||
return (
|
||||
<div className="input-group">
|
||||
<input
|
||||
type="text"
|
||||
className="input rg-p-input"
|
||||
aria-label={label}
|
||||
value={String(cur ?? '')}
|
||||
onChange={(e) => setKey(k, e.target.value)}
|
||||
/>
|
||||
<Button onClick={async () => {
|
||||
try {
|
||||
const path = pathField === true ? await api.PickDirectory(label) : await api.PickFile(label, pathField)
|
||||
if (path) setKey(k, path)
|
||||
} catch (error) {
|
||||
onPickError?.(error)
|
||||
}
|
||||
}}>{t(locale, 'choose')}</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<input
|
||||
type="text"
|
||||
|
||||
@@ -8,6 +8,7 @@ import { Button } from '../ui/controls'
|
||||
import { PopupSelect } from '../ui/settings'
|
||||
import { gpuCompatHint, recommendedMemoryGB, shortGPUName } from '../lib/format'
|
||||
import { describeHostWHPX } from '../lib/hypervisor'
|
||||
import { hasStambhaRuntime } from '../lib/endpoints'
|
||||
import { api } from '../wails'
|
||||
import { PluginAppIcon } from './PluginAppIcon'
|
||||
import { RuntimeOnline } from './RuntimeOnline'
|
||||
@@ -205,7 +206,7 @@ const FolderStep: React.FC<StepProps> = ({ locale, locales, state, tr, onLocale,
|
||||
}
|
||||
|
||||
const RuntimeStep: React.FC<StepProps> = ({ locale, tr, state, runtimeTask, onChannel, onInstallRuntime, onCancelTask, onImportRuntime, onFolderDone, onFinish, onError }) => {
|
||||
const ready = !!state.active_runtime
|
||||
const ready = !!state.active_runtime || hasStambhaRuntime(state.runtimes)
|
||||
const { host } = state
|
||||
const [enabling, setEnabling] = useState(false)
|
||||
const [activating, setActivating] = useState('')
|
||||
|
||||
@@ -2,6 +2,12 @@
|
||||
import { registerBuiltinDomain } from '../runtime'
|
||||
|
||||
export const wizardZh: Record<string, string> = {
|
||||
"armRestoreDownload": "下载 IPSW",
|
||||
"armRestoreDownloaded": "已下载的 IPSW",
|
||||
"armRestoreGroup": "ARM 恢复镜像",
|
||||
"armRestoreMediaHint": "从 Apple 下载 IPSW。创建虚拟机时,请在下方选择已制作的 Stambha 启动介质和可写虚拟磁盘。",
|
||||
"armRestoreVersion": "macOS 27.2.1 (26B131) · 25.6 GB",
|
||||
"armRuntimeLabel": "ARM64 来宾",
|
||||
"commandToggle": "等效命令",
|
||||
"commandToggleHint": "在终端运行下面这条命令效果相同",
|
||||
"createNow": "创建",
|
||||
@@ -90,9 +96,16 @@ export const wizardZh: Record<string, string> = {
|
||||
"wizardDriverGroup": "客体平台驱动",
|
||||
"wizardDriverType": "驱动类型",
|
||||
"wizardTitle": "新建虚拟机",
|
||||
"x86RuntimeLabel": "x86-64 来宾",
|
||||
}
|
||||
|
||||
export const wizardEn: Record<string, string> = {
|
||||
"armRestoreDownload": "Download IPSW",
|
||||
"armRestoreDownloaded": "Downloaded IPSW",
|
||||
"armRestoreGroup": "ARM restore image",
|
||||
"armRestoreMediaHint": "Download the IPSW from Apple. To create a VM, select prepared Stambha boot media and a writable virtual disk below.",
|
||||
"armRestoreVersion": "macOS 27.2.1 (26B131) · 25.6 GB",
|
||||
"armRuntimeLabel": "ARM64 guest",
|
||||
"commandToggle": "Equivalent command",
|
||||
"commandToggleHint": "Running this in a terminal does the same thing",
|
||||
"createNow": "Create",
|
||||
@@ -181,6 +194,7 @@ export const wizardEn: Record<string, string> = {
|
||||
"wizardDriverGroup": "Guest driver",
|
||||
"wizardDriverType": "Driver",
|
||||
"wizardTitle": "New virtual machine",
|
||||
"x86RuntimeLabel": "x86-64 guest",
|
||||
}
|
||||
|
||||
registerBuiltinDomain(wizardZh, wizardEn)
|
||||
@@ -68,6 +68,12 @@ export type I18nKey =
|
||||
| "appVersionTitle"
|
||||
| "appearance"
|
||||
| "appliesNextStart"
|
||||
| "armRestoreDownload"
|
||||
| "armRestoreDownloaded"
|
||||
| "armRestoreGroup"
|
||||
| "armRestoreMediaHint"
|
||||
| "armRestoreVersion"
|
||||
| "armRuntimeLabel"
|
||||
| "attachGuestTools"
|
||||
| "attachInstaller"
|
||||
| "audioBackendAuto"
|
||||
@@ -1189,4 +1195,5 @@ export type I18nKey =
|
||||
| "wizardBasics"
|
||||
| "wizardDriverGroup"
|
||||
| "wizardDriverType"
|
||||
| "wizardTitle";
|
||||
| "wizardTitle"
|
||||
| "x86RuntimeLabel";
|
||||
@@ -1,9 +1,15 @@
|
||||
import type { VMEndpoint, VMInfo, VMListItem } from '../types'
|
||||
import type { InstalledRuntime, VMEndpoint, VMInfo, VMListItem } from '../types'
|
||||
|
||||
// Guest family, driver capabilities and endpoint ordering for non-macOS guests.
|
||||
// Everything here is pure so node:test can load it (scripts/test-endpoints.mjs).
|
||||
|
||||
const BUILTIN_MACOS_DRIVER = 'builtin.driver.reims-macos'
|
||||
export const STAMBHA_DRIVER_ID = 'builtin.driver.stambha'
|
||||
export const STAMBHA_RUNTIME_KIND = 'stambha-hosted'
|
||||
|
||||
export function hasStambhaRuntime(runtimes?: InstalledRuntime[] | null): boolean {
|
||||
return runtimes?.some((rt) => rt.kind === STAMBHA_RUNTIME_KIND && rt.manifest.runtime_api === '0.1.0') ?? false
|
||||
}
|
||||
|
||||
export type GuestFamily = 'macos' | 'linux' | 'windows' | 'android' | ''
|
||||
|
||||
|
||||
@@ -67,7 +67,7 @@ export function isInstallerTask(task: Task): boolean {
|
||||
}
|
||||
|
||||
export function taskInstallerKind(task: Task): InstallerKind | '' {
|
||||
if (task.installer_kind === 'offline' || task.installer_kind === 'online') return task.installer_kind
|
||||
if (task.installer_kind === 'offline' || task.installer_kind === 'online' || task.installer_kind === 'arm-ipsw') return task.installer_kind
|
||||
if (task.kind === 'installer-download') return 'offline'
|
||||
if (task.kind === 'recovery-download') return 'online'
|
||||
return ''
|
||||
|
||||
@@ -246,6 +246,9 @@ export const InstallersPage: React.FC<Props> = ({
|
||||
active,
|
||||
}
|
||||
}
|
||||
if (kind === 'arm-ipsw') {
|
||||
return { key: `active-${task.id}`, title: task.subject, version, kind: 'ipsw', active }
|
||||
}
|
||||
return {
|
||||
key: `active-${taskInstallerKey(task) || task.id}`,
|
||||
title: formatOnlineTitle(version),
|
||||
|
||||
@@ -126,7 +126,7 @@ export type CreateOpts = Model<reims.CreateOpts> & {
|
||||
|
||||
type TaskStatus = 'running' | 'done' | 'failed' | 'canceled'
|
||||
|
||||
export type InstallerKind = 'offline' | 'online'
|
||||
export type InstallerKind = 'offline' | 'online' | 'arm-ipsw'
|
||||
export type InstallerPhase = 'queued' | 'downloading'
|
||||
|
||||
/** A tracked long-running job pushed as "reims:task" (internal/app/tasks.go). */
|
||||
|
||||
Vendored
+2
@@ -72,6 +72,8 @@ export function DownloadAppUpdate():Promise<string>;
|
||||
|
||||
export function DownloadInstaller(arg1:string):Promise<string>;
|
||||
|
||||
export function DownloadARMImage():Promise<string>;
|
||||
|
||||
export function EjectInstaller(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function EnablePlugin(arg1:string,arg2:boolean):Promise<void>;
|
||||
|
||||
@@ -118,6 +118,10 @@ export function DownloadAppUpdate() {
|
||||
return window['go']['app']['App']['DownloadAppUpdate']();
|
||||
}
|
||||
|
||||
export function DownloadARMImage() {
|
||||
return window['go']['app']['App']['DownloadARMImage']();
|
||||
}
|
||||
|
||||
export function DownloadInstaller(arg1) {
|
||||
return window['go']['app']['App']['DownloadInstaller'](arg1);
|
||||
}
|
||||
|
||||
+44
-52
@@ -21,6 +21,7 @@ import (
|
||||
vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle"
|
||||
"github.com/Nwflower/reims-go/internal/packetbridge"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/market"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/tray"
|
||||
"github.com/Nwflower/reims-go/internal/version"
|
||||
@@ -121,55 +122,41 @@ type App struct {
|
||||
trayMgr *tray.Manager
|
||||
allowQuit bool
|
||||
launchPrevDataRoot string
|
||||
quitMode string
|
||||
vmStarts sync.WaitGroup
|
||||
lastVMs []driver.VMListItem
|
||||
lastVMsAt time.Time // when pollVMs last refreshed lastVMs; zero = stale
|
||||
lastVMListErr error
|
||||
pollWake chan struct{} // wakePoll: run pollVMs now instead of at its next tick
|
||||
diskPaths map[string]cachedDiskPath
|
||||
procSamples map[string]host.ProcessSample
|
||||
recentLogs []string
|
||||
needsSetup bool
|
||||
root dataroot.Status // how the current data folder opened (dataroot_flow.go)
|
||||
launch cli.WindowArgs // flags this window was started with (window_launch.go)
|
||||
trayIcon []byte // embedded PNG passed in from package main
|
||||
logCaptures map[string][]*logCapture // emitLog source → captures (window_launch.go)
|
||||
pluginMgr *plugin.Manager
|
||||
pluginFiles map[string]pluginFileGrant
|
||||
pluginMarket *plugin.MarketClient
|
||||
controlServer *control.Server
|
||||
driverRouter *driver.Router
|
||||
vmStateTable *driver.StateTable
|
||||
lifecycleSvc *vmlifecycle.Service
|
||||
runtimeKinds *rt.KindRegistry
|
||||
uiHealth uiHealthState
|
||||
themeMode string
|
||||
vmClosePrompts sync.Map
|
||||
displayHost vmDisplayHost
|
||||
quitMode string
|
||||
vmStarts sync.WaitGroup
|
||||
lastVMs []driver.VMListItem
|
||||
lastVMsAt time.Time // when pollVMs last refreshed lastVMs; zero = stale
|
||||
lastVMListErr error
|
||||
pollWake chan struct{} // wakePoll: run pollVMs now instead of at its next tick
|
||||
diskPaths map[string]cachedDiskPath
|
||||
procSamples map[string]host.ProcessSample
|
||||
recentLogs []string
|
||||
needsSetup bool
|
||||
root dataroot.Status // how the current data folder opened (dataroot_flow.go)
|
||||
launch cli.WindowArgs // flags this window was started with (window_launch.go)
|
||||
trayIcon []byte // embedded PNG passed in from package main
|
||||
logCaptures map[string][]*logCapture // emitLog source → captures (window_launch.go)
|
||||
pluginMgr *plugin.Manager
|
||||
pluginMarket *market.MarketClient
|
||||
controlServer *control.Server
|
||||
driverRouter *driver.Router
|
||||
vmStateTable *driver.StateTable
|
||||
lifecycleSvc *vmlifecycle.Service
|
||||
runtimeKinds *rt.KindRegistry
|
||||
uiHealth uiHealthState
|
||||
themeMode string
|
||||
vmClosePrompts sync.Map
|
||||
displayHost vmDisplayHost
|
||||
|
||||
displayPlacements sync.Map
|
||||
|
||||
inputShuttingDown bool
|
||||
// computerUseOwnedVMs caches ownership markers for MCP-created temporary VMs.
|
||||
computerUseOwnedVMs map[string]map[string]bool
|
||||
computerUseCloneMu sync.Mutex
|
||||
// computerUseHeld records the keys and pointer buttons each plugin left
|
||||
// held in a guest, so the host can release them when the plugin goes away.
|
||||
computerUseHeld map[string]map[string]*heldInputs
|
||||
computerUseHeldMu sync.Mutex
|
||||
fullscreenHotkey host.FullscreenHotkeyService
|
||||
fullscreenSyncMu sync.Mutex
|
||||
fullscreenTargets fullscreenHotkeyTargetCache
|
||||
|
||||
// Plugin elevation requests (elevate_flow.go).
|
||||
elevatePromptMu sync.Mutex
|
||||
elevateMu sync.Mutex
|
||||
elevatePending map[string]chan bool
|
||||
elevateSeq uint64
|
||||
elevateEmit func(ElevationPrompt)
|
||||
elevateDismiss func(string)
|
||||
elevateRunner elevationRunner
|
||||
// Host-side plugin API service (computer-use, secrets, downloads, elevation, file grants).
|
||||
hostAPI HostAPIService
|
||||
}
|
||||
|
||||
// Lifecycle exposes Wails lifecycle callbacks without exporting them as
|
||||
@@ -204,17 +191,18 @@ func New(trayIcon []byte, launch cli.WindowArgs) (*App, Lifecycle) {
|
||||
needsSetup: needsSetup,
|
||||
launch: launch,
|
||||
launchPrevDataRoot: launchPrevDataRoot,
|
||||
trayIcon: trayIcon,
|
||||
transitions: make(map[string]string),
|
||||
pendingChanges: make(map[string][]PendingChange),
|
||||
rebootWatchers: make(map[string]rebootWatcherEntry),
|
||||
pollWake: make(chan struct{}, 1),
|
||||
diskPaths: make(map[string]cachedDiskPath),
|
||||
procSamples: make(map[string]host.ProcessSample),
|
||||
pluginFiles: make(map[string]pluginFileGrant),
|
||||
uiHealth: uiHealthState{windowHidden: launch.Background},
|
||||
displayHost: vmDisplayHost{displays: host.ConnectedDisplays, move: host.MoveProcessWindowToDisplay},
|
||||
trayIcon: trayIcon,
|
||||
transitions: make(map[string]string),
|
||||
pendingChanges: make(map[string][]PendingChange),
|
||||
rebootWatchers: make(map[string]rebootWatcherEntry),
|
||||
pollWake: make(chan struct{}, 1),
|
||||
diskPaths: make(map[string]cachedDiskPath),
|
||||
procSamples: make(map[string]host.ProcessSample),
|
||||
uiHealth: uiHealthState{windowHidden: launch.Background},
|
||||
displayHost: vmDisplayHost{displays: host.ConnectedDisplays, move: host.MoveProcessWindowToDisplay},
|
||||
}
|
||||
a.hostAPI.app = a
|
||||
a.hostAPI.pluginFiles = make(map[string]pluginFileGrant)
|
||||
return a, Lifecycle{
|
||||
OnStartup: a.startup,
|
||||
OnBeforeClose: a.beforeClose,
|
||||
@@ -617,8 +605,8 @@ func (a *App) resetDataRootCaches() {
|
||||
a.lastVMListErr = nil
|
||||
a.diskPaths = make(map[string]cachedDiskPath)
|
||||
a.procSamples = make(map[string]host.ProcessSample)
|
||||
a.pluginFiles = make(map[string]pluginFileGrant)
|
||||
a.mu.Unlock()
|
||||
a.hostAPISvc().ResetPluginFiles()
|
||||
cancelPluginTasks("")
|
||||
}
|
||||
|
||||
@@ -834,6 +822,10 @@ func (a *App) InstallRuntimeArchive(archivePath string) (*rt.Installed, error) {
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if inst.Kind == rt.StambhaKind {
|
||||
a.emitLog("runtime", fmt.Sprintf("Runtime %s installed -> %s", inst.Commit, inst.Dir))
|
||||
return inst, nil
|
||||
}
|
||||
if err := a.activateInstalledRuntime(&cfg, inst.Commit); err != nil {
|
||||
inst.Active = false
|
||||
a.emitLog("runtime", err.Error())
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/fetch"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/macos/installer"
|
||||
"github.com/Nwflower/reims-go/internal/netproxy"
|
||||
)
|
||||
|
||||
const (
|
||||
armImageBuild = "26B131"
|
||||
armImageName = "UniversalMac_27.2.1_26B131_Restore.ipsw"
|
||||
armImageURL = "https://updates.cdn-apple.com/2026FallFCS/c202a724-db7e-4d56-917b-110aa0226507/" + armImageName
|
||||
armImageSHA = "233e85a09887579d47d0b195e7db72be7f204261059c6946f719acf6b300814f"
|
||||
armImageSize = int64(25595954706)
|
||||
)
|
||||
|
||||
// DownloadARMImage fetches the pinned ARM restore image from Apple into the user data folder.
|
||||
func (a *App) DownloadARMImage() (string, error) {
|
||||
cfg := a.runtimeConfig()
|
||||
if err := cfg.EnsureDirs(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
final := filepath.Join(cfg.ImagesDir(), "arm64", armImageName)
|
||||
if err := os.MkdirAll(filepath.Dir(final), 0o755); err != nil {
|
||||
return "", err
|
||||
}
|
||||
a.ensureTaskEmitter()
|
||||
var ctx context.Context
|
||||
var cancel context.CancelFunc
|
||||
run, id, owned := installerDownloads.reserveOrFind("arm-ipsw", armImageBuild, "installer-download", func(initialPhase string) string {
|
||||
ctx, cancel = context.WithCancel(a.baseCtx())
|
||||
return tasks.startWithInstaller("installer-download", "macOS 27.2.1 · ARM64", "", "arm-ipsw", armImageBuild, initialPhase, cancel)
|
||||
})
|
||||
if !owned {
|
||||
return id, nil
|
||||
}
|
||||
go func() {
|
||||
defer cancel()
|
||||
client := netproxy.NewClient()
|
||||
client.Timeout = 0
|
||||
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
|
||||
if len(via) >= 10 || req.URL.Scheme != "https" || req.URL.Hostname() != "updates.cdn-apple.com" {
|
||||
return errors.New("ARM restore image download redirected outside Apple's update server")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
path, err := fetch.ResumeDirect(ctx, client, armImageURL, final, armImageSize, armImageSHA, func(done, total int64) {
|
||||
update := host.Update{Kind: host.KindProgress, Done: done, Total: total, Percent: percent(done, total)}
|
||||
tasks.update(id, update)
|
||||
run.publish(update)
|
||||
}, fetch.ResumeOptions{MaxBytes: armImageSize, StallTimeout: 45 * time.Second})
|
||||
if err == nil {
|
||||
if info, statErr := os.Stat(path); statErr != nil {
|
||||
err = statErr
|
||||
} else if info.Size() != armImageSize {
|
||||
err = errors.New("ARM restore image size does not match the pinned build")
|
||||
}
|
||||
}
|
||||
if err != nil && ctx.Err() != nil {
|
||||
err = ctx.Err()
|
||||
}
|
||||
var result *installer.Result
|
||||
if err == nil {
|
||||
result = &installer.Result{Image: path}
|
||||
} else {
|
||||
path = ""
|
||||
}
|
||||
installerDownloads.complete(run, result, err)
|
||||
tasks.finish(id, path, err)
|
||||
}()
|
||||
return id, nil
|
||||
}
|
||||
@@ -44,8 +44,8 @@ type heldInputs struct {
|
||||
// noteHeldKey records or forgets one key transition. code must already be a
|
||||
// QKeyCode.
|
||||
func (a *App) noteHeldKey(pluginID, vmKey, code string, down bool) {
|
||||
a.computerUseHeldMu.Lock()
|
||||
defer a.computerUseHeldMu.Unlock()
|
||||
a.hostAPI.heldMu.Lock()
|
||||
defer a.hostAPI.heldMu.Unlock()
|
||||
held := a.heldLocked(pluginID, vmKey)
|
||||
if down {
|
||||
held.keys[code] = true
|
||||
@@ -57,8 +57,8 @@ func (a *App) noteHeldKey(pluginID, vmKey, code string, down bool) {
|
||||
|
||||
// noteHeldButton records or forgets one pointer button transition.
|
||||
func (a *App) noteHeldButton(pluginID, vmKey, button string, down bool) {
|
||||
a.computerUseHeldMu.Lock()
|
||||
defer a.computerUseHeldMu.Unlock()
|
||||
a.hostAPI.heldMu.Lock()
|
||||
defer a.hostAPI.heldMu.Unlock()
|
||||
held := a.heldLocked(pluginID, vmKey)
|
||||
if down {
|
||||
held.buttons[button] = true
|
||||
@@ -71,13 +71,13 @@ func (a *App) noteHeldButton(pluginID, vmKey, button string, down bool) {
|
||||
// heldLocked returns the record for one plugin and VM, creating it when
|
||||
// needed. The caller holds computerUseHeldMu.
|
||||
func (a *App) heldLocked(pluginID, vmKey string) *heldInputs {
|
||||
if a.computerUseHeld == nil {
|
||||
a.computerUseHeld = map[string]map[string]*heldInputs{}
|
||||
if a.hostAPI.computerUseHeld == nil {
|
||||
a.hostAPI.computerUseHeld = map[string]map[string]*heldInputs{}
|
||||
}
|
||||
byVM := a.computerUseHeld[pluginID]
|
||||
byVM := a.hostAPI.computerUseHeld[pluginID]
|
||||
if byVM == nil {
|
||||
byVM = map[string]*heldInputs{}
|
||||
a.computerUseHeld[pluginID] = byVM
|
||||
a.hostAPI.computerUseHeld[pluginID] = byVM
|
||||
}
|
||||
held := byVM[vmKey]
|
||||
if held == nil {
|
||||
@@ -113,7 +113,7 @@ func (a *App) armHeldTimerLocked(pluginID, vmKey string, held *heldInputs, d tim
|
||||
// pruneHeldLocked drops a record that holds nothing, so an idle plugin leaves
|
||||
// no state behind. The caller holds computerUseHeldMu.
|
||||
func (a *App) pruneHeldLocked(pluginID, vmKey string) {
|
||||
byVM := a.computerUseHeld[pluginID]
|
||||
byVM := a.hostAPI.computerUseHeld[pluginID]
|
||||
if byVM == nil {
|
||||
return
|
||||
}
|
||||
@@ -125,16 +125,16 @@ func (a *App) pruneHeldLocked(pluginID, vmKey string) {
|
||||
delete(byVM, vmKey)
|
||||
}
|
||||
if len(byVM) == 0 {
|
||||
delete(a.computerUseHeld, pluginID)
|
||||
delete(a.hostAPI.computerUseHeld, pluginID)
|
||||
}
|
||||
}
|
||||
|
||||
// heldSnapshot returns what one plugin holds in one VM, sorted, with the
|
||||
// generation it was read at.
|
||||
func (a *App) heldSnapshot(pluginID, vmKey string) (keys, buttons []string, generation uint64) {
|
||||
a.computerUseHeldMu.Lock()
|
||||
defer a.computerUseHeldMu.Unlock()
|
||||
byVM := a.computerUseHeld[pluginID]
|
||||
a.hostAPI.heldMu.Lock()
|
||||
defer a.hostAPI.heldMu.Unlock()
|
||||
byVM := a.hostAPI.computerUseHeld[pluginID]
|
||||
if byVM == nil {
|
||||
return nil, nil, 0
|
||||
}
|
||||
@@ -156,9 +156,9 @@ func (a *App) heldSnapshot(pluginID, vmKey string) (keys, buttons []string, gene
|
||||
// heldGeneration returns the record's current generation, or 0 when there is
|
||||
// no record.
|
||||
func (a *App) heldGeneration(pluginID, vmKey string) uint64 {
|
||||
a.computerUseHeldMu.Lock()
|
||||
defer a.computerUseHeldMu.Unlock()
|
||||
if held := a.computerUseHeld[pluginID][vmKey]; held != nil {
|
||||
a.hostAPI.heldMu.Lock()
|
||||
defer a.hostAPI.heldMu.Unlock()
|
||||
if held := a.hostAPI.computerUseHeld[pluginID][vmKey]; held != nil {
|
||||
return held.generation
|
||||
}
|
||||
return 0
|
||||
@@ -166,10 +166,10 @@ func (a *App) heldGeneration(pluginID, vmKey string) uint64 {
|
||||
|
||||
// heldVMs lists the VMs one plugin currently holds input in.
|
||||
func (a *App) heldVMs(pluginID string) map[string]bool {
|
||||
a.computerUseHeldMu.Lock()
|
||||
defer a.computerUseHeldMu.Unlock()
|
||||
a.hostAPI.heldMu.Lock()
|
||||
defer a.hostAPI.heldMu.Unlock()
|
||||
out := map[string]bool{}
|
||||
for vmKey := range a.computerUseHeld[pluginID] {
|
||||
for vmKey := range a.hostAPI.computerUseHeld[pluginID] {
|
||||
out[vmKey] = true
|
||||
}
|
||||
return out
|
||||
@@ -179,9 +179,9 @@ func (a *App) heldVMs(pluginID string) map[string]bool {
|
||||
// when the caller itself named what it lifted, so there is no snapshot to
|
||||
// compare with.
|
||||
func (a *App) dropHeld(pluginID, vmKey string, keys, buttons []string) {
|
||||
a.computerUseHeldMu.Lock()
|
||||
defer a.computerUseHeldMu.Unlock()
|
||||
held := a.computerUseHeld[pluginID][vmKey]
|
||||
a.hostAPI.heldMu.Lock()
|
||||
defer a.hostAPI.heldMu.Unlock()
|
||||
held := a.hostAPI.computerUseHeld[pluginID][vmKey]
|
||||
if held == nil {
|
||||
return
|
||||
}
|
||||
@@ -199,9 +199,9 @@ func (a *App) dropHeld(pluginID, vmKey string, keys, buttons []string) {
|
||||
// meantime may hold a press this release did not lift, so it keeps everything
|
||||
// and its timer releases it later.
|
||||
func (a *App) dropHeldIfGeneration(pluginID, vmKey string, keys, buttons []string, generation uint64) bool {
|
||||
a.computerUseHeldMu.Lock()
|
||||
defer a.computerUseHeldMu.Unlock()
|
||||
held := a.computerUseHeld[pluginID][vmKey]
|
||||
a.hostAPI.heldMu.Lock()
|
||||
defer a.hostAPI.heldMu.Unlock()
|
||||
held := a.hostAPI.computerUseHeld[pluginID][vmKey]
|
||||
if held == nil {
|
||||
return false
|
||||
}
|
||||
@@ -221,9 +221,9 @@ func (a *App) dropHeldIfGeneration(pluginID, vmKey string, keys, buttons []strin
|
||||
// rearmHeld schedules another fallback release for a record whose release
|
||||
// failed while the VM is still running.
|
||||
func (a *App) rearmHeld(pluginID, vmKey string) {
|
||||
a.computerUseHeldMu.Lock()
|
||||
defer a.computerUseHeldMu.Unlock()
|
||||
held := a.computerUseHeld[pluginID][vmKey]
|
||||
a.hostAPI.heldMu.Lock()
|
||||
defer a.hostAPI.heldMu.Unlock()
|
||||
held := a.hostAPI.computerUseHeld[pluginID][vmKey]
|
||||
if held == nil || len(held.keys)+len(held.buttons) == 0 {
|
||||
return
|
||||
}
|
||||
@@ -235,8 +235,8 @@ func (a *App) rearmHeld(pluginID, vmKey string) {
|
||||
// can still be held, and a release sent later could lift a key the user is
|
||||
// pressing after the VM starts again.
|
||||
func (a *App) forgetHeld(pluginID, vmKey string) {
|
||||
a.computerUseHeldMu.Lock()
|
||||
defer a.computerUseHeldMu.Unlock()
|
||||
a.hostAPI.heldMu.Lock()
|
||||
defer a.hostAPI.heldMu.Unlock()
|
||||
a.pruneHeldLocked(pluginID, vmKey)
|
||||
}
|
||||
|
||||
|
||||
@@ -48,23 +48,23 @@ func (a *App) computerUseHostHandlers(mgr *plugin.Manager, pluginID string) map[
|
||||
return nil
|
||||
}
|
||||
return map[string]plugin.RPCRequestHandler{
|
||||
"host/vm.list": a.hostVMMethod(mgr, pluginID, "host/vm.list", a.handleComputerUseVMList),
|
||||
"host/vm.get": a.hostVMMethod(mgr, pluginID, "host/vm.get", a.handleComputerUseVMGet),
|
||||
"host/vm.start": a.hostVMMethod(mgr, pluginID, "host/vm.start", a.handleComputerUseVMStart),
|
||||
"host/vm.shutdown": a.hostVMMethod(mgr, pluginID, "host/vm.shutdown", a.handleComputerUseVMShutdown),
|
||||
"host/vm.suspend": a.hostVMMethod(mgr, pluginID, "host/vm.suspend", a.handleComputerUseVMStateChange("host/vm.suspend", a.SuspendVM)),
|
||||
"host/vm.resume": a.hostVMMethod(mgr, pluginID, "host/vm.resume", a.handleComputerUseVMStateChange("host/vm.resume", a.ResumeVM)),
|
||||
"host/vm.clone": a.hostVMMethod(mgr, pluginID, "host/vm.clone", a.handleComputerUseVMClone),
|
||||
"host/vm.delete": a.hostVMMethod(mgr, pluginID, "host/vm.delete", a.handleComputerUseVMDelete),
|
||||
"host/vm.snapshot.list": a.hostVMMethod(mgr, pluginID, "host/vm.snapshot.list", a.handleComputerUseVMSnapshotList),
|
||||
"host/vm.snapshot.create": a.hostVMMethod(mgr, pluginID, "host/vm.snapshot.create", a.handleComputerUseVMSnapshotCreate),
|
||||
"host/vm.snapshot.restore": a.hostVMMethod(mgr, pluginID, "host/vm.snapshot.restore", a.handleComputerUseVMSnapshotRestore),
|
||||
"host/console.screenshot": a.hostVMMethod(mgr, pluginID, "host/console.screenshot", a.handleComputerUseScreenshot),
|
||||
"host/console.pointer": a.hostVMMethod(mgr, pluginID, "host/console.pointer", a.handleComputerUsePointer),
|
||||
"host/console.key": a.hostVMMethod(mgr, pluginID, "host/console.key", a.handleComputerUseKey),
|
||||
"host/console.type": a.hostVMMethod(mgr, pluginID, "host/console.type", a.handleComputerUseType),
|
||||
"host/console.typeSecret": a.hostVMMethod(mgr, pluginID, "host/console.typeSecret", a.handleComputerUseTypeSecret),
|
||||
"host/console.release": a.hostVMMethod(mgr, pluginID, "host/console.release", a.handleComputerUseRelease),
|
||||
"host/vm.list": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.list", a.handleComputerUseVMList),
|
||||
"host/vm.get": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.get", a.handleComputerUseVMGet),
|
||||
"host/vm.start": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.start", a.handleComputerUseVMStart),
|
||||
"host/vm.shutdown": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.shutdown", a.handleComputerUseVMShutdown),
|
||||
"host/vm.suspend": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.suspend", a.handleComputerUseVMStateChange("host/vm.suspend", a.SuspendVM)),
|
||||
"host/vm.resume": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.resume", a.handleComputerUseVMStateChange("host/vm.resume", a.ResumeVM)),
|
||||
"host/vm.clone": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.clone", a.handleComputerUseVMClone),
|
||||
"host/vm.delete": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.delete", a.handleComputerUseVMDelete),
|
||||
"host/vm.snapshot.list": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.snapshot.list", a.handleComputerUseVMSnapshotList),
|
||||
"host/vm.snapshot.create": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.snapshot.create", a.handleComputerUseVMSnapshotCreate),
|
||||
"host/vm.snapshot.restore": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.snapshot.restore", a.handleComputerUseVMSnapshotRestore),
|
||||
"host/console.screenshot": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/console.screenshot", a.handleComputerUseScreenshot),
|
||||
"host/console.pointer": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/console.pointer", a.handleComputerUsePointer),
|
||||
"host/console.key": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/console.key", a.handleComputerUseKey),
|
||||
"host/console.type": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/console.type", a.handleComputerUseType),
|
||||
"host/console.typeSecret": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/console.typeSecret", a.handleComputerUseTypeSecret),
|
||||
"host/console.release": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/console.release", a.handleComputerUseRelease),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -243,8 +243,8 @@ func (a *App) handleComputerUseVMClone(ctx context.Context, raw json.RawMessage,
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a.computerUseCloneMu.Lock()
|
||||
defer a.computerUseCloneMu.Unlock()
|
||||
a.hostAPI.computerUseCloneMu.Lock()
|
||||
defer a.hostAPI.computerUseCloneMu.Unlock()
|
||||
if existing, listErr := a.listVMsInternal(ctx); listErr != nil {
|
||||
return nil, listErr
|
||||
} else if slices.ContainsFunc(existing, func(item driver.VMListItem) bool {
|
||||
@@ -446,24 +446,26 @@ func (a *App) computerUseVMAccessEnabled(mgr *plugin.Manager, pluginID, vmKey st
|
||||
}
|
||||
|
||||
func (a *App) computerUseOwned(pluginID, vmKey string) bool {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return a.computerUseOwnedVMs != nil && a.computerUseOwnedVMs[pluginID] != nil && a.computerUseOwnedVMs[pluginID][vmKey]
|
||||
h := a.hostAPISvc()
|
||||
h.ownedMu.Lock()
|
||||
defer h.ownedMu.Unlock()
|
||||
return h.computerUseOwnedVMs != nil && h.computerUseOwnedVMs[pluginID] != nil && h.computerUseOwnedVMs[pluginID][vmKey]
|
||||
}
|
||||
|
||||
func (a *App) markComputerUseOwnedVM(pluginID, vmKey string, owned bool) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if a.computerUseOwnedVMs == nil {
|
||||
a.computerUseOwnedVMs = make(map[string]map[string]bool)
|
||||
h := a.hostAPISvc()
|
||||
h.ownedMu.Lock()
|
||||
defer h.ownedMu.Unlock()
|
||||
if h.computerUseOwnedVMs == nil {
|
||||
h.computerUseOwnedVMs = make(map[string]map[string]bool)
|
||||
}
|
||||
if a.computerUseOwnedVMs[pluginID] == nil {
|
||||
a.computerUseOwnedVMs[pluginID] = make(map[string]bool)
|
||||
if h.computerUseOwnedVMs[pluginID] == nil {
|
||||
h.computerUseOwnedVMs[pluginID] = make(map[string]bool)
|
||||
}
|
||||
if owned {
|
||||
a.computerUseOwnedVMs[pluginID][vmKey] = true
|
||||
h.computerUseOwnedVMs[pluginID][vmKey] = true
|
||||
} else {
|
||||
delete(a.computerUseOwnedVMs[pluginID], vmKey)
|
||||
delete(h.computerUseOwnedVMs[pluginID], vmKey)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -472,12 +474,13 @@ func (a *App) forgetComputerUseOwnedVM(vmKey string) {
|
||||
if vmKey == "" {
|
||||
return
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for pluginID, owned := range a.computerUseOwnedVMs {
|
||||
h := a.hostAPISvc()
|
||||
h.ownedMu.Lock()
|
||||
defer h.ownedMu.Unlock()
|
||||
for pluginID, owned := range h.computerUseOwnedVMs {
|
||||
delete(owned, vmKey)
|
||||
if len(owned) == 0 {
|
||||
delete(a.computerUseOwnedVMs, pluginID)
|
||||
delete(h.computerUseOwnedVMs, pluginID)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -611,14 +614,15 @@ func (a *App) syncComputerUseOwnership(vms []driver.VMListItem) {
|
||||
continue
|
||||
}
|
||||
key := vm.Ref().Key()
|
||||
a.mu.Lock()
|
||||
h := a.hostAPISvc()
|
||||
h.ownedMu.Lock()
|
||||
var pluginIDs []string
|
||||
for pluginID, owned := range a.computerUseOwnedVMs {
|
||||
for pluginID, owned := range h.computerUseOwnedVMs {
|
||||
if owned[key] {
|
||||
pluginIDs = append(pluginIDs, pluginID)
|
||||
}
|
||||
}
|
||||
a.mu.Unlock()
|
||||
h.ownedMu.Unlock()
|
||||
for _, pluginID := range pluginIDs {
|
||||
// The source VM is no longer known on this repair path (the marker
|
||||
// was lost), so write an empty source: no fallback, same as before.
|
||||
|
||||
@@ -51,7 +51,7 @@ func (a *App) downloadHostHandlers(mgr *plugin.Manager, pluginID string) map[str
|
||||
}
|
||||
broker := mgr.Broker()
|
||||
return map[string]plugin.RPCRequestHandler{
|
||||
"host/download.start": a.hostMethod(mgr, pluginID, "host/download.start", func(_ context.Context, raw json.RawMessage) (any, error) {
|
||||
"host/download.start": a.hostAPISvc().hostMethod(mgr, pluginID, "host/download.start", func(_ context.Context, raw json.RawMessage) (any, error) {
|
||||
a.mu.Lock()
|
||||
dataRoot := ""
|
||||
if a.cfg != nil {
|
||||
@@ -62,7 +62,7 @@ func (a *App) downloadHostHandlers(mgr *plugin.Manager, pluginID string) map[str
|
||||
notify := func(method string, params any) { mgr.NotifySidecar(pluginID, method, params) }
|
||||
return a.startPluginDownload(mgr, broker, notify, pluginID, roots, raw)
|
||||
}),
|
||||
"host/download.cancel": a.hostMethod(mgr, pluginID, "host/download.cancel", func(_ context.Context, raw json.RawMessage) (any, error) {
|
||||
"host/download.cancel": a.hostAPISvc().hostMethod(mgr, pluginID, "host/download.cancel", func(_ context.Context, raw json.RawMessage) (any, error) {
|
||||
return cancelPluginDownload(mgr, pluginID, raw)
|
||||
}),
|
||||
}
|
||||
|
||||
@@ -33,14 +33,14 @@ type ElevationPrompt struct {
|
||||
|
||||
type elevationRunner func(ctx context.Context, action, targetUser string) (host.ElevationResult, error)
|
||||
|
||||
func (a *App) elevateHostHandlers(mgr *plugin.Manager, pluginID string) map[string]plugin.RPCRequestHandler {
|
||||
func (h *HostAPIService) elevateHostHandlers(mgr *plugin.Manager, pluginID string) map[string]plugin.RPCRequestHandler {
|
||||
if mgr == nil || mgr.Broker() == nil {
|
||||
return nil
|
||||
}
|
||||
broker := mgr.Broker()
|
||||
return map[string]plugin.RPCRequestHandler{
|
||||
"host/elevate.request": a.hostMethod(mgr, pluginID, "host/elevate.request", func(ctx context.Context, raw json.RawMessage) (any, error) {
|
||||
return a.requestElevation(ctx, mgr, broker, mgr.Registry(), pluginID, raw)
|
||||
"host/elevate.request": h.hostMethod(mgr, pluginID, "host/elevate.request", func(ctx context.Context, raw json.RawMessage) (any, error) {
|
||||
return h.app.requestElevation(ctx, mgr, broker, mgr.Registry(), pluginID, raw)
|
||||
}),
|
||||
}
|
||||
}
|
||||
@@ -60,9 +60,6 @@ func (a *App) requestElevation(ctx context.Context, kernel hostMethodHost, broke
|
||||
}
|
||||
|
||||
a.mu.Lock()
|
||||
emit := a.elevateEmit
|
||||
dismiss := a.elevateDismiss
|
||||
runner := a.elevateRunner
|
||||
winCtx := a.ctx
|
||||
hasWindow := winCtx != nil
|
||||
locale := i18n.EffectiveLocale(i18n.Auto)
|
||||
@@ -70,14 +67,20 @@ func (a *App) requestElevation(ctx context.Context, kernel hostMethodHost, broke
|
||||
locale = i18n.EffectiveLocale(a.cfg.Locale)
|
||||
}
|
||||
a.mu.Unlock()
|
||||
h := a.hostAPISvc()
|
||||
h.elevateMu.Lock()
|
||||
emit := h.elevateEmit
|
||||
dismiss := h.elevateDismiss
|
||||
runner := h.elevateRunner
|
||||
h.elevateMu.Unlock()
|
||||
if emit == nil && !hasWindow {
|
||||
broker.Audit(pluginID, "ELEVATE_UNAVAILABLE", spec.Action)
|
||||
return nil, errors.New("elevation_unavailable: the desktop window is required to confirm elevation")
|
||||
}
|
||||
|
||||
// One confirmation and one servicing run at a time.
|
||||
a.elevatePromptMu.Lock()
|
||||
defer a.elevatePromptMu.Unlock()
|
||||
h.elevatePromptMu.Lock()
|
||||
defer h.elevatePromptMu.Unlock()
|
||||
|
||||
prompt := ElevationPrompt{
|
||||
PluginID: pluginID, PluginName: pluginID, Action: spec.Action,
|
||||
@@ -92,19 +95,19 @@ func (a *App) requestElevation(ctx context.Context, kernel hostMethodHost, broke
|
||||
}
|
||||
|
||||
ch := make(chan bool, 1)
|
||||
a.elevateMu.Lock()
|
||||
if a.elevatePending == nil {
|
||||
a.elevatePending = map[string]chan bool{}
|
||||
h.elevateMu.Lock()
|
||||
if h.elevatePending == nil {
|
||||
h.elevatePending = map[string]chan bool{}
|
||||
}
|
||||
a.elevateSeq++
|
||||
prompt.ID = fmt.Sprintf("elevate-%d", a.elevateSeq)
|
||||
a.elevatePending[prompt.ID] = ch
|
||||
a.elevateMu.Unlock()
|
||||
h.elevateSeq++
|
||||
prompt.ID = fmt.Sprintf("elevate-%d", h.elevateSeq)
|
||||
h.elevatePending[prompt.ID] = ch
|
||||
h.elevateMu.Unlock()
|
||||
dismissed := false
|
||||
clearPrompt := func() {
|
||||
a.elevateMu.Lock()
|
||||
delete(a.elevatePending, prompt.ID)
|
||||
a.elevateMu.Unlock()
|
||||
h.elevateMu.Lock()
|
||||
delete(h.elevatePending, prompt.ID)
|
||||
h.elevateMu.Unlock()
|
||||
if dismissed {
|
||||
return
|
||||
}
|
||||
@@ -178,10 +181,11 @@ func (a *App) requestElevation(ctx context.Context, kernel hostMethodHost, broke
|
||||
// ResolveElevationRequest delivers the person's answer to a pending plugin
|
||||
// elevation request. An expired or answered request is ignored.
|
||||
func (a *App) ResolveElevationRequest(id string, approved bool) error {
|
||||
a.elevateMu.Lock()
|
||||
ch, ok := a.elevatePending[id]
|
||||
delete(a.elevatePending, id)
|
||||
a.elevateMu.Unlock()
|
||||
h := a.hostAPISvc()
|
||||
h.elevateMu.Lock()
|
||||
ch, ok := h.elevatePending[id]
|
||||
delete(h.elevatePending, id)
|
||||
h.elevateMu.Unlock()
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
@@ -195,10 +199,11 @@ func (a *App) ResolveElevationRequest(id string, approved bool) error {
|
||||
// cancelPendingElevations answers every waiting request with a no, so
|
||||
// shutting down never leaves a plugin waiting on a dialog.
|
||||
func (a *App) cancelPendingElevations() {
|
||||
a.elevateMu.Lock()
|
||||
pending := a.elevatePending
|
||||
a.elevatePending = nil
|
||||
a.elevateMu.Unlock()
|
||||
h := a.hostAPISvc()
|
||||
h.elevateMu.Lock()
|
||||
pending := h.elevatePending
|
||||
h.elevatePending = nil
|
||||
h.elevateMu.Unlock()
|
||||
for _, ch := range pending {
|
||||
close(ch)
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ func newElevateTestEnv(t *testing.T) *elevateTestEnv {
|
||||
e := &elevateTestEnv{h: h, plugin: "test.fake.elev"}
|
||||
h.Add("hosted", e.plugin, "test.driver.elev")
|
||||
e.app = &App{cfg: &config.Config{DataRoot: h.DataRoot}}
|
||||
e.app.elevateEmit = func(p ElevationPrompt) {
|
||||
e.app.hostAPI.elevateEmit = func(p ElevationPrompt) {
|
||||
e.mu.Lock()
|
||||
e.prompts = append(e.prompts, p)
|
||||
answer := e.onPrompt
|
||||
@@ -49,12 +49,12 @@ func newElevateTestEnv(t *testing.T) *elevateTestEnv {
|
||||
go answer(p)
|
||||
}
|
||||
}
|
||||
e.app.elevateDismiss = func(id string) {
|
||||
e.app.hostAPI.elevateDismiss = func(id string) {
|
||||
e.mu.Lock()
|
||||
e.dismissed = append(e.dismissed, id)
|
||||
e.mu.Unlock()
|
||||
}
|
||||
e.app.elevateRunner = func(_ context.Context, action, targetUser string) (host.ElevationResult, error) {
|
||||
e.app.hostAPI.elevateRunner = func(_ context.Context, action, targetUser string) (host.ElevationResult, error) {
|
||||
e.runs.Add(1)
|
||||
e.mu.Lock()
|
||||
e.runArgs = []string{action, targetUser}
|
||||
@@ -83,7 +83,7 @@ func (e *elevateTestEnv) kernel() testHostMethodHost {
|
||||
|
||||
func (e *elevateTestEnv) request(ctx context.Context, pluginID, action string) (any, error) {
|
||||
raw, _ := json.Marshal(map[string]any{"action": action})
|
||||
handler := e.app.hostMethod(e.kernel(), pluginID, "host/elevate.request", func(ctx context.Context, raw json.RawMessage) (any, error) {
|
||||
handler := e.app.hostAPISvc().hostMethod(e.kernel(), pluginID, "host/elevate.request", func(ctx context.Context, raw json.RawMessage) (any, error) {
|
||||
return e.app.requestElevation(ctx, e.kernel(), e.h.Broker, e.h.Registry, pluginID, raw)
|
||||
})
|
||||
return handler(ctx, raw)
|
||||
@@ -138,7 +138,7 @@ func TestElevationRejectsActionsOutsideTheWhitelist(t *testing.T) {
|
||||
|
||||
func TestElevationIsRefusedWithoutADesktopWindow(t *testing.T) {
|
||||
e := newElevateTestEnv(t)
|
||||
e.app.elevateEmit = nil
|
||||
e.app.hostAPI.elevateEmit = nil
|
||||
_, err := e.request(context.Background(), e.plugin, host.ElevateHyperVEnable)
|
||||
if err == nil || !strings.Contains(err.Error(), "elevation_unavailable") {
|
||||
t.Fatalf("err = %v, want elevation_unavailable", err)
|
||||
|
||||
@@ -77,7 +77,7 @@ func decodeHostParams[T any](host hostMethodHost, pluginID, method string, raw j
|
||||
// audits the call under the method name, and hands the request to run. No
|
||||
// handler states its own permission, so a permission cannot drift from the
|
||||
// method it guards.
|
||||
func (a *App) hostMethod(host hostMethodHost, pluginID, method string, run hostMethodHandler) plugin.RPCRequestHandler {
|
||||
func (h *HostAPIService) hostMethod(host hostMethodHost, pluginID, method string, run hostMethodHandler) plugin.RPCRequestHandler {
|
||||
return func(ctx context.Context, raw json.RawMessage) (any, error) {
|
||||
if err := authorizeHostMethod(host, pluginID, method); err != nil {
|
||||
return nil, err
|
||||
@@ -94,8 +94,8 @@ func (a *App) hostMethod(host hostMethodHost, pluginID, method string, run hostM
|
||||
}
|
||||
|
||||
// hostVMMethod wraps a handler that needs the manager and the calling plugin.
|
||||
func (a *App) hostVMMethod(mgr *plugin.Manager, pluginID, method string, run computerUseVMHandler) plugin.RPCRequestHandler {
|
||||
return a.hostMethod(mgr, pluginID, method, func(ctx context.Context, raw json.RawMessage) (any, error) {
|
||||
func (h *HostAPIService) hostVMMethod(mgr *plugin.Manager, pluginID, method string, run computerUseVMHandler) plugin.RPCRequestHandler {
|
||||
return h.hostMethod(mgr, pluginID, method, func(ctx context.Context, raw json.RawMessage) (any, error) {
|
||||
return run(ctx, raw, mgr, pluginID)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package app
|
||||
|
||||
import "sync"
|
||||
|
||||
// HostAPIService owns the state and RPC handlers for all host-side plugin
|
||||
// capabilities: computer-use VM control & held inputs, secret materialization,
|
||||
// host downloads, plugin elevation prompts, and panel file grants.
|
||||
// Keeping this state off *App isolates lock domains and keeps *App focused on
|
||||
// Wails IPC bindings and desktop lifecycle coordination.
|
||||
type HostAPIService struct {
|
||||
app *App
|
||||
|
||||
// Plugin panel file grants (plugin_bridge_files.go).
|
||||
filesMu sync.Mutex
|
||||
pluginFiles map[string]pluginFileGrant
|
||||
|
||||
// Computer-use VM ownership & held console inputs (computer_use_host.go, computer_use_held.go).
|
||||
ownedMu sync.Mutex
|
||||
computerUseOwnedVMs map[string]map[string]bool
|
||||
computerUseCloneMu sync.Mutex
|
||||
heldMu sync.Mutex
|
||||
computerUseHeld map[string]map[string]*heldInputs
|
||||
|
||||
// Plugin elevation requests (elevate_flow.go).
|
||||
elevatePromptMu sync.Mutex
|
||||
elevateMu sync.Mutex
|
||||
elevatePending map[string]chan bool
|
||||
elevateSeq uint64
|
||||
elevateEmit func(ElevationPrompt)
|
||||
elevateDismiss func(string)
|
||||
elevateRunner elevationRunner
|
||||
}
|
||||
|
||||
func (h *HostAPIService) ResetPluginFiles() {
|
||||
h.filesMu.Lock()
|
||||
h.pluginFiles = make(map[string]pluginFileGrant)
|
||||
h.filesMu.Unlock()
|
||||
}
|
||||
|
||||
func (a *App) hostAPISvc() *HostAPIService {
|
||||
a.mu.Lock()
|
||||
if a.hostAPI.app == nil {
|
||||
a.hostAPI.app = a
|
||||
}
|
||||
svc := &a.hostAPI
|
||||
a.mu.Unlock()
|
||||
return svc
|
||||
}
|
||||
@@ -51,7 +51,7 @@ func TestEveryStableHostMethodIsServed(t *testing.T) {
|
||||
for _, method := range plugin.ReverseHostAPIMethods() {
|
||||
served[method] = true
|
||||
}
|
||||
for method := range app.hostHandlers(mgr, hostContractPlugin) {
|
||||
for method := range app.hostAPISvc().Handlers(mgr, hostContractPlugin) {
|
||||
if _, ok := pluginproto.Lookup(method); !ok {
|
||||
t.Errorf("%s is served but not in the contract catalog", method)
|
||||
}
|
||||
|
||||
@@ -2,15 +2,15 @@ package app
|
||||
|
||||
import "github.com/Nwflower/reims-go/internal/plugin"
|
||||
|
||||
// hostHandlers returns every host-owned RPC a Sidecar may call, each guarded
|
||||
// Handlers returns every host-owned RPC a Sidecar may call, each guarded
|
||||
// by its own permission check.
|
||||
func (a *App) hostHandlers(mgr *plugin.Manager, pluginID string) map[string]plugin.RPCRequestHandler {
|
||||
func (h *HostAPIService) Handlers(mgr *plugin.Manager, pluginID string) map[string]plugin.RPCRequestHandler {
|
||||
out := map[string]plugin.RPCRequestHandler{}
|
||||
for _, set := range []map[string]plugin.RPCRequestHandler{
|
||||
a.computerUseHostHandlers(mgr, pluginID),
|
||||
a.secretHostHandlers(mgr, pluginID),
|
||||
a.downloadHostHandlers(mgr, pluginID),
|
||||
a.elevateHostHandlers(mgr, pluginID),
|
||||
h.app.computerUseHostHandlers(mgr, pluginID),
|
||||
h.app.secretHostHandlers(mgr, pluginID),
|
||||
h.app.downloadHostHandlers(mgr, pluginID),
|
||||
h.elevateHostHandlers(mgr, pluginID),
|
||||
} {
|
||||
for method, handler := range set {
|
||||
out[method] = handler
|
||||
|
||||
@@ -219,9 +219,9 @@ func TestPluginFileGrantsExpireAndAreCapped(t *testing.T) {
|
||||
if _, err := a.issuePluginFileGrant("vendor.panel", path, true); err == nil {
|
||||
t.Fatal("plugin exceeded its file grant limit")
|
||||
}
|
||||
grant := a.pluginFiles[first]
|
||||
grant := a.hostAPI.pluginFiles[first]
|
||||
grant.Expires = time.Now().Add(-time.Minute)
|
||||
a.pluginFiles[first] = grant
|
||||
a.hostAPI.pluginFiles[first] = grant
|
||||
if _, err := a.pluginFilePath("vendor.panel", first, true); err == nil {
|
||||
t.Fatal("expired file grant was accepted")
|
||||
}
|
||||
|
||||
@@ -50,13 +50,14 @@ func (a *App) issuePluginFileGrant(pluginID, path string, write bool) (map[strin
|
||||
} else if !write {
|
||||
return nil, err
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
h := a.hostAPISvc()
|
||||
h.filesMu.Lock()
|
||||
defer h.filesMu.Unlock()
|
||||
now := time.Now()
|
||||
count := 0
|
||||
for key, grant := range a.pluginFiles {
|
||||
for key, grant := range h.pluginFiles {
|
||||
if !now.Before(grant.Expires) {
|
||||
delete(a.pluginFiles, key)
|
||||
delete(h.pluginFiles, key)
|
||||
} else if grant.PluginID == pluginID {
|
||||
count++
|
||||
}
|
||||
@@ -64,29 +65,31 @@ func (a *App) issuePluginFileGrant(pluginID, path string, write bool) (map[strin
|
||||
if count >= maxPluginFileGrants {
|
||||
return nil, errors.New("too many open file handles for this plugin")
|
||||
}
|
||||
if a.pluginFiles == nil {
|
||||
a.pluginFiles = make(map[string]pluginFileGrant)
|
||||
if h.pluginFiles == nil {
|
||||
h.pluginFiles = make(map[string]pluginFileGrant)
|
||||
}
|
||||
a.pluginFiles[id] = pluginFileGrant{PluginID: pluginID, Path: clean, Write: write, Expires: now.Add(pluginFileGrantTTL)}
|
||||
h.pluginFiles[id] = pluginFileGrant{PluginID: pluginID, Path: clean, Write: write, Expires: now.Add(pluginFileGrantTTL)}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (a *App) revokePluginFiles(pluginID string) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for id, grant := range a.pluginFiles {
|
||||
h := a.hostAPISvc()
|
||||
h.filesMu.Lock()
|
||||
defer h.filesMu.Unlock()
|
||||
for id, grant := range h.pluginFiles {
|
||||
if grant.PluginID == pluginID {
|
||||
delete(a.pluginFiles, id)
|
||||
delete(h.pluginFiles, id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) pluginFilePath(pluginID, id string, write bool) (string, error) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
grant, ok := a.pluginFiles[id]
|
||||
h := a.hostAPISvc()
|
||||
h.filesMu.Lock()
|
||||
defer h.filesMu.Unlock()
|
||||
grant, ok := h.pluginFiles[id]
|
||||
if ok && !time.Now().Before(grant.Expires) {
|
||||
delete(a.pluginFiles, id)
|
||||
delete(h.pluginFiles, id)
|
||||
ok = false
|
||||
}
|
||||
if !ok || grant.PluginID != pluginID || (write && !grant.Write) {
|
||||
|
||||
@@ -25,6 +25,7 @@ import (
|
||||
"github.com/Nwflower/reims-go/internal/macos/guest"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/market"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/version"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
@@ -87,7 +88,7 @@ func (a *App) initPlugins() {
|
||||
a.mu.Lock()
|
||||
current := a.pluginMgr
|
||||
a.mu.Unlock()
|
||||
return a.hostHandlers(current, pluginID)
|
||||
return a.hostAPISvc().Handlers(current, pluginID)
|
||||
},
|
||||
OnSettingsChanged: func(pluginID, vmName string) {
|
||||
a.onPluginSettingsChanged(pluginID, vmName)
|
||||
@@ -265,7 +266,7 @@ func (a *App) shutdownPlugins() {
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) getPluginMarket() *plugin.MarketClient {
|
||||
func (a *App) getPluginMarket() *market.MarketClient {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if a.needsSetup {
|
||||
@@ -273,7 +274,7 @@ func (a *App) getPluginMarket() *plugin.MarketClient {
|
||||
// only the default suggestion), so nothing may be cached or
|
||||
// downloaded into it. A throwaway client keeps the index in memory;
|
||||
// the first call after setup builds the real one.
|
||||
return plugin.NewMarketClient(plugin.MarketClientOptions{HostVersion: version.Version})
|
||||
return market.NewMarketClient(market.MarketClientOptions{HostVersion: version.Version})
|
||||
}
|
||||
if a.pluginMarket != nil {
|
||||
return a.pluginMarket
|
||||
@@ -282,7 +283,7 @@ func (a *App) getPluginMarket() *plugin.MarketClient {
|
||||
if a.cfg != nil {
|
||||
dataRoot = a.cfg.DataRoot
|
||||
}
|
||||
a.pluginMarket = plugin.NewMarketClient(plugin.MarketClientOptions{
|
||||
a.pluginMarket = market.NewMarketClient(market.MarketClientOptions{
|
||||
Layout: plugin.NewPluginsLayout(dataRoot),
|
||||
HostVersion: version.Version,
|
||||
})
|
||||
@@ -948,7 +949,7 @@ func (a *App) ScanInstalledPlugin(pluginID string) (plugin.ScanReport, error) {
|
||||
|
||||
// BrowsePluginMarket lazily queries the remote/cached/fallback plugin market
|
||||
// index (never called at app startup, §8.1, §9).
|
||||
func (a *App) BrowsePluginMarket(query, kind string, includeAlpha, forceRefresh bool) plugin.MarketBrowseResult {
|
||||
func (a *App) BrowsePluginMarket(query, kind string, includeAlpha, forceRefresh bool) market.MarketBrowseResult {
|
||||
a.mu.Lock()
|
||||
mgr := a.pluginMgr
|
||||
a.mu.Unlock()
|
||||
@@ -956,7 +957,7 @@ func (a *App) BrowsePluginMarket(query, kind string, includeAlpha, forceRefresh
|
||||
if mgr != nil {
|
||||
installed = mgr.Registry().List()
|
||||
}
|
||||
return a.getPluginMarket().Browse(context.Background(), installed, plugin.MarketBrowseOptions{
|
||||
return a.getPluginMarket().Browse(context.Background(), installed, market.MarketBrowseOptions{
|
||||
Query: query,
|
||||
Kind: kind,
|
||||
IncludeAlpha: includeAlpha,
|
||||
@@ -967,7 +968,7 @@ func (a *App) BrowsePluginMarket(query, kind string, includeAlpha, forceRefresh
|
||||
// PeekPluginMarket returns the market from memory, disk cache or the embedded
|
||||
// fallback with no network I/O, so the page can paint before
|
||||
// BrowsePluginMarket revalidates.
|
||||
func (a *App) PeekPluginMarket(query, kind string) plugin.MarketBrowseResult {
|
||||
func (a *App) PeekPluginMarket(query, kind string) market.MarketBrowseResult {
|
||||
a.mu.Lock()
|
||||
mgr := a.pluginMgr
|
||||
a.mu.Unlock()
|
||||
@@ -975,7 +976,7 @@ func (a *App) PeekPluginMarket(query, kind string) plugin.MarketBrowseResult {
|
||||
if mgr != nil {
|
||||
installed = mgr.Registry().List()
|
||||
}
|
||||
return a.getPluginMarket().Peek(installed, plugin.MarketBrowseOptions{Query: query, Kind: kind, IncludeAlpha: true})
|
||||
return a.getPluginMarket().Peek(installed, market.MarketBrowseOptions{Query: query, Kind: kind, IncludeAlpha: true})
|
||||
}
|
||||
|
||||
// SuggestLanguagePack looks up the market once for a language pack matching
|
||||
@@ -983,7 +984,7 @@ func (a *App) PeekPluginMarket(query, kind string) plugin.MarketBrowseResult {
|
||||
// request made without the user opening the market (§8.1), and returns nil
|
||||
// when a built-in language already covers the OS language, the market is
|
||||
// unreachable or turned off, or nothing matches.
|
||||
func (a *App) SuggestLanguagePack() *plugin.MarketCatalogItem {
|
||||
func (a *App) SuggestLanguagePack() *market.MarketCatalogItem {
|
||||
tag := i18n.DetectOSLocaleTag()
|
||||
if builtinCoversLocale(string(tag)) {
|
||||
return nil
|
||||
@@ -1044,13 +1045,13 @@ func (a *App) installMarketPlugin(pluginID, ver string, includeAlpha bool) (*plu
|
||||
}
|
||||
var (
|
||||
progMu sync.Mutex
|
||||
phase = plugin.MarketPhaseDownload
|
||||
phase = market.MarketPhaseDownload
|
||||
lastEmit time.Time
|
||||
)
|
||||
emit := func(p MarketInstallProgress) {
|
||||
a.emit("reims:plugin-install", p)
|
||||
}
|
||||
info, err := a.getPluginMarket().InstallFromMarket(context.Background(), mgr, pluginID, plugin.MarketInstallOptions{
|
||||
info, err := a.getPluginMarket().InstallFromMarket(context.Background(), mgr, pluginID, market.MarketInstallOptions{
|
||||
Version: ver,
|
||||
IncludeAlpha: includeAlpha,
|
||||
OnPhase: func(ph string) {
|
||||
|
||||
@@ -62,10 +62,10 @@ func (a *App) secretHostHandlers(mgr *plugin.Manager, pluginID string) map[strin
|
||||
return value, err
|
||||
}
|
||||
return map[string]plugin.RPCRequestHandler{
|
||||
"host/secret.materialize": a.hostMethod(mgr, pluginID, "host/secret.materialize", func(_ context.Context, raw json.RawMessage) (any, error) {
|
||||
"host/secret.materialize": a.hostAPISvc().hostMethod(mgr, pluginID, "host/secret.materialize", func(_ context.Context, raw json.RawMessage) (any, error) {
|
||||
return a.materializeSecret(mgr, broker, source, pluginID, raw)
|
||||
}),
|
||||
"host/secret.discard": a.hostMethod(mgr, pluginID, "host/secret.discard", func(_ context.Context, raw json.RawMessage) (any, error) {
|
||||
"host/secret.discard": a.hostAPISvc().hostMethod(mgr, pluginID, "host/secret.discard", func(_ context.Context, raw json.RawMessage) (any, error) {
|
||||
return a.discardSecret(mgr, broker, pluginID, raw)
|
||||
}),
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ var renameOwners = map[string]bool{
|
||||
"internal/macos/reims/suspend_fileops_other.go": true, // state and metadata commit together
|
||||
"internal/macos/reims/suspend_fileops_windows.go": true, // state and metadata commit together
|
||||
"internal/plugin/broker.go": true, // log rotation
|
||||
"internal/plugin/pack.go": true, // archive
|
||||
"internal/plugin/market/pack.go": true, // archive
|
||||
"internal/plugin/package_rename_other.go": true, // plugin directory
|
||||
"internal/plugin/package_rename_windows.go": true, // plugin directory
|
||||
"internal/runtime/runtime.go": true, // runtime directory
|
||||
|
||||
+80
-8
@@ -305,8 +305,10 @@ func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error {
|
||||
}
|
||||
return err
|
||||
}
|
||||
if err := activateRuntime(context.Background(), cfg, loc, inst.Commit); err != nil {
|
||||
return err
|
||||
if inst.Kind != rt.StambhaKind {
|
||||
if err := activateRuntime(context.Background(), cfg, loc, inst.Commit); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
fmt.Println(i18n.T(loc, "runtime.installed", inst.Commit, inst.Dir))
|
||||
return nil
|
||||
@@ -409,11 +411,16 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e
|
||||
}
|
||||
return startVM(ctx, cfg, driverID, name, viaWindow)
|
||||
case "stop":
|
||||
driverID, name, err := parseVMTarget(args)
|
||||
if err != nil {
|
||||
fs := flag.NewFlagSet("vm stop", flag.ContinueOnError)
|
||||
driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous")
|
||||
force := fs.Bool("force", false, "Force stop without waiting for guest shutdown")
|
||||
if err := fs.Parse(args[1:]); err != nil {
|
||||
return err
|
||||
}
|
||||
return stopVM(ctx, cfg, driverID, name)
|
||||
if fs.NArg() != 1 {
|
||||
return errors.New("usage: reims-go vm stop [--driver <id>] [--force] <name>")
|
||||
}
|
||||
return stopVM(ctx, cfg, *driverID, fs.Arg(0), *force)
|
||||
case "suspend":
|
||||
driverID, name, err := parseVMTarget(args)
|
||||
if err != nil {
|
||||
@@ -511,6 +518,7 @@ func vmCreate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []s
|
||||
logs := fs.Bool("logs", true, "Keep graphics and serial logs")
|
||||
guestLang := fs.String("guest-lang", defaultMacOSGuestLang(loc), "macOS boot/recovery language prev-lang:kbd (e.g. zh-Hans:0, en-US:0)")
|
||||
start := fs.Bool("start", false, "Start VM immediately after creation")
|
||||
stambhaFlags := registerStambhaVMFlags(fs, disk)
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -518,6 +526,10 @@ func vmCreate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []s
|
||||
return fmt.Errorf("usage: reims-go vm create [flags] <name>")
|
||||
}
|
||||
name := fs.Arg(0)
|
||||
stambhaOpts := collectStambhaVMFlags(fs, stambhaFlags)
|
||||
if len(stambhaOpts) > 0 && *driverID != driver.BuiltinStambhaDriverID {
|
||||
return fmt.Errorf("Stambha VM flags require --driver %s", driver.BuiltinStambhaDriverID)
|
||||
}
|
||||
// Route non-reims guest drivers through the plugin Driver Router (§5.3, §10).
|
||||
if strings.TrimSpace(*driverID) != "" && *driverID != driver.BuiltinReimsMacOSDriverID {
|
||||
mgr, router, err := openCLIPluginManager(cfg, false)
|
||||
@@ -529,8 +541,11 @@ func vmCreate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []s
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if strings.TrimSpace(*disk) != "" || strings.TrimSpace(*diskMode) != "" || strings.TrimSpace(*diskCache) != "" {
|
||||
return fmt.Errorf("--disk, --disk-mode, and --disk-cache are only supported by the %s driver", driver.BuiltinReimsMacOSDriverID)
|
||||
if strings.TrimSpace(*diskMode) != "" || strings.TrimSpace(*diskCache) != "" {
|
||||
return fmt.Errorf("--disk-mode and --disk-cache are only supported by the %s driver", driver.BuiltinReimsMacOSDriverID)
|
||||
}
|
||||
if drv.ID() != driver.BuiltinStambhaDriverID && strings.TrimSpace(*disk) != "" {
|
||||
return fmt.Errorf("--disk is not supported by the %s driver", drv.ID())
|
||||
}
|
||||
req := driver.CreateRequest{
|
||||
DriverID: drv.ID(),
|
||||
@@ -542,6 +557,14 @@ func vmCreate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []s
|
||||
"disk_size": *diskSize,
|
||||
},
|
||||
}
|
||||
if drv.ID() == driver.BuiltinStambhaDriverID {
|
||||
delete(req.Options, "disk_size")
|
||||
req.Options["gpu"] = *gpu
|
||||
req.Options["raw_disk"] = *disk
|
||||
for key, value := range stambhaOpts {
|
||||
req.Options[key] = value
|
||||
}
|
||||
}
|
||||
if issues := drv.ValidateCreate(ctx, req); len(issues) > 0 {
|
||||
return fmt.Errorf("%s", issues[0].Message)
|
||||
}
|
||||
@@ -569,13 +592,17 @@ func vmSet(ctx context.Context, cfg *config.Config, args []string) error {
|
||||
audioBackend := fs.String("audio-backend", "", "Audio backend (auto, dsound, none, wav)")
|
||||
guestLang := fs.String("guest-lang", "", "macOS boot/recovery language prev-lang:kbd")
|
||||
nestedVirt := fs.Bool("nested-virt", false, "Enable nested virtualization on the next cold start (macOS only)")
|
||||
stambhaFlags := registerStambhaVMFlags(fs, nil)
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
if fs.NArg() < 1 {
|
||||
return fmt.Errorf("usage: reims-go vm set [--driver <id>] [flags] <name>")
|
||||
}
|
||||
changes := map[string]any{}
|
||||
changes := collectStambhaVMFlags(fs, stambhaFlags)
|
||||
if len(changes) > 0 && *driverID != driver.BuiltinStambhaDriverID {
|
||||
return fmt.Errorf("Stambha VM flags require --driver %s", driver.BuiltinStambhaDriverID)
|
||||
}
|
||||
if *cpus != 0 {
|
||||
changes["cpus"] = *cpus
|
||||
}
|
||||
@@ -605,6 +632,51 @@ func vmSet(ctx context.Context, cfg *config.Config, args []string) error {
|
||||
return setVM(ctx, cfg, *driverID, fs.Arg(0), changes)
|
||||
}
|
||||
|
||||
type stambhaVMFlag struct {
|
||||
option string
|
||||
value func() any
|
||||
}
|
||||
|
||||
func registerStambhaVMFlags(fs *flag.FlagSet, disk *string) map[string]stambhaVMFlag {
|
||||
boot := fs.String("boot-volume", "", "Stambha boot folder containing EFI/stela/stela.cfg")
|
||||
usb := fs.String("usb-image", "", "Stambha RAW boot image")
|
||||
bus := fs.String("media-bus", "", "Stambha RAW boot image bus (usb or nvme)")
|
||||
sharedDisk := disk != nil
|
||||
if !sharedDisk {
|
||||
disk = fs.String("disk", "", "Stambha writable RAW or QCOW2 virtual disk")
|
||||
}
|
||||
fs.StringVar(disk, "raw-disk", "", "Alias for --disk")
|
||||
accelerator := fs.String("accelerator", "", "Stambha accelerator (whpx or tcg)")
|
||||
hosted := fs.Bool("hosted-gpu", true, "Use Reims vGPU for a Stambha VM")
|
||||
headless := fs.Bool("headless", false, "Run Stambha without a display window")
|
||||
args := fs.String("stela-args", "", "Additional Stambha options for a boot folder")
|
||||
flags := map[string]stambhaVMFlag{
|
||||
"boot-volume": {"boot_volume", func() any { return *boot }},
|
||||
"usb-image": {"usb_image", func() any { return *usb }},
|
||||
"media-bus": {"media_bus", func() any { return *bus }},
|
||||
"disk": {"raw_disk", func() any { return *disk }},
|
||||
"raw-disk": {"raw_disk", func() any { return *disk }},
|
||||
"accelerator": {"accelerator", func() any { return *accelerator }},
|
||||
"hosted-gpu": {"hosted_gpu", func() any { return *hosted }},
|
||||
"headless": {"display", func() any { return !*headless }},
|
||||
"stela-args": {"stela_args", func() any { return *args }},
|
||||
}
|
||||
if sharedDisk {
|
||||
delete(flags, "disk")
|
||||
}
|
||||
return flags
|
||||
}
|
||||
|
||||
func collectStambhaVMFlags(fs *flag.FlagSet, declared map[string]stambhaVMFlag) map[string]any {
|
||||
options := make(map[string]any)
|
||||
fs.Visit(func(f *flag.Flag) {
|
||||
if spec, ok := declared[f.Name]; ok {
|
||||
options[spec.option] = spec.value()
|
||||
}
|
||||
})
|
||||
return options
|
||||
}
|
||||
|
||||
func printJSON(v any) error {
|
||||
enc := json.NewEncoder(os.Stdout)
|
||||
enc.SetIndent("", " ")
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"github.com/Nwflower/reims-go/internal/macos/guest"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/market"
|
||||
"github.com/Nwflower/reims-go/internal/version"
|
||||
)
|
||||
|
||||
@@ -51,8 +52,8 @@ func openCLIPluginManager(cfg *config.Config, safeMode bool) (*plugin.Manager, *
|
||||
return mgr, router, nil
|
||||
}
|
||||
|
||||
func openCLIMarketClient(cfg *config.Config) *plugin.MarketClient {
|
||||
return plugin.NewMarketClient(plugin.MarketClientOptions{
|
||||
func openCLIMarketClient(cfg *config.Config) *market.MarketClient {
|
||||
return market.NewMarketClient(market.MarketClientOptions{
|
||||
Layout: plugin.NewPluginsLayout(cfg.DataRoot),
|
||||
HostVersion: version.Version,
|
||||
})
|
||||
@@ -113,7 +114,7 @@ func pluginSearch(ctx context.Context, cfg *config.Config, loc i18n.Locale, args
|
||||
defer mgr.Close()
|
||||
mc := openCLIMarketClient(cfg)
|
||||
query := strings.TrimSpace(strings.Join(fs.Args(), " "))
|
||||
res := mc.Browse(ctx, mgr.Registry().List(), plugin.MarketBrowseOptions{
|
||||
res := mc.Browse(ctx, mgr.Registry().List(), market.MarketBrowseOptions{
|
||||
Query: query,
|
||||
Kind: *kind,
|
||||
IncludeAlpha: *includeAlpha,
|
||||
@@ -219,7 +220,7 @@ func pluginInstall(ctx context.Context, cfg *config.Config, loc i18n.Locale, arg
|
||||
info, err = mgr.InstallLocalArchive(ctx, target, plugin.PackageInstallOptions{})
|
||||
} else {
|
||||
mc := openCLIMarketClient(cfg)
|
||||
info, err = mc.InstallFromMarket(ctx, mgr, target, plugin.MarketInstallOptions{
|
||||
info, err = mc.InstallFromMarket(ctx, mgr, target, market.MarketInstallOptions{
|
||||
IncludeAlpha: *includeAlpha,
|
||||
ForceRefresh: *refresh,
|
||||
})
|
||||
@@ -249,7 +250,7 @@ func pluginUpdate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args
|
||||
if _, ok := mgr.Registry().Info(id); !ok {
|
||||
return fmt.Errorf("%s", i18n.T(loc, "plugin.not_found", id))
|
||||
}
|
||||
info, uErr := mc.InstallFromMarket(ctx, mgr, id, plugin.MarketInstallOptions{
|
||||
info, uErr := mc.InstallFromMarket(ctx, mgr, id, market.MarketInstallOptions{
|
||||
IncludeAlpha: *includeAlpha,
|
||||
ForceRefresh: *refresh,
|
||||
})
|
||||
@@ -268,7 +269,7 @@ func pluginUpdate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args
|
||||
return nil
|
||||
}
|
||||
for _, up := range updates {
|
||||
info, uErr := mc.InstallFromMarket(ctx, mgr, up.Entry.ID, plugin.MarketInstallOptions{
|
||||
info, uErr := mc.InstallFromMarket(ctx, mgr, up.Entry.ID, market.MarketInstallOptions{
|
||||
IncludeAlpha: *includeAlpha,
|
||||
ForceRefresh: false,
|
||||
})
|
||||
@@ -296,7 +297,7 @@ func pluginPack(loc i18n.Locale, args []string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
packOpts := plugin.PackOptions{
|
||||
packOpts := market.PackOptions{
|
||||
HostVersion: version.Version,
|
||||
Contract: contract,
|
||||
OutputPath: *outPath,
|
||||
@@ -308,7 +309,7 @@ func pluginPack(loc i18n.Locale, args []string) error {
|
||||
}
|
||||
packOpts.SignKey = pk
|
||||
}
|
||||
res, pErr := plugin.PackDirectory(fs.Arg(0), packOpts)
|
||||
res, pErr := market.PackDirectory(fs.Arg(0), packOpts)
|
||||
if pErr != nil {
|
||||
if res.Report.HardBlocked && !*asJSON {
|
||||
fmt.Fprintln(os.Stderr, res.Report.SummaryText(string(loc)))
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
)
|
||||
|
||||
func TestStambhaCLIUsesPreviewMediaWithoutAnIntelRuntime(t *testing.T) {
|
||||
if runtime.GOOS != "windows" || runtime.GOARCH != "amd64" {
|
||||
t.Skip("the built-in Stambha driver runs on Windows x86-64")
|
||||
}
|
||||
dir := t.TempDir()
|
||||
cfg := &config.Config{DataRoot: filepath.Join(dir, "data-root")}
|
||||
boot := filepath.Join(dir, "boot")
|
||||
bootConfig := filepath.Join(boot, "EFI", "stela", "stela.cfg")
|
||||
if err := os.MkdirAll(filepath.Dir(bootConfig), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(bootConfig, []byte("--system\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
disk := filepath.Join(dir, "system.qcow2")
|
||||
if err := os.WriteFile(disk, []byte("fixture"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := context.Background()
|
||||
args := []string{"--driver", driver.BuiltinStambhaDriverID, "--boot-volume", boot, "--disk", disk, "arm"}
|
||||
if err := vmCreate(ctx, cfg, i18n.Detect(), args, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
args = []string{"--driver", driver.BuiltinStambhaDriverID, "--hosted-gpu=false", "--headless", "arm"}
|
||||
if err := vmSet(ctx, cfg, args); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, err := os.ReadFile(filepath.Join(cfg.XDGDataDir(), "stambha", "vms", "arm", "stambha.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var profile struct {
|
||||
Disk string `json:"raw_disk"`
|
||||
Display bool `json:"display"`
|
||||
HostedGPU bool `json:"hosted_gpu"`
|
||||
Accelerator string `json:"accelerator"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &profile); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if profile.Disk != disk || profile.Display || profile.HostedGPU || profile.Accelerator != "whpx" {
|
||||
t.Fatalf("unexpected preview profile %+v", profile)
|
||||
}
|
||||
}
|
||||
@@ -103,13 +103,13 @@ func compactVM(ctx context.Context, cfg *config.Config, driverID, name string) (
|
||||
return svc.CompactDisk(ctx, driver.VMRef{DriverID: driverID, Name: name}, os.Stdout, os.Stderr)
|
||||
}
|
||||
|
||||
func stopVM(ctx context.Context, cfg *config.Config, driverID, name string) error {
|
||||
func stopVM(ctx context.Context, cfg *config.Config, driverID, name string, force bool) error {
|
||||
svc, closeService, err := openCLILifecycle(cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer closeService()
|
||||
return svc.Stop(ctx, driver.VMRef{DriverID: driverID, Name: name}, false, os.Stdout, os.Stderr)
|
||||
return svc.Stop(ctx, driver.VMRef{DriverID: driverID, Name: name}, force, os.Stdout, os.Stderr)
|
||||
}
|
||||
|
||||
func startInWindow(ctx context.Context, cfg *config.Config, driverID, name string) error {
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/atomicfile"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
)
|
||||
@@ -19,6 +20,8 @@ import (
|
||||
const (
|
||||
// BuiltinReimsMacOSDriverID is the default driver for all unmarked/existing VMs.
|
||||
BuiltinReimsMacOSDriverID = "builtin.driver.reims-macos"
|
||||
// BuiltinStambhaDriverID is the ARM64 macOS driver's persisted ID.
|
||||
BuiltinStambhaDriverID = "builtin.driver.stambha"
|
||||
// OwnerMarkerFile persists the owning driver ID inside a VM directory.
|
||||
OwnerMarkerFile = ".reims-go-driver"
|
||||
)
|
||||
@@ -324,6 +327,14 @@ func WriteOwnerDriver(vmDir, driverID string) error {
|
||||
return os.WriteFile(filepath.Join(vmDir, OwnerMarkerFile), []byte(strings.TrimSpace(driverID)+"\n"), 0o644)
|
||||
}
|
||||
|
||||
// WriteVMRecord atomically replaces a driver's local JSON record in its VM directory.
|
||||
func WriteVMRecord(vmDir, name string, value any) error {
|
||||
if !filepath.IsLocal(name) || filepath.Base(name) != name || name == "." {
|
||||
return fmt.Errorf("invalid VM record name %q", name)
|
||||
}
|
||||
return atomicfile.WriteJSON(filepath.Join(vmDir, name), value, 0o600)
|
||||
}
|
||||
|
||||
// HostedReportMaxAge is how long a driver-pushed state counts as fresh; past
|
||||
// it the host asks the driver with `driver/show` while listing.
|
||||
const HostedReportMaxAge = 15 * time.Second
|
||||
|
||||
@@ -24,5 +24,8 @@ func Register(reg *plugin.Registry, cb builtin.HostCallbacks, desiredFn func(str
|
||||
if err := reg.Register(Definition(ver, cb, desiredFn(ID, true))); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := reg.Register(stambhaDefinition(ver, cb, desiredFn)); err != nil {
|
||||
return err
|
||||
}
|
||||
return reg.Register(ImagesDefinition(ver, desiredFn(IDImages, true)))
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package guest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"runtime"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/macos/stambhadriver"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
)
|
||||
|
||||
func stambhaDefinition(ver string, cb builtin.HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef {
|
||||
drv := stambhadriver.NewStambhaDriver(cb.GetConfig)
|
||||
pack := plugin.RuntimeKindContribution{
|
||||
Kind: drv.RuntimeKind(), Name: plugin.LocalizedText{ZhCN: "Stambha 运行时", EnUS: "Stambha Runtime"},
|
||||
RequiredFiles: stambhadriver.StambhaRuntimeFiles(),
|
||||
DefaultAPIVer: drv.RuntimeAPIRange(),
|
||||
}
|
||||
return plugin.PluginDef{
|
||||
Manifest: plugin.Manifest{Schema: 1, ID: stambhadriver.StambhaDriverID, Version: ver,
|
||||
Name: drv.DisplayName(), Publisher: "Reims-Go", License: "Apache-2.0",
|
||||
Permissions: []string{"driver:vm", "vm:control", "runtime:provider"}, DefaultEnabled: true,
|
||||
Contributes: plugin.Contributes{RuntimeKinds: []plugin.RuntimeKindContribution{pack},
|
||||
GuestDrivers: []plugin.GuestDriverContribution{{ID: drv.ID(), Name: drv.DisplayName(), RuntimeKind: drv.RuntimeKind(),
|
||||
RuntimeAPIRange: drv.RuntimeAPIRange(), Capabilities: drv.Capabilities(),
|
||||
CreateSchema: drv.CreateSchema(), SettingsSchema: drv.SettingsSchema(),
|
||||
VMRoots: []string{"data/stambha/vms"}}}},
|
||||
},
|
||||
Source: plugin.SourceBuiltin, Trust: plugin.TrustOfficial,
|
||||
Desired: runtime.GOOS == "windows" && runtime.GOARCH == "amd64" && cb.GetConfig != nil && desiredFn(drv.ID(), true),
|
||||
Activate: func(_ context.Context, sc *plugin.Scope) error {
|
||||
sc.Registry().RegisterRuntimeKind(sc, pack)
|
||||
sc.Registry().RegisterGuestDriver(sc, drv.ID(), drv)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,17 @@
|
||||
//go:build !windows
|
||||
|
||||
package stambhadriver
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os/exec"
|
||||
)
|
||||
|
||||
type stambhaProcess struct{ PID int }
|
||||
|
||||
func stambhaHideConsole(*exec.Cmd) {}
|
||||
func stambhaStartProcess(*exec.Cmd, string) (int, error) {
|
||||
return 0, errors.New("Stambha requires Windows x86-64")
|
||||
}
|
||||
func stambhaLiveProcess(string) (stambhaProcess, error) { return stambhaProcess{}, nil }
|
||||
func (stambhaProcess) kill() error { return nil }
|
||||
@@ -0,0 +1,497 @@
|
||||
package stambhadriver
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
)
|
||||
|
||||
func TestResolveStambhaRuntimeUsesCompleteCompatiblePackage(t *testing.T) {
|
||||
cfg := config.Config{DataRoot: t.TempDir(), ActiveRuntime: "intel-runtime"}
|
||||
install := func(commit, api, builtAt string, complete bool) {
|
||||
t.Helper()
|
||||
dir := filepath.Join(cfg.RuntimesDir(), StambhaRuntimeKind, commit)
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
manifest, _ := json.Marshal(rt.Manifest{Commit: commit, Kind: StambhaRuntimeKind, RuntimeAPI: api, BuiltAt: builtAt})
|
||||
if err := os.WriteFile(filepath.Join(dir, "manifest.json"), manifest, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !complete {
|
||||
return
|
||||
}
|
||||
for _, rel := range StambhaRuntimeFiles() {
|
||||
path := filepath.Join(dir, filepath.FromSlash(rel))
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(path, []byte("fixture"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
install("working", stambhaAPI, "2026-12-01T00:00:00Z", true)
|
||||
install("incomplete", stambhaAPI, "2026-12-02T00:00:00Z", false)
|
||||
install("future-api", "2.0.0", "2026-12-03T00:00:00Z", true)
|
||||
got, err := resolveStambhaRuntime(&cfg)
|
||||
if err != nil || got.Commit != "working" {
|
||||
t.Fatalf("selected runtime = %q, err = %v", got.Commit, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveStambhaRuntimeReportsNewestRejection(t *testing.T) {
|
||||
cfg := config.Config{DataRoot: t.TempDir(), ActiveRuntime: "intel-runtime"}
|
||||
if _, err := resolveStambhaRuntime(&cfg); !errors.Is(err, rt.ErrNoActiveRuntime) {
|
||||
t.Fatalf("empty runtime error = %v, want ErrNoActiveRuntime", err)
|
||||
}
|
||||
|
||||
install := func(commit, api, builtAt string, omit ...string) {
|
||||
t.Helper()
|
||||
dir := filepath.Join(cfg.RuntimesDir(), StambhaRuntimeKind, commit)
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
manifest, err := json.Marshal(rt.Manifest{Commit: commit, Kind: StambhaRuntimeKind, RuntimeAPI: api, BuiltAt: builtAt})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "manifest.json"), manifest, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, rel := range StambhaRuntimeFiles() {
|
||||
if slices.Contains(omit, rel) {
|
||||
continue
|
||||
}
|
||||
path := filepath.Join(dir, filepath.FromSlash(rel))
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(path, []byte("fixture"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
install("newest-compatible-missing-efi", stambhaAPI, "2026-12-03T00:00:00Z", stambhaEFIPath)
|
||||
install("older-incompatible", "2.0.0", "2026-12-02T00:00:00Z")
|
||||
|
||||
got, err := resolveStambhaRuntime(&cfg)
|
||||
if err == nil {
|
||||
t.Fatalf("unexpectedly resolved runtime %q", got.Commit)
|
||||
}
|
||||
if errors.Is(err, rt.ErrNoActiveRuntime) {
|
||||
t.Fatalf("error = %v, did not expect ErrNoActiveRuntime when Stambha packages exist", err)
|
||||
}
|
||||
msg := err.Error()
|
||||
if !strings.Contains(msg, "newest-compatible-missing-efi") || !strings.Contains(msg, "firmware/stambha.efi") {
|
||||
t.Fatalf("error = %q, want newest-compatible-missing-efi and firmware/stambha.efi", msg)
|
||||
}
|
||||
if strings.Contains(msg, "older-incompatible") {
|
||||
t.Fatalf("error = %q, must not report older-incompatible", msg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStambhaSocketPathUsesBoundedPerUserFallback(t *testing.T) {
|
||||
volume := filepath.VolumeName(t.TempDir())
|
||||
root := volume + string(os.PathSeparator)
|
||||
cache := filepath.Join(root, "cache")
|
||||
vmDir := filepath.Join(root, strings.Repeat("字", 42), "data", "stambha", "vms", "arm")
|
||||
otherVMDir := filepath.Join(root, strings.Repeat("字", 42), "other", "stambha", "vms", "arm")
|
||||
longTemp := filepath.Join(root, strings.Repeat("l", 100), "tmp")
|
||||
sock, err := stambhaSocketPath(vmDir, longTemp, cache)
|
||||
if err != nil || !stambhaPathWithin(cache, sock) || len(sock) > 103 {
|
||||
t.Fatalf("socket = %q, length = %d, err = %v", sock, len(sock), err)
|
||||
}
|
||||
other, err := stambhaSocketPath(otherVMDir, longTemp, cache)
|
||||
if err != nil || other == sock {
|
||||
t.Fatalf("different data root shares socket %q, err = %v", other, err)
|
||||
}
|
||||
if _, err := stambhaSocketPath(vmDir, longTemp); err == nil {
|
||||
t.Fatal("expected a clear error when no bounded socket is available")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStambhaRejectsWritableDiskInStageBeforeCleanup(t *testing.T) {
|
||||
cfg := config.Config{DataRoot: t.TempDir()}
|
||||
d := NewStambhaDriver(func() config.Config { return cfg })
|
||||
vmDir, err := d.directory("arm")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stage := filepath.Join(vmDir, stambhaStagedMediaDir)
|
||||
if err := os.MkdirAll(stage, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
disk := filepath.Join(stage, "disk.qcow2")
|
||||
if err := os.WriteFile(disk, []byte("keep this disk"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
boot := t.TempDir()
|
||||
bootConfig := filepath.Join(boot, "EFI", "stela", "stela.cfg")
|
||||
if err := os.MkdirAll(filepath.Dir(bootConfig), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(bootConfig, []byte("--system\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
profile := stambhaProfile{BootVolume: boot, Disk: disk}
|
||||
if err := stambhaValidateMedia(vmDir, &profile); err == nil {
|
||||
t.Fatal("accepted disk inside staging")
|
||||
}
|
||||
if _, err := stageStambhaBootVolume(boot, vmDir, "", profile); err == nil {
|
||||
t.Fatal("allowed staging with an attached disk inside it")
|
||||
}
|
||||
if err := driver.WriteVMRecord(vmDir, stambhaProfileName, profile); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := d.Delete(context.Background(), "arm", false, nil, nil); err == nil {
|
||||
t.Fatal("allowed deleting an old profile with an attached disk inside its stage")
|
||||
}
|
||||
raw, err := os.ReadFile(disk)
|
||||
if err != nil || string(raw) != "keep this disk" {
|
||||
t.Fatalf("disk = %q, err = %v", raw, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStambhaRejectsSymlinkedDiskInStage(t *testing.T) {
|
||||
vmDir := t.TempDir()
|
||||
stage := filepath.Join(vmDir, stambhaStagedMediaDir)
|
||||
if err := os.MkdirAll(stage, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
disk := filepath.Join(stage, "disk.qcow2")
|
||||
if err := os.WriteFile(disk, []byte("fixture"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
alias := filepath.Join(t.TempDir(), "alias.qcow2")
|
||||
if err := os.Symlink(disk, alias); err != nil {
|
||||
t.Skipf("could not create symlink: %v", err)
|
||||
}
|
||||
if err := ensureStambhaMediaOutsideStage(vmDir, stambhaProfile{Disk: alias}); err == nil {
|
||||
t.Fatal("accepted a disk alias that resolves inside staging")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStambhaDiskOwnersRejectsRunningWritableHardlink(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
disk, alias := filepath.Join(dir, "system.qcow2"), filepath.Join(dir, "alias.qcow2")
|
||||
if err := os.WriteFile(disk, []byte("fixture"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Link(disk, alias); err != nil {
|
||||
t.Skipf("could not create hardlink: %v", err)
|
||||
}
|
||||
vm := driver.VMInfo{Name: "other", State: "running", DiskPath: alias}
|
||||
if err := checkStambhaDiskOwners("arm", disk, []driver.VMInfo{vm}); err == nil {
|
||||
t.Fatal("accepted a hardlink of a disk already in use")
|
||||
}
|
||||
vm.State = "stopped"
|
||||
if err := checkStambhaDiskOwners("arm", disk, []driver.VMInfo{vm}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStambhaRewriteArgsHostedGPUAndQcow2(t *testing.T) {
|
||||
rawArgs := []string{
|
||||
"-accel", "tcg,thread=multi",
|
||||
"-cpu", "max,vendor=GenuineIntel",
|
||||
"-nodefaults",
|
||||
"-device", "isa-debug-exit,iobase=0xf4,iosize=4",
|
||||
"-machine", "q35,smm=off,sata=off,usb=off,smbus=off,hpet=off,i8042=off,vmport=off",
|
||||
"-display", "sdl",
|
||||
"-device", "VGA",
|
||||
"-device", "virtio-keyboard-pci",
|
||||
"-device", "virtio-tablet-pci",
|
||||
"-drive", "if=none,id=guest,format=raw,file=D:\\vm\\disk.qcow2",
|
||||
"-device", "nvme,drive=guest,serial=STELAANS",
|
||||
}
|
||||
profile := stambhaProfile{
|
||||
Accel: "whpx",
|
||||
Display: true,
|
||||
HostedGPU: true,
|
||||
MemoryMiB: 16384,
|
||||
}
|
||||
got := rewriteStambhaArgs(rawArgs, profile, `D:\rt\qemu\share`, true, `D:\vm\qmp.sock`)
|
||||
|
||||
assertArgPair(t, got, "-accel", "whpx,kernel-irqchip=off")
|
||||
assertArgPair(t, got, "-cpu", "host")
|
||||
assertArgPair(t, got, "-display", "none")
|
||||
assertArgPair(t, got, "-machine", "q35,smm=off,sata=off,usb=off,smbus=off,hpet=on,i8042=off,vmport=off,memory-backend=ram")
|
||||
assertArgPair(t, got, "-object", "memory-backend-ram,id=ram,size=16384M,share=on")
|
||||
assertArgPair(t, got, "-drive", "if=none,id=guest,format=qcow2,l2-cache-size=16M,file=D:\\vm\\disk.qcow2")
|
||||
assertArgPair(t, got, "-L", `D:\rt\qemu\share`)
|
||||
assertArgPair(t, got, "-device", "VGA,id=stela-console")
|
||||
assertArgPair(t, got, "-device", "virtio-keyboard-pci")
|
||||
assertArgPair(t, got, "-device", "virtio-tablet-pci")
|
||||
assertArgPair(t, got, "-device", "reims-graphics-pci,id=gfx,x-hosted-arm64=on")
|
||||
assertArgPair(t, got, "-qmp", `unix:D:\vm\qmp.sock,server=on,wait=off`)
|
||||
|
||||
for _, a := range got {
|
||||
if strings.HasPrefix(a, "isa-debug-exit,") {
|
||||
t.Fatalf("isa-debug-exit must be stripped in hosted GPU mode: %v", got)
|
||||
}
|
||||
if a == "VGA" {
|
||||
t.Fatalf("bare VGA must be replaced by VGA,id=stela-console: %v", got)
|
||||
}
|
||||
}
|
||||
if countArg(got, "virtio-keyboard-pci") != 1 || countArg(got, "virtio-tablet-pci") != 1 {
|
||||
t.Fatalf("virtio input devices must appear exactly once: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStambhaRewriteArgsLegacyPreserved(t *testing.T) {
|
||||
rawArgs := []string{
|
||||
"-accel", "tcg,thread=multi",
|
||||
"-cpu", "max,vendor=GenuineIntel",
|
||||
"-device", "isa-debug-exit,iobase=0xf4,iosize=4",
|
||||
"-machine", "q35,hpet=off,vmport=off",
|
||||
"-display", "none",
|
||||
"-device", "usb-storage,drive=volume,serial=STELAUSBIMAGE,bus=host-usb.0,bootindex=0",
|
||||
"-drive", "if=none,id=guest,format=raw,file=D:\\vm\\disk.img",
|
||||
}
|
||||
profile := stambhaProfile{
|
||||
Accel: "tcg",
|
||||
MediaBus: "nvme",
|
||||
Display: false,
|
||||
HostedGPU: false,
|
||||
}
|
||||
got := rewriteStambhaArgs(rawArgs, profile, `D:\rt\qemu\share`, false, `D:\vm\qmp.sock`)
|
||||
|
||||
assertArgPair(t, got, "-accel", "tcg,thread=multi")
|
||||
assertArgPair(t, got, "-cpu", "max,vendor=GenuineIntel")
|
||||
assertArgPair(t, got, "-device", "isa-debug-exit,iobase=0xf4,iosize=4")
|
||||
assertArgPair(t, got, "-device", "nvme,drive=volume,serial=STELAMEDIA,bootindex=0")
|
||||
assertArgPair(t, got, "-drive", "if=none,id=guest,format=raw,file=D:\\vm\\disk.img")
|
||||
assertArgPair(t, got, "-device", "VGA")
|
||||
if slices.Contains(got, "reims-graphics-pci,id=gfx,x-hosted-arm64=on") {
|
||||
t.Fatalf("legacy mode must not attach hosted Reims GPU: %v", got)
|
||||
}
|
||||
if slices.Contains(got, "-object") {
|
||||
t.Fatalf("legacy mode must not attach shared RAM memory-backend: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStambhaNonHostedDisplayUsesPackagedGTK(t *testing.T) {
|
||||
args := rewriteStambhaArgs([]string{"-display", "sdl"}, stambhaProfile{Display: true}, "", false, "")
|
||||
assertArgPair(t, args, "-display", "gtk")
|
||||
}
|
||||
|
||||
func TestParseStambhaImageInfo(t *testing.T) {
|
||||
for _, format := range []string{"raw", "qcow2"} {
|
||||
raw, _ := json.Marshal(map[string]any{"format": format, "virtual-size": 65536})
|
||||
if got, err := parseStambhaImageInfo(raw); err != nil || got != format {
|
||||
t.Fatalf("format = %q, err = %v, want %q", got, err, format)
|
||||
}
|
||||
}
|
||||
raw, _ := json.Marshal(map[string]any{"format": "vhdx", "virtual-size": 65536})
|
||||
if _, err := parseStambhaImageInfo(raw); err == nil {
|
||||
t.Fatal("unexpectedly accepted VHDX")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStambhaApplyEnv(t *testing.T) {
|
||||
base := []string{"PATH=C:\\Windows\\System32", "REIMS_VGPU_WINDOW=0", "FOO=bar"}
|
||||
|
||||
// Windowed hosted GPU with PCI VID:DID selector drops REIMS_VGPU_WINDOW=0 and sets Vulkan selectors.
|
||||
got := applyStambhaEnv(base, `D:\rt\qemu\bin`, stambhaProfile{HostedGPU: true, Display: true, GPU: "10DE:2231"}, `C:\rec.json`)
|
||||
if hasEnvKey(got, "REIMS_VGPU_WINDOW") {
|
||||
t.Fatalf("windowed hosted GPU should drop REIMS_VGPU_WINDOW: %v", got)
|
||||
}
|
||||
assertEnvVal(t, got, "MESA_VK_DEVICE_SELECT", "10de:2231")
|
||||
assertEnvVal(t, got, "VK_LOADER_DEVICE_SELECT", "10de:2231")
|
||||
if !strings.HasPrefix(getEnvVal(got, "PATH"), `D:\rt\qemu\bin`+string(os.PathListSeparator)) {
|
||||
t.Fatalf("PATH must prepend qemu/bin: %s", getEnvVal(got, "PATH"))
|
||||
}
|
||||
|
||||
// Headless hosted GPU with auto GPU sets REIMS_VGPU_WINDOW=0 and recommended ICD.
|
||||
headless := applyStambhaEnv(base, `D:\rt\qemu\bin`, stambhaProfile{HostedGPU: true, Display: false, GPU: "auto"}, `C:\nv-vk64.json`)
|
||||
assertEnvVal(t, headless, "REIMS_VGPU_WINDOW", "0")
|
||||
assertEnvVal(t, headless, "VK_ICD_FILENAMES", `C:\nv-vk64.json`)
|
||||
assertEnvVal(t, headless, "VK_DRIVER_FILES", `C:\nv-vk64.json`)
|
||||
}
|
||||
|
||||
func TestStageStambhaBootVolumeDoesNotMutateSource(t *testing.T) {
|
||||
src := t.TempDir()
|
||||
vmDir := t.TempDir()
|
||||
efiPath := filepath.Join(src, "EFI", "BOOT", "BOOTX64.EFI")
|
||||
cfgPath := filepath.Join(src, "EFI", "stela", "stela.cfg")
|
||||
if err := os.MkdirAll(filepath.Dir(efiPath), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(cfgPath), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(efiPath, []byte("EFI-PAYLOAD"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
origCfg := "--storage STELAANS:11111111-2222-3333-4444-555555555555\n"
|
||||
if err := os.WriteFile(cfgPath, []byte(origCfg), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
runtimeEFI := filepath.Join(t.TempDir(), "stambha.efi")
|
||||
if err := os.WriteFile(runtimeEFI, []byte("RUNTIME-EFI"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
staged, err := stageStambhaBootVolume(src, vmDir, runtimeEFI, stambhaProfile{
|
||||
HostedGPU: true,
|
||||
StelaArgs: "--tier2 on --tlbi-keep on",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gotCfg, err := os.ReadFile(filepath.Join(staged, "EFI", "stela", "stela.cfg"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wantCfg := "--storage STELAANS:11111111-2222-3333-4444-555555555555 --hosted-reims-base 0x300000000 --hosted-reims-irq auto --hosted-reims-irq-mode poll --tier2 on --tlbi-keep on\n"
|
||||
if string(gotCfg) != wantCfg {
|
||||
t.Fatalf("staged stela.cfg = %q, want %q", string(gotCfg), wantCfg)
|
||||
}
|
||||
gotEFI, err := os.ReadFile(filepath.Join(staged, "EFI", "BOOT", "BOOTX64.EFI"))
|
||||
if err != nil || string(gotEFI) != "RUNTIME-EFI" {
|
||||
t.Fatalf("staged EFI = %q, err = %v", gotEFI, err)
|
||||
}
|
||||
sourceEFI, err := os.ReadFile(efiPath)
|
||||
if err != nil || string(sourceEFI) != "EFI-PAYLOAD" {
|
||||
t.Fatalf("source EFI = %q, err = %v", sourceEFI, err)
|
||||
}
|
||||
|
||||
afterSrc, err := os.ReadFile(cfgPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(afterSrc) != origCfg {
|
||||
t.Fatalf("source stela.cfg was mutated: %q", string(afterSrc))
|
||||
}
|
||||
}
|
||||
|
||||
func TestStambhaCreateSetShowHostedGPU(t *testing.T) {
|
||||
dataRoot := t.TempDir()
|
||||
mediaDir := filepath.Join(t.TempDir(), "media")
|
||||
if err := os.MkdirAll(filepath.Join(mediaDir, "EFI", "BOOT"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfgPath := filepath.Join(mediaDir, "EFI", "stela", "stela.cfg")
|
||||
if err := os.MkdirAll(filepath.Dir(cfgPath), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(cfgPath, []byte("--system\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
diskFile := filepath.Join(t.TempDir(), "guest.qcow2")
|
||||
if err := os.WriteFile(diskFile, []byte{'Q', 'F', 'I', 0xfb, 0, 0, 0, 3}, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
drv := NewStambhaDriver(func() config.Config { return config.Config{DataRoot: dataRoot} })
|
||||
ctx := context.Background()
|
||||
err := drv.Create(ctx, driver.CreateRequest{
|
||||
DriverID: StambhaDriverID,
|
||||
Name: "arm-desktop",
|
||||
Options: map[string]any{
|
||||
"boot_volume": mediaDir,
|
||||
"raw_disk": diskFile,
|
||||
"memory": "16G",
|
||||
"cpus": 8,
|
||||
"accelerator": "whpx",
|
||||
"hosted_gpu": true,
|
||||
"gpu": "10de:2231",
|
||||
"display": false,
|
||||
"stela_args": "--tier2 on --tlbi-keep on",
|
||||
},
|
||||
}, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Create failed: %v", err)
|
||||
}
|
||||
|
||||
info, err := drv.Show(ctx, "arm-desktop")
|
||||
if err != nil {
|
||||
t.Fatalf("Show failed: %v", err)
|
||||
}
|
||||
if info.DriverData["hosted_gpu"] != true || info.DriverData["gpu"] != "10de:2231" || info.DriverData["stela_args"] != "--tier2 on --tlbi-keep on" {
|
||||
t.Fatalf("unexpected DriverData: %+v", info.DriverData)
|
||||
}
|
||||
|
||||
if err := drv.Set(ctx, driver.SetRequest{Name: "arm-desktop", Changes: map[string]any{"gpu": "auto", "hosted_gpu": false}}, nil, nil); err != nil {
|
||||
t.Fatalf("Set failed: %v", err)
|
||||
}
|
||||
raw, err := os.ReadFile(filepath.Join(info.Directory, stambhaProfileName))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var saved stambhaProfile
|
||||
if err := json.Unmarshal(raw, &saved); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if saved.HostedGPU || saved.GPU != "auto" {
|
||||
t.Fatalf("unexpected saved profile: %+v", saved)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStambhaCapabilities(t *testing.T) {
|
||||
drv := NewStambhaDriver(nil)
|
||||
caps := drv.Capabilities()
|
||||
for _, want := range []string{"guest.arm64", "serial_log", driver.CapAffinity} {
|
||||
if !slices.Contains(caps, want) {
|
||||
t.Fatalf("Capabilities() = %v, missing %q", caps, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func assertArgPair(t *testing.T, args []string, flag, want string) {
|
||||
t.Helper()
|
||||
for i := 0; i+1 < len(args); i++ {
|
||||
if args[i] == flag && args[i+1] == want {
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatalf("missing arg pair %q %q in %v", flag, want, args)
|
||||
}
|
||||
|
||||
func countArg(args []string, value string) int {
|
||||
n := 0
|
||||
for _, a := range args {
|
||||
if a == value {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func getEnvVal(env []string, key string) string {
|
||||
for _, kv := range env {
|
||||
if k, v, ok := strings.Cut(kv, "="); ok && strings.EqualFold(k, key) {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func hasEnvKey(env []string, key string) bool {
|
||||
for _, kv := range env {
|
||||
if k, _, ok := strings.Cut(kv, "="); ok && strings.EqualFold(k, key) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func assertEnvVal(t *testing.T, env []string, key, want string) {
|
||||
t.Helper()
|
||||
if got := getEnvVal(env, key); got != want {
|
||||
t.Fatalf("env %s = %q, want %q (env=%v)", key, got, want, env)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
//go:build windows
|
||||
|
||||
package stambhadriver
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
type stambhaProcess struct {
|
||||
PID int `json:"pid"`
|
||||
Created windows.Filetime `json:"created"`
|
||||
}
|
||||
|
||||
const stambhaProcessRecord = "stambha-process.json"
|
||||
|
||||
func stambhaHideConsole(cmd *exec.Cmd) {
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: windows.CREATE_NO_WINDOW}
|
||||
}
|
||||
|
||||
func stambhaStartProcess(cmd *exec.Cmd, dir string) (int, error) {
|
||||
// Use CREATE_NO_WINDOW without HideWindow (STARTF_USESHOWWINDOW/SW_HIDE) so
|
||||
// QEMU opens no console window while reims-vgpu's first ShowWindow(SW_SHOW)
|
||||
// on its native Vulkan display window is not swallowed by Win32.
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{
|
||||
CreationFlags: windows.CREATE_NO_WINDOW | windows.CREATE_NEW_PROCESS_GROUP | windows.CREATE_BREAKAWAY_FROM_JOB,
|
||||
}
|
||||
active := cmd
|
||||
if err := active.Start(); err != nil {
|
||||
if !errors.Is(err, windows.ERROR_ACCESS_DENIED) {
|
||||
return 0, err
|
||||
}
|
||||
// Parent Job Objects without JOB_OBJECT_LIMIT_BREAKAWAY_OK reject
|
||||
// CREATE_BREAKAWAY_FROM_JOB with ERROR_ACCESS_DENIED; retry in-job.
|
||||
retry := exec.Command(cmd.Path, cmd.Args[1:]...)
|
||||
retry.Dir, retry.Env = cmd.Dir, cmd.Env
|
||||
retry.Stdin, retry.Stdout, retry.Stderr = cmd.Stdin, cmd.Stdout, cmd.Stderr
|
||||
retry.SysProcAttr = &syscall.SysProcAttr{
|
||||
CreationFlags: windows.CREATE_NO_WINDOW | windows.CREATE_NEW_PROCESS_GROUP,
|
||||
}
|
||||
if err2 := retry.Start(); err2 != nil {
|
||||
return 0, err2
|
||||
}
|
||||
active = retry
|
||||
}
|
||||
pid := active.Process.Pid
|
||||
handle, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(pid))
|
||||
var created windows.Filetime
|
||||
if err == nil {
|
||||
var exit, kernel, user windows.Filetime
|
||||
err = windows.GetProcessTimes(handle, &created, &exit, &kernel, &user)
|
||||
windows.CloseHandle(handle)
|
||||
}
|
||||
if err == nil {
|
||||
err = driver.WriteVMRecord(dir, stambhaProcessRecord, stambhaProcess{PID: pid, Created: created})
|
||||
}
|
||||
if err != nil {
|
||||
_ = active.Process.Kill()
|
||||
_ = active.Wait()
|
||||
return 0, err
|
||||
}
|
||||
go func() { _ = active.Wait() }()
|
||||
return pid, nil
|
||||
}
|
||||
|
||||
func stambhaLiveProcess(dir string) (stambhaProcess, error) {
|
||||
raw, err := os.ReadFile(filepath.Join(dir, stambhaProcessRecord))
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return stambhaProcess{}, nil
|
||||
}
|
||||
if err != nil {
|
||||
return stambhaProcess{}, err
|
||||
}
|
||||
var proc stambhaProcess
|
||||
if err := json.Unmarshal(raw, &proc); err != nil {
|
||||
return stambhaProcess{}, err
|
||||
}
|
||||
handle, err := proc.open(0)
|
||||
if handle == 0 || err != nil {
|
||||
return stambhaProcess{}, err
|
||||
}
|
||||
defer windows.CloseHandle(handle)
|
||||
return proc, nil
|
||||
}
|
||||
|
||||
func (proc stambhaProcess) open(extra uint32) (windows.Handle, error) {
|
||||
if proc.PID <= 0 || proc.Created == (windows.Filetime{}) {
|
||||
return 0, nil
|
||||
}
|
||||
handle, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION|windows.SYNCHRONIZE|extra, false, uint32(proc.PID))
|
||||
if errors.Is(err, windows.ERROR_INVALID_PARAMETER) {
|
||||
return 0, nil
|
||||
}
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
state, err := windows.WaitForSingleObject(handle, 0)
|
||||
if err != nil || state == windows.WAIT_OBJECT_0 {
|
||||
windows.CloseHandle(handle)
|
||||
return 0, err
|
||||
}
|
||||
var created, exit, kernel, user windows.Filetime
|
||||
err = windows.GetProcessTimes(handle, &created, &exit, &kernel, &user)
|
||||
if err != nil || created != proc.Created {
|
||||
windows.CloseHandle(handle)
|
||||
return 0, err
|
||||
}
|
||||
return handle, nil
|
||||
}
|
||||
|
||||
func (proc stambhaProcess) kill() error {
|
||||
handle, err := proc.open(windows.PROCESS_TERMINATE)
|
||||
if handle == 0 || err != nil {
|
||||
return err
|
||||
}
|
||||
defer windows.CloseHandle(handle)
|
||||
return windows.TerminateProcess(handle, 1)
|
||||
}
|
||||
@@ -12,6 +12,8 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/plugin/sidecarproc"
|
||||
)
|
||||
|
||||
const maxPluginLogBytes = 2 << 20 // 2 MiB log rotation threshold (§6.1)
|
||||
@@ -26,7 +28,7 @@ type ManagedProcess struct {
|
||||
// DriverID is empty only for legacy spawns that named no driver.
|
||||
DriverID string
|
||||
cmd *exec.Cmd
|
||||
job *vmJob
|
||||
job *sidecarproc.VMJob
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
@@ -479,15 +481,15 @@ func (b *Broker) SpawnManagedVMProcessWithRef(ctx context.Context, pluginID stri
|
||||
cmd.Env = append(os.Environ(), env...)
|
||||
}
|
||||
if breakaway {
|
||||
configureDetachedVMProcess(cmd)
|
||||
sidecarproc.ConfigureDetachedVMProcess(cmd)
|
||||
} else {
|
||||
configureNestedVMProcess(cmd)
|
||||
sidecarproc.ConfigureNestedVMProcess(cmd)
|
||||
}
|
||||
return cmd
|
||||
}
|
||||
cmd := build(true)
|
||||
startErr := cmd.Start()
|
||||
if startErr != nil && isBreakawayDenied(startErr) {
|
||||
if startErr != nil && sidecarproc.IsBreakawayDenied(startErr) {
|
||||
// The host itself runs in a job that forbids breakaway (some launchers
|
||||
// and CI sandboxes do). Start the VM inside that job instead; it is
|
||||
// still moved into its own per-VM job below.
|
||||
@@ -500,7 +502,7 @@ func (b *Broker) SpawnManagedVMProcessWithRef(ctx context.Context, pluginID stri
|
||||
return 0, startErr
|
||||
}
|
||||
pid := cmd.Process.Pid
|
||||
job, jobErr := newVMJob()
|
||||
job, jobErr := sidecarproc.NewVMJob()
|
||||
if jobErr == nil {
|
||||
if jobErr = job.Assign(pid); jobErr != nil {
|
||||
job.Close()
|
||||
@@ -512,7 +514,7 @@ func (b *Broker) SpawnManagedVMProcessWithRef(ctx context.Context, pluginID stri
|
||||
if jobErr != nil {
|
||||
b.Audit(pluginID, "JOB_ERR", fmt.Sprintf("vm=%s pid=%d: %v (only the launcher process is tracked)", vmName, pid, jobErr))
|
||||
}
|
||||
if err := resumeVMProcess(pid); err != nil {
|
||||
if err := sidecarproc.ResumeVMProcess(pid); err != nil {
|
||||
_ = cmd.Process.Kill()
|
||||
_ = cmd.Wait()
|
||||
job.Close()
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/plugin/sidecarproc"
|
||||
"github.com/Nwflower/reims-go/pkg/pluginproto"
|
||||
)
|
||||
|
||||
@@ -33,8 +34,8 @@ func TestSupervisorHostMethodsAreCatalogued(t *testing.T) {
|
||||
func TestHandlerErrorKeepsItsCode(t *testing.T) {
|
||||
hostRead, pluginWrite := net.Pipe()
|
||||
pluginRead, hostWrite := net.Pipe()
|
||||
host := NewRPCConn(hostRead, hostWrite)
|
||||
plugin := NewRPCConn(pluginRead, pluginWrite)
|
||||
host := sidecarproc.NewRPCConn(hostRead, hostWrite)
|
||||
plugin := sidecarproc.NewRPCConn(pluginRead, pluginWrite)
|
||||
t.Cleanup(func() {
|
||||
host.Close()
|
||||
plugin.Close()
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
//go:build !windows
|
||||
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"os/exec"
|
||||
"sync"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func configureSidecarCmd(cmd *exec.Cmd) {
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
|
||||
}
|
||||
|
||||
func configureDetachedVMProcess(cmd *exec.Cmd) {
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
|
||||
}
|
||||
|
||||
func configureNestedVMProcess(cmd *exec.Cmd) { configureDetachedVMProcess(cmd) }
|
||||
|
||||
func resumeVMProcess(int) error { return nil }
|
||||
|
||||
func isBreakawayDenied(error) bool { return false }
|
||||
|
||||
type sidecarJob struct {
|
||||
pgid int
|
||||
closeOnce sync.Once
|
||||
}
|
||||
|
||||
func newSidecarJob(_ uintptr) (*sidecarJob, error) {
|
||||
return &sidecarJob{}, nil
|
||||
}
|
||||
|
||||
func (j *sidecarJob) Assign(pid int) error {
|
||||
if j != nil {
|
||||
j.pgid = pid
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (j *sidecarJob) Close() {
|
||||
if j == nil {
|
||||
return
|
||||
}
|
||||
j.closeOnce.Do(func() {
|
||||
if j.pgid > 0 {
|
||||
_ = syscall.Kill(-j.pgid, syscall.SIGKILL)
|
||||
j.pgid = 0
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
package plugin
|
||||
package market
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
)
|
||||
|
||||
// MarketEntryLocales returns the canonical UI language tags a locale pack
|
||||
@@ -60,7 +61,7 @@ func primaryLanguage(tag string) string {
|
||||
// installable (compatible, not withdrawn, not installed), exact language
|
||||
// first, then the most trusted. It returns nil when there is none or the
|
||||
// market is unreachable.
|
||||
func (c *MarketClient) SuggestLocalePack(ctx context.Context, installed []PluginInfo, tag string) *MarketCatalogItem {
|
||||
func (c *MarketClient) SuggestLocalePack(ctx context.Context, installed []plugin.PluginInfo, tag string) *MarketCatalogItem {
|
||||
want, ok := i18n.ParseLocale(tag)
|
||||
if !ok {
|
||||
return nil
|
||||
+6
-5
@@ -1,4 +1,4 @@
|
||||
package plugin_test
|
||||
package market_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/market"
|
||||
)
|
||||
|
||||
// Entries shaped like the live index: no explicit locales, the language shows
|
||||
@@ -38,18 +39,18 @@ const localeIndexJSON = `{
|
||||
}`
|
||||
|
||||
func TestMarketEntryLocales(t *testing.T) {
|
||||
var idx plugin.MarketIndex
|
||||
var idx market.MarketIndex
|
||||
if err := json.Unmarshal([]byte(strings.ReplaceAll(localeIndexJSON, "SUM", strings.Repeat("a", 64))), &idx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := plugin.MarketEntryLocales(idx.Plugins[0])
|
||||
got := market.MarketEntryLocales(idx.Plugins[0])
|
||||
sort.Strings(got)
|
||||
// Non-language tags such as "locale" and "i18n" are dropped.
|
||||
want := []string{"zh-HK", "zh-TW"}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("zh-TW pack locales = %v, want %v", got, want)
|
||||
}
|
||||
if got := plugin.MarketEntryLocales(idx.Plugins[2]); !reflect.DeepEqual(got, []string{"ja-JP"}) {
|
||||
if got := market.MarketEntryLocales(idx.Plugins[2]); !reflect.DeepEqual(got, []string{"ja-JP"}) {
|
||||
t.Fatalf("explicit locales = %v, want [ja-JP]", got)
|
||||
}
|
||||
}
|
||||
@@ -60,7 +61,7 @@ func TestSuggestLocalePack(t *testing.T) {
|
||||
_, _ = w.Write([]byte(body))
|
||||
}))
|
||||
defer srv.Close()
|
||||
mc := plugin.NewMarketClient(plugin.MarketClientOptions{
|
||||
mc := market.NewMarketClient(market.MarketClientOptions{
|
||||
Layout: plugin.PluginsLayout{}, HostVersion: "0.2.10",
|
||||
URLs: []string{srv.URL + "/index.json"}, CacheTTL: time.Minute, AllowInsecureLocalhost: true,
|
||||
})
|
||||
@@ -1,4 +1,4 @@
|
||||
package plugin
|
||||
package market
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -20,8 +20,15 @@ import (
|
||||
"github.com/Nwflower/reims-go/internal/atomicfile"
|
||||
"github.com/Nwflower/reims-go/internal/fetch"
|
||||
"github.com/Nwflower/reims-go/internal/netproxy"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
)
|
||||
|
||||
// MarketEntryRisks estimates risk categories for a market listing from its
|
||||
// declared kind, tier and permissions before anything is downloaded.
|
||||
func MarketEntryRisks(e MarketEntry) []string {
|
||||
return plugin.EstimateMarketRisks(e.Tier, e.Kind, e.Permissions)
|
||||
}
|
||||
|
||||
//go:embed market_fallback.json
|
||||
var embeddedMarketFallbackJSON []byte
|
||||
|
||||
@@ -52,32 +59,32 @@ type MarketRelease struct {
|
||||
SHA256 string `json:"sha256"`
|
||||
SizeBytes int64 `json:"size_bytes,omitempty"`
|
||||
PublishedAt string `json:"published_at,omitempty"`
|
||||
Changelog LocalizedText `json:"changelog,omitempty"`
|
||||
Changelog plugin.LocalizedText `json:"changelog,omitempty"`
|
||||
}
|
||||
|
||||
// MarketEntry describes one plugin published in the remote/embedded market index (§9).
|
||||
type MarketEntry struct {
|
||||
ID string `json:"id"`
|
||||
Version string `json:"version"`
|
||||
Name LocalizedText `json:"name"`
|
||||
Description LocalizedText `json:"description"`
|
||||
Name plugin.LocalizedText `json:"name"`
|
||||
Description plugin.LocalizedText `json:"description"`
|
||||
Publisher string `json:"publisher"`
|
||||
License string `json:"license"`
|
||||
Channel string `json:"channel"` // "stable" | "alpha"
|
||||
Trust TrustLevel `json:"trust"`
|
||||
Trust plugin.TrustLevel `json:"trust"`
|
||||
Kind string `json:"kind,omitempty"` // "theme" | "locale" | "driver" | "tool" | "template" | "runtime"
|
||||
Tier Tier `json:"tier,omitempty"`
|
||||
Icon *PluginIcon `json:"icon,omitempty"`
|
||||
Tier plugin.Tier `json:"tier,omitempty"`
|
||||
Icon *plugin.PluginIcon `json:"icon,omitempty"`
|
||||
Homepage string `json:"homepage,omitempty"`
|
||||
ReadmeURL string `json:"readme_url,omitempty"`
|
||||
Engines Engines `json:"engines"`
|
||||
Engines plugin.Engines `json:"engines"`
|
||||
Platforms []string `json:"platforms,omitempty"`
|
||||
Permissions []string `json:"permissions,omitempty"`
|
||||
DownloadURL string `json:"download_url"`
|
||||
SHA256 string `json:"sha256"`
|
||||
SizeBytes int64 `json:"size_bytes,omitempty"`
|
||||
Signer string `json:"signer,omitempty"`
|
||||
Changelog LocalizedText `json:"changelog,omitempty"`
|
||||
Changelog plugin.LocalizedText `json:"changelog,omitempty"`
|
||||
Releases []MarketRelease `json:"releases,omitempty"`
|
||||
Tags []string `json:"tags,omitempty"`
|
||||
// Locales lists the UI languages a locale pack provides. When absent,
|
||||
@@ -92,7 +99,7 @@ type MarketEntry struct {
|
||||
// while already-installed users keep running with a replacement advisory.
|
||||
type MarketWithdrawal struct {
|
||||
ID string `json:"id"`
|
||||
Reason LocalizedText `json:"reason"`
|
||||
Reason plugin.LocalizedText `json:"reason"`
|
||||
InsteadID string `json:"instead_id,omitempty"`
|
||||
InsteadName string `json:"instead_name,omitempty"`
|
||||
WithdrawnAt string `json:"withdrawn_at,omitempty"`
|
||||
@@ -169,7 +176,7 @@ type MarketInstallOptions struct {
|
||||
Version string
|
||||
IncludeAlpha bool
|
||||
ForceRefresh bool
|
||||
Keyring []SigningKey
|
||||
Keyring []plugin.SigningKey
|
||||
OnProgress fetch.Progress
|
||||
// OnPhase is called when the install moves to a new phase.
|
||||
OnPhase func(phase string)
|
||||
@@ -177,7 +184,7 @@ type MarketInstallOptions struct {
|
||||
|
||||
// MarketClientOptions configures MarketClient.
|
||||
type MarketClientOptions struct {
|
||||
Layout PluginsLayout
|
||||
Layout plugin.PluginsLayout
|
||||
HostVersion string
|
||||
URLs []string
|
||||
HTTPClient *http.Client
|
||||
@@ -193,7 +200,7 @@ type MarketClientOptions struct {
|
||||
// MarketClient lazily fetches, caches, searches, and installs plugins from the
|
||||
// static remote market index with disk-cache + embedded fallback (§9).
|
||||
type MarketClient struct {
|
||||
layout PluginsLayout
|
||||
layout plugin.PluginsLayout
|
||||
hostVersion string
|
||||
urls []string
|
||||
httpClient *http.Client
|
||||
@@ -379,19 +386,19 @@ func (c *MarketClient) cachedSnapshot() (idx MarketIndex, source string, stale b
|
||||
}
|
||||
|
||||
// Peek is Browse over CachedIndex: no network I/O.
|
||||
func (c *MarketClient) Peek(installed []PluginInfo, opts MarketBrowseOptions) MarketBrowseResult {
|
||||
func (c *MarketClient) Peek(installed []plugin.PluginInfo, opts MarketBrowseOptions) MarketBrowseResult {
|
||||
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 {
|
||||
func (c *MarketClient) Browse(ctx context.Context, installed []plugin.PluginInfo, opts MarketBrowseOptions) MarketBrowseResult {
|
||||
idx, source, stale, fetchErr := c.LoadIndex(ctx, opts.ForceRefresh)
|
||||
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, vouched bool) MarketBrowseResult {
|
||||
func (c *MarketClient) browseIndex(idx MarketIndex, source string, stale bool, fetchErr error, installed []plugin.PluginInfo, opts MarketBrowseOptions, vouched bool) MarketBrowseResult {
|
||||
res := MarketBrowseResult{
|
||||
Source: source,
|
||||
Stale: stale,
|
||||
@@ -403,7 +410,7 @@ func (c *MarketClient) browseIndex(idx MarketIndex, source string, stale bool, f
|
||||
res.FetchError = fetchErr.Error()
|
||||
}
|
||||
|
||||
instMap := make(map[string]PluginInfo, len(installed))
|
||||
instMap := make(map[string]plugin.PluginInfo, len(installed))
|
||||
for _, info := range installed {
|
||||
instMap[info.ID] = info
|
||||
}
|
||||
@@ -435,17 +442,17 @@ func (c *MarketClient) browseIndex(idx MarketIndex, source string, stale bool, f
|
||||
if kindFilter != "" && !strings.EqualFold(entry.Kind, kindFilter) {
|
||||
continue
|
||||
}
|
||||
if !vouched && entry.Trust != TrustCommunity {
|
||||
if !vouched && entry.Trust != plugin.TrustCommunity {
|
||||
// An index that cannot vouch (third-party or stale cache) must show
|
||||
// the trust its packages will actually install with.
|
||||
entry.Trust = TrustCommunity
|
||||
entry.Trust = plugin.TrustCommunity
|
||||
}
|
||||
compat, incompatReason := CheckMarketCompatibility(entry, c.hostVersion)
|
||||
item := MarketCatalogItem{
|
||||
Entry: entry,
|
||||
Compatible: compat,
|
||||
IncompatibleReason: incompatReason,
|
||||
HighRiskPermissions: HighRiskPermissions(entry.Permissions),
|
||||
HighRiskPermissions: plugin.HighRiskPermissions(entry.Permissions),
|
||||
Risks: MarketEntryRisks(entry),
|
||||
}
|
||||
if w, ok := withdrawnMap[entry.ID]; ok {
|
||||
@@ -467,7 +474,7 @@ func (c *MarketClient) browseIndex(idx MarketIndex, source string, stale bool, f
|
||||
if a.UpdateAvailable != b.UpdateAvailable {
|
||||
return a.UpdateAvailable
|
||||
}
|
||||
ra, rb := trustSortRank(a.Entry.Trust), trustSortRank(b.Entry.Trust)
|
||||
ra, rb := plugin.TrustSortRank(a.Entry.Trust), plugin.TrustSortRank(b.Entry.Trust)
|
||||
if ra != rb {
|
||||
return ra > rb
|
||||
}
|
||||
@@ -488,7 +495,7 @@ func (c *MarketClient) browseIndex(idx MarketIndex, source string, stale bool, f
|
||||
|
||||
// CheckUpdates returns installed plugins that have a compatible, non-withdrawn
|
||||
// newer version available in the market.
|
||||
func (c *MarketClient) CheckUpdates(ctx context.Context, installed []PluginInfo, includeAlpha, forceRefresh bool) ([]MarketCatalogItem, MarketBrowseResult) {
|
||||
func (c *MarketClient) CheckUpdates(ctx context.Context, installed []plugin.PluginInfo, includeAlpha, forceRefresh bool) ([]MarketCatalogItem, MarketBrowseResult) {
|
||||
browse := c.Browse(ctx, installed, MarketBrowseOptions{
|
||||
IncludeAlpha: includeAlpha,
|
||||
ForceRefresh: forceRefresh,
|
||||
@@ -504,12 +511,12 @@ func (c *MarketClient) CheckUpdates(ctx context.Context, installed []PluginInfo,
|
||||
|
||||
// InstallFromMarket downloads, verifies SHA-256, static-scans, and
|
||||
// transactionally installs pluginID from the market index.
|
||||
func (c *MarketClient) InstallFromMarket(ctx context.Context, mgr *Manager, pluginID string, opts MarketInstallOptions) (*PluginInfo, error) {
|
||||
func (c *MarketClient) InstallFromMarket(ctx context.Context, mgr *plugin.Manager, pluginID string, opts MarketInstallOptions) (*plugin.PluginInfo, error) {
|
||||
if mgr == nil {
|
||||
return nil, errors.New("plugin manager is nil")
|
||||
}
|
||||
pluginID = strings.TrimSpace(pluginID)
|
||||
if !reReverseDomainID.MatchString(pluginID) {
|
||||
if !plugin.IsValidReverseDomainID(pluginID) {
|
||||
return nil, fmt.Errorf("invalid plugin id %q", pluginID)
|
||||
}
|
||||
|
||||
@@ -582,10 +589,10 @@ func (c *MarketClient) InstallFromMarket(ctx context.Context, mgr *Manager, plug
|
||||
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 {
|
||||
if _, err := plugin.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 {
|
||||
if entry.SizeBytes < 0 || entry.SizeBytes > plugin.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))
|
||||
@@ -603,7 +610,7 @@ 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, err := safeJoin(c.layout.TmpDir(), archiveName)
|
||||
archivePath, err := plugin.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)
|
||||
}
|
||||
@@ -615,7 +622,7 @@ func (c *MarketClient) InstallFromMarket(ctx context.Context, mgr *Manager, plug
|
||||
if opts.OnPhase != nil {
|
||||
opts.OnPhase(MarketPhaseDownload)
|
||||
}
|
||||
maxBytes := maxPluginArchiveBytes
|
||||
maxBytes := plugin.MaxPluginArchiveBytes
|
||||
if entry.SizeBytes > 0 && entry.SizeBytes < maxBytes {
|
||||
maxBytes = entry.SizeBytes
|
||||
}
|
||||
@@ -630,7 +637,7 @@ func (c *MarketClient) InstallFromMarket(ctx context.Context, mgr *Manager, plug
|
||||
opts.OnPhase(MarketPhaseInstall)
|
||||
}
|
||||
|
||||
return mgr.InstallArchiveWithSource(ctx, archivePath, SourceMarket, PackageInstallOptions{
|
||||
return mgr.InstallArchiveWithSource(ctx, archivePath, plugin.SourceMarket, plugin.PackageInstallOptions{
|
||||
ExpectedID: entry.ID,
|
||||
ExpectedVersion: entry.Version,
|
||||
HostVersion: c.hostVersion,
|
||||
@@ -642,7 +649,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) {
|
||||
return checkHostCompatibility(entry.Platforms, entry.Engines, hostVersion)
|
||||
return plugin.CheckHostCompatibility(entry.Platforms, entry.Engines, hostVersion)
|
||||
}
|
||||
|
||||
func (c *MarketClient) fetchRemoteIndex(ctx context.Context, rawURL string) (MarketIndex, error) {
|
||||
@@ -828,8 +835,8 @@ func selectChannelEntries(entries []MarketEntry, includeAlpha bool) map[string]M
|
||||
}
|
||||
|
||||
func isVersionNewer(candidate, current string) bool {
|
||||
vc, err1 := ParseSemVer(candidate)
|
||||
vcur, err2 := ParseSemVer(current)
|
||||
vc, err1 := plugin.ParseSemVer(candidate)
|
||||
vcur, err2 := plugin.ParseSemVer(current)
|
||||
if err1 != nil || err2 != nil {
|
||||
return candidate != current && candidate > current
|
||||
}
|
||||
@@ -864,19 +871,6 @@ func marketEntryMatchesQuery(e MarketEntry, q string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func trustSortRank(t TrustLevel) int {
|
||||
switch t {
|
||||
case TrustOfficial:
|
||||
return 3
|
||||
case TrustVerified:
|
||||
return 2
|
||||
case TrustCommunity:
|
||||
return 1
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
func cloneMarketIndex(idx MarketIndex) MarketIndex {
|
||||
cp := MarketIndex{
|
||||
Schema: idx.Schema,
|
||||
@@ -910,11 +904,11 @@ func (c *MarketClient) vouches(source string, stale bool) bool {
|
||||
}
|
||||
|
||||
// indexTrust is the trust an install inherits from a vouching index.
|
||||
func indexTrust(entry MarketEntry, vouched bool) TrustLevel {
|
||||
func indexTrust(entry MarketEntry, vouched bool) plugin.TrustLevel {
|
||||
if !vouched {
|
||||
return ""
|
||||
}
|
||||
if entry.Trust == TrustOfficial || entry.Trust == TrustVerified {
|
||||
if entry.Trust == plugin.TrustOfficial || entry.Trust == plugin.TrustVerified {
|
||||
return entry.Trust
|
||||
}
|
||||
return ""
|
||||
File renamed without changes.
@@ -1,4 +1,4 @@
|
||||
package plugin_test
|
||||
package market_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"github.com/Nwflower/reims-go/internal/downloader"
|
||||
"github.com/Nwflower/reims-go/internal/fetch"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/market"
|
||||
)
|
||||
|
||||
func TestMarketFetchCacheAndFallback(t *testing.T) {
|
||||
@@ -23,10 +24,10 @@ func TestMarketFetchCacheAndFallback(t *testing.T) {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
idx := plugin.MarketIndex{
|
||||
idx := market.MarketIndex{
|
||||
Schema: 1,
|
||||
UpdatedAt: "2026-11-30T00:00:00Z",
|
||||
Plugins: []plugin.MarketEntry{{
|
||||
Plugins: []market.MarketEntry{{
|
||||
ID: "community.theme.nord",
|
||||
Version: "1.2.0",
|
||||
Name: plugin.LocalizedText{ZhCN: "北欧主题", EnUS: "Nord Theme"},
|
||||
@@ -46,7 +47,7 @@ func TestMarketFetchCacheAndFallback(t *testing.T) {
|
||||
|
||||
dataRoot := t.TempDir()
|
||||
layout := plugin.NewPluginsLayout(dataRoot)
|
||||
mc := plugin.NewMarketClient(plugin.MarketClientOptions{
|
||||
mc := market.NewMarketClient(market.MarketClientOptions{
|
||||
Layout: layout,
|
||||
HostVersion: "0.2.8",
|
||||
URLs: []string{srv.URL + "/index.json"},
|
||||
@@ -71,7 +72,7 @@ func TestMarketFetchCacheAndFallback(t *testing.T) {
|
||||
|
||||
// 3. Server goes down + forceRefresh: must retain valid disk/mem cache with stale=true.
|
||||
fail.Store(true)
|
||||
mcFresh := plugin.NewMarketClient(plugin.MarketClientOptions{
|
||||
mcFresh := market.NewMarketClient(market.MarketClientOptions{
|
||||
Layout: layout,
|
||||
HostVersion: "0.2.8",
|
||||
URLs: []string{srv.URL + "/index.json"},
|
||||
@@ -132,10 +133,10 @@ func TestMarketBrowseAndInstallGates(t *testing.T) {
|
||||
w.Header().Set("Content-Type", "application/zip")
|
||||
_, _ = w.Write(evilBytes)
|
||||
case "/index.json":
|
||||
idx := plugin.MarketIndex{
|
||||
idx := market.MarketIndex{
|
||||
Schema: 1,
|
||||
UpdatedAt: "2026-11-30T00:00:00Z",
|
||||
Plugins: []plugin.MarketEntry{
|
||||
Plugins: []market.MarketEntry{
|
||||
{
|
||||
ID: "community.theme.mist",
|
||||
Version: "1.1.0",
|
||||
@@ -194,7 +195,7 @@ func TestMarketBrowseAndInstallGates(t *testing.T) {
|
||||
SHA256: evilSum,
|
||||
},
|
||||
},
|
||||
Withdrawn: []plugin.MarketWithdrawal{{
|
||||
Withdrawn: []market.MarketWithdrawal{{
|
||||
ID: "community.old.tool",
|
||||
Reason: plugin.LocalizedText{ZhCN: "已合并进新插件", EnUS: "Merged into new plugin"},
|
||||
InsteadID: "community.theme.mist",
|
||||
@@ -219,7 +220,7 @@ func TestMarketBrowseAndInstallGates(t *testing.T) {
|
||||
}
|
||||
defer mgr.Close()
|
||||
|
||||
mc := plugin.NewMarketClient(plugin.MarketClientOptions{
|
||||
mc := market.NewMarketClient(market.MarketClientOptions{
|
||||
Layout: mgr.Layout(),
|
||||
HostVersion: "0.2.8",
|
||||
URLs: []string{srvURL + "/index.json"},
|
||||
@@ -230,11 +231,11 @@ func TestMarketBrowseAndInstallGates(t *testing.T) {
|
||||
res := mc.Browse(context.Background(), []plugin.PluginInfo{
|
||||
{ID: "community.old.tool", Version: "0.9.0"},
|
||||
{ID: "community.theme.mist", Version: "1.0.0"},
|
||||
}, plugin.MarketBrowseOptions{})
|
||||
}, market.MarketBrowseOptions{})
|
||||
if len(res.WithdrawnInstalled) != 1 || res.WithdrawnInstalled[0].InsteadID != "community.theme.mist" {
|
||||
t.Fatalf("expected withdrawn installed advisory, got %+v", res.WithdrawnInstalled)
|
||||
}
|
||||
var mistItem *plugin.MarketCatalogItem
|
||||
var mistItem *market.MarketCatalogItem
|
||||
for i := range res.Items {
|
||||
if res.Items[i].Entry.ID == "community.theme.mist" {
|
||||
mistItem = &res.Items[i]
|
||||
@@ -245,27 +246,27 @@ func TestMarketBrowseAndInstallGates(t *testing.T) {
|
||||
}
|
||||
|
||||
// Withdrawn plugin install refused with replacement hint.
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "community.old.tool", plugin.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "withdrawn") {
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "community.old.tool", market.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "withdrawn") {
|
||||
t.Fatalf("expected withdrawn refusal, got: %v", err)
|
||||
}
|
||||
|
||||
// Incompatible plugin refused BEFORE download.
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "community.theme.incompat", plugin.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "incompatible") {
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "community.theme.incompat", market.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "incompatible") {
|
||||
t.Fatalf("expected incompatible refusal, got: %v", err)
|
||||
}
|
||||
|
||||
// SHA-256 mismatch refused.
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "community.theme.badhash", plugin.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "SHA256 mismatch") {
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "community.theme.badhash", market.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "SHA256 mismatch") {
|
||||
t.Fatalf("expected SHA256 mismatch refusal, got: %v", err)
|
||||
}
|
||||
|
||||
// Smuggled .ps1 in L1 zip refused by static security gate even when archive SHA-256 matches.
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "community.theme.evil", plugin.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "static security gate") {
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "community.theme.evil", market.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "static security gate") {
|
||||
t.Fatalf("expected static gate refusal for smuggled .ps1, got: %v", err)
|
||||
}
|
||||
|
||||
// Valid market plugin installs cleanly with SourceMarket.
|
||||
info, err := mc.InstallFromMarket(context.Background(), mgr, "community.theme.mist", plugin.MarketInstallOptions{})
|
||||
info, err := mc.InstallFromMarket(context.Background(), mgr, "community.theme.mist", market.MarketInstallOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("InstallFromMarket valid plugin: %v", err)
|
||||
}
|
||||
@@ -275,7 +276,7 @@ func TestMarketBrowseAndInstallGates(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestCheckMarketCompatibilityUnified(t *testing.T) {
|
||||
base := plugin.MarketEntry{
|
||||
base := market.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"},
|
||||
@@ -283,24 +284,24 @@ func TestCheckMarketCompatibilityUnified(t *testing.T) {
|
||||
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 {
|
||||
if ok, reason := market.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 {
|
||||
if ok, reason := market.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 {
|
||||
if ok, _ := market.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") {
|
||||
if ok, reason := market.CheckMarketCompatibility(badBridge, "0.2.11"); ok || !strings.Contains(reason, "bridgeApi") {
|
||||
t.Fatalf("expected bridgeApi incompatibility, got ok=%v reason=%q", ok, reason)
|
||||
}
|
||||
}
|
||||
@@ -310,10 +311,10 @@ func TestMarketSecurityGatesSearchExtraAndConcurrentCache(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/index.json":
|
||||
idx := plugin.MarketIndex{
|
||||
idx := market.MarketIndex{
|
||||
Schema: 1,
|
||||
UpdatedAt: "2026-12-02T00:00:00Z",
|
||||
Plugins: []plugin.MarketEntry{
|
||||
Plugins: []market.MarketEntry{
|
||||
{
|
||||
ID: "evil.theme.traversal",
|
||||
Version: "../../escape",
|
||||
@@ -423,7 +424,7 @@ func TestMarketSecurityGatesSearchExtraAndConcurrentCache(t *testing.T) {
|
||||
}
|
||||
defer mgr.Close()
|
||||
|
||||
mc := plugin.NewMarketClient(plugin.MarketClientOptions{
|
||||
mc := market.NewMarketClient(market.MarketClientOptions{
|
||||
Layout: mgr.Layout(),
|
||||
HostVersion: "0.2.11",
|
||||
URLs: []string{srvURL + "/index.json"},
|
||||
@@ -440,37 +441,37 @@ func TestMarketSecurityGatesSearchExtraAndConcurrentCache(t *testing.T) {
|
||||
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") {
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "evil.theme.traversal", market.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") {
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "evil.theme.spacesver", market.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") {
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "evil.theme.huge", market.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") {
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "evil.theme.oversize-body", market.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") {
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "evil.theme.stall", market.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") {
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "evil.theme.downgrade", market.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: "日本語"})
|
||||
resName := mc.Browse(context.Background(), nil, market.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: "한국어"})
|
||||
resDesc := mc.Browse(context.Background(), nil, market.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)
|
||||
}
|
||||
@@ -496,7 +497,7 @@ func TestMarketSecurityGatesSearchExtraAndConcurrentCache(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("read disk cache: %v", err)
|
||||
}
|
||||
var cached plugin.MarketIndex
|
||||
var cached market.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))
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package plugin
|
||||
package market
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
@@ -12,12 +12,14 @@ import (
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
)
|
||||
|
||||
// PackOptions configures PackDirectory.
|
||||
type PackOptions struct {
|
||||
HostVersion string
|
||||
Contract *UIContract
|
||||
Contract *plugin.UIContract
|
||||
OutputPath string // optional; defaults to "<cwd>/<id>-<version>.zip"
|
||||
SignKey ed25519.PrivateKey
|
||||
}
|
||||
@@ -25,15 +27,15 @@ type PackOptions struct {
|
||||
// PackResult describes a freshly packed plugin archive ready for distribution
|
||||
// or market submission.
|
||||
type PackResult struct {
|
||||
PluginID string `json:"plugin_id"`
|
||||
Version string `json:"version"`
|
||||
Tier Tier `json:"tier"`
|
||||
OutputPath string `json:"output_path"`
|
||||
SHA256 string `json:"sha256"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
FileCount int `json:"file_count"`
|
||||
Signed bool `json:"signed"`
|
||||
Report ScanReport `json:"report"`
|
||||
PluginID string `json:"plugin_id"`
|
||||
Version string `json:"version"`
|
||||
Tier plugin.Tier `json:"tier"`
|
||||
OutputPath string `json:"output_path"`
|
||||
SHA256 string `json:"sha256"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
FileCount int `json:"file_count"`
|
||||
Signed bool `json:"signed"`
|
||||
Report plugin.ScanReport `json:"report"`
|
||||
}
|
||||
|
||||
// PackDirectory validates dir through the unified static security gate, generates
|
||||
@@ -56,13 +58,13 @@ func PackDirectory(dir string, opts PackOptions) (PackResult, error) {
|
||||
if err != nil {
|
||||
return PackResult{}, fmt.Errorf("read plugin.json: %w", err)
|
||||
}
|
||||
var m Manifest
|
||||
var m plugin.Manifest
|
||||
if err := json.Unmarshal(rawMan, &m); err != nil {
|
||||
return PackResult{}, fmt.Errorf("parse plugin.json: %w", err)
|
||||
}
|
||||
|
||||
// Run static security gate before creating any output archive.
|
||||
report := ScanDirectory(absDir, opts.HostVersion, ScanOptions{
|
||||
report := plugin.ScanDirectory(absDir, opts.HostVersion, plugin.ScanOptions{
|
||||
Contract: opts.Contract,
|
||||
RequireChecksums: false,
|
||||
})
|
||||
@@ -116,7 +118,7 @@ func PackDirectory(dir string, opts PackOptions) (PackResult, error) {
|
||||
if slash == "SHA256SUMS" || slash == "SHA256SUMS.sig" || info.Name() == ".DS_Store" || info.Name() == "Thumbs.db" {
|
||||
return nil
|
||||
}
|
||||
h, hErr := fileSHA256Hex(p)
|
||||
h, hErr := plugin.FileSHA256Hex(p)
|
||||
if hErr != nil {
|
||||
return hErr
|
||||
}
|
||||
@@ -232,7 +234,7 @@ func PackDirectory(dir string, opts PackOptions) (PackResult, error) {
|
||||
return PackResult{}, err
|
||||
}
|
||||
|
||||
zipHash, err := fileSHA256Hex(absOut)
|
||||
zipHash, err := plugin.FileSHA256Hex(absOut)
|
||||
if err != nil {
|
||||
return PackResult{}, err
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package plugin_test
|
||||
package market_test
|
||||
|
||||
import (
|
||||
"crypto/ed25519"
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/market"
|
||||
)
|
||||
|
||||
func TestPackDirectorySignAndInstallRoundTrip(t *testing.T) {
|
||||
@@ -42,7 +43,7 @@ func TestPackDirectorySignAndInstallRoundTrip(t *testing.T) {
|
||||
_ = os.WriteFile(filepath.Join(srcDir, ".DS_Store"), []byte("junk"), 0o644)
|
||||
|
||||
outZip := filepath.Join(t.TempDir(), "official.theme.packtest-1.0.0.zip")
|
||||
res, err := plugin.PackDirectory(srcDir, plugin.PackOptions{
|
||||
res, err := market.PackDirectory(srcDir, market.PackOptions{
|
||||
HostVersion: "0.2.8",
|
||||
OutputPath: outZip,
|
||||
SignKey: priv,
|
||||
@@ -94,7 +95,7 @@ func TestPackDirectoryRefusesBlockedPackage(t *testing.T) {
|
||||
_ = os.WriteFile(filepath.Join(srcDir, "sneak.ps1"), []byte(`Write-Host "nope"`), 0o644)
|
||||
|
||||
outZip := filepath.Join(t.TempDir(), "should-not-exist.zip")
|
||||
res, err := plugin.PackDirectory(srcDir, plugin.PackOptions{
|
||||
res, err := market.PackDirectory(srcDir, market.PackOptions{
|
||||
HostVersion: "0.2.8",
|
||||
OutputPath: outZip,
|
||||
})
|
||||
@@ -107,16 +108,16 @@ func TestPackDirectoryRefusesBlockedPackage(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestDefaultMarketURLsPointToReimsGoOrg(t *testing.T) {
|
||||
t.Setenv(plugin.EnvPluginMarketURL, "")
|
||||
urls := plugin.DefaultMarketURLs()
|
||||
t.Setenv(market.EnvPluginMarketURL, "")
|
||||
urls := market.DefaultMarketURLs()
|
||||
if len(urls) < 2 {
|
||||
t.Fatalf("expected primary + mirror URLs, got %v", urls)
|
||||
}
|
||||
if !strings.Contains(urls[0], "reims-go/plugins") || !strings.Contains(urls[1], "reims-go/plugins") {
|
||||
t.Fatalf("expected reims-go/plugins URLs, got %v", urls)
|
||||
}
|
||||
t.Setenv(plugin.EnvPluginMarketURL, "off")
|
||||
if got := plugin.DefaultMarketURLs(); got != nil {
|
||||
t.Setenv(market.EnvPluginMarketURL, "off")
|
||||
if got := market.DefaultMarketURLs(); got != nil {
|
||||
t.Fatalf("expected nil URLs in offline mode, got %v", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package market_test
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"crypto/ed25519"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func makePluginZip(t *testing.T, files map[string][]byte, priv ed25519.PrivateKey, corruptSum bool) string {
|
||||
t.Helper()
|
||||
zipPath := filepath.Join(t.TempDir(), "plugin.zip")
|
||||
f, err := os.Create(zipPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
zw := zip.NewWriter(f)
|
||||
|
||||
var sumLines []string
|
||||
for rel, content := range files {
|
||||
w, err := zw.Create(rel)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, _ = w.Write(content)
|
||||
h := sha256.Sum256(content)
|
||||
hexSum := hex.EncodeToString(h[:])
|
||||
if corruptSum {
|
||||
hexSum = strings.Repeat("0", 64)
|
||||
}
|
||||
sumLines = append(sumLines, fmt.Sprintf("%s %s", hexSum, rel))
|
||||
}
|
||||
sumsBytes := []byte(strings.Join(sumLines, "\n") + "\n")
|
||||
w, _ := zw.Create("SHA256SUMS")
|
||||
_, _ = w.Write(sumsBytes)
|
||||
|
||||
if len(priv) > 0 {
|
||||
sig := ed25519.Sign(priv, sumsBytes)
|
||||
sw, _ := zw.Create("SHA256SUMS.sig")
|
||||
_, _ = sw.Write([]byte(base64.StdEncoding.EncodeToString(sig)))
|
||||
}
|
||||
if err := zw.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = f.Close()
|
||||
return zipPath
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package plugin
|
||||
|
||||
import "github.com/Nwflower/reims-go/internal/plugin/uiassets"
|
||||
|
||||
// MaxPluginArchiveBytes is the maximum accepted size of a plugin archive.
|
||||
const MaxPluginArchiveBytes = maxPluginArchiveBytes
|
||||
|
||||
// IsValidReverseDomainID reports whether id matches the reverse-domain plugin ID format.
|
||||
func IsValidReverseDomainID(id string) bool {
|
||||
return reReverseDomainID.MatchString(id)
|
||||
}
|
||||
|
||||
// CheckHostCompatibility checks whether a plugin's platform list and engine
|
||||
// constraints are compatible with the running host version.
|
||||
func CheckHostCompatibility(platforms []string, engines Engines, hostVersion string) (bool, string) {
|
||||
return checkHostCompatibility(platforms, engines, hostVersion)
|
||||
}
|
||||
|
||||
// FileSHA256Hex returns the lowercase hex SHA-256 digest of the file at path.
|
||||
func FileSHA256Hex(path string) (string, error) {
|
||||
return fileSHA256Hex(path)
|
||||
}
|
||||
|
||||
// SafeJoin joins rel under root and blocks lexical and symlink traversal.
|
||||
func SafeJoin(root, rel string) (string, error) {
|
||||
return uiassets.SafeJoin(root, rel)
|
||||
}
|
||||
|
||||
// TrustSortRank orders trust levels with higher numbers being more trusted.
|
||||
func TrustSortRank(t TrustLevel) int {
|
||||
switch t {
|
||||
case TrustOfficial:
|
||||
return 3
|
||||
case TrustVerified:
|
||||
return 2
|
||||
case TrustCommunity:
|
||||
return 1
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
func trustSortRank(t TrustLevel) int {
|
||||
return TrustSortRank(t)
|
||||
}
|
||||
@@ -1123,15 +1123,6 @@ func verifyEd25519Signature(message, sigRaw []byte, keyring []SigningKey) (Trust
|
||||
return TrustCommunity, errors.New("signature did not match any trusted signing key")
|
||||
}
|
||||
|
||||
func pathWithinRoot(root, candidate string) bool {
|
||||
if runtime.GOOS == "windows" {
|
||||
r := strings.ToLower(root)
|
||||
c := strings.ToLower(candidate)
|
||||
return c == r || strings.HasPrefix(c, r+string(os.PathSeparator))
|
||||
}
|
||||
return candidate == root || strings.HasPrefix(candidate, root+string(os.PathSeparator))
|
||||
}
|
||||
|
||||
func validateDiskContributions(m Manifest, rootDir string) error {
|
||||
for _, th := range m.Contributes.Themes {
|
||||
if err := ValidateThemeContribution(th, rootDir); err != nil {
|
||||
@@ -1151,63 +1142,6 @@ func validateDiskContributions(m Manifest, rootDir string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func safeJoin(root, rel string) (string, error) {
|
||||
absRoot, err := filepath.Abs(root)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("resolve root path: %w", err)
|
||||
}
|
||||
cleanRoot := filepath.Clean(absRoot)
|
||||
joined := filepath.Clean(filepath.Join(cleanRoot, filepath.FromSlash(rel)))
|
||||
if !pathWithinRoot(cleanRoot, joined) {
|
||||
return "", fmt.Errorf("path traversal blocked: %q", rel)
|
||||
}
|
||||
// Guard against symlinks / NTFS junctions escaping rootDir, including when
|
||||
// the leaf path does not exist yet (check nearest existing ancestor).
|
||||
evalRoot := cleanRoot
|
||||
if r, err := filepath.EvalSymlinks(cleanRoot); err == nil {
|
||||
evalRoot = filepath.Clean(r)
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return "", fmt.Errorf("evaluate root path: %w", err)
|
||||
}
|
||||
|
||||
evalJoined, err := filepath.EvalSymlinks(joined)
|
||||
if err == nil {
|
||||
evalJoined = filepath.Clean(evalJoined)
|
||||
if !pathWithinRoot(evalRoot, evalJoined) {
|
||||
return "", fmt.Errorf("symlink traversal blocked: %q", rel)
|
||||
}
|
||||
return evalJoined, nil
|
||||
}
|
||||
if !errors.Is(err, os.ErrNotExist) {
|
||||
return "", fmt.Errorf("evaluate path %q: %w", rel, err)
|
||||
}
|
||||
|
||||
// Walk upward to the nearest existing ancestor directory and verify it resolves within evalRoot.
|
||||
cur := joined
|
||||
var tail []string
|
||||
for cur != cleanRoot {
|
||||
parent := filepath.Dir(cur)
|
||||
if parent == cur {
|
||||
break
|
||||
}
|
||||
tail = append(tail, filepath.Base(cur))
|
||||
cur = parent
|
||||
if evalAnc, aErr := filepath.EvalSymlinks(cur); aErr == nil {
|
||||
evalAnc = filepath.Clean(evalAnc)
|
||||
if !pathWithinRoot(evalRoot, evalAnc) {
|
||||
return "", fmt.Errorf("symlink ancestor traversal blocked: %q", rel)
|
||||
}
|
||||
for i := len(tail) - 1; i >= 0; i-- {
|
||||
evalAnc = filepath.Join(evalAnc, tail[i])
|
||||
}
|
||||
return evalAnc, nil
|
||||
} else if !errors.Is(aErr, os.ErrNotExist) {
|
||||
return "", fmt.Errorf("evaluate ancestor path %q: %w", rel, aErr)
|
||||
}
|
||||
}
|
||||
return joined, nil
|
||||
}
|
||||
|
||||
func fileSHA256Hex(p string) (string, error) {
|
||||
f, err := os.Open(p)
|
||||
if err != nil {
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
@@ -311,7 +314,40 @@ func packRenameTestPlugin(t *testing.T, id, version, entry, contents string) str
|
||||
t.Fatal(err)
|
||||
}
|
||||
archive := filepath.Join(t.TempDir(), "plugin.zip")
|
||||
if _, err := PackDirectory(source, PackOptions{HostVersion: "0.3.0", OutputPath: archive}); err != nil {
|
||||
f, err := os.Create(archive)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
zw := zip.NewWriter(f)
|
||||
entryRel := filepath.ToSlash(entry)
|
||||
files := map[string][]byte{
|
||||
"plugin.json": []byte(manifest),
|
||||
entryRel: []byte(contents),
|
||||
}
|
||||
var sums strings.Builder
|
||||
for _, name := range []string{entryRel, "plugin.json"} {
|
||||
data := files[name]
|
||||
w, err := zw.Create(name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := w.Write(data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h := sha256.Sum256(data)
|
||||
fmt.Fprintf(&sums, "%s %s\n", hex.EncodeToString(h[:]), name)
|
||||
}
|
||||
sw, err := zw.Create("SHA256SUMS")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := sw.Write([]byte(sums.String())); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := zw.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return archive
|
||||
|
||||
@@ -54,16 +54,16 @@ func ManifestRisks(m Manifest, tier Tier) []string {
|
||||
return orderedRisks(set)
|
||||
}
|
||||
|
||||
// MarketEntryRisks estimates risk categories for a market listing from its
|
||||
// EstimateMarketRisks estimates risk categories for a market listing from its
|
||||
// declared kind, tier and permissions, before anything is downloaded. The
|
||||
// installed manifest is authoritative once the package is on disk.
|
||||
func MarketEntryRisks(e MarketEntry) []string {
|
||||
func EstimateMarketRisks(tier Tier, kind string, permissions []string) []string {
|
||||
set := map[string]bool{}
|
||||
addTierRisks(set, e.Tier)
|
||||
for _, p := range e.Permissions {
|
||||
addTierRisks(set, tier)
|
||||
for _, p := range permissions {
|
||||
addPermissionRisks(set, p)
|
||||
}
|
||||
switch strings.ToLower(strings.TrimSpace(e.Kind)) {
|
||||
switch strings.ToLower(strings.TrimSpace(kind)) {
|
||||
case "theme", "locale":
|
||||
set[RiskUI] = true
|
||||
case "driver", "runtime":
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/market"
|
||||
)
|
||||
|
||||
func TestManifestRisks(t *testing.T) {
|
||||
@@ -48,11 +49,11 @@ func TestManifestRisks(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestMarketEntryRisks(t *testing.T) {
|
||||
got := plugin.MarketEntryRisks(plugin.MarketEntry{Kind: "locale", Tier: plugin.TierL1})
|
||||
got := market.MarketEntryRisks(market.MarketEntry{Kind: "locale", Tier: plugin.TierL1})
|
||||
if !reflect.DeepEqual(got, []string{plugin.RiskUI}) {
|
||||
t.Fatalf("locale entry risks = %v", got)
|
||||
}
|
||||
got = plugin.MarketEntryRisks(plugin.MarketEntry{Kind: "tool", Tier: plugin.TierL2, Permissions: []string{"net:x.example"}})
|
||||
got = market.MarketEntryRisks(market.MarketEntry{Kind: "tool", Tier: plugin.TierL2, Permissions: []string{"net:x.example"}})
|
||||
if !reflect.DeepEqual(got, []string{plugin.RiskBackground, plugin.RiskNetwork}) {
|
||||
t.Fatalf("script entry risks = %v", got)
|
||||
}
|
||||
@@ -60,8 +61,8 @@ func TestMarketEntryRisks(t *testing.T) {
|
||||
|
||||
func TestMarketKindFacetsAndPeek(t *testing.T) {
|
||||
var hits atomic.Int32
|
||||
entry := func(id, kind string) plugin.MarketEntry {
|
||||
return plugin.MarketEntry{
|
||||
entry := func(id, kind string) market.MarketEntry {
|
||||
return market.MarketEntry{
|
||||
ID: id, Version: "1.0.0", Kind: kind, Channel: "stable",
|
||||
Name: plugin.LocalizedText{EnUS: id},
|
||||
DownloadURL: "https://example.invalid/x.zip", SHA256: strings.Repeat("a", 64),
|
||||
@@ -69,9 +70,9 @@ func TestMarketKindFacetsAndPeek(t *testing.T) {
|
||||
}
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hits.Add(1)
|
||||
_ = json.NewEncoder(w).Encode(plugin.MarketIndex{
|
||||
_ = json.NewEncoder(w).Encode(market.MarketIndex{
|
||||
Schema: 1,
|
||||
Plugins: []plugin.MarketEntry{
|
||||
Plugins: []market.MarketEntry{
|
||||
entry("a.theme.one", "theme"), entry("a.theme.two", "theme"),
|
||||
entry("a.lang.one", "locale"), entry("a.tool.one", ""),
|
||||
},
|
||||
@@ -80,23 +81,23 @@ func TestMarketKindFacetsAndPeek(t *testing.T) {
|
||||
defer srv.Close()
|
||||
|
||||
layout := plugin.NewPluginsLayout(t.TempDir())
|
||||
opts := plugin.MarketClientOptions{
|
||||
opts := market.MarketClientOptions{
|
||||
Layout: layout, URLs: []string{srv.URL + "/index.json"},
|
||||
CacheTTL: time.Minute, AllowInsecureLocalhost: true,
|
||||
}
|
||||
mc := plugin.NewMarketClient(opts)
|
||||
mc := market.NewMarketClient(opts)
|
||||
|
||||
// Nothing cached yet: Peek serves the embedded fallback without a request.
|
||||
if res := mc.Peek(nil, plugin.MarketBrowseOptions{}); res.Source != "fallback" || hits.Load() != 0 {
|
||||
if res := mc.Peek(nil, market.MarketBrowseOptions{}); res.Source != "fallback" || hits.Load() != 0 {
|
||||
t.Fatalf("cold Peek = source %q, %d requests", res.Source, hits.Load())
|
||||
}
|
||||
|
||||
// Facets count the whole index even while a kind filter narrows items.
|
||||
res := mc.Browse(context.Background(), nil, plugin.MarketBrowseOptions{Kind: "theme"})
|
||||
res := mc.Browse(context.Background(), nil, market.MarketBrowseOptions{Kind: "theme"})
|
||||
if len(res.Items) != 2 {
|
||||
t.Fatalf("filtered items = %d, want 2", len(res.Items))
|
||||
}
|
||||
wantKinds := []plugin.MarketKindFacet{{Kind: "theme", Count: 2}, {Kind: "locale", Count: 1}}
|
||||
wantKinds := []market.MarketKindFacet{{Kind: "theme", Count: 2}, {Kind: "locale", Count: 1}}
|
||||
if !reflect.DeepEqual(res.Kinds, wantKinds) {
|
||||
t.Fatalf("kinds = %+v, want %+v", res.Kinds, wantKinds)
|
||||
}
|
||||
@@ -104,11 +105,11 @@ func TestMarketKindFacetsAndPeek(t *testing.T) {
|
||||
// A new client reads the disk cache in Peek, and its next Browse still
|
||||
// goes to the network because nothing was fetched in this session.
|
||||
before := hits.Load()
|
||||
mc2 := plugin.NewMarketClient(opts)
|
||||
if res := mc2.Peek(nil, plugin.MarketBrowseOptions{}); res.Source != "cache" || len(res.Items) != 4 || hits.Load() != before {
|
||||
mc2 := market.NewMarketClient(opts)
|
||||
if res := mc2.Peek(nil, market.MarketBrowseOptions{}); res.Source != "cache" || len(res.Items) != 4 || hits.Load() != before {
|
||||
t.Fatalf("warm Peek = source %q, %d items, %d new requests", res.Source, len(res.Items), hits.Load()-before)
|
||||
}
|
||||
if res := mc2.Browse(context.Background(), nil, plugin.MarketBrowseOptions{}); res.Source != "remote" {
|
||||
if res := mc2.Browse(context.Background(), nil, market.MarketBrowseOptions{}); res.Source != "remote" {
|
||||
t.Fatalf("Browse after Peek = source %q, want remote", res.Source)
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/plugin/sidecarproc"
|
||||
"github.com/Nwflower/reims-go/pkg/pluginproto"
|
||||
)
|
||||
|
||||
@@ -38,7 +39,7 @@ type SidecarOptions struct {
|
||||
|
||||
type sidecarInstance struct {
|
||||
cmd *exec.Cmd
|
||||
job *sidecarJob
|
||||
job *sidecarproc.SidecarJob
|
||||
rpc *RPCConn
|
||||
stdin io.WriteCloser
|
||||
exited chan struct{}
|
||||
@@ -163,7 +164,7 @@ func (s *SidecarSupervisor) spawnInstance(ctx context.Context) (*sidecarInstance
|
||||
}
|
||||
cmd := exec.Command(s.opts.ExePath, s.opts.Args...)
|
||||
cmd.Dir = s.opts.DataDir
|
||||
configureSidecarCmd(cmd)
|
||||
sidecarproc.ConfigureSidecarCmd(cmd)
|
||||
|
||||
stdin, err := cmd.StdinPipe()
|
||||
if err != nil {
|
||||
@@ -181,7 +182,7 @@ func (s *SidecarSupervisor) spawnInstance(ctx context.Context) (*sidecarInstance
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
job, err := newSidecarJob(s.opts.MemLimitBytes)
|
||||
job, err := sidecarproc.NewSidecarJob(s.opts.MemLimitBytes)
|
||||
if err != nil {
|
||||
_ = stdin.Close()
|
||||
_ = stdout.Close()
|
||||
@@ -203,7 +204,7 @@ func (s *SidecarSupervisor) spawnInstance(ctx context.Context) (*sidecarInstance
|
||||
return nil, nil, fmt.Errorf("assign sidecar %s to job: %w", s.opts.PluginID, err)
|
||||
}
|
||||
|
||||
rpcConn := NewRPCConn(stdout, stdin)
|
||||
rpcConn := sidecarproc.NewRPCConn(stdout, stdin)
|
||||
s.registerReverseHostAPI(rpcConn)
|
||||
|
||||
inst := &sidecarInstance{
|
||||
@@ -257,7 +258,7 @@ func (s *SidecarSupervisor) spawnInstance(ctx context.Context) (*sidecarInstance
|
||||
|
||||
// StdoutPipe and StderrPipe must be drained before Wait closes their handles.
|
||||
go func() {
|
||||
<-rpcConn.doneCh
|
||||
<-rpcConn.Done()
|
||||
<-stderrDone
|
||||
err := cmd.Wait()
|
||||
rpcConn.Close()
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
//go:build !windows
|
||||
|
||||
package sidecarproc
|
||||
|
||||
import (
|
||||
"os/exec"
|
||||
"sync"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func ConfigureSidecarCmd(cmd *exec.Cmd) {
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
|
||||
}
|
||||
|
||||
func ConfigureDetachedVMProcess(cmd *exec.Cmd) {
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
|
||||
}
|
||||
|
||||
func ConfigureNestedVMProcess(cmd *exec.Cmd) { ConfigureDetachedVMProcess(cmd) }
|
||||
|
||||
func ResumeVMProcess(int) error { return nil }
|
||||
|
||||
func IsBreakawayDenied(error) bool { return false }
|
||||
|
||||
type SidecarJob struct {
|
||||
pgid int
|
||||
closeOnce sync.Once
|
||||
}
|
||||
|
||||
func NewSidecarJob(_ uintptr) (*SidecarJob, error) {
|
||||
return &SidecarJob{}, nil
|
||||
}
|
||||
|
||||
func (j *SidecarJob) Assign(pid int) error {
|
||||
if j != nil {
|
||||
j.pgid = pid
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (j *SidecarJob) Close() {
|
||||
if j == nil {
|
||||
return
|
||||
}
|
||||
j.closeOnce.Do(func() {
|
||||
if j.pgid > 0 {
|
||||
_ = syscall.Kill(-j.pgid, syscall.SIGKILL)
|
||||
j.pgid = 0
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//go:build windows
|
||||
|
||||
package plugin
|
||||
package sidecarproc
|
||||
|
||||
import (
|
||||
"errors"
|
||||
@@ -19,25 +19,25 @@ const (
|
||||
createNewProcessGroup = 0x00000200
|
||||
)
|
||||
|
||||
func configureSidecarCmd(cmd *exec.Cmd) {
|
||||
func ConfigureSidecarCmd(cmd *exec.Cmd) {
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{
|
||||
HideWindow: true,
|
||||
CreationFlags: createNoWindow | createNewProcessGroup,
|
||||
}
|
||||
}
|
||||
|
||||
// configureDetachedVMProcess starts the VM suspended, so it joins its job before
|
||||
// it can start children; resumeVMProcess lets it run.
|
||||
func configureDetachedVMProcess(cmd *exec.Cmd) {
|
||||
// ConfigureDetachedVMProcess starts the VM suspended, so it joins its job before
|
||||
// it can start children; ResumeVMProcess lets it run.
|
||||
func ConfigureDetachedVMProcess(cmd *exec.Cmd) {
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{
|
||||
HideWindow: true,
|
||||
CreationFlags: createNoWindow | createNewProcessGroup | createBreakawayFromJob | windows.CREATE_SUSPENDED,
|
||||
}
|
||||
}
|
||||
|
||||
// configureNestedVMProcess is the fallback when the host's own job forbids
|
||||
// ConfigureNestedVMProcess is the fallback when the host's own job forbids
|
||||
// breakaway: the VM starts inside that job and moves into its per-VM job.
|
||||
func configureNestedVMProcess(cmd *exec.Cmd) {
|
||||
func ConfigureNestedVMProcess(cmd *exec.Cmd) {
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{
|
||||
HideWindow: true,
|
||||
CreationFlags: createNoWindow | createNewProcessGroup | windows.CREATE_SUSPENDED,
|
||||
@@ -46,7 +46,7 @@ func configureNestedVMProcess(cmd *exec.Cmd) {
|
||||
|
||||
var procNtResumeProcess = windows.NewLazySystemDLL("ntdll.dll").NewProc("NtResumeProcess")
|
||||
|
||||
func resumeVMProcess(pid int) error {
|
||||
func ResumeVMProcess(pid int) error {
|
||||
proc, err := windows.OpenProcess(windows.PROCESS_SUSPEND_RESUME, false, uint32(pid))
|
||||
if err != nil {
|
||||
return fmt.Errorf("OpenProcess(%d): %w", pid, err)
|
||||
@@ -58,20 +58,20 @@ func resumeVMProcess(pid int) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// isBreakawayDenied reports a failed CREATE_BREAKAWAY_FROM_JOB start.
|
||||
func isBreakawayDenied(err error) bool {
|
||||
// IsBreakawayDenied reports a failed CREATE_BREAKAWAY_FROM_JOB start.
|
||||
func IsBreakawayDenied(err error) bool {
|
||||
return errors.Is(err, windows.ERROR_ACCESS_DENIED)
|
||||
}
|
||||
|
||||
type sidecarJob struct {
|
||||
type SidecarJob struct {
|
||||
handle windows.Handle
|
||||
closeOnce sync.Once
|
||||
}
|
||||
|
||||
// newSidecarJob creates a Windows Job Object with KILL_ON_JOB_CLOSE so that
|
||||
// NewSidecarJob creates a Windows Job Object with KILL_ON_JOB_CLOSE so that
|
||||
// closing the job (or host exit/crash) reclaims the entire Sidecar process tree
|
||||
// with zero orphan processes (§8). Optional memLimitBytes caps process memory (L2).
|
||||
func newSidecarJob(memLimitBytes uintptr) (*sidecarJob, error) {
|
||||
func NewSidecarJob(memLimitBytes uintptr) (*SidecarJob, error) {
|
||||
h, err := windows.CreateJobObject(nil, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("CreateJobObject: %w", err)
|
||||
@@ -91,10 +91,10 @@ func newSidecarJob(memLimitBytes uintptr) (*sidecarJob, error) {
|
||||
_ = windows.CloseHandle(h)
|
||||
return nil, fmt.Errorf("SetInformationJobObject: %w", err)
|
||||
}
|
||||
return &sidecarJob{handle: h}, nil
|
||||
return &SidecarJob{handle: h}, nil
|
||||
}
|
||||
|
||||
func (j *sidecarJob) Assign(pid int) error {
|
||||
func (j *SidecarJob) Assign(pid int) error {
|
||||
if j == nil || j.handle == 0 || pid <= 0 {
|
||||
return nil
|
||||
}
|
||||
@@ -106,7 +106,7 @@ func (j *sidecarJob) Assign(pid int) error {
|
||||
return windows.AssignProcessToJobObject(j.handle, proc)
|
||||
}
|
||||
|
||||
func (j *sidecarJob) Close() {
|
||||
func (j *SidecarJob) Close() {
|
||||
if j == nil {
|
||||
return
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package plugin
|
||||
package sidecarproc
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
const maxRPCFrameBytes = 8 << 20 // 8 MiB per JSON-RPC frame (large blobs go via file paths, §8)
|
||||
const MaxRPCFrameBytes = 8 << 20 // 8 MiB per JSON-RPC frame (large blobs go via file paths, §8)
|
||||
|
||||
// RPCMethodNotFound is the code a peer answers for a method it does not serve.
|
||||
const RPCMethodNotFound = -32601
|
||||
@@ -80,6 +80,11 @@ func NewRPCConn(r io.Reader, w io.Writer) *RPCConn {
|
||||
return c
|
||||
}
|
||||
|
||||
// Done returns a channel that is closed when the connection's read loop exits.
|
||||
func (c *RPCConn) Done() <-chan struct{} {
|
||||
return c.doneCh
|
||||
}
|
||||
|
||||
// Handle registers a handler for inbound peer requests of method.
|
||||
func (c *RPCConn) Handle(method string, h RPCRequestHandler) {
|
||||
c.mu.Lock()
|
||||
@@ -337,7 +342,7 @@ func readContentLengthFrame(r *bufio.Reader) ([]byte, error) {
|
||||
k, v, ok := strings.Cut(line, ":")
|
||||
if ok && strings.EqualFold(strings.TrimSpace(k), "Content-Length") {
|
||||
n, err := strconv.Atoi(strings.TrimSpace(v))
|
||||
if err != nil || n < 0 || n > maxRPCFrameBytes {
|
||||
if err != nil || n < 0 || n > MaxRPCFrameBytes {
|
||||
return nil, fmt.Errorf("invalid Content-Length %q", v)
|
||||
}
|
||||
contentLen = n
|
||||
@@ -1,37 +1,37 @@
|
||||
//go:build !windows
|
||||
|
||||
package plugin
|
||||
package sidecarproc
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// vmJob approximates the Windows per-VM job with a process group: it tracks
|
||||
// VMJob approximates the Windows per-VM job with a process group: it tracks
|
||||
// the root process and the group it leads. Reims-Go runs VMs on Windows; this
|
||||
// keeps the package compiling and testable elsewhere.
|
||||
type vmJob struct {
|
||||
type VMJob struct {
|
||||
mu sync.Mutex
|
||||
pgid int
|
||||
done chan struct{}
|
||||
doneOnce sync.Once
|
||||
}
|
||||
|
||||
func newVMJob() (*vmJob, error) { return &vmJob{done: make(chan struct{})}, nil }
|
||||
func NewVMJob() (*VMJob, error) { return &VMJob{done: make(chan struct{})}, nil }
|
||||
|
||||
func (j *vmJob) markDone() { j.doneOnce.Do(func() { close(j.done) }) }
|
||||
func (j *VMJob) markDone() { j.doneOnce.Do(func() { close(j.done) }) }
|
||||
|
||||
// Done is closed once the root process has exited.
|
||||
func (j *vmJob) Done() <-chan struct{} { return j.done }
|
||||
func (j *VMJob) Done() <-chan struct{} { return j.done }
|
||||
|
||||
// RootExited closes Done: without a job object the root is the whole tree.
|
||||
func (j *vmJob) RootExited() {
|
||||
func (j *VMJob) RootExited() {
|
||||
if j != nil {
|
||||
j.markDone()
|
||||
}
|
||||
}
|
||||
|
||||
func (j *vmJob) Assign(pid int) error {
|
||||
func (j *VMJob) Assign(pid int) error {
|
||||
if j == nil || pid <= 0 {
|
||||
return nil
|
||||
}
|
||||
@@ -41,7 +41,7 @@ func (j *vmJob) Assign(pid int) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (j *vmJob) PIDs() []uint32 {
|
||||
func (j *VMJob) PIDs() []uint32 {
|
||||
if j == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -59,9 +59,9 @@ func (j *vmJob) PIDs() []uint32 {
|
||||
}
|
||||
|
||||
// SetAffinity is a no-op off Windows.
|
||||
func (j *vmJob) SetAffinity(uint64) error { return nil }
|
||||
func (j *VMJob) SetAffinity(uint64) error { return nil }
|
||||
|
||||
func (j *vmJob) Terminate() error {
|
||||
func (j *VMJob) Terminate() error {
|
||||
if j == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -74,7 +74,7 @@ func (j *vmJob) Terminate() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (j *vmJob) Close() {
|
||||
func (j *VMJob) Close() {
|
||||
if j != nil {
|
||||
j.markDone()
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//go:build windows
|
||||
|
||||
package plugin
|
||||
package sidecarproc
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
@@ -15,18 +15,17 @@ const (
|
||||
vmJobCompletionKey = 0x5247564d // "RGVM"
|
||||
)
|
||||
|
||||
// vmJobAssociateCompletionPort mirrors JOBOBJECT_ASSOCIATE_COMPLETION_PORT.
|
||||
type vmJobAssociateCompletionPort struct {
|
||||
CompletionKey uintptr
|
||||
CompletionPort windows.Handle
|
||||
}
|
||||
|
||||
// vmJob holds the process tree of one driver-spawned VM. Unlike sidecarJob it
|
||||
// VMJob holds the process tree of one driver-spawned VM. Unlike SidecarJob it
|
||||
// does not kill its processes when the handle closes: a VM must survive a
|
||||
// restart of the desktop client (for example an in-app update). Only an
|
||||
// explicit Terminate stops it. A completion port reports when the last
|
||||
// process of the tree has exited.
|
||||
type vmJob struct {
|
||||
type VMJob struct {
|
||||
mu sync.Mutex
|
||||
job windows.Handle
|
||||
port windows.Handle
|
||||
@@ -34,7 +33,7 @@ type vmJob struct {
|
||||
doneOnce sync.Once
|
||||
}
|
||||
|
||||
func newVMJob() (*vmJob, error) {
|
||||
func NewVMJob() (*VMJob, error) {
|
||||
job, err := windows.CreateJobObject(nil, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("CreateJobObject: %w", err)
|
||||
@@ -51,18 +50,17 @@ func newVMJob() (*vmJob, error) {
|
||||
_ = windows.CloseHandle(job)
|
||||
return nil, fmt.Errorf("associate job completion port: %w", err)
|
||||
}
|
||||
j := &vmJob{job: job, port: port, done: make(chan struct{})}
|
||||
j := &VMJob{job: job, port: port, done: make(chan struct{})}
|
||||
go j.watch(port)
|
||||
return j, nil
|
||||
}
|
||||
|
||||
func (j *vmJob) watch(port windows.Handle) {
|
||||
func (j *VMJob) watch(port windows.Handle) {
|
||||
for {
|
||||
var qty uint32
|
||||
var key uintptr
|
||||
var ov *windows.Overlapped
|
||||
if err := windows.GetQueuedCompletionStatus(port, &qty, &key, &ov, windows.INFINITE); err != nil {
|
||||
// The port was closed.
|
||||
j.markDone()
|
||||
return
|
||||
}
|
||||
@@ -73,17 +71,17 @@ func (j *vmJob) watch(port windows.Handle) {
|
||||
}
|
||||
}
|
||||
|
||||
func (j *vmJob) markDone() { j.doneOnce.Do(func() { close(j.done) }) }
|
||||
func (j *VMJob) markDone() { j.doneOnce.Do(func() { close(j.done) }) }
|
||||
|
||||
// Done is closed once the job holds no process.
|
||||
func (j *vmJob) Done() <-chan struct{} { return j.done }
|
||||
func (j *VMJob) Done() <-chan struct{} { return j.done }
|
||||
|
||||
// RootExited tells the job the root process was reaped. On Windows the job
|
||||
// itself reports when the whole tree is gone, so there is nothing to do.
|
||||
func (j *vmJob) RootExited() {}
|
||||
func (j *VMJob) RootExited() {}
|
||||
|
||||
// Assign puts the process, and every child it starts afterwards, in the job.
|
||||
func (j *vmJob) Assign(pid int) error {
|
||||
func (j *VMJob) Assign(pid int) error {
|
||||
if j == nil || pid <= 0 {
|
||||
return nil
|
||||
}
|
||||
@@ -101,7 +99,7 @@ func (j *vmJob) Assign(pid int) error {
|
||||
}
|
||||
|
||||
// PIDs lists the processes currently in the job.
|
||||
func (j *vmJob) PIDs() []uint32 {
|
||||
func (j *VMJob) PIDs() []uint32 {
|
||||
if j == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -138,7 +136,7 @@ func (j *vmJob) PIDs() []uint32 {
|
||||
|
||||
// SetAffinity limits every process of the job, present and future, to mask.
|
||||
// A zero mask removes the limit.
|
||||
func (j *vmJob) SetAffinity(mask uint64) error {
|
||||
func (j *VMJob) SetAffinity(mask uint64) error {
|
||||
if j == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -160,7 +158,7 @@ func (j *vmJob) SetAffinity(mask uint64) error {
|
||||
}
|
||||
|
||||
// Terminate kills every process of the job.
|
||||
func (j *vmJob) Terminate() error {
|
||||
func (j *VMJob) Terminate() error {
|
||||
if j == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -173,7 +171,7 @@ func (j *vmJob) Terminate() error {
|
||||
}
|
||||
|
||||
// Close releases the handles without touching the processes.
|
||||
func (j *vmJob) Close() {
|
||||
func (j *VMJob) Close() {
|
||||
if j == nil {
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package plugin
|
||||
|
||||
import "github.com/Nwflower/reims-go/internal/plugin/sidecarproc"
|
||||
|
||||
// Re-export JSON-RPC 2.0 transport types and error codes from sidecarproc so
|
||||
// callers outside internal/plugin keep their existing import paths.
|
||||
const (
|
||||
maxRPCFrameBytes = sidecarproc.MaxRPCFrameBytes
|
||||
RPCMethodNotFound = sidecarproc.RPCMethodNotFound
|
||||
RPCInvalidParams = sidecarproc.RPCInvalidParams
|
||||
)
|
||||
|
||||
type (
|
||||
RPCError = sidecarproc.RPCError
|
||||
RPCRequestHandler = sidecarproc.RPCRequestHandler
|
||||
RPCConn = sidecarproc.RPCConn
|
||||
)
|
||||
+20
-472
@@ -1,402 +1,35 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/plugin/uiassets"
|
||||
)
|
||||
|
||||
// Re-export AssetServer and CSS/SVG safety primitives from internal/plugin/uiassets.
|
||||
type AssetServer = uiassets.AssetServer
|
||||
|
||||
var (
|
||||
reTokenKey = regexp.MustCompile(`^--[a-z0-9][a-z0-9-]*$`)
|
||||
reSafeFontFamily = regexp.MustCompile(`^[\p{L}\p{N} _-]{1,80}$`)
|
||||
reFontWeight = regexp.MustCompile(`^[0-9a-zA-Z\s-]+$`)
|
||||
reFontStyle = regexp.MustCompile(`^(normal|italic|oblique(\s+-?[0-9]+(\.[0-9]+)?deg)?)$`)
|
||||
reUnicodeRange = regexp.MustCompile(`^[U+0-9a-fA-F?,\s-]+$`)
|
||||
reSafeAssetRel = regexp.MustCompile(`^[a-zA-Z0-9._/@ -]+$`)
|
||||
reSchemePrefix = regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9+.-]*:`)
|
||||
NewAssetServer = uiassets.NewAssetServer
|
||||
SanitizeSVG = uiassets.SanitizeSVG
|
||||
ValidateThemeCSSSafety = uiassets.ValidateThemeCSSSafety
|
||||
ValidateCSSTokenValue = uiassets.ValidateCSSTokenValue
|
||||
validateSafeManifestAsset = uiassets.ValidateSafeManifestAsset
|
||||
safeJoin = uiassets.SafeJoin
|
||||
|
||||
reTokenKey = uiassets.ReTokenKey
|
||||
reSafeFontFamily = uiassets.ReSafeFontFamily
|
||||
reFontWeight = uiassets.ReFontWeight
|
||||
reFontStyle = uiassets.ReFontStyle
|
||||
reUnicodeRange = uiassets.ReUnicodeRange
|
||||
reSafeAssetRel = uiassets.ReSafeAssetRel
|
||||
reSchemePrefix = uiassets.ReSchemePrefix
|
||||
isCSSIdentChar = uiassets.IsCSSIdentChar
|
||||
)
|
||||
|
||||
// ValidateThemeCSSSafety rejects unbalanced braces, unclosed strings/comments,
|
||||
// CSS-escaped url()/image-set()/expression() bypasses, remote @import, and
|
||||
// external or unsafe data: URLs. When rootDir is non-empty, every relative
|
||||
// url()/@import must also resolve to an existing file inside rootDir.
|
||||
func ValidateThemeCSSSafety(css, rootDir string) error {
|
||||
if strings.Contains(strings.ToLower(css), "</style") {
|
||||
return errors.New("theme stylesheet cannot contain </style")
|
||||
}
|
||||
n := len(css)
|
||||
i := 0
|
||||
braceDepth := 0
|
||||
|
||||
skipWSAndComments := func() error {
|
||||
for i < n {
|
||||
if css[i] == ' ' || css[i] == '\t' || css[i] == '\r' || css[i] == '\n' || css[i] == '\f' {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
if i+1 < n && css[i] == '/' && css[i+1] == '*' {
|
||||
end := strings.Index(css[i+2:], "*/")
|
||||
if end < 0 {
|
||||
return errors.New("unclosed CSS comment in theme stylesheet")
|
||||
}
|
||||
i += 2 + end + 2
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
readString := func(quote byte) (string, error) {
|
||||
i++ // consume opening quote
|
||||
var b strings.Builder
|
||||
for i < n {
|
||||
c := css[i]
|
||||
if c == '\n' || c == '\r' || c == '\f' {
|
||||
return "", errors.New("unclosed CSS string literal")
|
||||
}
|
||||
if c == quote {
|
||||
i++
|
||||
return b.String(), nil
|
||||
}
|
||||
if c == '\\' {
|
||||
i++
|
||||
if i >= n {
|
||||
return "", errors.New("dangling escape in CSS string")
|
||||
}
|
||||
if css[i] == '\n' || css[i] == '\r' || css[i] == '\f' {
|
||||
if css[i] == '\r' && i+1 < n && css[i+1] == '\n' {
|
||||
i += 2
|
||||
} else {
|
||||
i++
|
||||
}
|
||||
continue
|
||||
}
|
||||
r, next := decodeCSSEscape(css, i)
|
||||
b.WriteRune(r)
|
||||
i = next
|
||||
continue
|
||||
}
|
||||
b.WriteByte(c)
|
||||
i++
|
||||
}
|
||||
return "", errors.New("unclosed CSS string literal")
|
||||
}
|
||||
|
||||
readIdent := func() string {
|
||||
var b strings.Builder
|
||||
for i < n {
|
||||
c := css[i]
|
||||
if c == '\\' && i+1 < n && css[i+1] != '\n' && css[i+1] != '\r' {
|
||||
r, next := decodeCSSEscape(css, i+1)
|
||||
b.WriteRune(r)
|
||||
i = next
|
||||
continue
|
||||
}
|
||||
if isCSSIdentChar(c) {
|
||||
b.WriteByte(c)
|
||||
i++
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
readURLArg := func() (string, error) {
|
||||
if err := skipWSAndComments(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if i >= n {
|
||||
return "", errors.New("unclosed url() in theme stylesheet")
|
||||
}
|
||||
if css[i] == '"' || css[i] == '\'' {
|
||||
val, err := readString(css[i])
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := skipWSAndComments(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if i >= n || css[i] != ')' {
|
||||
return "", errors.New("malformed url() in theme stylesheet")
|
||||
}
|
||||
i++ // consume ')'
|
||||
return val, nil
|
||||
}
|
||||
var b strings.Builder
|
||||
for i < n {
|
||||
c := css[i]
|
||||
if c == ')' {
|
||||
i++
|
||||
return strings.TrimSpace(b.String()), nil
|
||||
}
|
||||
if c == '(' || c == '"' || c == '\'' || c == '\n' || c == '\r' {
|
||||
return "", errors.New("malformed unquoted url() in theme stylesheet")
|
||||
}
|
||||
if c == '\\' {
|
||||
if i+1 >= n {
|
||||
return "", errors.New("dangling escape in url()")
|
||||
}
|
||||
r, next := decodeCSSEscape(css, i+1)
|
||||
b.WriteRune(r)
|
||||
i = next
|
||||
continue
|
||||
}
|
||||
b.WriteByte(c)
|
||||
i++
|
||||
}
|
||||
return "", errors.New("unclosed url() in theme stylesheet")
|
||||
}
|
||||
|
||||
for i < n {
|
||||
if err := skipWSAndComments(); err != nil {
|
||||
return err
|
||||
}
|
||||
if i >= n {
|
||||
break
|
||||
}
|
||||
c := css[i]
|
||||
switch {
|
||||
case c == '{':
|
||||
braceDepth++
|
||||
i++
|
||||
case c == '}':
|
||||
braceDepth--
|
||||
if braceDepth < 0 {
|
||||
return errors.New("unbalanced '}' in theme stylesheet (layer breakout blocked)")
|
||||
}
|
||||
i++
|
||||
case c == '"' || c == '\'':
|
||||
if _, err := readString(c); err != nil {
|
||||
return err
|
||||
}
|
||||
case c == '@':
|
||||
i++
|
||||
atName := strings.ToLower(readIdent())
|
||||
if atName == "import" {
|
||||
if err := skipWSAndComments(); err != nil {
|
||||
return err
|
||||
}
|
||||
var target string
|
||||
var err error
|
||||
if i < n && (css[i] == '"' || css[i] == '\'') {
|
||||
target, err = readString(css[i])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
fn := strings.ToLower(readIdent())
|
||||
if fn != "url" || i >= n || css[i] != '(' {
|
||||
return errors.New("@import syntax not allowed in theme stylesheet")
|
||||
}
|
||||
i++ // '('
|
||||
target, err = readURLArg()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := validateCSSResourceURL(target, rootDir, true); err != nil {
|
||||
return fmt.Errorf("@import %q forbidden: %w", target, err)
|
||||
}
|
||||
}
|
||||
case isCSSIdentStart(c) || c == '\\':
|
||||
ident := strings.ToLower(readIdent())
|
||||
if i < n && css[i] == '(' {
|
||||
switch ident {
|
||||
case "expression":
|
||||
return errors.New("CSS expression() is forbidden in theme stylesheets")
|
||||
case "url", "src":
|
||||
i++ // consume '('
|
||||
u, err := readURLArg()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateCSSResourceURL(u, rootDir, false); err != nil {
|
||||
return err
|
||||
}
|
||||
case "image-set", "-webkit-image-set":
|
||||
i++ // consume '('
|
||||
if err := validateImageSetArgs(css, &i, rootDir, skipWSAndComments, readString, readIdent, readURLArg); err != nil {
|
||||
return err
|
||||
}
|
||||
default:
|
||||
i++ // consume '('
|
||||
}
|
||||
}
|
||||
default:
|
||||
i++
|
||||
}
|
||||
}
|
||||
|
||||
if braceDepth != 0 {
|
||||
return errors.New("unbalanced '{' in theme stylesheet")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateImageSetArgs(
|
||||
css string,
|
||||
idx *int,
|
||||
rootDir string,
|
||||
skipWS func() error,
|
||||
readString func(byte) (string, error),
|
||||
readIdent func() string,
|
||||
readURLArg func() (string, error),
|
||||
) error {
|
||||
depth := 1
|
||||
n := len(css)
|
||||
for *idx < n && depth > 0 {
|
||||
if err := skipWS(); err != nil {
|
||||
return err
|
||||
}
|
||||
if *idx >= n {
|
||||
break
|
||||
}
|
||||
c := css[*idx]
|
||||
switch {
|
||||
case c == ')':
|
||||
depth--
|
||||
*idx++
|
||||
case c == '(':
|
||||
depth++
|
||||
*idx++
|
||||
case c == '"' || c == '\'':
|
||||
s, err := readString(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Bare strings inside image-set() are URLs unless inside type("...").
|
||||
if depth == 1 {
|
||||
if err := validateCSSResourceURL(s, rootDir, false); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case isCSSIdentStart(c) || c == '\\':
|
||||
fn := strings.ToLower(readIdent())
|
||||
if *idx < n && css[*idx] == '(' {
|
||||
switch fn {
|
||||
case "url", "src":
|
||||
*idx++
|
||||
u, err := readURLArg()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateCSSResourceURL(u, rootDir, false); err != nil {
|
||||
return err
|
||||
}
|
||||
case "image-set", "-webkit-image-set":
|
||||
*idx++
|
||||
if err := validateImageSetArgs(css, idx, rootDir, skipWS, readString, readIdent, readURLArg); err != nil {
|
||||
return err
|
||||
}
|
||||
default:
|
||||
depth++
|
||||
*idx++
|
||||
}
|
||||
}
|
||||
default:
|
||||
*idx++
|
||||
}
|
||||
}
|
||||
if depth != 0 {
|
||||
return errors.New("unclosed image-set() in theme stylesheet")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateCSSResourceURL(rawURL, rootDir string, isImport bool) error {
|
||||
u := strings.TrimSpace(rawURL)
|
||||
if u == "" {
|
||||
if isImport {
|
||||
return errors.New("empty @import URL")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if strings.ContainsAny(u, "\r\n\x00") {
|
||||
return errors.New("control characters in CSS URL")
|
||||
}
|
||||
lower := strings.ToLower(u)
|
||||
if strings.HasPrefix(lower, "//") {
|
||||
return fmt.Errorf("external protocol-relative URL %q is forbidden", u)
|
||||
}
|
||||
if strings.HasPrefix(lower, "data:") {
|
||||
if isImport {
|
||||
return errors.New("data: URL forbidden in @import")
|
||||
}
|
||||
allowedData := []string{
|
||||
"data:image/png;", "data:image/png,",
|
||||
"data:image/jpeg;", "data:image/jpeg,",
|
||||
"data:image/webp;", "data:image/webp,",
|
||||
"data:image/gif;", "data:image/gif,",
|
||||
"data:font/woff2;", "data:font/woff;",
|
||||
}
|
||||
for _, pfx := range allowedData {
|
||||
if strings.HasPrefix(lower, pfx) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("unsafe data: URL %q is forbidden in theme stylesheets", u)
|
||||
}
|
||||
if reSchemePrefix.MatchString(u) {
|
||||
return fmt.Errorf("external/scheme URL %q is forbidden in theme stylesheets", u)
|
||||
}
|
||||
// Strip query/fragment for path validation.
|
||||
pathOnly := u
|
||||
if q := strings.IndexAny(pathOnly, "?#"); q >= 0 {
|
||||
pathOnly = pathOnly[:q]
|
||||
}
|
||||
if pathOnly == "" {
|
||||
// Fragment-only URL like url(#clip) — allowed for SVG/local refs, not @import.
|
||||
if isImport {
|
||||
return errors.New("fragment URL forbidden in @import")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if strings.HasPrefix(pathOnly, "/") || strings.Contains(pathOnly, "\\") {
|
||||
return fmt.Errorf("absolute or backslash path %q is forbidden in theme stylesheets", u)
|
||||
}
|
||||
for _, seg := range strings.Split(pathOnly, "/") {
|
||||
if seg == ".." {
|
||||
return fmt.Errorf("path traversal %q is forbidden in theme stylesheets", u)
|
||||
}
|
||||
}
|
||||
if rootDir != "" {
|
||||
full, err := safeJoin(rootDir, pathOnly)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
st, err := os.Stat(full)
|
||||
if err != nil || st.IsDir() {
|
||||
return fmt.Errorf("theme CSS asset %q not found in package", pathOnly)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ValidateCSSTokenValue checks a single CSS custom property or seed value to
|
||||
// ensure it cannot break out of a declaration, close @layer, or load external URLs.
|
||||
func ValidateCSSTokenValue(val string) error {
|
||||
if strings.ContainsAny(val, "\r\n\x00{};") || strings.HasSuffix(strings.TrimSpace(val), `\`) {
|
||||
return fmt.Errorf("CSS token value %q contains forbidden characters", val)
|
||||
}
|
||||
if strings.Contains(val, "/*") || strings.Contains(val, "*/") {
|
||||
return fmt.Errorf("CSS token value %q must not contain CSS comments", val)
|
||||
}
|
||||
decoded := strings.ToLower(decodeAllCSSEscapes(val))
|
||||
for _, bad := range []string{"</style", "url(", "src(", "image-set(", "-webkit-image-set(", "expression(", "@import", "javascript:", "data:", "http://", "https://", "//"} {
|
||||
if strings.Contains(decoded, bad) {
|
||||
return fmt.Errorf("CSS token value %q contains forbidden construct %q", val, bad)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ValidateThemeContribution validates all theme manifest fields (tokens, seeds,
|
||||
// fonts, background, and stylesheet) so untrusted strings cannot inject CSS.
|
||||
func ValidateThemeContribution(th ThemeContribution, rootDir string) error {
|
||||
@@ -503,88 +136,3 @@ func ValidateThemeContribution(th ThemeContribution, rootDir string) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateSafeManifestAsset(rel, rootDir string) error {
|
||||
if rel == "" {
|
||||
return errors.New("empty asset path")
|
||||
}
|
||||
if strings.ContainsAny(rel, "\"'\\;{}()\r\n\x00") || !reSafeAssetRel.MatchString(rel) {
|
||||
return errors.New("asset path contains forbidden characters")
|
||||
}
|
||||
if strings.HasPrefix(rel, "/") || reSchemePrefix.MatchString(rel) {
|
||||
return errors.New("asset path must be package-relative")
|
||||
}
|
||||
for _, seg := range strings.Split(rel, "/") {
|
||||
if seg == ".." {
|
||||
return errors.New("path traversal in asset path")
|
||||
}
|
||||
}
|
||||
if rootDir != "" {
|
||||
full, err := safeJoin(rootDir, rel)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
st, err := os.Stat(full)
|
||||
if err != nil || st.IsDir() {
|
||||
return errors.New("asset file not found in package")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func decodeCSSEscape(s string, pos int) (rune, int) {
|
||||
n := len(s)
|
||||
if pos >= n {
|
||||
return 0xFFFD, pos
|
||||
}
|
||||
if isHexByte(s[pos]) {
|
||||
start := pos
|
||||
for pos < n && pos-start < 6 && isHexByte(s[pos]) {
|
||||
pos++
|
||||
}
|
||||
code, err := strconv.ParseInt(s[start:pos], 16, 32)
|
||||
// CSS spec: one optional whitespace char after hex escape is consumed.
|
||||
if pos < n {
|
||||
if s[pos] == '\r' && pos+1 < n && s[pos+1] == '\n' {
|
||||
pos += 2
|
||||
} else if s[pos] == ' ' || s[pos] == '\t' || s[pos] == '\n' || s[pos] == '\r' || s[pos] == '\f' {
|
||||
pos++
|
||||
}
|
||||
}
|
||||
if err != nil || code <= 0 || code > unicode.MaxRune {
|
||||
return 0xFFFD, pos
|
||||
}
|
||||
return rune(code), pos
|
||||
}
|
||||
return rune(s[pos]), pos + 1
|
||||
}
|
||||
|
||||
func decodeAllCSSEscapes(s string) string {
|
||||
if !strings.ContainsRune(s, '\\') {
|
||||
return s
|
||||
}
|
||||
var b strings.Builder
|
||||
for i := 0; i < len(s); {
|
||||
if s[i] == '\\' && i+1 < len(s) {
|
||||
r, next := decodeCSSEscape(s, i+1)
|
||||
b.WriteRune(r)
|
||||
i = next
|
||||
continue
|
||||
}
|
||||
b.WriteByte(s[i])
|
||||
i++
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func isHexByte(c byte) bool {
|
||||
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')
|
||||
}
|
||||
|
||||
func isCSSIdentStart(c byte) bool {
|
||||
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || c == '-' || c >= 0x80
|
||||
}
|
||||
|
||||
func isCSSIdentChar(c byte) bool {
|
||||
return isCSSIdentStart(c) || (c >= '0' && c <= '9')
|
||||
}
|
||||
@@ -11,11 +11,12 @@ import (
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/fetch"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/market"
|
||||
)
|
||||
|
||||
// marketFixture serves one plugin package and an index that lists it with the
|
||||
// given trust level and permissions.
|
||||
func marketFixture(t *testing.T, id string, trust plugin.TrustLevel, perms []string) (*httptest.Server, func() plugin.MarketIndex) {
|
||||
func marketFixture(t *testing.T, id string, trust plugin.TrustLevel, perms []string) (*httptest.Server, func() market.MarketIndex) {
|
||||
t.Helper()
|
||||
manifest, _ := json.Marshal(plugin.Manifest{
|
||||
Schema: 1,
|
||||
@@ -38,8 +39,8 @@ func marketFixture(t *testing.T, id string, trust plugin.TrustLevel, perms []str
|
||||
sum, _ := fetch.FileSHA256(zipPath)
|
||||
|
||||
var srv *httptest.Server
|
||||
index := func() plugin.MarketIndex {
|
||||
return plugin.MarketIndex{Schema: 1, Plugins: []plugin.MarketEntry{{
|
||||
index := func() market.MarketIndex {
|
||||
return market.MarketIndex{Schema: 1, Plugins: []market.MarketEntry{{
|
||||
ID: id, Version: "1.0.0", Channel: "stable", Trust: trust, Kind: "theme",
|
||||
Name: plugin.LocalizedText{EnUS: id}, Permissions: perms,
|
||||
DownloadURL: srv.URL + "/pkg.zip", SHA256: sum, SizeBytes: int64(len(zipBytes)),
|
||||
@@ -78,16 +79,16 @@ func TestFirstPartyIndexVouchesForInstalls(t *testing.T) {
|
||||
|
||||
install := func(firstParty bool) plugin.TrustLevel {
|
||||
mgr := newTrustTestManager(t)
|
||||
mc := plugin.NewMarketClient(plugin.MarketClientOptions{
|
||||
mc := market.NewMarketClient(market.MarketClientOptions{
|
||||
Layout: mgr.Layout(), HostVersion: "0.2.10",
|
||||
URLs: []string{srv.URL + "/index.json"}, CacheTTL: time.Minute,
|
||||
AllowInsecureLocalhost: true, FirstParty: firstParty,
|
||||
})
|
||||
browse := mc.Browse(context.Background(), nil, plugin.MarketBrowseOptions{})
|
||||
browse := mc.Browse(context.Background(), nil, market.MarketBrowseOptions{})
|
||||
if len(browse.Items) != 1 {
|
||||
t.Fatalf("browse items = %d", len(browse.Items))
|
||||
}
|
||||
info, err := mc.InstallFromMarket(context.Background(), mgr, id, plugin.MarketInstallOptions{})
|
||||
info, err := mc.InstallFromMarket(context.Background(), mgr, id, market.MarketInstallOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("install: %v", err)
|
||||
}
|
||||
@@ -110,7 +111,7 @@ func TestStaleIndexDoesNotVouch(t *testing.T) {
|
||||
const id = "official.theme.stale"
|
||||
srv, _ := marketFixture(t, id, plugin.TrustOfficial, nil)
|
||||
mgr := newTrustTestManager(t)
|
||||
opts := plugin.MarketClientOptions{
|
||||
opts := market.MarketClientOptions{
|
||||
Layout: mgr.Layout(), HostVersion: "0.2.10",
|
||||
URLs: []string{srv.URL + "/index.json"}, CacheTTL: time.Minute,
|
||||
AllowInsecureLocalhost: true, FirstParty: true,
|
||||
@@ -118,28 +119,28 @@ func TestStaleIndexDoesNotVouch(t *testing.T) {
|
||||
// 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{})
|
||||
market.NewMarketClient(opts).Browse(context.Background(), nil, market.MarketBrowseOptions{})
|
||||
opts.URLs = []string{srv.URL + "/missing-index.json"}
|
||||
staleClient := plugin.NewMarketClient(opts)
|
||||
staleClient := market.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 {
|
||||
if coldPeek := staleClient.Peek(nil, market.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{})
|
||||
browse := staleClient.Browse(context.Background(), nil, market.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})
|
||||
followUp := staleClient.Browse(context.Background(), nil, market.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 {
|
||||
if peek := staleClient.Peek(nil, market.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{})
|
||||
info, err := staleClient.InstallFromMarket(context.Background(), mgr, id, market.MarketInstallOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("install: %v", err)
|
||||
}
|
||||
@@ -159,24 +160,24 @@ func TestStaleIndexDoesNotVouch(t *testing.T) {
|
||||
_ = json.NewEncoder(w).Encode(indexFn())
|
||||
}))
|
||||
t.Cleanup(switchSrv.Close)
|
||||
liveClient := plugin.NewMarketClient(plugin.MarketClientOptions{
|
||||
liveClient := market.NewMarketClient(market.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 {
|
||||
if okRes := liveClient.Browse(context.Background(), nil, market.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 {
|
||||
if failRes := liveClient.Browse(context.Background(), nil, market.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 {
|
||||
if afterFail := liveClient.Browse(context.Background(), nil, market.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 {
|
||||
if recovered := liveClient.Browse(context.Background(), nil, market.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)
|
||||
}
|
||||
}
|
||||
@@ -185,12 +186,12 @@ func TestOfficialPluginsStillNeedApproval(t *testing.T) {
|
||||
const id = "official.theme.clip"
|
||||
srv, _ := marketFixture(t, id, plugin.TrustOfficial, []string{"host:clipboard"})
|
||||
mgr := newTrustTestManager(t)
|
||||
mc := plugin.NewMarketClient(plugin.MarketClientOptions{
|
||||
mc := market.NewMarketClient(market.MarketClientOptions{
|
||||
Layout: mgr.Layout(), HostVersion: "0.2.10",
|
||||
URLs: []string{srv.URL + "/index.json"}, CacheTTL: time.Minute,
|
||||
AllowInsecureLocalhost: true, FirstParty: true,
|
||||
})
|
||||
info, err := mc.InstallFromMarket(context.Background(), mgr, id, plugin.MarketInstallOptions{})
|
||||
info, err := mc.InstallFromMarket(context.Background(), mgr, id, market.MarketInstallOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("install: %v", err)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package plugin
|
||||
package uiassets
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
@@ -70,7 +70,7 @@ func (a *AssetServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
fullPath, err := safeJoin(rootDir, relPath)
|
||||
fullPath, err := SafeJoin(rootDir, relPath)
|
||||
if err != nil {
|
||||
http.Error(w, "forbidden path", http.StatusForbidden)
|
||||
return
|
||||
@@ -0,0 +1,482 @@
|
||||
package uiassets
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
var (
|
||||
ReTokenKey = regexp.MustCompile(`^--[a-z0-9][a-z0-9-]*$`)
|
||||
ReSafeFontFamily = regexp.MustCompile(`^[\p{L}\p{N} _-]{1,80}$`)
|
||||
ReFontWeight = regexp.MustCompile(`^[0-9a-zA-Z\s-]+$`)
|
||||
ReFontStyle = regexp.MustCompile(`^(normal|italic|oblique(\s+-?[0-9]+(\.[0-9]+)?deg)?)$`)
|
||||
ReUnicodeRange = regexp.MustCompile(`^[U+0-9a-fA-F?,\s-]+$`)
|
||||
ReSafeAssetRel = regexp.MustCompile(`^[a-zA-Z0-9._/@ -]+$`)
|
||||
ReSchemePrefix = regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9+.-]*:`)
|
||||
)
|
||||
|
||||
// ValidateThemeCSSSafety rejects unbalanced braces, unclosed strings/comments,
|
||||
// CSS-escaped url()/image-set()/expression() bypasses, remote @import, and
|
||||
// external or unsafe data: URLs. When rootDir is non-empty, every relative
|
||||
// url()/@import must also resolve to an existing file inside rootDir.
|
||||
func ValidateThemeCSSSafety(css, rootDir string) error {
|
||||
if strings.Contains(strings.ToLower(css), "</style") {
|
||||
return errors.New("theme stylesheet cannot contain </style")
|
||||
}
|
||||
n := len(css)
|
||||
i := 0
|
||||
braceDepth := 0
|
||||
|
||||
skipWSAndComments := func() error {
|
||||
for i < n {
|
||||
if css[i] == ' ' || css[i] == '\t' || css[i] == '\r' || css[i] == '\n' || css[i] == '\f' {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
if i+1 < n && css[i] == '/' && css[i+1] == '*' {
|
||||
end := strings.Index(css[i+2:], "*/")
|
||||
if end < 0 {
|
||||
return errors.New("unclosed CSS comment in theme stylesheet")
|
||||
}
|
||||
i += 2 + end + 2
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
readString := func(quote byte) (string, error) {
|
||||
i++ // consume opening quote
|
||||
var b strings.Builder
|
||||
for i < n {
|
||||
c := css[i]
|
||||
if c == '\n' || c == '\r' || c == '\f' {
|
||||
return "", errors.New("unclosed CSS string literal")
|
||||
}
|
||||
if c == quote {
|
||||
i++
|
||||
return b.String(), nil
|
||||
}
|
||||
if c == '\\' {
|
||||
i++
|
||||
if i >= n {
|
||||
return "", errors.New("dangling escape in CSS string")
|
||||
}
|
||||
if css[i] == '\n' || css[i] == '\r' || css[i] == '\f' {
|
||||
if css[i] == '\r' && i+1 < n && css[i+1] == '\n' {
|
||||
i += 2
|
||||
} else {
|
||||
i++
|
||||
}
|
||||
continue
|
||||
}
|
||||
r, next := decodeCSSEscape(css, i)
|
||||
b.WriteRune(r)
|
||||
i = next
|
||||
continue
|
||||
}
|
||||
b.WriteByte(c)
|
||||
i++
|
||||
}
|
||||
return "", errors.New("unclosed CSS string literal")
|
||||
}
|
||||
|
||||
readIdent := func() string {
|
||||
var b strings.Builder
|
||||
for i < n {
|
||||
c := css[i]
|
||||
if c == '\\' && i+1 < n && css[i+1] != '\n' && css[i+1] != '\r' {
|
||||
r, next := decodeCSSEscape(css, i+1)
|
||||
b.WriteRune(r)
|
||||
i = next
|
||||
continue
|
||||
}
|
||||
if IsCSSIdentChar(c) {
|
||||
b.WriteByte(c)
|
||||
i++
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
readURLArg := func() (string, error) {
|
||||
if err := skipWSAndComments(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if i >= n {
|
||||
return "", errors.New("unclosed url() in theme stylesheet")
|
||||
}
|
||||
if css[i] == '"' || css[i] == '\'' {
|
||||
val, err := readString(css[i])
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := skipWSAndComments(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if i >= n || css[i] != ')' {
|
||||
return "", errors.New("malformed url() in theme stylesheet")
|
||||
}
|
||||
i++ // consume ')'
|
||||
return val, nil
|
||||
}
|
||||
var b strings.Builder
|
||||
for i < n {
|
||||
c := css[i]
|
||||
if c == ')' {
|
||||
i++
|
||||
return strings.TrimSpace(b.String()), nil
|
||||
}
|
||||
if c == '(' || c == '"' || c == '\'' || c == '\n' || c == '\r' {
|
||||
return "", errors.New("malformed unquoted url() in theme stylesheet")
|
||||
}
|
||||
if c == '\\' {
|
||||
if i+1 >= n {
|
||||
return "", errors.New("dangling escape in url()")
|
||||
}
|
||||
r, next := decodeCSSEscape(css, i+1)
|
||||
b.WriteRune(r)
|
||||
i = next
|
||||
continue
|
||||
}
|
||||
b.WriteByte(c)
|
||||
i++
|
||||
}
|
||||
return "", errors.New("unclosed url() in theme stylesheet")
|
||||
}
|
||||
|
||||
for i < n {
|
||||
if err := skipWSAndComments(); err != nil {
|
||||
return err
|
||||
}
|
||||
if i >= n {
|
||||
break
|
||||
}
|
||||
c := css[i]
|
||||
switch {
|
||||
case c == '{':
|
||||
braceDepth++
|
||||
i++
|
||||
case c == '}':
|
||||
braceDepth--
|
||||
if braceDepth < 0 {
|
||||
return errors.New("unbalanced '}' in theme stylesheet (layer breakout blocked)")
|
||||
}
|
||||
i++
|
||||
case c == '"' || c == '\'':
|
||||
if _, err := readString(c); err != nil {
|
||||
return err
|
||||
}
|
||||
case c == '@':
|
||||
i++
|
||||
atName := strings.ToLower(readIdent())
|
||||
if atName == "import" {
|
||||
if err := skipWSAndComments(); err != nil {
|
||||
return err
|
||||
}
|
||||
var target string
|
||||
var err error
|
||||
if i < n && (css[i] == '"' || css[i] == '\'') {
|
||||
target, err = readString(css[i])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
fn := strings.ToLower(readIdent())
|
||||
if fn != "url" || i >= n || css[i] != '(' {
|
||||
return errors.New("@import syntax not allowed in theme stylesheet")
|
||||
}
|
||||
i++ // '('
|
||||
target, err = readURLArg()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := validateCSSResourceURL(target, rootDir, true); err != nil {
|
||||
return fmt.Errorf("@import %q forbidden: %w", target, err)
|
||||
}
|
||||
}
|
||||
case isCSSIdentStart(c) || c == '\\':
|
||||
ident := strings.ToLower(readIdent())
|
||||
if i < n && css[i] == '(' {
|
||||
switch ident {
|
||||
case "expression":
|
||||
return errors.New("CSS expression() is forbidden in theme stylesheets")
|
||||
case "url", "src":
|
||||
i++ // consume '('
|
||||
u, err := readURLArg()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateCSSResourceURL(u, rootDir, false); err != nil {
|
||||
return err
|
||||
}
|
||||
case "image-set", "-webkit-image-set":
|
||||
i++ // consume '('
|
||||
if err := validateImageSetArgs(css, &i, rootDir, skipWSAndComments, readString, readIdent, readURLArg); err != nil {
|
||||
return err
|
||||
}
|
||||
default:
|
||||
i++ // consume '('
|
||||
}
|
||||
}
|
||||
default:
|
||||
i++
|
||||
}
|
||||
}
|
||||
|
||||
if braceDepth != 0 {
|
||||
return errors.New("unbalanced '{' in theme stylesheet")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateImageSetArgs(
|
||||
css string,
|
||||
idx *int,
|
||||
rootDir string,
|
||||
skipWS func() error,
|
||||
readString func(byte) (string, error),
|
||||
readIdent func() string,
|
||||
readURLArg func() (string, error),
|
||||
) error {
|
||||
depth := 1
|
||||
n := len(css)
|
||||
for *idx < n && depth > 0 {
|
||||
if err := skipWS(); err != nil {
|
||||
return err
|
||||
}
|
||||
if *idx >= n {
|
||||
break
|
||||
}
|
||||
c := css[*idx]
|
||||
switch {
|
||||
case c == ')':
|
||||
depth--
|
||||
*idx++
|
||||
case c == '(':
|
||||
depth++
|
||||
*idx++
|
||||
case c == '"' || c == '\'':
|
||||
s, err := readString(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Bare strings inside image-set() are URLs unless inside type("...").
|
||||
if depth == 1 {
|
||||
if err := validateCSSResourceURL(s, rootDir, false); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case isCSSIdentStart(c) || c == '\\':
|
||||
fn := strings.ToLower(readIdent())
|
||||
if *idx < n && css[*idx] == '(' {
|
||||
switch fn {
|
||||
case "url", "src":
|
||||
*idx++
|
||||
u, err := readURLArg()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateCSSResourceURL(u, rootDir, false); err != nil {
|
||||
return err
|
||||
}
|
||||
case "image-set", "-webkit-image-set":
|
||||
*idx++
|
||||
if err := validateImageSetArgs(css, idx, rootDir, skipWS, readString, readIdent, readURLArg); err != nil {
|
||||
return err
|
||||
}
|
||||
default:
|
||||
depth++
|
||||
*idx++
|
||||
}
|
||||
}
|
||||
default:
|
||||
*idx++
|
||||
}
|
||||
}
|
||||
if depth != 0 {
|
||||
return errors.New("unclosed image-set() in theme stylesheet")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateCSSResourceURL(rawURL, rootDir string, isImport bool) error {
|
||||
u := strings.TrimSpace(rawURL)
|
||||
if u == "" {
|
||||
if isImport {
|
||||
return errors.New("empty @import URL")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if strings.ContainsAny(u, "\r\n\x00") {
|
||||
return errors.New("control characters in CSS URL")
|
||||
}
|
||||
lower := strings.ToLower(u)
|
||||
if strings.HasPrefix(lower, "//") {
|
||||
return fmt.Errorf("external protocol-relative URL %q is forbidden", u)
|
||||
}
|
||||
if strings.HasPrefix(lower, "data:") {
|
||||
if isImport {
|
||||
return errors.New("data: URL forbidden in @import")
|
||||
}
|
||||
allowedData := []string{
|
||||
"data:image/png;", "data:image/png,",
|
||||
"data:image/jpeg;", "data:image/jpeg,",
|
||||
"data:image/webp;", "data:image/webp,",
|
||||
"data:image/gif;", "data:image/gif,",
|
||||
"data:font/woff2;", "data:font/woff;",
|
||||
}
|
||||
for _, pfx := range allowedData {
|
||||
if strings.HasPrefix(lower, pfx) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("unsafe data: URL %q is forbidden in theme stylesheets", u)
|
||||
}
|
||||
if ReSchemePrefix.MatchString(u) {
|
||||
return fmt.Errorf("external/scheme URL %q is forbidden in theme stylesheets", u)
|
||||
}
|
||||
// Strip query/fragment for path validation.
|
||||
pathOnly := u
|
||||
if q := strings.IndexAny(pathOnly, "?#"); q >= 0 {
|
||||
pathOnly = pathOnly[:q]
|
||||
}
|
||||
if pathOnly == "" {
|
||||
// Fragment-only URL like url(#clip) — allowed for SVG/local refs, not @import.
|
||||
if isImport {
|
||||
return errors.New("fragment URL forbidden in @import")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if strings.HasPrefix(pathOnly, "/") || strings.Contains(pathOnly, "\\") {
|
||||
return fmt.Errorf("absolute or backslash path %q is forbidden in theme stylesheets", u)
|
||||
}
|
||||
for _, seg := range strings.Split(pathOnly, "/") {
|
||||
if seg == ".." {
|
||||
return fmt.Errorf("path traversal %q is forbidden in theme stylesheets", u)
|
||||
}
|
||||
}
|
||||
if rootDir != "" {
|
||||
full, err := SafeJoin(rootDir, pathOnly)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
st, err := os.Stat(full)
|
||||
if err != nil || st.IsDir() {
|
||||
return fmt.Errorf("theme CSS asset %q not found in package", pathOnly)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ValidateCSSTokenValue checks a single CSS custom property or seed value to
|
||||
// ensure it cannot break out of a declaration, close @layer, or load external URLs.
|
||||
func ValidateCSSTokenValue(val string) error {
|
||||
if strings.ContainsAny(val, "\r\n\x00{};") || strings.HasSuffix(strings.TrimSpace(val), `\`) {
|
||||
return fmt.Errorf("CSS token value %q contains forbidden characters", val)
|
||||
}
|
||||
if strings.Contains(val, "/*") || strings.Contains(val, "*/") {
|
||||
return fmt.Errorf("CSS token value %q must not contain CSS comments", val)
|
||||
}
|
||||
decoded := strings.ToLower(decodeAllCSSEscapes(val))
|
||||
for _, bad := range []string{"</style", "url(", "src(", "image-set(", "-webkit-image-set(", "expression(", "@import", "javascript:", "data:", "http://", "https://", "//"} {
|
||||
if strings.Contains(decoded, bad) {
|
||||
return fmt.Errorf("CSS token value %q contains forbidden construct %q", val, bad)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ValidateSafeManifestAsset(rel, rootDir string) error {
|
||||
if rel == "" {
|
||||
return errors.New("empty asset path")
|
||||
}
|
||||
if strings.ContainsAny(rel, "\"'\\;{}()\r\n\x00") || !ReSafeAssetRel.MatchString(rel) {
|
||||
return errors.New("asset path contains forbidden characters")
|
||||
}
|
||||
if strings.HasPrefix(rel, "/") || ReSchemePrefix.MatchString(rel) {
|
||||
return errors.New("asset path must be package-relative")
|
||||
}
|
||||
for _, seg := range strings.Split(rel, "/") {
|
||||
if seg == ".." {
|
||||
return errors.New("path traversal in asset path")
|
||||
}
|
||||
}
|
||||
if rootDir != "" {
|
||||
full, err := SafeJoin(rootDir, rel)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
st, err := os.Stat(full)
|
||||
if err != nil || st.IsDir() {
|
||||
return errors.New("asset file not found in package")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func decodeCSSEscape(s string, pos int) (rune, int) {
|
||||
n := len(s)
|
||||
if pos >= n {
|
||||
return 0xFFFD, pos
|
||||
}
|
||||
if isHexByte(s[pos]) {
|
||||
start := pos
|
||||
for pos < n && pos-start < 6 && isHexByte(s[pos]) {
|
||||
pos++
|
||||
}
|
||||
code, err := strconv.ParseInt(s[start:pos], 16, 32)
|
||||
// CSS spec: one optional whitespace char after hex escape is consumed.
|
||||
if pos < n {
|
||||
if s[pos] == '\r' && pos+1 < n && s[pos+1] == '\n' {
|
||||
pos += 2
|
||||
} else if s[pos] == ' ' || s[pos] == '\t' || s[pos] == '\n' || s[pos] == '\r' || s[pos] == '\f' {
|
||||
pos++
|
||||
}
|
||||
}
|
||||
if err != nil || code <= 0 || code > unicode.MaxRune {
|
||||
return 0xFFFD, pos
|
||||
}
|
||||
return rune(code), pos
|
||||
}
|
||||
return rune(s[pos]), pos + 1
|
||||
}
|
||||
|
||||
func decodeAllCSSEscapes(s string) string {
|
||||
if !strings.ContainsRune(s, '\\') {
|
||||
return s
|
||||
}
|
||||
var b strings.Builder
|
||||
for i := 0; i < len(s); {
|
||||
if s[i] == '\\' && i+1 < len(s) {
|
||||
r, next := decodeCSSEscape(s, i+1)
|
||||
b.WriteRune(r)
|
||||
i = next
|
||||
continue
|
||||
}
|
||||
b.WriteByte(s[i])
|
||||
i++
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func isHexByte(c byte) bool {
|
||||
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')
|
||||
}
|
||||
|
||||
func isCSSIdentStart(c byte) bool {
|
||||
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || c == '-' || c >= 0x80
|
||||
}
|
||||
|
||||
func IsCSSIdentChar(c byte) bool {
|
||||
return isCSSIdentStart(c) || (c >= '0' && c <= '9')
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package uiassets
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func pathWithinRoot(root, candidate string) bool {
|
||||
if runtime.GOOS == "windows" {
|
||||
r := strings.ToLower(root)
|
||||
c := strings.ToLower(candidate)
|
||||
return c == r || strings.HasPrefix(c, r+string(os.PathSeparator))
|
||||
}
|
||||
return candidate == root || strings.HasPrefix(candidate, root+string(os.PathSeparator))
|
||||
}
|
||||
|
||||
// SafeJoin joins rel under root and verifies that neither lexical traversal
|
||||
// nor symlinks / NTFS junctions escape root.
|
||||
func SafeJoin(root, rel string) (string, error) {
|
||||
absRoot, err := filepath.Abs(root)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("resolve root path: %w", err)
|
||||
}
|
||||
cleanRoot := filepath.Clean(absRoot)
|
||||
joined := filepath.Clean(filepath.Join(cleanRoot, filepath.FromSlash(rel)))
|
||||
if !pathWithinRoot(cleanRoot, joined) {
|
||||
return "", fmt.Errorf("path traversal blocked: %q", rel)
|
||||
}
|
||||
evalRoot := cleanRoot
|
||||
if r, err := filepath.EvalSymlinks(cleanRoot); err == nil {
|
||||
evalRoot = filepath.Clean(r)
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return "", fmt.Errorf("evaluate root path: %w", err)
|
||||
}
|
||||
|
||||
evalJoined, err := filepath.EvalSymlinks(joined)
|
||||
if err == nil {
|
||||
evalJoined = filepath.Clean(evalJoined)
|
||||
if !pathWithinRoot(evalRoot, evalJoined) {
|
||||
return "", fmt.Errorf("symlink traversal blocked: %q", rel)
|
||||
}
|
||||
return evalJoined, nil
|
||||
}
|
||||
if !errors.Is(err, os.ErrNotExist) {
|
||||
return "", fmt.Errorf("evaluate path %q: %w", rel, err)
|
||||
}
|
||||
|
||||
cur := joined
|
||||
var tail []string
|
||||
for cur != cleanRoot {
|
||||
parent := filepath.Dir(cur)
|
||||
if parent == cur {
|
||||
break
|
||||
}
|
||||
tail = append(tail, filepath.Base(cur))
|
||||
cur = parent
|
||||
if evalAnc, aErr := filepath.EvalSymlinks(cur); aErr == nil {
|
||||
evalAnc = filepath.Clean(evalAnc)
|
||||
if !pathWithinRoot(evalRoot, evalAnc) {
|
||||
return "", fmt.Errorf("symlink ancestor traversal blocked: %q", rel)
|
||||
}
|
||||
for i := len(tail) - 1; i >= 0; i-- {
|
||||
evalAnc = filepath.Join(evalAnc, tail[i])
|
||||
}
|
||||
return evalAnc, nil
|
||||
} else if !errors.Is(aErr, os.ErrNotExist) {
|
||||
return "", fmt.Errorf("evaluate ancestor path %q: %w", rel, aErr)
|
||||
}
|
||||
}
|
||||
return joined, nil
|
||||
}
|
||||
@@ -20,6 +20,8 @@ var ErrNoActiveRuntime = errors.New("no active runtime installed")
|
||||
const (
|
||||
// DefaultKind is the built-in macOS vGPU runtime kind.
|
||||
DefaultKind = "reims-vgpu"
|
||||
// StambhaKind is a standalone ARM64 macOS preview runtime.
|
||||
StambhaKind = "stambha-hosted"
|
||||
// DefaultRuntimeAPI is the baseline CLI/output contract version for reims-vgpu.
|
||||
DefaultRuntimeAPI = "1.0.0"
|
||||
)
|
||||
|
||||
@@ -97,7 +97,7 @@ func requestedSelection(next config.Config, commit string, aslr *bool) (config.C
|
||||
return next, err
|
||||
}
|
||||
if !slices.ContainsFunc(installed, func(r Installed) bool {
|
||||
return r.Commit == commit || r.Kind+"/"+r.Commit == commit
|
||||
return r.Kind != StambhaKind && (r.Commit == commit || r.Kind+"/"+r.Commit == commit)
|
||||
}) {
|
||||
return next, fmt.Errorf("%w: %s", ErrNotFound, commit)
|
||||
}
|
||||
|
||||
@@ -190,3 +190,16 @@ func TestNonWindowsIgnoresSavedQEMUASLR(t *testing.T) {
|
||||
t.Fatalf("lost runtime selection or portable preference: %+v, %v", saved, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelectionDoesNotActivateARMRuntimeForX86(t *testing.T) {
|
||||
cfg := config.Config{DataRoot: t.TempDir(), ActiveRuntime: "intel"}
|
||||
writeFakeRuntime(t, filepath.Join(cfg.RuntimesDir(), "intel"), Manifest{Commit: "intel"})
|
||||
writeFakeRuntime(t, filepath.Join(cfg.RuntimesDir(), StambhaKind, "arm"), Manifest{Commit: "arm", Kind: StambhaKind})
|
||||
|
||||
for _, ref := range []string{"arm", StambhaKind + "/arm"} {
|
||||
got, err := requestedSelection(cfg, ref, nil)
|
||||
if !errors.Is(err, ErrNotFound) || got.ActiveRuntime != cfg.ActiveRuntime {
|
||||
t.Fatalf("select %q: active = %q, err = %v", ref, got.ActiveRuntime, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -89,5 +89,12 @@
|
||||
"wizardBasics": "Basics",
|
||||
"offlineListFailedDetail": "Couldn’t read Apple’s release list: {err}",
|
||||
"setupLangPackOffer": "Also install “{name}”",
|
||||
"setupLangPackFailed": "Could not install the language pack; you can retry from the Plugins page"
|
||||
"setupLangPackFailed": "Could not install the language pack; you can retry from the Plugins page",
|
||||
"armRestoreGroup": "ARM restore image",
|
||||
"armRestoreVersion": "macOS 27.2.1 (26B131) · 25.6 GB",
|
||||
"armRestoreMediaHint": "Download the IPSW from Apple. To create a VM, select prepared Stambha boot media and a writable virtual disk below.",
|
||||
"armRestoreDownload": "Download IPSW",
|
||||
"armRestoreDownloaded": "Downloaded IPSW",
|
||||
"armRuntimeLabel": "ARM64 guest",
|
||||
"x86RuntimeLabel": "x86-64 guest"
|
||||
}
|
||||
@@ -89,5 +89,12 @@
|
||||
"wizardBasics": "基本信息",
|
||||
"offlineListFailedDetail": "无法读取 Apple 的版本列表:{err}",
|
||||
"setupLangPackOffer": "同时安装「{name}」",
|
||||
"setupLangPackFailed": "语言包安装失败,可稍后在插件页重试"
|
||||
"setupLangPackFailed": "语言包安装失败,可稍后在插件页重试",
|
||||
"armRestoreGroup": "ARM 恢复镜像",
|
||||
"armRestoreVersion": "macOS 27.2.1 (26B131) · 25.6 GB",
|
||||
"armRestoreMediaHint": "从 Apple 下载 IPSW。创建虚拟机时,请在下方选择已制作的 Stambha 启动介质和可写虚拟磁盘。",
|
||||
"armRestoreDownload": "下载 IPSW",
|
||||
"armRestoreDownloaded": "已下载的 IPSW",
|
||||
"armRuntimeLabel": "ARM64 来宾",
|
||||
"x86RuntimeLabel": "x86-64 来宾"
|
||||
}
|
||||
Reference in new issue
Block a user