mirror of
https://github.com/stablyai/orca.git
synced 2026-09-22 08:02:28 +00:00
* feat(plugins): Orca plugin system — kernel, content packs, panels, workers, marketplace v0 (experimental) Adds Orca's experimental plugin system behind a settings flag: a supervised kernel, declarative content packs (VM recipes, commands and keybindings, language packs), sandboxed iframe panels, forked worker hosts, and a Git-backed marketplace v0 with consent, provenance and kill-list enforcement. Theme, icon-theme and terminal-theme contributions are deferred to a follow-up pass. * fix(plugins): make unsupported marketplace listings unreachable by key findPlugin() backs preview/install/previewInstalledUpdate via requireListing(), so filtering only listPlugins() hid the catalog card while leaving the dead install path reachable one click later. * fix(plugins): fan Pi session-only status out to plugin subscribers The providerSessionOnly early-return in applyNormalizedStatus emitted to onAgentStatus (main-window fanout) but skipped enrichedStatusListeners, so plugins subscribed to agent.status.changed silently missed every Pi session_start event. Route both emit sites through one helper so a future early return cannot drop the plugin tap again. Co-authored-by: Orca <help@stably.ai> * plugins: drop dead code and hoist duplicated trust-boundary patterns Cleanup pass over the P1 diff, no behavior change: - Delete `readPluginTreeSnapshot`/`readSnapshotFile` and their types, plus the now-vestigial `directories`/`signal` plumbing in `collectFiles`. - Delete `resolveContainedPluginDirectory` (no callers). - Delete `plugin-content-load-pool.ts`; it reimplemented the existing `mapWithConcurrency`, whose index arg also removes the pairing wrapper in `buildPluginList`. - Hoist `PLUGIN_CONTENT_HASH_PATTERN` and `PLUGIN_COMMIT_PATTERN` into the install-lockfile module; 11 sites hand-rolled these identically. - Point the new reliability gate at the PR instead of gitignored docs paths, matching every other gate's link form. * fix(plugins): retry plugin state renames on Windows AV/EPERM locks Six plugin write paths (lockfile, provenance, current pointer, kill list, marketplace cache, staged install dir) did a plain rename, so an antivirus or indexer holding the target open surfaced as a failed install. The repo already retries this hazard for issue #1507, but only through a sync helper; these paths are all async. Adds one bounded async retry + atomic write used by all six, and trims a consent-provenance header that restated its own JSX. * test(plugins): cover the Windows rename retry path The retry loop shipped untested: both existing cases hit the non-retry path, and the temp-cleanup test passed identically with the `finally` removed. Mock `rename` to queue errno codes so CI can exercise locks it cannot provoke. Co-authored-by: Orca <help@stably.ai> * fix(plugins): pin bundled plugin resources to LF Windows CI checks out with autocrlf, so the byte-hashed launch tree arrived as CRLF and verify-packaged-plugin-resources rejected it — the packaged build could never pass on Windows. Reproduced locally: CRLF yields the exact CI error, LF verifies clean. Files are already LF, so nothing renormalizes. Co-authored-by: Orca <help@stably.ai> * test: guard the bundled-plugin LF pin against a CRLF checkout The byte-hash mismatch only surfaced in Windows packaging CI. Assert the .gitattributes pin and that a CRLF tree is rejected, so a regression fails on any platform instead of waiting for a packaged Windows build. Co-authored-by: Orca <help@stably.ai> * ci: trigger packaged-build check on bundled plugin resource changes The launch tree is byte-hashed during packaging, but no trigger path covered it — so the CRLF fix for that check would not have re-run the check. Add the resources, verifier and .gitattributes paths that can break packaging. Co-authored-by: Orca <help@stably.ai> * perf(plugins): rebuild the panel frame only when its baked theme values change The revision keys the panel iframe, so every bump destroys the sandboxed frame and its in-panel state. It counted root attribute mutations, but --workspace-sidebar-live-width is written every rAF of a sidebar drag, so dragging with a panel open blanked it ~60x/sec. Compare the two values the shell actually bakes in instead. Co-authored-by: Orca <help@stably.ai> * test: stop pinning a plugin name in the CRLF guard The CRLF case rewrites every launch file, so the reported mismatch is whichever plugin sorts first. P2 adds theme plugins that sort ahead of orca-navigation-shortcuts, which broke the assertion there. Co-authored-by: Orca <help@stably.ai> * style: drop stray blank lines left by the rebase resolutions Both sides of the agent-hooks and orca-runtime conflicts contributed a trailing blank, which oxfmt rejects. Whitespace only. Co-authored-by: Orca <help@stably.ai> * test(plugins): stop the startup budget failing on machine load P95 runs 16-34ms idle but exceeds the 50ms bound under full-suite parallelism, so the gate flaked. Widen it to catch an order-of-magnitude regression instead; the no-worker/no-plugin-code assertions are the real guarantee. Verified a 400ms regression still fails. Co-authored-by: Orca <help@stably.ai> --------- Co-authored-by: Orca <help@stably.ai>
345 lines
13 KiB
TypeScript
345 lines
13 KiB
TypeScript
/**
|
|
* Invariant: a plugin panel cannot exfiltrate, navigate, or bypass bridge budgets.
|
|
* Oracle: a permissive loopback server receives zero requests while the real
|
|
* sandboxed iframe reports CSP/navigation containment and actual budget refusals.
|
|
* Chromium is required because Vitest cannot exercise CSP or iframe sandboxing.
|
|
* Maturity: experimental until this has CI soak history on all desktop platforms.
|
|
*/
|
|
|
|
import { cp, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
|
|
import { createServer, type Server } from 'node:http'
|
|
import { tmpdir } from 'node:os'
|
|
import { join } from 'node:path'
|
|
import type { AddressInfo } from 'node:net'
|
|
import type { ElectronApplication, FrameLocator, Page, TestInfo } from '@stablyai/playwright-test'
|
|
import { expect, test } from './helpers/orca-app'
|
|
|
|
type InstalledPanel = {
|
|
pluginKey: string
|
|
tabKey: string
|
|
title: string
|
|
}
|
|
|
|
type ProbeServer = {
|
|
origin: string
|
|
requests: string[]
|
|
close: () => Promise<void>
|
|
}
|
|
|
|
type PanelDocumentSnapshot = {
|
|
url: string
|
|
title: string
|
|
html: string
|
|
}
|
|
|
|
type ElectronFrameProcess = {
|
|
frameTreeNodeId: number
|
|
parentFrameTreeNodeId: number | null
|
|
processId: number
|
|
osProcessId: number
|
|
url: string
|
|
origin: string
|
|
marker: string | null
|
|
}
|
|
|
|
async function closeServer(server: Server): Promise<void> {
|
|
await new Promise<void>((resolve, reject) => {
|
|
server.close((error) => {
|
|
if (error) {
|
|
reject(error)
|
|
return
|
|
}
|
|
resolve()
|
|
})
|
|
})
|
|
}
|
|
|
|
async function startPermissiveProbeServer(): Promise<ProbeServer> {
|
|
const requests: string[] = []
|
|
const gif = Buffer.from('R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=', 'base64')
|
|
const server = createServer((request, response) => {
|
|
requests.push(request.url ?? '/')
|
|
response.setHeader('Access-Control-Allow-Origin', '*')
|
|
if (request.url?.includes('beacon.gif')) {
|
|
response.writeHead(200, { 'Content-Type': 'image/gif', 'Content-Length': gif.byteLength })
|
|
response.end(gif)
|
|
return
|
|
}
|
|
response.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' })
|
|
response.end('permissive probe response')
|
|
})
|
|
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
|
|
const port = (server.address() as AddressInfo).port
|
|
return {
|
|
origin: `http://127.0.0.1:${port}`,
|
|
requests,
|
|
close: () => closeServer(server)
|
|
}
|
|
}
|
|
|
|
async function materializeHostilePlugin(origin: string): Promise<string> {
|
|
const tempRoot = await mkdtemp(join(tmpdir(), 'orca-hostile-panel-e2e-'))
|
|
const pluginRoot = join(tempRoot, 'hostile-panel')
|
|
await cp(join(process.cwd(), 'examples', 'plugins', 'hostile-panel'), pluginRoot, {
|
|
recursive: true
|
|
})
|
|
const panelPath = join(pluginRoot, 'panel.html')
|
|
const panelHtml = await readFile(panelPath, 'utf8')
|
|
await writeFile(panelPath, panelHtml.replaceAll('https://example.com', origin))
|
|
return pluginRoot
|
|
}
|
|
|
|
async function installApprovedPanel(page: Page, sourcePath: string): Promise<InstalledPanel> {
|
|
return page.evaluate(async (pluginPath) => {
|
|
const settings = await window.api.settings.set({ pluginSystemEnabled: true })
|
|
window.__store?.setState({ settings })
|
|
await window.api.plugins.refresh()
|
|
const installed = await window.api.plugins.install({ kind: 'local-path', path: pluginPath })
|
|
if (!installed.ok) {
|
|
throw new Error(installed.error)
|
|
}
|
|
const listed = await window.api.plugins.refresh()
|
|
const plugin = listed.find((entry) => entry.pluginKey === installed.pluginKey)
|
|
if (!plugin?.consentFingerprint || !plugin.panels[0]) {
|
|
throw new Error(`installed plugin ${installed.pluginKey} has no reviewable panel`)
|
|
}
|
|
const approved = await window.api.plugins.consent({
|
|
pluginKey: plugin.pluginKey,
|
|
reviewedFingerprint: plugin.consentFingerprint,
|
|
decision: 'approve'
|
|
})
|
|
const approvedPlugin = approved.find((entry) => entry.pluginKey === plugin.pluginKey)
|
|
const panel = approvedPlugin?.panels[0]
|
|
if (!panel) {
|
|
throw new Error(`approved plugin ${plugin.pluginKey} has no panel`)
|
|
}
|
|
return { pluginKey: plugin.pluginKey, tabKey: panel.tabKey, title: panel.title }
|
|
}, sourcePath)
|
|
}
|
|
|
|
async function openPanel(page: Page, panel: InstalledPanel): Promise<void> {
|
|
await page.evaluate(async () => {
|
|
const store = window.__store?.getState()
|
|
if (!store) {
|
|
throw new Error('window.__store is unavailable')
|
|
}
|
|
if (!store.rightSidebarOpen) {
|
|
store.toggleRightSidebar()
|
|
}
|
|
// Refresh after the sidebar subscription exists so this isolated profile
|
|
// cannot miss the install/consent change events emitted just before mount.
|
|
await window.api.plugins.refresh()
|
|
})
|
|
const panelButton = page.getByRole('button', { name: panel.title })
|
|
await expect(panelButton).toBeVisible({ timeout: 15_000 })
|
|
await panelButton.click()
|
|
await expect(page.locator(`iframe[title="${panel.title}"]`)).toBeVisible({ timeout: 15_000 })
|
|
}
|
|
|
|
async function attachProbeRequests(testInfo: TestInfo, requests: readonly string[]): Promise<void> {
|
|
await testInfo.attach('hostile-panel-loopback-requests', {
|
|
body: Buffer.from(JSON.stringify(requests, null, 2)),
|
|
contentType: 'application/json'
|
|
})
|
|
}
|
|
|
|
async function readPanelDocument(frame: FrameLocator): Promise<PanelDocumentSnapshot> {
|
|
return frame.locator('html').evaluate((element) => ({
|
|
url: element.ownerDocument.location.href,
|
|
title: element.ownerDocument.title,
|
|
html: element.outerHTML
|
|
}))
|
|
}
|
|
|
|
async function inspectElectronFrameProcesses(
|
|
electronApp: ElectronApplication,
|
|
pageUrl: string
|
|
): Promise<ElectronFrameProcess[]> {
|
|
return electronApp.evaluate(async ({ BrowserWindow }, expectedUrl) => {
|
|
const browserWindow =
|
|
BrowserWindow.getAllWindows().find(
|
|
(candidate) => candidate.webContents.getURL() === expectedUrl
|
|
) ?? BrowserWindow.getAllWindows()[0]
|
|
if (!browserWindow) {
|
|
return []
|
|
}
|
|
return Promise.all(
|
|
browserWindow.webContents.mainFrame.framesInSubtree.map(async (frame) => {
|
|
let marker: string | null = null
|
|
try {
|
|
const value = await frame.executeJavaScript(
|
|
"document.querySelector('h1')?.textContent ?? null"
|
|
)
|
|
marker = typeof value === 'string' ? value : null
|
|
} catch {
|
|
// A frame can detach while Chromium reports the live frame tree.
|
|
}
|
|
return {
|
|
frameTreeNodeId: frame.frameTreeNodeId,
|
|
parentFrameTreeNodeId: frame.parent?.frameTreeNodeId ?? null,
|
|
processId: frame.processId,
|
|
osProcessId: frame.osProcessId,
|
|
url: frame.url,
|
|
origin: frame.origin,
|
|
marker
|
|
}
|
|
})
|
|
)
|
|
}, pageUrl)
|
|
}
|
|
|
|
test('contains hostile panel network, navigation, and bridge-flood probes', async ({
|
|
orcaPage
|
|
}, testInfo) => {
|
|
testInfo.annotations.push({ type: 'maturity', description: 'experimental' })
|
|
const server = await startPermissiveProbeServer()
|
|
const pluginRoot = await materializeHostilePlugin(server.origin)
|
|
const tempRoot = join(pluginRoot, '..')
|
|
const appUrl = orcaPage.url()
|
|
const browserEvents: string[] = []
|
|
const panelDocuments: PanelDocumentSnapshot[] = []
|
|
orcaPage.on('console', (message) => {
|
|
browserEvents.push(`console:${message.type()}:${message.text()}`)
|
|
})
|
|
orcaPage.on('pageerror', (error) => {
|
|
browserEvents.push(`pageerror:${error.message}`)
|
|
})
|
|
orcaPage.on('framenavigated', (frame) => {
|
|
browserEvents.push(`framenavigated:${frame.url()}`)
|
|
})
|
|
try {
|
|
const panel = await installApprovedPanel(orcaPage, pluginRoot)
|
|
await openPanel(orcaPage, panel)
|
|
|
|
const iframe = orcaPage.locator(`iframe[title="${panel.title}"]`)
|
|
await expect(iframe).toHaveAttribute('sandbox', 'allow-scripts')
|
|
const frame = orcaPage.frameLocator(`iframe[title="${panel.title}"]`)
|
|
await expect(frame.locator('meta[http-equiv="Content-Security-Policy"]')).toHaveAttribute(
|
|
'content',
|
|
/connect-src 'none'.*img-src data:/
|
|
)
|
|
const initialPanelDebug = await frame.locator('html').evaluate((element) => ({
|
|
readyState: element.ownerDocument.readyState,
|
|
scriptCount: element.ownerDocument.scripts.length,
|
|
resultCount: element.querySelectorAll('[data-probe]').length,
|
|
bodyText: element.ownerDocument.body?.textContent ?? '',
|
|
scriptText: Array.from(element.ownerDocument.scripts, (script) => script.textContent ?? '')
|
|
}))
|
|
await testInfo.attach('hostile-panel-initial-debug', {
|
|
body: Buffer.from(JSON.stringify(initialPanelDebug, null, 2)),
|
|
contentType: 'application/json'
|
|
})
|
|
|
|
for (const probe of ['fetch-exfil', 'img-beacon']) {
|
|
await expect(frame.locator(`[data-probe="${probe}"]`)).toHaveAttribute(
|
|
'data-contained',
|
|
'true',
|
|
{ timeout: 5_000 }
|
|
)
|
|
}
|
|
|
|
await frame.getByRole('button', { name: 'Run bridge budget probes' }).click()
|
|
for (const probe of ['oversized-message', 'message-flood']) {
|
|
await expect(frame.locator(`[data-probe="${probe}"]`)).toHaveAttribute(
|
|
'data-contained',
|
|
'true',
|
|
{ timeout: 5_000 }
|
|
)
|
|
}
|
|
|
|
expect(server.requests).toEqual([])
|
|
expect(orcaPage.url()).toBe(appUrl)
|
|
await expect(iframe).toBeVisible()
|
|
|
|
const initialDocument = await readPanelDocument(frame)
|
|
panelDocuments.push(initialDocument)
|
|
for (const navigation of [
|
|
{ button: 'Try top navigation', probe: 'top-navigation' },
|
|
{ button: 'Try self navigation', probe: 'self-navigation' },
|
|
{ button: 'Try anchor and form navigation', probe: 'anchor-form-navigation' },
|
|
{ button: 'Try meta refresh navigation', probe: 'meta-refresh-navigation' }
|
|
]) {
|
|
await frame.getByRole('button', { name: navigation.button }).click()
|
|
await expect(frame.locator(`[data-probe="${navigation.probe}"]`)).toHaveAttribute(
|
|
'data-contained',
|
|
'true',
|
|
{ timeout: 5_000 }
|
|
)
|
|
const currentDocument = await readPanelDocument(frame)
|
|
panelDocuments.push(currentDocument)
|
|
expect(currentDocument.url).toBe(initialDocument.url)
|
|
expect(currentDocument.html).toContain('Hostile panel fixture')
|
|
expect(server.requests).toEqual([])
|
|
expect(orcaPage.url()).toBe(appUrl)
|
|
}
|
|
} finally {
|
|
await attachProbeRequests(testInfo, server.requests)
|
|
await testInfo.attach('hostile-panel-browser-events', {
|
|
body: Buffer.from(browserEvents.join('\n')),
|
|
contentType: 'text/plain'
|
|
})
|
|
await testInfo.attach('hostile-panel-documents', {
|
|
body: Buffer.from(JSON.stringify(panelDocuments, null, 2)),
|
|
contentType: 'application/json'
|
|
})
|
|
await server.close()
|
|
await rm(tempRoot, { recursive: true, force: true })
|
|
}
|
|
})
|
|
|
|
test('detects and suspends a busy-looping panel in an isolated renderer', async ({
|
|
electronApp,
|
|
orcaPage
|
|
}, testInfo) => {
|
|
testInfo.annotations.push({ type: 'maturity', description: 'experimental' })
|
|
const server = await startPermissiveProbeServer()
|
|
const pluginRoot = await materializeHostilePlugin(server.origin)
|
|
const tempRoot = join(pluginRoot, '..')
|
|
const appUrl = orcaPage.url()
|
|
let frameProcesses: ElectronFrameProcess[] = []
|
|
try {
|
|
const panel = await installApprovedPanel(orcaPage, pluginRoot)
|
|
await openPanel(orcaPage, panel)
|
|
|
|
await expect
|
|
.poll(
|
|
async () => {
|
|
frameProcesses = await inspectElectronFrameProcesses(electronApp, appUrl)
|
|
return frameProcesses.some((frame) => frame.marker === 'Hostile panel fixture')
|
|
},
|
|
{ timeout: 5_000, message: 'hostile panel should appear in Electron frame tree' }
|
|
)
|
|
.toBe(true)
|
|
|
|
const mainFrame = frameProcesses.find((frame) => frame.parentFrameTreeNodeId === null)
|
|
const panelFrame = frameProcesses.find((frame) => frame.marker === 'Hostile panel fixture')
|
|
expect(mainFrame).toBeTruthy()
|
|
expect(panelFrame).toBeTruthy()
|
|
expect(panelFrame?.processId).not.toBe(mainFrame?.processId)
|
|
expect(panelFrame?.osProcessId).not.toBe(mainFrame?.osProcessId)
|
|
|
|
const iframe = orcaPage.locator(`iframe[title="${panel.title}"]`)
|
|
await iframe.evaluate((element) => {
|
|
const panelWindow = (element as HTMLIFrameElement).contentWindow
|
|
panelWindow?.postMessage({ type: 'orca-hostile-busy-probe' }, '*')
|
|
})
|
|
|
|
await expect(
|
|
orcaPage.getByText('This plugin panel stopped responding and was suspended.')
|
|
).toBeVisible({ timeout: 20_000 })
|
|
await expect(
|
|
orcaPage.getByRole('button', { name: new RegExp(`${panel.title}.*Error`) })
|
|
).toBeVisible()
|
|
expect(orcaPage.url()).toBe(appUrl)
|
|
expect(server.requests).toEqual([])
|
|
} finally {
|
|
await testInfo.attach('hostile-panel-frame-processes', {
|
|
body: Buffer.from(JSON.stringify(frameProcesses, null, 2)),
|
|
contentType: 'application/json'
|
|
})
|
|
await attachProbeRequests(testInfo, server.requests)
|
|
await server.close()
|
|
await rm(tempRoot, { recursive: true, force: true })
|
|
}
|
|
})
|