feat(plugins): Orca plugin system — kernel, content packs, panels, workers, marketplace v0 (experimental) (#8549)

* 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>
This commit is contained in:
Neil
2026-07-27 01:14:33 -07:00
committed by GitHub
co-authored by Orca
parent 7dab1e86e2
commit 97e4776dfe
316 changed files with 31576 additions and 456 deletions
@@ -0,0 +1,26 @@
import {
getPluginActivationState,
type PluginConsentLists
} from '../../shared/plugins/plugin-consent-state'
import type { ValidDiscoveredPlugin } from './plugin-discovery'
export function snapshotPluginConsentLists(source: {
getPluginConsents: () => Record<string, string>
getDisabledPlugins: () => string[]
}): PluginConsentLists {
return {
pluginConsents: source.getPluginConsents(),
disabledPlugins: source.getDisabledPlugins()
}
}
export function isPluginApproved(
enabled: boolean,
plugin: ValidDiscoveredPlugin,
lists: PluginConsentLists
): boolean {
return (
enabled &&
getPluginActivationState(plugin.pluginKey, plugin.consentFingerprint, lists) === 'approved'
)
}
@@ -0,0 +1,12 @@
import type { OrcaVmRecipe } from '../../shared/types'
import type { PluginService } from './plugin-service'
export async function getApprovedPluginVmRecipes(
pluginService?: PluginService
): Promise<OrcaVmRecipe[]> {
if (!pluginService) {
return []
}
await pluginService.whenReady()
return pluginService.contentPacks.vmRecipes.list().map(({ recipe }) => recipe)
}
@@ -0,0 +1,193 @@
import { createReadStream } from 'node:fs'
import { realpath, stat } from 'node:fs/promises'
import { isAbsolute, relative, resolve, sep } from 'node:path'
import type { PluginManifest } from '../../shared/plugins/plugin-manifest'
import { parsePluginVmRecipeArtifact } from '../../shared/plugins/plugin-vm-recipe-artifact'
export type PluginArtifactValidationResult = { ok: true } | { ok: false; error: string }
export const PLUGIN_PANEL_ENTRY_MAX_BYTES = 10 * 1024 * 1024
export const PLUGIN_WORKER_ENTRY_MAX_BYTES = 50 * 1024 * 1024
const PLUGIN_ICON_MAX_BYTES = 2 * 1024 * 1024
export const PLUGIN_LANGUAGE_PACK_MAX_BYTES = 5 * 1024 * 1024
export const PLUGIN_VM_RECIPE_MAX_BYTES = 256 * 1024
const PLUGIN_AGENT_PROFILE_MAX_BYTES = 1024 * 1024
type DeclaredArtifact =
| { label: string; path: string; kind: 'file'; maxBytes: number }
| { label: string; path: string; kind: 'directory' }
function declaredArtifactPaths(manifest: PluginManifest): DeclaredArtifact[] {
return [
...(manifest.icon
? [
{
label: 'icon',
path: manifest.icon,
kind: 'file' as const,
maxBytes: PLUGIN_ICON_MAX_BYTES
}
]
: []),
...(manifest.main
? [
{
label: 'worker entry',
path: manifest.main,
kind: 'file' as const,
maxBytes: PLUGIN_WORKER_ENTRY_MAX_BYTES
}
]
: []),
...manifest.contributes.panels.map((panel) => ({
label: `panel "${panel.id}" entry`,
path: panel.entry,
kind: 'file' as const,
maxBytes: PLUGIN_PANEL_ENTRY_MAX_BYTES
})),
...manifest.contributes.languagePacks.map((languagePack) => ({
label: `language pack "${languagePack.locale}"`,
path: languagePack.path,
kind: 'file' as const,
maxBytes: PLUGIN_LANGUAGE_PACK_MAX_BYTES
})),
...manifest.contributes.vmRecipes.map((recipe) => ({
label: 'VM recipe',
path: recipe.path,
kind: 'file' as const,
maxBytes: PLUGIN_VM_RECIPE_MAX_BYTES
})),
...manifest.contributes.agents.map((agent) => ({
label: 'agent profile',
path: agent.path,
kind: 'file' as const,
maxBytes: PLUGIN_AGENT_PROFILE_MAX_BYTES
}))
]
}
export async function resolveContainedPluginArtifact(
rootDir: string,
relativePath: string,
maxBytes = PLUGIN_WORKER_ENTRY_MAX_BYTES
): Promise<string> {
const rootReal = await realpath(resolve(rootDir))
return resolvePathFromRealRoot(rootDir, rootReal, relativePath, 'file', maxBytes)
}
export async function readContainedPluginArtifactText(
rootDir: string,
relativePath: string,
maxBytes: number
): Promise<string> {
const artifact = await resolveContainedPluginArtifact(rootDir, relativePath, maxBytes)
const chunks: Buffer[] = []
let totalBytes = 0
for await (const chunk of createReadStream(artifact)) {
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
totalBytes += bytes.byteLength
if (totalBytes > maxBytes) {
throw new Error(`exceeds the ${maxBytes}-byte artifact limit`)
}
chunks.push(bytes)
}
return Buffer.concat(chunks, totalBytes).toString('utf8')
}
async function resolvePathFromRealRoot(
rootDir: string,
rootReal: string,
relativePath: string,
kind: 'file' | 'directory',
maxBytes?: number
): Promise<string> {
const artifactReal = await realpath(resolve(rootDir, ...relativePath.split(/[\\/]/)))
const fromRoot = relative(rootReal, artifactReal)
if (
fromRoot.length === 0 ||
isAbsolute(fromRoot) ||
fromRoot === '..' ||
fromRoot.startsWith(`..${sep}`)
) {
throw new Error('resolves outside the plugin directory')
}
const artifactStat = await stat(artifactReal)
if (kind === 'file' && !artifactStat.isFile()) {
throw new Error('is not a regular file')
}
if (kind === 'directory' && !artifactStat.isDirectory()) {
throw new Error('is not a directory')
}
if (kind === 'file' && maxBytes !== undefined && artifactStat.size > maxBytes) {
throw new Error(`exceeds the ${maxBytes}-byte artifact limit`)
}
return artifactReal
}
/** Presence and containment checks are bounded by the manifest's declared artifacts. */
export async function validateDeclaredPluginArtifacts(
rootDir: string,
manifest: PluginManifest
): Promise<PluginArtifactValidationResult> {
const artifacts = declaredArtifactPaths(manifest)
if (artifacts.length === 0) {
return { ok: true }
}
const seen = new Set<string>()
let rootReal: string
try {
rootReal = await realpath(resolve(rootDir))
} catch (error) {
return { ok: false, error: error instanceof Error ? error.message : String(error) }
}
for (const artifact of artifacts) {
if (seen.has(artifact.path)) {
continue
}
seen.add(artifact.path)
try {
await resolvePathFromRealRoot(
rootDir,
rootReal,
artifact.path,
artifact.kind,
artifact.kind === 'file' ? artifact.maxBytes : undefined
)
} catch (error) {
return {
ok: false,
error: `${artifact.label} ${artifact.path}: ${error instanceof Error ? error.message : String(error)}`
}
}
}
return { ok: true }
}
/** Parses declared VM recipe artifacts at the immutable install boundary. */
export async function validatePluginInstallContent(
rootDir: string,
manifest: PluginManifest
): Promise<PluginArtifactValidationResult> {
const vmRecipeIds = new Set<string>()
for (const contribution of manifest.contributes.vmRecipes) {
try {
const recipe = parsePluginVmRecipeArtifact(
await readContainedPluginArtifactText(
rootDir,
contribution.path,
PLUGIN_VM_RECIPE_MAX_BYTES
)
)
if (vmRecipeIds.has(recipe.id)) {
throw new Error(`duplicate VM recipe id "${recipe.id}"`)
}
vmRecipeIds.add(recipe.id)
} catch (error) {
return {
ok: false,
error: `VM recipe ${contribution.path}: ${error instanceof Error ? error.message : String(error)}`
}
}
}
return { ok: true }
}
@@ -0,0 +1,187 @@
import { mkdtemp, readFile, readdir, rm, stat } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type * as FsPromises from 'node:fs/promises'
import {
renamePluginFileWithWindowsRetry,
writePluginFileAtomically
} from './plugin-atomic-file-write'
// Windows AV/indexer locks cannot be provoked on CI, so queue the errno codes instead.
const locks = vi.hoisted(() => ({ codes: [] as string[] }))
vi.mock('node:fs/promises', async (importOriginal) => {
const actual = await importOriginal<typeof FsPromises>()
return {
...actual,
rename: async (source: string, target: string) => {
const code = locks.codes.shift()
if (!code) {
return actual.rename(source, target)
}
throw Object.assign(new Error(`simulated ${code}`), { code })
}
}
})
function withPlatform(platform: string): () => void {
const original = Object.getOwnPropertyDescriptor(process, 'platform')
Object.defineProperty(process, 'platform', { value: platform, configurable: true })
return () => {
if (original) {
Object.defineProperty(process, 'platform', original)
}
}
}
describe('writePluginFileAtomically', () => {
let dir: string
beforeEach(async () => {
dir = await mkdtemp(join(tmpdir(), 'orca-plugin-atomic-'))
})
afterEach(async () => {
await rm(dir, { recursive: true, force: true })
})
it('writes contents and leaves no temp file behind', async () => {
const target = join(dir, 'current')
await writePluginFileAtomically(target, 'abc123')
expect(await readFile(target, 'utf8')).toBe('abc123')
expect(await readdir(dir)).toEqual(['current'])
})
it('replaces an existing file', async () => {
const target = join(dir, 'plugins.lock.json')
await writePluginFileAtomically(target, 'first')
await writePluginFileAtomically(target, 'second')
expect(await readFile(target, 'utf8')).toBe('second')
expect(await readdir(dir)).toEqual(['plugins.lock.json'])
})
it('applies the requested mode', async () => {
const target = join(dir, 'provenance.json')
await writePluginFileAtomically(target, '{}', { mode: 0o600 })
const mode = (await stat(target)).mode & 0o777
// Windows does not model POSIX permission bits.
if (process.platform !== 'win32') {
expect(mode).toBe(0o600)
}
})
it('cleans up the temp file when the write fails', async () => {
await expect(writePluginFileAtomically(join(dir, 'missing', 'x'), 'v')).rejects.toThrow()
expect(await readdir(dir)).toEqual([])
})
it('cleans up the temp file when the rename gives up', async () => {
const restorePlatform = withPlatform('win32')
locks.codes = Array.from({ length: 6 }, () => 'EPERM')
try {
await expect(writePluginFileAtomically(join(dir, 'current'), 'v')).rejects.toMatchObject({
code: 'EPERM'
})
expect(await readdir(dir)).toEqual([])
} finally {
restorePlatform()
locks.codes = []
}
})
it('runs concurrent writers to one target without leaking temp files', async () => {
const target = join(dir, 'sources.json')
await Promise.all(
Array.from({ length: 8 }, (_unused, index) =>
writePluginFileAtomically(target, `value-${index}`)
)
)
expect(await readdir(dir)).toEqual(['sources.json'])
expect(await readFile(target, 'utf8')).toMatch(/^value-\d$/)
})
})
describe('renamePluginFileWithWindowsRetry', () => {
it('renames when the source exists', async () => {
const dir = await mkdtemp(join(tmpdir(), 'orca-plugin-rename-'))
try {
await writePluginFileAtomically(join(dir, 'from'), 'payload')
await renamePluginFileWithWindowsRetry(join(dir, 'from'), join(dir, 'to'))
expect(await readFile(join(dir, 'to'), 'utf8')).toBe('payload')
} finally {
await rm(dir, { recursive: true, force: true })
}
})
it('rethrows a non-retryable error', async () => {
const dir = await mkdtemp(join(tmpdir(), 'orca-plugin-rename-'))
try {
await expect(
renamePluginFileWithWindowsRetry(join(dir, 'absent'), join(dir, 'to'))
).rejects.toMatchObject({ code: 'ENOENT' })
} finally {
await rm(dir, { recursive: true, force: true })
}
})
describe('on Windows', () => {
let dir: string
let restorePlatform: () => void
beforeEach(async () => {
dir = await mkdtemp(join(tmpdir(), 'orca-plugin-rename-win-'))
restorePlatform = withPlatform('win32')
})
afterEach(async () => {
restorePlatform()
locks.codes = []
await rm(dir, { recursive: true, force: true })
})
it.each(['EPERM', 'EACCES', 'EBUSY'])('retries past a transient %s lock', async (code) => {
await writePluginFileAtomically(join(dir, 'from'), 'payload')
locks.codes = [code, code]
await renamePluginFileWithWindowsRetry(join(dir, 'from'), join(dir, 'to'))
expect(await readFile(join(dir, 'to'), 'utf8')).toBe('payload')
expect(locks.codes).toEqual([])
})
it('gives up after the last delay rather than looping forever', async () => {
await writePluginFileAtomically(join(dir, 'from'), 'payload')
// One more lock than there are delays, so the loop must exit on the bound.
locks.codes = Array.from({ length: 6 }, () => 'EBUSY')
await expect(
renamePluginFileWithWindowsRetry(join(dir, 'from'), join(dir, 'to'))
).rejects.toMatchObject({ code: 'EBUSY' })
expect(locks.codes).toEqual([])
})
it('rethrows a non-retryable code without retrying', async () => {
await writePluginFileAtomically(join(dir, 'from'), 'payload')
locks.codes = ['ENOSPC', 'ENOSPC']
await expect(
renamePluginFileWithWindowsRetry(join(dir, 'from'), join(dir, 'to'))
).rejects.toMatchObject({ code: 'ENOSPC' })
expect(locks.codes).toEqual(['ENOSPC'])
})
})
it('does not retry off Windows', async () => {
const dir = await mkdtemp(join(tmpdir(), 'orca-plugin-rename-posix-'))
const restorePlatform = withPlatform('linux')
try {
await writePluginFileAtomically(join(dir, 'from'), 'payload')
locks.codes = ['EPERM', 'EPERM']
await expect(
renamePluginFileWithWindowsRetry(join(dir, 'from'), join(dir, 'to'))
).rejects.toMatchObject({ code: 'EPERM' })
expect(locks.codes).toEqual(['EPERM'])
} finally {
restorePlatform()
locks.codes = []
await rm(dir, { recursive: true, force: true })
}
})
})
@@ -0,0 +1,55 @@
import { randomUUID } from 'node:crypto'
import { rename, rm, writeFile } from 'node:fs/promises'
/**
* Atomic write for plugin state files (lockfile, provenance, pointers, caches).
*
* Why the retry: on Windows the rename can fail with EPERM/EACCES/EBUSY while
* antivirus or an indexer holds the target open (issue #1507). The repo's
* existing `renameFileWithWindowsRetry` covers the same hazard but is sync;
* every plugin write path is async, so the backoff parks on a timer instead.
*/
const WINDOWS_RENAME_RETRY_DELAYS_MS = [50, 100, 150, 200, 250]
export type PluginAtomicWriteOptions = { mode?: number }
export async function writePluginFileAtomically(
target: string,
contents: string,
options?: PluginAtomicWriteOptions
): Promise<void> {
// Unique temp name so concurrent writers in one plugins dir cannot collide.
const temporary = `${target}.${process.pid}.${randomUUID()}.tmp`
try {
await writeFile(temporary, contents, { encoding: 'utf8', mode: options?.mode })
await renamePluginFileWithWindowsRetry(temporary, target)
} finally {
await rm(temporary, { force: true }).catch(() => undefined)
}
}
export async function renamePluginFileWithWindowsRetry(
source: string,
target: string
): Promise<void> {
for (let attempt = 0; ; attempt += 1) {
try {
await rename(source, target)
return
} catch (error) {
const code = (error as NodeJS.ErrnoException).code
const retryable = code === 'EPERM' || code === 'EACCES' || code === 'EBUSY'
if (
process.platform !== 'win32' ||
!retryable ||
attempt >= WINDOWS_RENAME_RETRY_DELAYS_MS.length
) {
throw error
}
await new Promise<void>((resolve) =>
setTimeout(resolve, WINDOWS_RENAME_RETRY_DELAYS_MS[attempt])
)
}
}
}
+38
View File
@@ -0,0 +1,38 @@
import { mkdtemp, rm, stat } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { PluginAuditLog } from './plugin-audit-log'
const roots: string[] = []
afterEach(async () => {
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })))
})
describe('PluginAuditLog retention', () => {
it('rotates bounded segments while preserving recent entries across the boundary', async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-plugin-audit-'))
roots.push(root)
const audit = new PluginAuditLog(root, { maxBytes: 240 })
for (let index = 0; index < 8; index += 1) {
await audit.record({
ts: index,
actor: 'plugin:orca-samples.demo',
method: 'storage.set',
summary: `key=${index}`,
outcome: 'ok'
})
}
await expect(stat(join(root, 'audit.log'))).resolves.toMatchObject({
isFile: expect.any(Function)
})
await expect(stat(join(root, 'audit.log.1'))).resolves.toMatchObject({
isFile: expect.any(Function)
})
const recent = await audit.readRecent(3)
expect(recent.map((entry) => entry.ts)).toEqual([5, 6, 7])
})
})
+86
View File
@@ -0,0 +1,86 @@
import { appendFile, mkdir, readFile, rename, rm, stat } from 'node:fs/promises'
import { dirname, join } from 'node:path'
/**
* Append-only audit trail for host-API mutations performed on a plugin's
* behalf, with actor `plugin:<qualifiedKey>`. One JSONL file so support and
* enterprise policy tooling can replay exactly what plugins did through the
* gated API. (Honest scope: worker code acting through its own Node access
* bypasses this — stated in the consent UI.) Mutation intents are awaited
* before their handler runs so an API-mediated write cannot outrun the log.
*/
export type PluginAuditEntry = {
ts: number
actor: `plugin:${string}`
method: string
/** Bounded summary — never full params (they may contain user content). */
summary: string
outcome: 'attempt' | 'ok' | 'error'
}
export class PluginAuditLog {
private readonly filePath: string
private readonly rotatedFilePath: string
private readonly maxBytes: number
private writeChain: Promise<void> = Promise.resolve()
private fileBytes: number | null = null
constructor(pluginsDataDir: string, options: { maxBytes?: number } = {}) {
this.filePath = join(pluginsDataDir, 'audit.log')
this.rotatedFilePath = join(pluginsDataDir, 'audit.log.1')
this.maxBytes = options.maxBytes ?? 10 * 1024 * 1024
}
record(entry: PluginAuditEntry): Promise<void> {
const write = this.writeChain.then(async () => {
await mkdir(dirname(this.filePath), { recursive: true })
const line = `${JSON.stringify(entry)}\n`
if (this.fileBytes === null) {
this.fileBytes = await stat(this.filePath).then(
(file) => file.size,
() => 0
)
}
const lineBytes = Buffer.byteLength(line, 'utf8')
if (this.fileBytes > 0 && this.fileBytes + lineBytes > this.maxBytes) {
await rm(this.rotatedFilePath, { force: true })
await rename(this.filePath, this.rotatedFilePath).catch((error) => {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
throw error
}
})
this.fileBytes = 0
}
await appendFile(this.filePath, line, 'utf8')
this.fileBytes += lineBytes
})
// Keep the serialization chain usable after a failed append while still
// exposing this write's failure to the mutation chokepoint.
this.writeChain = write.catch(() => undefined)
return write
}
async flush(): Promise<void> {
await this.writeChain
}
async readRecent(limit = 200): Promise<PluginAuditEntry[]> {
try {
const [rotated, current] = await Promise.all(
[this.rotatedFilePath, this.filePath].map((path) => readFile(path, 'utf8').catch(() => ''))
)
const text = rotated + current
const lines = text.split('\n').filter((line) => line.length > 0)
return lines.slice(-limit).flatMap((line) => {
try {
return [JSON.parse(line) as PluginAuditEntry]
} catch {
return []
}
})
} catch {
return []
}
}
}
@@ -0,0 +1,74 @@
import { describe, expect, it, vi } from 'vitest'
import type { PluginBundledBootstrapResult } from './plugin-bundled-bootstrap'
import { PluginBundledBootstrapCoordinator } from './plugin-bundled-bootstrap-coordinator'
const unchanged: PluginBundledBootstrapResult = {
installed: [],
unchanged: ['stablyai.orca-theme'],
errors: []
}
describe('PluginBundledBootstrapCoordinator', () => {
it('skips disabled requests and refreshes discovery only after publication', async () => {
let enabled = false
const bootstrap = vi
.fn()
.mockResolvedValueOnce(unchanged)
.mockResolvedValueOnce({
installed: ['stablyai.orca-theme'],
unchanged: [],
errors: []
})
const refreshPlugins = vi.fn().mockResolvedValue(undefined)
const coordinator = new PluginBundledBootstrapCoordinator({
root: 'resources',
userDataPath: 'user-data',
hostVersion: '1.4.0',
isEnabled: () => enabled,
refreshPlugins,
bootstrap
})
await expect(coordinator.request()).resolves.toBeNull()
enabled = true
await expect(coordinator.request()).resolves.toEqual(unchanged)
expect(refreshPlugins).not.toHaveBeenCalled()
await coordinator.request()
expect(refreshPlugins).toHaveBeenCalledOnce()
})
it('serializes overlapping startup and feature-toggle requests', async () => {
let active = 0
let maximumActive = 0
let releaseFirst: (() => void) | undefined
const firstGate = new Promise<void>((resolve) => {
releaseFirst = resolve
})
const bootstrap = vi.fn(async (): Promise<PluginBundledBootstrapResult> => {
active += 1
maximumActive = Math.max(maximumActive, active)
if (bootstrap.mock.calls.length === 1) {
await firstGate
}
active -= 1
return unchanged
})
const coordinator = new PluginBundledBootstrapCoordinator({
root: 'resources',
userDataPath: 'user-data',
hostVersion: '1.4.0',
isEnabled: () => true,
refreshPlugins: vi.fn().mockResolvedValue(undefined),
bootstrap
})
const first = coordinator.request()
const second = coordinator.request()
await vi.waitFor(() => expect(bootstrap).toHaveBeenCalledTimes(1))
releaseFirst?.()
await Promise.all([first, second])
expect(bootstrap).toHaveBeenCalledTimes(2)
expect(maximumActive).toBe(1)
})
})
@@ -0,0 +1,48 @@
import {
bootstrapBundledPlugins,
type PluginBundledBootstrapResult
} from './plugin-bundled-bootstrap'
type PluginBundledBootstrapRequest = Parameters<typeof bootstrapBundledPlugins>[0]
export class PluginBundledBootstrapCoordinator {
private readonly options: PluginBundledBootstrapRequest & {
isEnabled: () => boolean
refreshPlugins: () => Promise<void>
bootstrap?: typeof bootstrapBundledPlugins
}
private pending: Promise<void> = Promise.resolve()
constructor(options: PluginBundledBootstrapCoordinator['options']) {
this.options = options
}
request(): Promise<PluginBundledBootstrapResult | null> {
const run = this.pending.then(() => this.runOnce())
// Why: feature-toggle and startup requests can overlap; preserve their
// order even when one resource read fails.
this.pending = run.then(
() => undefined,
() => undefined
)
return run
}
private async runOnce(): Promise<PluginBundledBootstrapResult | null> {
if (!this.options.isEnabled()) {
return null
}
const result = await (this.options.bootstrap ?? bootstrapBundledPlugins)({
root: this.options.root,
userDataPath: this.options.userDataPath,
hostVersion: this.options.hostVersion,
...(this.options.blockedPluginReason
? { blockedPluginReason: this.options.blockedPluginReason }
: {})
})
if (result.installed.length > 0) {
await this.options.refreshPlugins()
}
return result
}
}
@@ -0,0 +1,134 @@
import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { hashPluginTree } from './plugin-content-hash'
import { readPluginLockfile } from './plugin-install'
import { bootstrapBundledPlugins, resolveBundledPluginRoot } from './plugin-bundled-bootstrap'
const roots: string[] = []
async function tempRoot(prefix: string): Promise<string> {
const root = await mkdtemp(join(tmpdir(), prefix))
roots.push(root)
return root
}
async function writeBundle(root: string, name = 'Skills'): Promise<{ path: string; hash: string }> {
const path = 'stablyai.orca-skills'
const pluginRoot = join(root, path)
await mkdir(pluginRoot, { recursive: true })
await writeFile(
join(pluginRoot, 'orca-plugin.json'),
JSON.stringify({
manifestVersion: 1,
id: 'orca-skills',
publisher: 'stablyai',
name,
version: '1.0.0',
engines: { orca: '>=1.0.0' },
pluginApi: 1,
capabilities: []
})
)
const hashed = await hashPluginTree(pluginRoot)
if (!hashed.ok) {
throw new Error(hashed.error)
}
return { path, hash: hashed.hash }
}
async function writeIndex(root: string, path: string, contentHash: string): Promise<void> {
await writeFile(
join(root, 'bundled-plugins.json'),
JSON.stringify({
version: 1,
plugins: [{ pluginKey: 'stablyai.orca-skills', path, contentHash }]
})
)
}
afterEach(async () => {
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })))
})
describe('bundled plugin bootstrap', () => {
it('installs release-indexed content once and keeps unchanged startup work bounded', async () => {
const root = await tempRoot('orca-bundled-resources-')
const userDataPath = await tempRoot('orca-bundled-user-data-')
const bundle = await writeBundle(root)
await writeIndex(root, bundle.path, bundle.hash)
await expect(
bootstrapBundledPlugins({ root, userDataPath, hostVersion: '1.4.0' })
).resolves.toEqual({ installed: ['stablyai.orca-skills'], unchanged: [], errors: [] })
await expect(
bootstrapBundledPlugins({ root, userDataPath, hostVersion: '1.4.0' })
).resolves.toEqual({ installed: [], unchanged: ['stablyai.orca-skills'], errors: [] })
})
it('publishes an updated immutable bundle only when the indexed hash matches', async () => {
const root = await tempRoot('orca-bundled-resources-')
const userDataPath = await tempRoot('orca-bundled-user-data-')
const first = await writeBundle(root)
await writeIndex(root, first.path, first.hash)
await bootstrapBundledPlugins({ root, userDataPath, hostVersion: '1.4.0' })
const second = await writeBundle(root, 'Updated Skills')
await writeIndex(root, second.path, second.hash)
const updated = await bootstrapBundledPlugins({ root, userDataPath, hostVersion: '1.4.0' })
expect(updated).toEqual({ installed: ['stablyai.orca-skills'], unchanged: [], errors: [] })
const lock = await readPluginLockfile(join(userDataPath, 'plugins'))
expect(lock.plugins['stablyai.orca-skills']?.contentHash).toBe(second.hash)
})
it('repairs a missing or modified bundled current version', async () => {
const root = await tempRoot('orca-bundled-resources-')
const userDataPath = await tempRoot('orca-bundled-user-data-')
const bundle = await writeBundle(root)
await writeIndex(root, bundle.path, bundle.hash)
await bootstrapBundledPlugins({ root, userDataPath, hostVersion: '1.4.0' })
const versionDir = join(userDataPath, 'plugins', 'stablyai.orca-skills', bundle.hash)
await writeFile(join(versionDir, 'orca-plugin.json'), '{}')
await expect(
bootstrapBundledPlugins({ root, userDataPath, hostVersion: '1.4.0' })
).resolves.toEqual({ installed: ['stablyai.orca-skills'], unchanged: [], errors: [] })
await rm(versionDir, { recursive: true, force: true })
await expect(
bootstrapBundledPlugins({ root, userDataPath, hostVersion: '1.4.0' })
).resolves.toEqual({ installed: ['stablyai.orca-skills'], unchanged: [], errors: [] })
})
it('refuses mismatched release hashes before publication', async () => {
const root = await tempRoot('orca-bundled-resources-')
const userDataPath = await tempRoot('orca-bundled-user-data-')
const bundle = await writeBundle(root)
await writeIndex(root, bundle.path, 'f'.repeat(64))
const result = await bootstrapBundledPlugins({ root, userDataPath, hostVersion: '1.4.0' })
expect(result.installed).toEqual([])
expect(result.errors[0]?.error).toContain('does not match its release index')
expect((await readPluginLockfile(join(userDataPath, 'plugins'))).plugins).toEqual({})
})
it('resolves packaged and development resource roots without platform separators', () => {
expect(
resolveBundledPluginRoot({
isPackaged: true,
resourcesPath: join('app', 'resources'),
appPath: join('repo', 'app')
})
).toBe(join('app', 'resources', 'plugins', 'launch'))
expect(
resolveBundledPluginRoot({
isPackaged: false,
resourcesPath: join('app', 'resources'),
appPath: join('repo', 'app')
})
).toBe(join('repo', 'app', 'resources', 'plugins', 'launch'))
})
})
@@ -0,0 +1,154 @@
import { readFile, realpath, stat } from 'node:fs/promises'
import { isAbsolute, join, relative, sep } from 'node:path'
import { z } from 'zod'
import { isQualifiedPluginKey } from '../../shared/plugins/plugin-manifest'
import { pluginRelativeDirectorySchema } from '../../shared/plugins/plugin-manifest-fields'
import { isOfficialPluginIdentity } from '../../shared/plugins/plugin-marketplace'
import { getUserPluginsDir } from './plugin-discovery'
import { installBundledPlugin, readPluginLockfile } from './plugin-install'
import { inspectPluginInstallTree } from './plugin-install-staging'
import { readPluginCurrentPointer } from './plugin-current-pointer'
import { hashPluginTree } from './plugin-content-hash'
export const BUNDLED_PLUGIN_INDEX_FILENAME = 'bundled-plugins.json'
const BUNDLED_PLUGIN_INDEX_MAX_BYTES = 64 * 1024
const bundledPluginIndexSchema = z
.object({
version: z.literal(1),
plugins: z
.array(
z
.object({
pluginKey: z
.string()
.refine(isQualifiedPluginKey, 'invalid qualified plugin identity')
.refine(isOfficialPluginIdentity, 'bundled plugins must use an official identity'),
path: pluginRelativeDirectorySchema,
contentHash: z.string().regex(/^[0-9a-f]{64}$/)
})
.strict()
)
.max(32)
})
.strict()
.superRefine((index, ctx) => {
const keys = new Set<string>()
for (const [entryIndex, plugin] of index.plugins.entries()) {
if (keys.has(plugin.pluginKey)) {
ctx.addIssue({
code: 'custom',
path: ['plugins', entryIndex, 'pluginKey'],
message: 'duplicate bundled plugin identity'
})
}
keys.add(plugin.pluginKey)
}
})
export type PluginBundledBootstrapResult = {
installed: string[]
unchanged: string[]
errors: { pluginKey: string; error: string }[]
}
export function resolveBundledPluginRoot(options: {
isPackaged: boolean
resourcesPath: string
appPath: string
}): string {
return options.isPackaged
? join(options.resourcesPath, 'plugins', 'launch')
: join(options.appPath, 'resources', 'plugins', 'launch')
}
async function readBundledPluginIndex(
root: string
): Promise<z.infer<typeof bundledPluginIndexSchema>> {
const indexPath = join(root, BUNDLED_PLUGIN_INDEX_FILENAME)
const metadata = await stat(indexPath)
if (!metadata.isFile() || metadata.size > BUNDLED_PLUGIN_INDEX_MAX_BYTES) {
throw new Error(`bundled plugin index exceeds ${BUNDLED_PLUGIN_INDEX_MAX_BYTES} bytes`)
}
return bundledPluginIndexSchema.parse(JSON.parse(await readFile(indexPath, 'utf8')))
}
async function resolveBundlePath(root: string, path: string): Promise<string> {
const [resolvedRoot, resolvedPath] = await Promise.all([
realpath(root),
realpath(join(root, path))
])
const fromRoot = relative(resolvedRoot, resolvedPath)
if (!fromRoot || fromRoot === '..' || fromRoot.startsWith(`..${sep}`) || isAbsolute(fromRoot)) {
throw new Error('bundled plugin path escapes the resource root')
}
return resolvedPath
}
async function bundledInstallIsIntact(
pluginsDir: string,
pluginKey: string,
contentHash: string
): Promise<boolean> {
const pluginDir = join(pluginsDir, pluginKey)
if ((await readPluginCurrentPointer(pluginDir).catch(() => null)) !== contentHash) {
return false
}
const hashed = await hashPluginTree(join(pluginDir, contentHash))
return hashed.ok && hashed.hash === contentHash
}
export async function bootstrapBundledPlugins(options: {
root: string
userDataPath: string
hostVersion: string
blockedPluginReason?: (pluginKey: string) => string | null
}): Promise<PluginBundledBootstrapResult> {
const index = await readBundledPluginIndex(options.root)
const pluginsDir = getUserPluginsDir(options.userDataPath)
const lock = await readPluginLockfile(pluginsDir)
const result: PluginBundledBootstrapResult = { installed: [], unchanged: [], errors: [] }
for (const entry of index.plugins) {
const locked = lock.plugins[entry.pluginKey]
if (
locked?.source.kind === 'bundled' &&
locked.source.bundleId === entry.pluginKey &&
locked.contentHash === entry.contentHash &&
(await bundledInstallIsIntact(pluginsDir, entry.pluginKey, entry.contentHash))
) {
result.unchanged.push(entry.pluginKey)
continue
}
try {
const sourcePath = await resolveBundlePath(options.root, entry.path)
const inspection = await inspectPluginInstallTree({
rootDir: sourcePath,
hostVersion: options.hostVersion,
expectedPluginKey: entry.pluginKey
})
if (!inspection.ok) {
throw new Error(inspection.error)
}
if (inspection.contentHash !== entry.contentHash) {
throw new Error('bundled plugin content does not match its release index')
}
const installed = await installBundledPlugin({
pluginsDir,
sourcePath,
hostVersion: options.hostVersion,
expectedPluginKey: entry.pluginKey,
blockedPluginReason: options.blockedPluginReason
})
if (!installed.ok) {
throw new Error(installed.error)
}
result.installed.push(entry.pluginKey)
} catch (error) {
result.errors.push({
pluginKey: entry.pluginKey,
error: error instanceof Error ? error.message : String(error)
})
}
}
return result
}
@@ -0,0 +1,13 @@
import type { ValidDiscoveredPlugin } from './plugin-discovery'
export function assertPluginWorkerCommand(plugin: ValidDiscoveredPlugin, commandId: string): void {
const command = plugin.manifest.contributes.commands.find((entry) => entry.id === commandId)
if (!command) {
throw new Error(`plugin ${plugin.pluginKey} does not contribute command ${commandId}`)
}
// Declarative aliases are renderer-owned and must never cross the worker
// activation boundary, even if a compromised renderer invokes IPC directly.
if (command.action !== undefined) {
throw new Error(`plugin ${plugin.pluginKey} command ${commandId} is a built-in action alias`)
}
}
@@ -0,0 +1,180 @@
import { describe, expect, it } from 'vitest'
import { fingerprintPluginConsent } from '../../shared/plugins/plugin-consent-fingerprint'
import { pluginManifestSchema } from '../../shared/plugins/plugin-manifest'
import type { ValidDiscoveredPlugin } from './plugin-discovery'
import { PluginCommandRegistry } from './plugin-command-registry'
function commandPlugin(
id: string,
contributes: {
commands: Record<string, unknown>[]
keybindings?: Record<string, unknown>[]
}
): ValidDiscoveredPlugin {
const manifest = pluginManifestSchema.parse({
manifestVersion: 1,
id,
publisher: 'orca-samples',
name: id,
version: '1.0.0',
engines: { orca: '>=1.0.0' },
pluginApi: 1,
...(contributes.commands.some((command) => command.action === undefined)
? { main: 'worker.js' }
: {}),
contributes,
capabilities: []
})
return {
pluginKey: `orca-samples.${id}`,
rootDir: `/plugins/${id}`,
manifest,
consentFingerprint: fingerprintPluginConsent(manifest, `content-${id}`),
consentContentHash: `content-${id}`,
contentHash: `content-${id}`,
isDev: false
}
}
describe('PluginCommandRegistry', () => {
it('retains pending previews and exposes only approved commands', () => {
const plugin = commandPlugin('aliases', {
commands: [{ id: 'tasks', title: 'Open Tasks', action: 'view.tasks' }],
keybindings: [{ command: 'tasks', key: 'mod+alt+t' }]
})
const registry = new PluginCommandRegistry()
registry.reconcile([plugin], () => false)
expect(registry.list()).toEqual([])
expect(registry.preview(plugin.pluginKey)).toEqual([
{
pluginKey: plugin.pluginKey,
id: 'tasks',
title: 'Open Tasks',
context: 'global',
handler: { type: 'built-in', action: 'view.tasks' },
keybindings: [{ key: 'Mod+Alt+T', when: 'global' }]
}
])
registry.reconcile([plugin], () => true)
expect(registry.list()).toHaveLength(1)
})
it('projects worker commands and inherited worktree keybinding context', () => {
const plugin = commandPlugin('worker', {
commands: [{ id: 'create', title: 'Create Task', context: 'worktree' }],
keybindings: [{ command: 'create', key: 'Mod+Shift+A' }]
})
const registry = new PluginCommandRegistry()
registry.reconcile([plugin], () => true)
expect(registry.list()).toMatchObject([
{
context: 'worktree',
handler: { type: 'worker' },
keybindings: [{ key: 'Mod+Shift+A', when: 'worktree' }]
}
])
})
it('errors approved plugins whose keybindings overlap', () => {
const global = commandPlugin('global', {
commands: [{ id: 'tasks', title: 'Tasks', action: 'view.tasks' }],
keybindings: [{ command: 'tasks', key: 'Mod+Alt+T', when: 'global' }]
})
const worktree = commandPlugin('worktree', {
commands: [{ id: 'tasks', title: 'Tasks', context: 'worktree', action: 'view.tasks' }],
keybindings: [{ command: 'tasks', key: 'Mod+Alt+T', when: 'worktree' }]
})
const registry = new PluginCommandRegistry()
registry.reconcile([global, worktree], () => true)
expect(registry.list()).toEqual([])
expect(registry.error(global.pluginKey)).toContain('conflicts')
expect(registry.error(worktree.pluginKey)).toContain('conflicts')
})
it('uses saved effective bindings to recover conflicting plugins', () => {
const first = commandPlugin('first', {
commands: [{ id: 'tasks', title: 'Tasks', action: 'view.tasks' }],
keybindings: [{ command: 'tasks', key: 'Mod+Alt+T' }]
})
const second = commandPlugin('second', {
commands: [{ id: 'tasks', title: 'Tasks', action: 'view.tasks' }],
keybindings: [{ command: 'tasks', key: 'Mod+Alt+T' }]
})
const registry = new PluginCommandRegistry()
registry.reconcile(
[first, second],
() => true,
{ 'plugin:orca-samples.first/tasks': ['Mod+Shift+T'] },
'linux'
)
expect(registry.list()).toHaveLength(2)
expect(registry.error(first.pluginKey)).toBeNull()
expect(registry.error(second.pluginKey)).toBeNull()
})
it('rejects conflicting saved bindings within one plugin', () => {
const plugin = commandPlugin('aliases', {
commands: [
{ id: 'tasks', title: 'Tasks', action: 'view.tasks' },
{ id: 'sidebar', title: 'Sidebar', action: 'sidebar.left.toggle' }
]
})
const registry = new PluginCommandRegistry()
registry.reconcile(
[plugin],
() => true,
{
'plugin:orca-samples.aliases/tasks': ['Mod+Alt+T'],
'plugin:orca-samples.aliases/sidebar': ['Mod+Alt+T']
},
'linux'
)
expect(registry.list()).toEqual([])
expect(registry.error(plugin.pluginKey)).toContain('conflicts')
})
it('detects cross-platform Mod and physical Ctrl conflicts', () => {
const portable = commandPlugin('portable', {
commands: [{ id: 'tasks', title: 'Tasks', action: 'view.tasks' }],
keybindings: [{ command: 'tasks', key: 'Mod+Alt+T' }]
})
const physical = commandPlugin('physical', {
commands: [{ id: 'tasks', title: 'Tasks', action: 'view.tasks' }],
keybindings: [{ command: 'tasks', key: 'Ctrl+Alt+T' }]
})
const registry = new PluginCommandRegistry()
registry.reconcile([portable, physical], () => true, {}, 'linux')
expect(registry.list()).toEqual([])
expect(registry.error(portable.pluginKey)).toContain('conflicts')
expect(registry.error(physical.pluginKey)).toContain('conflicts')
})
it('allows the same worktree-only chord after one plugin is disabled', () => {
const first = commandPlugin('first', {
commands: [{ id: 'tasks', title: 'Tasks', context: 'worktree', action: 'view.tasks' }],
keybindings: [{ command: 'tasks', key: 'Mod+Alt+T' }]
})
const second = commandPlugin('second', {
commands: [{ id: 'tasks', title: 'Tasks', context: 'worktree', action: 'view.tasks' }],
keybindings: [{ command: 'tasks', key: 'Mod+Alt+T' }]
})
const registry = new PluginCommandRegistry()
registry.reconcile([first, second], (plugin) => plugin === first)
expect(registry.list()).toHaveLength(1)
expect(registry.error(first.pluginKey)).toBeNull()
})
})
+167
View File
@@ -0,0 +1,167 @@
import {
pluginCommandKeybindingActionId,
type PluginCommandAliasActionId
} from '../../shared/plugins/plugin-command-actions'
import { getKeybindingConflictIdentity, type KeybindingOverrides } from '../../shared/keybindings'
import type {
PluginCommandContribution,
PluginManifest
} from '../../shared/plugins/plugin-manifest'
import type { PluginKeybindingContribution } from '../../shared/plugins/plugin-content-pack-contributions'
import {
isInvalidDiscoveredPlugin,
type DiscoveredPlugin,
type ValidDiscoveredPlugin
} from './plugin-discovery'
export type PluginCommandKeybinding = {
key: string
when: 'global' | 'worktree'
}
export type PluginCommandRegistration = {
pluginKey: string
id: string
title: string
context: 'global' | 'worktree'
handler: { type: 'built-in'; action: PluginCommandAliasActionId } | { type: 'worker' }
keybindings: PluginCommandKeybinding[]
}
type CommandOwner = {
pluginKey: string
context: PluginCommandKeybinding['when']
key: string
}
export class PluginCommandRegistry {
private active: PluginCommandRegistration[] = []
private readonly previews = new Map<string, PluginCommandRegistration[]>()
private readonly errors = new Map<string, string>()
list(): readonly PluginCommandRegistration[] {
return this.active
}
preview(pluginKey: string): readonly PluginCommandRegistration[] {
return this.previews.get(pluginKey) ?? []
}
error(pluginKey: string): string | null {
return this.errors.get(pluginKey) ?? null
}
reconcile(
discovered: readonly DiscoveredPlugin[],
isApproved: (plugin: ValidDiscoveredPlugin) => boolean,
overrides: KeybindingOverrides = {},
platform: NodeJS.Platform = process.platform
): void {
const candidates = discovered.filter(
(plugin): plugin is ValidDiscoveredPlugin =>
!isInvalidDiscoveredPlugin(plugin) && plugin.manifest.contributes.commands.length > 0
)
const registrations = candidates.map((plugin) => ({
pluginKey: plugin.pluginKey,
approved: isApproved(plugin),
commands: registrationsForManifest(plugin.pluginKey, plugin.manifest)
}))
this.previews.clear()
this.errors.clear()
for (const plugin of registrations) {
this.previews.set(plugin.pluginKey, plugin.commands)
}
const approved = registrations.filter((plugin) => plugin.approved)
const chordOwners = new Map<string, CommandOwner[]>()
for (const plugin of approved) {
for (const command of plugin.commands) {
for (const keybinding of effectiveCommandKeybindings(command, overrides)) {
const identity = getKeybindingConflictIdentity(keybinding.key, platform)
const owners = chordOwners.get(identity) ?? []
owners.push({
pluginKey: plugin.pluginKey,
context: keybinding.when,
key: keybinding.key
})
chordOwners.set(identity, owners)
}
}
}
const conflicted = new Set<string>()
for (const owners of chordOwners.values()) {
for (let index = 0; index < owners.length; index += 1) {
for (let compared = index + 1; compared < owners.length; compared += 1) {
const first = owners[index]!
const second = owners[compared]!
if (!contextsOverlap(first.context, second.context)) {
continue
}
conflicted.add(first.pluginKey)
conflicted.add(second.pluginKey)
this.errors.set(
first.pluginKey,
`plugin keybinding ${first.key} conflicts with another plugin`
)
this.errors.set(
second.pluginKey,
`plugin keybinding ${second.key} conflicts with another plugin`
)
}
}
}
this.active = approved
.filter((plugin) => !conflicted.has(plugin.pluginKey))
.flatMap((plugin) => plugin.commands)
}
}
function effectiveCommandKeybindings(
command: PluginCommandRegistration,
overrides: KeybindingOverrides
): PluginCommandKeybinding[] {
const override = overrides[pluginCommandKeybindingActionId(command.pluginKey, command.id)]
if (!Array.isArray(override)) {
return command.keybindings
}
return override.map((key) => ({ key, when: command.context }))
}
function registrationsForManifest(
pluginKey: string,
manifest: PluginManifest
): PluginCommandRegistration[] {
return manifest.contributes.commands.map((command) => ({
pluginKey,
id: command.id,
title: command.title,
context: command.context ?? 'global',
handler:
command.action === undefined
? { type: 'worker' as const }
: { type: 'built-in' as const, action: command.action as PluginCommandAliasActionId },
keybindings: keybindingsForCommand(command, manifest.contributes.keybindings)
}))
}
function keybindingsForCommand(
command: PluginCommandContribution,
keybindings: readonly PluginKeybindingContribution[]
): PluginCommandKeybinding[] {
return keybindings
.filter((keybinding) => keybinding.command === command.id)
.map((keybinding) => ({
key: keybinding.key,
when: keybinding.when ?? command.context ?? 'global'
}))
}
function contextsOverlap(
first: PluginCommandKeybinding['when'],
second: PluginCommandKeybinding['when']
): boolean {
return first === 'global' || second === 'global' || first === second
}
+129
View File
@@ -0,0 +1,129 @@
import { createHash } from 'node:crypto'
import { createReadStream } from 'node:fs'
import { lstat, readdir } from 'node:fs/promises'
import { join, relative } from 'node:path'
import { pluginPathSegmentError } from '../../shared/plugins/plugin-path-safety'
/**
* Deterministic hash of a plugin's file tree. The hash names the immutable
* install directory (`<userData>/plugins/<publisher>.<id>/<hash>/`), so two
* installs of identical content share a name and a mutated install is
* detectable. Hashes relative paths + file bytes in sorted order; symlinks
* are refused outright (installed trees must be self-contained).
*/
const MAX_PLUGIN_FILES = 2_000
const MAX_PLUGIN_TOTAL_BYTES = 50 * 1024 * 1024
type PluginFile = { path: string; size: number }
export type PluginTreeHashResult =
| { ok: true; hash: string; fileCount: number; totalBytes: number }
| { ok: false; error: string }
async function collectFiles(
root: string,
dir: string,
files: PluginFile[],
counters: { entries: number; bytes: number }
): Promise<string | null> {
const entries = await readdir(dir, { withFileTypes: true })
// Why: localeCompare ordering varies with host locale/ICU data; content
// addresses must sort identically on macOS, Linux, and Windows.
entries.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0))
for (const entry of entries) {
if (dir === root && entry.name === '.git') {
continue
}
const segmentError = pluginPathSegmentError(entry.name)
if (segmentError) {
return `unsafe plugin path segment "${entry.name}": ${segmentError}`
}
const full = join(dir, entry.name)
const stat = await lstat(full)
counters.entries += 1
if (counters.entries > MAX_PLUGIN_FILES) {
return `plugin exceeds the ${MAX_PLUGIN_FILES}-entry limit`
}
if (stat.isSymbolicLink()) {
return `symlink not allowed in plugin content: ${relative(root, full)}`
}
if (stat.isDirectory()) {
const error = await collectFiles(root, full, files, counters)
if (error) {
return error
}
} else if (stat.isFile()) {
counters.bytes += stat.size
if (counters.bytes > MAX_PLUGIN_TOTAL_BYTES) {
return `plugin exceeds the ${MAX_PLUGIN_TOTAL_BYTES}-byte limit`
}
files.push({ path: full, size: stat.size })
} else {
return `unsupported plugin entry type: ${relative(root, full)}`
}
}
return null
}
async function hashFileBounded(
hash: ReturnType<typeof createHash>,
file: PluginFile
): Promise<number> {
let bytesRead = 0
for await (const chunk of createReadStream(file.path)) {
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
bytesRead += bytes.byteLength
if (bytesRead > file.size || bytesRead > MAX_PLUGIN_TOTAL_BYTES) {
throw new Error(`plugin file changed while hashing: ${file.path}`)
}
hash.update(bytes)
}
if (bytesRead !== file.size) {
throw new Error(`plugin file changed while hashing: ${file.path}`)
}
return bytesRead
}
export async function hashPluginTree(root: string): Promise<PluginTreeHashResult> {
const files: PluginFile[] = []
try {
const counters = { entries: 0, bytes: 0 }
const error = await collectFiles(root, root, files, counters)
if (error) {
return { ok: false, error }
}
const hash = createHash('sha256')
// Why: every record is length-framed so path/content delimiters inside a
// plugin file cannot make two different trees share one hash preimage.
hash.update('orca-plugin-tree-v1\0')
let totalBytes = 0
for (const file of files) {
totalBytes += file.size
if (totalBytes > MAX_PLUGIN_TOTAL_BYTES) {
return { ok: false, error: `plugin exceeds the ${MAX_PLUGIN_TOTAL_BYTES}-byte limit` }
}
// Normalize separators so the same tree hashes identically on Windows.
const rel = relative(root, file.path).replaceAll('\\', '/')
hashLength(hash, Buffer.byteLength(rel, 'utf8'))
hash.update(rel, 'utf8')
hashLength(hash, file.size)
await hashFileBounded(hash, file)
}
// Hex (not base64) because the hash becomes a directory name.
return {
ok: true,
hash: hash.digest('hex'),
fileCount: files.length,
totalBytes
}
} catch (error) {
return { ok: false, error: error instanceof Error ? error.message : String(error) }
}
}
function hashLength(hash: ReturnType<typeof createHash>, length: number): void {
const framedLength = Buffer.allocUnsafe(8)
framedLength.writeBigUInt64BE(BigInt(length))
hash.update(framedLength)
}
@@ -0,0 +1,58 @@
import { hashPluginTree } from './plugin-content-hash'
export type HashAddressedPluginContent = {
rootDir: string
contentHash: string | null
}
export type PluginContentIntegrityResult = { ok: true } | { ok: false; error: string }
/** Dev trees are intentionally mutable; installed hash-addressed trees are not. */
export async function verifyHashAddressedPluginContent(
plugin: HashAddressedPluginContent
): Promise<PluginContentIntegrityResult> {
if (plugin.contentHash === null) {
return { ok: true }
}
const actual = await hashPluginTree(plugin.rootDir)
if (!actual.ok) {
return { ok: false, error: actual.error }
}
const matchesCurrentHash = actual.hash === plugin.contentHash
// Early P0 installs used a 128-bit SHA-256 prefix as the directory name.
// Honor that existing address while all new installs use the full digest.
const matchesLegacyPrefix =
plugin.contentHash.length === 32 && actual.hash.startsWith(plugin.contentHash)
if (!matchesCurrentHash && !matchesLegacyPrefix) {
return {
ok: false,
error: `content hash mismatch (expected ${plugin.contentHash}, got ${actual.hash})`
}
}
return { ok: true }
}
/** Deduplicates the first lazy verification for each discovered install. */
export class PluginContentVerifier {
private readonly verifications = new Map<string, Promise<PluginContentIntegrityResult>>()
clear(): void {
this.verifications.clear()
}
async verify(plugin: HashAddressedPluginContent & { pluginKey: string }): Promise<void> {
// Why: a refresh can replace one same-key install while its old hash is
// still being verified. Cache by immutable content identity, never key.
const identity = JSON.stringify([plugin.pluginKey, plugin.rootDir, plugin.contentHash])
let verification = this.verifications.get(identity)
if (!verification) {
verification = verifyHashAddressedPluginContent(plugin)
this.verifications.set(identity, verification)
}
const result = await verification
if (!result.ok) {
this.verifications.delete(identity)
throw new Error(`plugin ${plugin.pluginKey} failed integrity verification: ${result.error}`)
}
}
}
@@ -0,0 +1,108 @@
import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { fingerprintPluginConsent } from '../../shared/plugins/plugin-consent-fingerprint'
import { pluginManifestSchema } from '../../shared/plugins/plugin-manifest'
import { PluginContentVerifier } from './plugin-content-integrity'
import { hashPluginTree } from './plugin-content-hash'
import { PluginContentPackRegistry } from './plugin-content-pack-registry'
import type { ValidDiscoveredPlugin } from './plugin-discovery'
const roots: string[] = []
afterEach(async () => {
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })))
})
describe('PluginContentPackRegistry', () => {
it('activates all contributions from a plugin atomically', async () => {
const rootDir = await mkdtemp(join(tmpdir(), 'orca-plugin-content-pack-registry-'))
roots.push(rootDir)
await mkdir(join(rootDir, 'locales'))
await Promise.all([
writeFile(
join(rootDir, 'locales', 'invalid.json'),
JSON.stringify({ settings: { title: 42 } })
),
writeFile(join(rootDir, 'locales', 'valid.json'), JSON.stringify({ settings: 'Ajustes' }))
])
const manifest = pluginManifestSchema.parse({
manifestVersion: 1,
id: 'mixed-content',
publisher: 'orca-samples',
name: 'Mixed Content',
version: '1.0.0',
engines: { orca: '>=1.0.0' },
pluginApi: 1,
contributes: {
languagePacks: [
{ locale: 'es', path: 'locales/valid.json' },
{ locale: 'pt-BR', path: 'locales/invalid.json' }
]
},
capabilities: []
})
const plugin: ValidDiscoveredPlugin = {
pluginKey: 'orca-samples.mixed-content',
rootDir,
manifest,
consentFingerprint: fingerprintPluginConsent(manifest),
contentHash: null,
isDev: true
}
const registry = new PluginContentPackRegistry(new PluginContentVerifier())
await registry.reconcile([plugin], () => true)
expect(registry.error(plugin.pluginKey)).toContain('string or object')
expect(registry.languagePacks.list()).toEqual([])
})
it('rolls back valid packs when a VM recipe from the same plugin is invalid', async () => {
const rootDir = await mkdtemp(join(tmpdir(), 'orca-plugin-content-pack-vm-'))
roots.push(rootDir)
await Promise.all([mkdir(join(rootDir, 'locales')), mkdir(join(rootDir, 'recipes'))])
await Promise.all([
writeFile(join(rootDir, 'locales', 'valid.json'), JSON.stringify({ settings: 'Ajustes' })),
writeFile(
join(rootDir, 'recipes', 'invalid.json'),
JSON.stringify({ schemaVersion: 1, id: 'bad', name: 'Bad', create: 'create', resume: 'up' })
)
])
const manifest = pluginManifestSchema.parse({
manifestVersion: 1,
id: 'mixed-recipes',
publisher: 'orca-samples',
name: 'Mixed Recipes',
version: '1.0.0',
engines: { orca: '>=1.0.0' },
pluginApi: 1,
contributes: {
languagePacks: [{ locale: 'es', path: 'locales/valid.json' }],
vmRecipes: [{ path: 'recipes/invalid.json' }]
},
capabilities: []
})
const content = await hashPluginTree(rootDir)
if (!content.ok) {
throw new Error(content.error)
}
const plugin: ValidDiscoveredPlugin = {
pluginKey: 'orca-samples.mixed-recipes',
rootDir,
manifest,
consentFingerprint: fingerprintPluginConsent(manifest, content.hash),
consentContentHash: content.hash,
contentHash: null,
isDev: true
}
const registry = new PluginContentPackRegistry(new PluginContentVerifier())
await registry.reconcile([plugin], () => true)
expect(registry.error(plugin.pluginKey)).toContain('suspend and resume')
expect(registry.languagePacks.list()).toEqual([])
expect(registry.vmRecipes.list()).toEqual([])
})
})
@@ -0,0 +1,95 @@
import type { PluginContentVerifier } from './plugin-content-integrity'
import {
isInvalidDiscoveredPlugin,
type DiscoveredPlugin,
type ValidDiscoveredPlugin
} from './plugin-discovery'
import { PluginLanguagePackRegistry } from './plugin-language-pack-registry'
import { PluginVmRecipeRegistry } from './plugin-vm-recipe-registry'
import { PluginCommandRegistry } from './plugin-command-registry'
import { verifyInstructionalPluginContent } from './plugin-instructional-content-integrity'
import type { KeybindingOverrides } from '../../shared/keybindings'
export class PluginContentPackRegistry {
readonly languagePacks: PluginLanguagePackRegistry
readonly vmRecipes: PluginVmRecipeRegistry
readonly commands: PluginCommandRegistry
private readonly activationErrors = new Map<string, string>()
constructor(contentVerifier: PluginContentVerifier) {
this.languagePacks = new PluginLanguagePackRegistry(contentVerifier)
this.vmRecipes = new PluginVmRecipeRegistry()
this.commands = new PluginCommandRegistry()
}
async reconcile(
discovered: readonly DiscoveredPlugin[],
isApproved: (plugin: ValidDiscoveredPlugin) => boolean,
keybindings: KeybindingOverrides = {}
): Promise<void> {
const approvedKeys = new Set(
discovered
.filter((plugin): plugin is ValidDiscoveredPlugin => !isInvalidDiscoveredPlugin(plugin))
.filter(isApproved)
.map((plugin) => plugin.pluginKey)
)
const excluded = new Set<string>()
this.activationErrors.clear()
await Promise.all(
discovered.map(async (plugin) => {
if (
isInvalidDiscoveredPlugin(plugin) ||
!approvedKeys.has(plugin.pluginKey) ||
plugin.manifest.contributes.vmRecipes.length > 0
) {
return
}
try {
await verifyInstructionalPluginContent(plugin)
} catch (error) {
excluded.add(plugin.pluginKey)
this.activationErrors.set(
plugin.pluginKey,
error instanceof Error ? error.message : String(error)
)
}
})
)
while (true) {
const approveAtomically = (plugin: ValidDiscoveredPlugin): boolean =>
approvedKeys.has(plugin.pluginKey) && !excluded.has(plugin.pluginKey)
await Promise.all([
this.languagePacks.reconcile(discovered, approveAtomically),
this.vmRecipes.reconcile(discovered, approveAtomically),
this.commands.reconcile(discovered, approveAtomically, keybindings)
])
let foundNewError = false
for (const pluginKey of approvedKeys) {
const error = this.registryError(pluginKey)
if (error && !excluded.has(pluginKey)) {
excluded.add(pluginKey)
this.activationErrors.set(pluginKey, error)
foundNewError = true
}
}
if (!foundNewError) {
break
}
}
}
error(pluginKey: string): string | null {
return this.activationErrors.get(pluginKey) ?? this.registryError(pluginKey)
}
private registryError(pluginKey: string): string | null {
return (
this.languagePacks.error(pluginKey) ??
this.vmRecipes.error(pluginKey) ??
this.commands.error(pluginKey)
)
}
}
@@ -0,0 +1,305 @@
import { mkdtemp, mkdir, rm, symlink, truncate, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { fingerprintPluginConsent } from '../../shared/plugins/plugin-consent-fingerprint'
import { pluginManifestSchema, type PluginManifest } from '../../shared/plugins/plugin-manifest'
import {
PLUGIN_PANEL_ENTRY_MAX_BYTES,
validateDeclaredPluginArtifacts,
validatePluginInstallContent
} from './plugin-artifact-validation'
import { hashPluginTree } from './plugin-content-hash'
import { verifyHashAddressedPluginContent } from './plugin-content-integrity'
import { PluginService } from './plugin-service'
const roots: string[] = []
async function tempRoot(): Promise<string> {
const root = await mkdtemp(join(tmpdir(), 'orca-plugin-content-test-'))
roots.push(root)
return root
}
type ManifestOverrides = Omit<Partial<PluginManifest>, 'contributes'> & {
contributes?: Partial<PluginManifest['contributes']>
}
function manifest(overrides: ManifestOverrides = {}): PluginManifest {
const { contributes, ...manifestOverrides } = overrides
return pluginManifestSchema.parse({
manifestVersion: 1,
id: 'demo',
publisher: 'orca-samples',
name: 'Demo',
version: '1.0.0',
engines: { orca: '>=1.0.0' },
pluginApi: 1,
capabilities: [],
...manifestOverrides,
contributes
})
}
afterEach(async () => {
vi.restoreAllMocks()
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })))
})
describe('declared plugin artifacts', () => {
it('validates every content-pack file and directory before enablement', async () => {
const root = await tempRoot()
await Promise.all([
mkdir(join(root, 'locales')),
mkdir(join(root, 'recipes')),
writeFile(join(root, 'agent.json'), '{}')
])
await Promise.all([
writeFile(join(root, 'locales', 'pt-BR.json'), '{}'),
writeFile(join(root, 'recipes', 'vm.json'), '{}')
])
const pluginManifest = manifest({
contributes: {
languagePacks: [{ locale: 'pt-BR', path: 'locales/pt-BR.json' }],
vmRecipes: [{ path: 'recipes/vm.json' }],
agents: [{ path: 'agent.json' }]
}
})
await expect(validateDeclaredPluginArtifacts(root, pluginManifest)).resolves.toEqual({
ok: true
})
})
it('requires declared files to exist and be regular files', async () => {
const root = await tempRoot()
await mkdir(join(root, 'panel.html'))
const result = await validateDeclaredPluginArtifacts(
root,
manifest({
main: 'missing-worker.js',
contributes: {
panels: [{ id: 'panel', title: 'Panel', entry: 'panel.html' }],
commands: [],
events: []
}
})
)
expect(result).toMatchObject({ ok: false })
})
it('refuses a panel reached through an escaping directory link or junction', async () => {
const root = await tempRoot()
const outsideDir = await tempRoot()
const userDataPath = await tempRoot()
await writeFile(join(outsideDir, 'panel.html'), '<h1>outside</h1>')
await symlink(
outsideDir,
join(root, 'escape'),
process.platform === 'win32' ? 'junction' : 'dir'
)
const pluginManifest = manifest({
contributes: {
panels: [{ id: 'panel', title: 'Panel', entry: 'escape/panel.html' }],
commands: [],
events: []
}
})
await writeFile(join(root, 'orca-plugin.json'), JSON.stringify(pluginManifest))
await expect(validateDeclaredPluginArtifacts(root, pluginManifest)).resolves.toMatchObject({
ok: false
})
const pluginKey = `${pluginManifest.publisher}.${pluginManifest.id}`
const service = new PluginService({
userDataPath,
hostVersion: '1.4.0',
isPluginSystemEnabled: () => true,
getDisabledPlugins: () => [],
getPluginConsents: () => ({
[pluginKey]: fingerprintPluginConsent(pluginManifest)
}),
getDevPluginPaths: () => [root]
})
try {
await service.initialize()
await expect(service.panels.readEntry(pluginKey, 'panel')).resolves.toBeNull()
} finally {
await service.dispose()
}
})
it('rejects a panel artifact too large to mount safely in a renderer', async () => {
const root = await tempRoot()
const panelPath = join(root, 'panel.html')
await writeFile(panelPath, '')
await truncate(panelPath, PLUGIN_PANEL_ENTRY_MAX_BYTES + 1)
const pluginManifest = manifest({
contributes: {
panels: [{ id: 'panel', title: 'Panel', entry: 'panel.html' }],
commands: [],
events: []
}
})
await expect(validateDeclaredPluginArtifacts(root, pluginManifest)).resolves.toMatchObject({
ok: false,
error: expect.stringContaining('artifact limit')
})
})
it('parses VM recipes at the immutable install boundary', async () => {
const root = await tempRoot()
await mkdir(join(root, 'recipes'))
await writeFile(
join(root, 'recipes', 'invalid.json'),
JSON.stringify({
schemaVersion: 1,
id: 'cloud',
name: 'Cloud',
create: 'create',
suspend: 'suspend'
})
)
const pluginManifest = manifest({
contributes: { vmRecipes: [{ path: 'recipes/invalid.json' }] }
})
await expect(validateDeclaredPluginArtifacts(root, pluginManifest)).resolves.toEqual({
ok: true
})
await expect(validatePluginInstallContent(root, pluginManifest)).resolves.toMatchObject({
ok: false,
error: expect.stringContaining('suspend and resume')
})
})
it('rejects duplicate VM recipe ids at the immutable install boundary', async () => {
const root = await tempRoot()
await mkdir(join(root, 'recipes'))
const recipe = JSON.stringify({
schemaVersion: 1,
id: 'cloud',
name: 'Cloud',
create: 'create'
})
await Promise.all([
writeFile(join(root, 'recipes', 'one.json'), recipe),
writeFile(join(root, 'recipes', 'two.json'), recipe)
])
const pluginManifest = manifest({
contributes: {
vmRecipes: [{ path: 'recipes/one.json' }, { path: 'recipes/two.json' }]
}
})
await expect(validatePluginInstallContent(root, pluginManifest)).resolves.toMatchObject({
ok: false,
error: expect.stringContaining('duplicate VM recipe id "cloud"')
})
})
})
describe('hash-addressed plugin content', () => {
it('uses unambiguous framing for paths and file contents', async () => {
const first = await tempRoot()
const second = await tempRoot()
await writeFile(join(first, 'a'), Buffer.from('x\0b\0y'))
await Promise.all([writeFile(join(second, 'a'), 'x'), writeFile(join(second, 'b'), 'y')])
const [firstHash, secondHash] = await Promise.all([
hashPluginTree(first),
hashPluginTree(second)
])
expect(firstHash).toMatchObject({ ok: true })
expect(secondHash).toMatchObject({ ok: true })
if (firstHash.ok && secondHash.ok) {
expect(firstHash.hash).not.toBe(secondHash.hash)
}
})
it('hashes and bounds nested .git directories as plugin content', async () => {
const root = await tempRoot()
const nestedGit = join(root, 'vendor', '.git')
await mkdir(nestedGit, { recursive: true })
const entry = join(nestedGit, 'main.mjs')
await writeFile(entry, 'export default function activate() {}')
const initial = await hashPluginTree(root)
await writeFile(entry, 'export default function activate() { throw new Error("changed") }')
const changed = await hashPluginTree(root)
expect(initial).toMatchObject({ ok: true })
expect(changed).toMatchObject({ ok: true })
if (initial.ok && changed.ok) {
expect(changed.hash).not.toBe(initial.hash)
}
await truncate(entry, 50 * 1024 * 1024 + 1)
await expect(hashPluginTree(root)).resolves.toMatchObject({
ok: false,
error: expect.stringContaining('byte limit')
})
})
it('does not let host locale collation change a content address', async () => {
const root = await tempRoot()
await writeFile(join(root, 'alpha.txt'), 'a')
await writeFile(join(root, 'zulu.txt'), 'z')
const expected = await hashPluginTree(root)
vi.spyOn(String.prototype, 'localeCompare').mockImplementation(() => -1)
const withDifferentCollation = await hashPluginTree(root)
expect(withDifferentCollation).toEqual(expected)
})
it.skipIf(process.platform === 'win32')(
'rejects Windows-reserved tree entries cross-platform',
async () => {
const root = await tempRoot()
await writeFile(join(root, 'CON.txt'), 'reserved')
await expect(hashPluginTree(root)).resolves.toMatchObject({ ok: false })
}
)
it('detects content changed after its address was computed', async () => {
const root = await tempRoot()
const entry = join(root, 'panel.html')
await writeFile(entry, '<h1>original</h1>')
const initial = await hashPluginTree(root)
expect(initial.ok).toBe(true)
if (!initial.ok) {
return
}
expect(initial.hash).toMatch(/^[0-9a-f]{64}$/)
await expect(
verifyHashAddressedPluginContent({
rootDir: root,
contentHash: initial.hash.slice(0, 32)
})
).resolves.toEqual({ ok: true })
await writeFile(entry, '<h1>tampered</h1>')
await expect(
verifyHashAddressedPluginContent({ rootDir: root, contentHash: initial.hash })
).resolves.toMatchObject({ ok: false })
})
it('rejects an oversized sparse file before reading it into memory', async () => {
const root = await tempRoot()
const oversized = join(root, 'oversized.bin')
await writeFile(oversized, '')
await truncate(oversized, 50 * 1024 * 1024 + 1)
await expect(hashPluginTree(root)).resolves.toMatchObject({
ok: false,
error: expect.stringContaining('byte limit')
})
})
})
@@ -0,0 +1,49 @@
import { createReadStream } from 'node:fs'
import { rm } from 'node:fs/promises'
import { join } from 'node:path'
import { writePluginFileAtomically } from './plugin-atomic-file-write'
export const PLUGIN_CURRENT_POINTER_FILENAME = 'current'
export const PLUGIN_CURRENT_POINTER_MAX_BYTES = 128
/** Reads the tiny hash pointer through a cap so discovery cannot allocate a
* corrupt sparse file during startup. Missing pointers resolve to null. */
export async function readPluginCurrentPointer(pluginDir: string): Promise<string | null> {
const target = join(pluginDir, PLUGIN_CURRENT_POINTER_FILENAME)
const chunks: Buffer[] = []
let totalBytes = 0
try {
for await (const chunk of createReadStream(target)) {
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
totalBytes += bytes.byteLength
if (totalBytes > PLUGIN_CURRENT_POINTER_MAX_BYTES) {
throw new Error('current-version pointer exceeds its size limit')
}
chunks.push(bytes)
}
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
return null
}
throw error
}
return Buffer.concat(chunks, totalBytes).toString('utf8').trim()
}
export async function writePluginCurrentPointer(
pluginDir: string,
contentHash: string
): Promise<void> {
await writePluginFileAtomically(join(pluginDir, PLUGIN_CURRENT_POINTER_FILENAME), contentHash)
}
export async function restorePluginCurrentPointer(
pluginDir: string,
previousContentHash: string | null
): Promise<void> {
if (previousContentHash === null) {
await rm(join(pluginDir, PLUGIN_CURRENT_POINTER_FILENAME), { force: true })
return
}
await writePluginCurrentPointer(pluginDir, previousContentHash)
}
@@ -0,0 +1,64 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { PluginDevWatcher } from './plugin-dev-watcher'
afterEach(() => {
vi.useRealTimers()
})
describe('PluginDevWatcher', () => {
it('contains asynchronous watcher errors and requests a retrying refresh', async () => {
vi.useFakeTimers()
let onEvent!: (error: Error | null) => void
const unsubscribe = vi.fn().mockResolvedValue(undefined)
const subscribePath = vi.fn(async (_path, callback: typeof onEvent) => {
onEvent = callback
return { unsubscribe }
})
const devWatcher = new PluginDevWatcher(subscribePath)
const refresh = vi.fn()
const onWatcherError = vi.fn()
devWatcher.start(['/plugins/demo'], refresh, onWatcherError)
await vi.waitFor(() => expect(subscribePath).toHaveBeenCalledOnce())
expect(() => onEvent(new Error('watch failed'))).not.toThrow()
await vi.waitFor(() => expect(unsubscribe).toHaveBeenCalledOnce())
expect(onWatcherError).toHaveBeenCalledOnce()
vi.advanceTimersByTime(300)
expect(refresh).toHaveBeenCalledOnce()
devWatcher.dispose()
})
it('unsubscribes a subscription that resolves after disposal', async () => {
let resolveSubscription!: (value: { unsubscribe: () => Promise<void> }) => void
const unsubscribe = vi.fn().mockResolvedValue(undefined)
const subscribePath = vi.fn(
() =>
new Promise<{ unsubscribe: () => Promise<void> }>((resolve) => {
resolveSubscription = resolve
})
)
const devWatcher = new PluginDevWatcher(subscribePath)
devWatcher.start(['/plugins/demo'], vi.fn())
devWatcher.dispose()
resolveSubscription({ unsubscribe })
await vi.waitFor(() => expect(unsubscribe).toHaveBeenCalledOnce())
})
it('does not spin refreshes when a missing path cannot be subscribed', async () => {
vi.useFakeTimers()
const subscribePath = vi.fn().mockRejectedValue(new Error('missing path'))
const refresh = vi.fn()
const onWatcherError = vi.fn()
const devWatcher = new PluginDevWatcher(subscribePath)
devWatcher.start(['/plugins/missing'], refresh, onWatcherError)
await vi.waitFor(() => expect(onWatcherError).toHaveBeenCalledOnce())
vi.advanceTimersByTime(10_000)
expect(refresh).not.toHaveBeenCalled()
devWatcher.dispose()
})
})
+108
View File
@@ -0,0 +1,108 @@
import {
subscribeViaWatcherProcess,
type WatcherProcessSubscription
} from '../ipc/parcel-watcher-process'
type SubscribePluginPath = (
path: string,
onEvent: (error: Error | null) => void,
onInterruption: () => void
) => Promise<WatcherProcessSubscription>
const subscribePluginPath: SubscribePluginPath = (path, onEvent, onInterruption) =>
subscribeViaWatcherProcess(
path,
(error) => onEvent(error),
{},
{
onInterruption,
onTerminalError: onEvent
}
)
/** Owns debounced manifest/panel refresh watchers for mutable dev plugins. */
export class PluginDevWatcher {
private readonly subscriptions: WatcherProcessSubscription[] = []
private refreshTimer: ReturnType<typeof setTimeout> | null = null
private generation = 0
constructor(private readonly subscribePath: SubscribePluginPath = subscribePluginPath) {}
start(devPaths: readonly string[], refresh: () => void, onWatcherError?: () => void): void {
const generation = ++this.generation
for (const devPath of devPaths) {
let subscription: WatcherProcessSubscription | null = null
let failedBeforeReady = false
const fail = (): void => {
if (generation !== this.generation) {
return
}
failedBeforeReady = true
if (subscription) {
this.removeSubscription(subscription)
void subscription.unsubscribe()
}
onWatcherError?.()
this.scheduleRefresh(refresh)
}
void this.subscribePath(
devPath,
(error) => {
if (error) {
fail()
} else if (generation === this.generation) {
this.scheduleRefresh(refresh)
}
},
() => {
if (generation === this.generation) {
// The watcher process recovered, but changes during the gap were
// lost, so refresh the complete plugin projection once.
this.scheduleRefresh(refresh)
}
}
)
.then((created) => {
subscription = created
if (generation !== this.generation || failedBeforeReady) {
void created.unsubscribe()
return
}
this.subscriptions.push(created)
})
.catch(() => {
if (generation === this.generation) {
onWatcherError?.()
}
})
}
}
dispose(): void {
this.generation += 1
if (this.refreshTimer) {
clearTimeout(this.refreshTimer)
this.refreshTimer = null
}
for (const subscription of this.subscriptions.splice(0)) {
void subscription.unsubscribe()
}
}
private removeSubscription(subscription: WatcherProcessSubscription): void {
const index = this.subscriptions.indexOf(subscription)
if (index >= 0) {
this.subscriptions.splice(index, 1)
}
}
private scheduleRefresh(refresh: () => void): void {
if (this.refreshTimer) {
clearTimeout(this.refreshTimer)
}
this.refreshTimer = setTimeout(() => {
this.refreshTimer = null
refresh()
}, 300)
}
}
+129
View File
@@ -0,0 +1,129 @@
import { mkdir, mkdtemp, rm, truncate, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { discoverPlugins, isInvalidDiscoveredPlugin } from './plugin-discovery'
import { PLUGIN_CURRENT_POINTER_MAX_BYTES } from './plugin-current-pointer'
const roots: string[] = []
afterEach(async () => {
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })))
})
async function tempPluginsDir(): Promise<string> {
const root = await mkdtemp(join(tmpdir(), 'orca-plugin-discovery-'))
roots.push(root)
return root
}
describe('installed plugin discovery identity', () => {
it('keeps the install directory identity when a manifest is invalid or mismatched', async () => {
const pluginsDir = await tempPluginsDir()
const installedKey = 'orca-samples.expected'
const hash = 'a'.repeat(64)
const versionDir = join(pluginsDir, installedKey, hash)
await mkdir(versionDir, { recursive: true })
await writeFile(join(pluginsDir, installedKey, 'current'), hash)
await writeFile(
join(versionDir, 'orca-plugin.json'),
JSON.stringify({
manifestVersion: 1,
id: 'different',
publisher: 'orca-samples',
name: 'Different',
version: '1.0.0',
engines: { orca: '>=1.0.0' },
pluginApi: 1,
contributes: { panels: [], commands: [], events: [] },
capabilities: []
})
)
const [plugin] = await discoverPlugins({ pluginsDir, devPluginPaths: [], hostVersion: '1.4.0' })
expect(plugin && isInvalidDiscoveredPlugin(plugin)).toBe(true)
expect(plugin?.pluginKey).toBe(installedKey)
expect(plugin && 'error' in plugin ? plugin.error : '').toContain('does not match')
})
it('keeps a removable qualified identity when the current pointer is missing', async () => {
const pluginsDir = await tempPluginsDir()
const installedKey = 'orca-samples.broken'
await mkdir(join(pluginsDir, installedKey), { recursive: true })
const [plugin] = await discoverPlugins({ pluginsDir, devPluginPaths: [], hostVersion: '1.4.0' })
expect(plugin && isInvalidDiscoveredPlugin(plugin)).toBe(true)
expect(plugin?.pluginKey).toBe(installedKey)
})
it('rejects an oversized current pointer without an unbounded startup read', async () => {
const pluginsDir = await tempPluginsDir()
const installedKey = 'orca-samples.broken'
const pluginDir = join(pluginsDir, installedKey)
await mkdir(pluginDir, { recursive: true })
const pointer = join(pluginDir, 'current')
await writeFile(pointer, '')
await truncate(pointer, PLUGIN_CURRENT_POINTER_MAX_BYTES + 1)
const [plugin] = await discoverPlugins({ pluginsDir, devPluginPaths: [], hostVersion: '1.4.0' })
expect(plugin && isInvalidDiscoveredPlugin(plugin)).toBe(true)
expect(plugin?.pluginKey).toBe(installedKey)
})
})
describe('instructional plugin discovery identity', () => {
it('changes dev consent when a VM recipe command changes', async () => {
const pluginsDir = await tempPluginsDir()
const devRoot = await tempPluginsDir()
await mkdir(join(devRoot, 'recipes'))
await writeFile(
join(devRoot, 'orca-plugin.json'),
JSON.stringify({
manifestVersion: 1,
id: 'recipes',
publisher: 'orca-samples',
name: 'Recipes',
version: '1.0.0',
engines: { orca: '>=1.0.0' },
pluginApi: 1,
contributes: { vmRecipes: [{ path: 'recipes/cloud.json' }] },
capabilities: []
})
)
const recipePath = join(devRoot, 'recipes', 'cloud.json')
await writeFile(
recipePath,
JSON.stringify({ schemaVersion: 1, id: 'cloud', name: 'Cloud', create: 'create-v1' })
)
const [first] = await discoverPlugins({
pluginsDir,
devPluginPaths: [devRoot],
hostVersion: '1.4.0'
})
await writeFile(
recipePath,
JSON.stringify({ schemaVersion: 1, id: 'cloud', name: 'Cloud', create: 'create-v2' })
)
const [second] = await discoverPlugins({
pluginsDir,
devPluginPaths: [devRoot],
hostVersion: '1.4.0'
})
expect(first && !isInvalidDiscoveredPlugin(first)).toBe(true)
expect(second && !isInvalidDiscoveredPlugin(second)).toBe(true)
if (
!first ||
!second ||
isInvalidDiscoveredPlugin(first) ||
isInvalidDiscoveredPlugin(second)
) {
return
}
expect(second.consentContentHash).not.toBe(first.consentContentHash)
expect(second.consentFingerprint).not.toBe(first.consentFingerprint)
})
})
+254
View File
@@ -0,0 +1,254 @@
import { readdir } from 'node:fs/promises'
import type { Dirent } from 'node:fs'
import { join } from 'node:path'
import { PLUGIN_CONTENT_HASH_PATTERN } from '../../shared/plugins/plugin-install-lockfile'
import {
PLUGIN_MANIFEST_FILENAME,
isQualifiedPluginKey,
parsePluginManifest,
qualifiedPluginKey,
satisfiesOrcaEngineRange,
type PluginManifest
} from '../../shared/plugins/plugin-manifest'
import {
fingerprintPluginConsent,
hasInstructionalPluginContributions
} from '../../shared/plugins/plugin-consent-fingerprint'
import { validateDeclaredPluginArtifacts } from './plugin-artifact-validation'
import { readPluginManifestText } from './plugin-manifest-file'
import { readPluginCurrentPointer } from './plugin-current-pointer'
import { hashPluginTree } from './plugin-content-hash'
export { PLUGIN_CURRENT_POINTER_FILENAME } from './plugin-current-pointer'
const INSTALLED_PLUGIN_DISCOVERY_CONCURRENCY = 8
/**
* Discovery over the hash-addressed install layout:
*
* <userData>/plugins/<publisher>.<id>/current ← text file naming the hash
* <userData>/plugins/<publisher>.<id>/<hash>/ ← immutable install tree
*
* plus dev-mode plugins loaded straight from arbitrary local directories.
* Discovery reads manifests and checks only their declared artifact paths —
* never plugin bytes or whole trees. Full content hashing stays lazy so
* startup cost is bounded by installed plugins plus declared entries.
*/
export type ValidDiscoveredPlugin = {
/** Qualified `<publisher>.<id>` key. */
pluginKey: string
rootDir: string
manifest: PluginManifest
/** Fingerprint of the capabilities and trusted-worker execution tier. */
consentFingerprint: string
/** Immutable tree identity included in consent for instructional packs. */
consentContentHash?: string | null
/** Content hash the install dir is named by; null for dev plugins. */
contentHash: string | null
isDev: boolean
}
export type InvalidDiscoveredPlugin = {
pluginKey?: string
rootDir: string
error: string
isDev: boolean
}
export type DiscoveredPlugin = ValidDiscoveredPlugin | InvalidDiscoveredPlugin
export function isInvalidDiscoveredPlugin(
plugin: DiscoveredPlugin
): plugin is InvalidDiscoveredPlugin {
return 'error' in plugin
}
export function getUserPluginsDir(userDataPath: string): string {
return join(userDataPath, 'plugins')
}
export function getPluginsDataDir(userDataPath: string): string {
return join(userDataPath, 'plugins-data')
}
async function readManifestDir(
rootDir: string,
hostVersion: string,
isDev: boolean,
installedContentHash?: string
): Promise<DiscoveredPlugin> {
let rawText: string
try {
rawText = await readPluginManifestText(rootDir)
} catch (error) {
return {
rootDir,
error:
error instanceof Error && error.message.includes('exceeds')
? error.message
: `missing ${PLUGIN_MANIFEST_FILENAME}`,
isDev
}
}
let raw: unknown
try {
raw = JSON.parse(rawText)
} catch (error) {
return {
rootDir,
error: `invalid JSON in ${PLUGIN_MANIFEST_FILENAME}: ${error instanceof Error ? error.message : String(error)}`,
isDev
}
}
const parsed = parsePluginManifest(raw)
if (!parsed.ok) {
return { rootDir, error: `invalid manifest: ${parsed.error}`, isDev }
}
const manifest = parsed.manifest
const pluginKey = qualifiedPluginKey(manifest)
if (!satisfiesOrcaEngineRange(hostVersion, manifest.engines.orca)) {
return {
pluginKey,
rootDir,
error: `requires Orca ${manifest.engines.orca} (this is ${hostVersion})`,
isDev
}
}
const artifacts = await validateDeclaredPluginArtifacts(rootDir, manifest)
if (!artifacts.ok) {
return {
pluginKey,
rootDir,
error: `invalid declared artifact: ${artifacts.error}`,
isDev
}
}
let consentContentIdentity: string | undefined
if (installedContentHash && hasInstructionalPluginContributions(manifest)) {
consentContentIdentity = installedContentHash
}
if (isDev && hasInstructionalPluginContributions(manifest)) {
const treeHash = await hashPluginTree(rootDir)
if (!treeHash.ok) {
return { pluginKey, rootDir, error: treeHash.error, isDev }
}
consentContentIdentity = treeHash.hash
}
return {
pluginKey,
rootDir,
manifest,
consentFingerprint: fingerprintPluginConsent(manifest, consentContentIdentity),
consentContentHash: consentContentIdentity ?? null,
contentHash: null,
isDev
}
}
async function readInstalledPlugin(
pluginDir: string,
dirName: string,
hostVersion: string
): Promise<DiscoveredPlugin> {
let contentHash: string
try {
contentHash = (await readPluginCurrentPointer(pluginDir)) ?? ''
} catch {
return {
pluginKey: dirName,
rootDir: pluginDir,
error: 'missing current-version pointer',
isDev: false
}
}
// The pointer names a sibling directory; refuse anything path-like so a
// corrupted pointer cannot address content outside the plugin dir.
if (!PLUGIN_CONTENT_HASH_PATTERN.test(contentHash)) {
return {
pluginKey: dirName,
rootDir: pluginDir,
error: 'corrupt current-version pointer',
isDev: false
}
}
const versionDir = join(pluginDir, contentHash)
const discovered = await readManifestDir(versionDir, hostVersion, false, contentHash)
if (isInvalidDiscoveredPlugin(discovered)) {
return { ...discovered, pluginKey: dirName }
}
// Why: the directory name is the install key (and the uninstall target); a
// mismatched manifest identity would let two dirs claim the same plugin.
if (discovered.pluginKey !== dirName) {
return {
pluginKey: dirName,
rootDir: versionDir,
error: `manifest identity "${discovered.pluginKey}" does not match install directory "${dirName}"`,
isDev: false
}
}
return { ...discovered, contentHash }
}
async function readInstalledPlugins(
pluginsDir: string,
entries: readonly Dirent[],
hostVersion: string
): Promise<DiscoveredPlugin[]> {
const results = Array.from({ length: entries.length }) as DiscoveredPlugin[]
let nextIndex = 0
const readers = Array.from(
{ length: Math.min(INSTALLED_PLUGIN_DISCOVERY_CONCURRENCY, entries.length) },
async () => {
while (nextIndex < entries.length) {
const index = nextIndex++
const entry = entries[index]!
results[index] = await readInstalledPlugin(
join(pluginsDir, entry.name),
entry.name,
hostVersion
)
}
}
)
await Promise.all(readers)
return results
}
export async function discoverPlugins(options: {
pluginsDir: string
devPluginPaths: readonly string[]
hostVersion: string
}): Promise<DiscoveredPlugin[]> {
const discovered: DiscoveredPlugin[] = []
let entries: Dirent[] = []
try {
entries = await readdir(options.pluginsDir, { withFileTypes: true })
} catch {
// A missing plugins dir just means no plugins are installed yet.
}
const installedEntries = entries.filter(
(entry) => entry.isDirectory() && isQualifiedPluginKey(entry.name)
)
// Installed manifests are independent immutable trees. Read them in
// a bounded pool so startup latency stays low without exhausting handles.
discovered.push(
...(await readInstalledPlugins(options.pluginsDir, installedEntries, options.hostVersion))
)
for (const devPath of options.devPluginPaths) {
const plugin = await readManifestDir(devPath, options.hostVersion, true)
// A dev path that duplicates an installed plugin's identity wins — that
// is the point of dev mode — but two dev paths must not collide.
if (!isInvalidDiscoveredPlugin(plugin)) {
const collision = discovered.find(
(existing) =>
!isInvalidDiscoveredPlugin(existing) && existing.pluginKey === plugin.pluginKey
)
if (collision) {
discovered.splice(discovered.indexOf(collision), 1)
}
}
discovered.push(plugin)
}
return discovered
}
+132
View File
@@ -0,0 +1,132 @@
import { tmpdir } from 'node:os'
import { describe, expect, it, vi } from 'vitest'
import { getDefaultSettings } from '../../shared/constants'
import type { GlobalSettings } from '../../shared/types'
import { pluginManifestSchema } from '../../shared/plugins/plugin-manifest'
import type { Store } from '../persistence'
import { applyPluginConsent, applyPluginEnablement } from './plugin-enablement'
import type { ValidDiscoveredPlugin } from './plugin-discovery'
import type { PluginService } from './plugin-service'
const pluginKey = 'orca-samples.demo'
const manifest = pluginManifestSchema.parse({
manifestVersion: 1,
id: 'demo',
publisher: 'orca-samples',
name: 'Demo',
version: '1.0.0',
engines: { orca: '>=1.0.0' },
pluginApi: 1,
contributes: {},
capabilities: []
})
function createStore(): {
store: Store
getSettings: () => GlobalSettings
updateSettings: ReturnType<typeof vi.fn>
} {
let settings = getDefaultSettings(tmpdir())
const updateSettings = vi.fn((updates: Partial<GlobalSettings>) => {
settings = { ...settings, ...updates }
})
return {
store: { getSettings: () => settings, updateSettings } as unknown as Store,
getSettings: () => settings,
updateSettings
}
}
function createPluginService(
getFingerprint: () => string,
overrides: Partial<ValidDiscoveredPlugin> = {}
): PluginService {
return {
findValidPlugin: (requestedKey: string) =>
requestedKey === pluginKey
? {
pluginKey,
rootDir: tmpdir(),
manifest,
consentFingerprint: getFingerprint(),
consentContentHash: null,
contentHash: null,
isDev: true,
...overrides
}
: null,
reconcileActivationState: vi.fn().mockResolvedValue(undefined)
} as unknown as PluginService
}
describe('applyPluginConsent', () => {
it('stores approval only for the fingerprint the user reviewed', async () => {
const harness = createStore()
const pluginService = createPluginService(() => 'sha256-reviewed')
await applyPluginConsent({
store: harness.store,
pluginService,
pluginKey,
reviewedFingerprint: 'sha256-reviewed',
decision: 'approve'
})
expect(harness.getSettings().pluginConsents[pluginKey]).toBe('sha256-reviewed')
expect(harness.getSettings().disabledPlugins).not.toContain(pluginKey)
})
it('rejects a stale review after a same-key plugin update without writing settings', async () => {
const harness = createStore()
let currentFingerprint = 'sha256-reviewed-v1'
const pluginService = createPluginService(() => currentFingerprint)
currentFingerprint = 'sha256-current-v2'
await expect(
applyPluginConsent({
store: harness.store,
pluginService,
pluginKey,
reviewedFingerprint: 'sha256-reviewed-v1',
decision: 'approve'
})
).rejects.toThrow('changed since its permissions were reviewed')
expect(harness.updateSettings).not.toHaveBeenCalled()
expect(harness.getSettings().pluginConsents[pluginKey]).toBeUndefined()
})
it('allows a stale dialog to keep the newer plugin disabled', async () => {
const harness = createStore()
const pluginService = createPluginService(() => 'sha256-current-v2')
await applyPluginConsent({
store: harness.store,
pluginService,
pluginKey,
reviewedFingerprint: 'sha256-reviewed-v1',
decision: 'keep-disabled'
})
expect(harness.getSettings().disabledPlugins).toContain(pluginKey)
expect(pluginService.reconcileActivationState).toHaveBeenCalledOnce()
})
})
describe('applyPluginEnablement', () => {
it('does not persist unknown plugin identities', async () => {
const harness = createStore()
const pluginService = createPluginService(() => 'sha256-current')
await expect(
applyPluginEnablement({
store: harness.store,
pluginService,
pluginKey: 'orca-samples.unknown',
enabled: false
})
).rejects.toThrow('unknown plugin')
expect(harness.updateSettings).not.toHaveBeenCalled()
})
})
+87
View File
@@ -0,0 +1,87 @@
import {
normalizePluginConsents,
normalizePluginIdList
} from '../../shared/plugins/plugin-consent-state'
import type { Store } from '../persistence'
import type { PluginService } from './plugin-service'
import type { PluginConsentRequest } from '../../shared/plugins/plugin-consent-request'
import { verifyInstructionalPluginContent } from './plugin-instructional-content-integrity'
/**
* Single write path for consent + enablement. Consent is recorded as
* (qualified key → consent fingerprint) — never a bare id — so a capability
* expansion or addition of trusted Node code requires re-consent. The desktop
* IPC handlers and the headless RPC methods both route through here.
*/
export type PluginConsentDecision = PluginConsentRequest['decision']
/** Records the user's consent-dialog answer. Approving stores the CURRENT
* consent fingerprint and clears any disable; declining disables so the plugin
* never re-prompts on later launches. */
export async function applyPluginConsent(input: {
store: Store
pluginService: PluginService
pluginKey: PluginConsentRequest['pluginKey']
reviewedFingerprint: PluginConsentRequest['reviewedFingerprint']
decision: PluginConsentRequest['decision']
originWebContentsId?: number
}): Promise<void> {
const { store, pluginService, pluginKey } = input
const plugin = pluginService.findValidPlugin(pluginKey)
if (!plugin) {
throw new Error(`cannot record consent for unknown plugin ${pluginKey}`)
}
// Why: a same-key install can change while the dialog is open; never apply a
// decision to capabilities or a worker trust tier the user did not review.
if (input.decision === 'approve' && plugin.consentFingerprint !== input.reviewedFingerprint) {
throw new Error(`plugin ${pluginKey} changed since its permissions were reviewed`)
}
if (input.decision === 'approve') {
// Why: IPC and serve callers can bypass the renderer dialog, so main must
// prove every instructional byte is still reviewable before enabling it.
await verifyInstructionalPluginContent(plugin)
}
const settings = store.getSettings()
const disabled = new Set(normalizePluginIdList(settings.disabledPlugins))
const consents = normalizePluginConsents(settings.pluginConsents)
if (input.decision === 'approve') {
consents[pluginKey] = plugin.consentFingerprint
disabled.delete(pluginKey)
} else {
disabled.add(pluginKey)
}
store.updateSettings(
{ disabledPlugins: [...disabled], pluginConsents: consents },
{ notifyListeners: true, originWebContentsId: input.originWebContentsId }
)
await pluginService.reconcileActivationState()
}
/** Enables/disables an already-consented plugin. Enabling never bypasses
* consent: with missing or stale consent the plugin stays pending and the
* caller must run the consent flow instead. */
export async function applyPluginEnablement(input: {
store: Store
pluginService: PluginService
pluginKey: string
enabled: boolean
originWebContentsId?: number
}): Promise<void> {
const { store, pluginService, pluginKey, enabled } = input
if (!pluginService.findValidPlugin(pluginKey)) {
throw new Error(`cannot change enablement for unknown plugin ${pluginKey}`)
}
const settings = store.getSettings()
const disabled = new Set(normalizePluginIdList(settings.disabledPlugins))
if (enabled) {
disabled.delete(pluginKey)
} else {
disabled.add(pluginKey)
}
store.updateSettings(
{ disabledPlugins: [...disabled] },
{ notifyListeners: true, originWebContentsId: input.originWebContentsId }
)
await pluginService.reconcileActivationState()
}
+42
View File
@@ -0,0 +1,42 @@
import { PLUGIN_EVENT_PAYLOAD_SCHEMAS } from '../../shared/plugins/plugin-events'
import type { PluginEventName } from '../../shared/plugins/plugin-manifest'
/**
* Server-side event filtering: plugins receive only events they subscribed
* to (manifest `contributes.events` or a runtime `events.subscribe` call) —
* never a firehose. Manifest subscriptions are durable activation triggers;
* dynamic subscriptions live only as long as the worker that made them.
*/
export class PluginEventBus {
private readonly dynamicSubscriptions = new Map<string, Set<PluginEventName>>()
subscribe(pluginKey: string, events: PluginEventName[]): PluginEventName[] {
const existing = this.dynamicSubscriptions.get(pluginKey) ?? new Set<PluginEventName>()
for (const event of events) {
existing.add(event)
}
this.dynamicSubscriptions.set(pluginKey, existing)
return [...existing]
}
isDynamicallySubscribed(pluginKey: string, event: PluginEventName): boolean {
return this.dynamicSubscriptions.get(pluginKey)?.has(event) ?? false
}
/** Dynamic subscriptions die with the worker that registered them. */
clear(pluginKey: string): void {
this.dynamicSubscriptions.delete(pluginKey)
}
/** Validates and bounds an event payload before it reaches any plugin. */
projectPayload(
event: PluginEventName,
payload: unknown
): { ok: true; payload: unknown } | { ok: false; error: string } {
const parsed = PLUGIN_EVENT_PAYLOAD_SCHEMAS[event].safeParse(payload)
return parsed.success
? { ok: true, payload: parsed.data }
: { ok: false, error: `malformed ${event} payload` }
}
}
+48
View File
@@ -0,0 +1,48 @@
import type { PluginEventName } from '../../shared/plugins/plugin-manifest'
import {
isInvalidDiscoveredPlugin,
type DiscoveredPlugin,
type ValidDiscoveredPlugin
} from './plugin-discovery'
import type { PluginEventBus } from './plugin-event-bus'
import type { PluginWorkerController } from './plugin-worker-controller'
export function deliverPluginEvent(options: {
event: PluginEventName
payload: unknown
plugins: readonly DiscoveredPlugin[]
eventBus: PluginEventBus
workerController: PluginWorkerController
isRuntimeApproved: (plugin: ValidDiscoveredPlugin) => boolean
logWarning: (pluginKey: string, line: string) => void
}): void {
const projected = options.eventBus.projectPayload(options.event, options.payload)
if (!projected.ok) {
return
}
for (const plugin of options.plugins) {
if (isInvalidDiscoveredPlugin(plugin) || !options.isRuntimeApproved(plugin)) {
continue
}
const manifestSubscribed = plugin.manifest.contributes.events.some(
(subscription) => subscription.on === options.event
)
if (manifestSubscribed && plugin.manifest.main) {
void options.workerController
.ensure(plugin)
.then((handle) => handle.deliverEvent(options.event, projected.payload))
.catch((error) => {
options.logWarning(
plugin.pluginKey,
`event ${options.event} dropped: ${error instanceof Error ? error.message : String(error)}`
)
})
} else if (options.eventBus.isDynamicallySubscribed(plugin.pluginKey, options.event)) {
options.workerController.deliverEventIfRunning(
plugin.pluginKey,
options.event,
projected.payload
)
}
}
}
+57
View File
@@ -0,0 +1,57 @@
import { execFile } from 'node:child_process'
import { promisify } from 'node:util'
import {
isAllowedPluginGitUrl,
PLUGIN_COMMIT_PATTERN
} from '../../shared/plugins/plugin-install-lockfile'
const execFileAsync = promisify(execFile)
const PLUGIN_GIT_TIMEOUT_MS = 120_000
/** Runs system Git with argv-only invocation so credential helpers and SSH
* remotes work without exposing an executable remote-helper surface. */
export async function runPluginGit(args: string[], cwd: string): Promise<string> {
const { stdout } = await execFileAsync('git', args, {
cwd,
timeout: PLUGIN_GIT_TIMEOUT_MS,
windowsHide: true,
env: {
...process.env,
// Existing non-interactive helpers and SSH agents still work, but a
// background marketplace refresh can never hang on a terminal prompt.
GIT_TERMINAL_PROMPT: '0'
}
})
return stdout.trim()
}
/** Checks out one Git ref into an empty destination and returns exact HEAD. */
export async function checkoutPluginGitSource(input: {
url: string
ref: string
destination: string
workingDirectory: string
}): Promise<string> {
if (!isAllowedPluginGitUrl(input.url)) {
throw new Error('plugin Git URL must use HTTPS or SSH')
}
const ref = input.ref.trim()
if (PLUGIN_COMMIT_PATTERN.test(ref)) {
await runPluginGit(['init', '--quiet', input.destination], input.workingDirectory)
await runPluginGit(['remote', 'add', 'origin', input.url], input.destination)
await runPluginGit(['fetch', '--quiet', '--depth', '1', 'origin', ref], input.destination)
await runPluginGit(['checkout', '--quiet', 'FETCH_HEAD'], input.destination)
} else {
const args = ['clone', '--quiet', '--depth', '1']
if (ref.length > 0) {
args.push('--branch', ref)
}
args.push('--', input.url, input.destination)
await runPluginGit(args, input.workingDirectory)
}
const resolvedCommit = await runPluginGit(['rev-parse', 'HEAD'], input.destination)
if (!PLUGIN_COMMIT_PATTERN.test(resolvedCommit)) {
throw new Error('Git resolved an invalid commit identity')
}
return resolvedCommit
}
@@ -0,0 +1,57 @@
import { z } from 'zod'
import { isQualifiedPluginKey } from '../../shared/plugins/plugin-manifest'
import type { PluginPanelActionOutcome } from '../../shared/plugins/plugin-panel-bridge'
import { executePluginHostCall, type ExecutePluginHostCallInput } from './plugin-host-methods'
const pluginHostCallRequestSchema = z
.object({
method: z.string().min(1).max(128),
params: z.unknown().optional()
})
.strict()
export type PluginHostCallRequest = z.infer<typeof pluginHostCallRequestSchema>
export function isPluginHostCallRequest(request: unknown): request is PluginHostCallRequest {
return pluginHostCallRequestSchema.safeParse(request).success
}
export type PluginHostCallPolicy = Pick<
ExecutePluginHostCallInput,
'grantedCapabilities' | 'services' | 'audit'
>
export type ResolvePluginHostCallPolicy = (
pluginKey: string
) => PluginHostCallPolicy | Promise<PluginHostCallPolicy>
/** Validates the transport envelope, resolves all authority host-side, then
* enters the one capability/schema/audit execution chokepoint. */
export async function executePluginHostCallRequest(input: {
/** Qualified identity already authenticated by the owning transport. */
pluginKey: string
request: unknown
viaPanel: boolean
resolvePolicy: ResolvePluginHostCallPolicy
}): Promise<PluginPanelActionOutcome> {
if (!isQualifiedPluginKey(input.pluginKey)) {
return { ok: false, code: 'invalid_request', error: 'invalid qualified plugin key' }
}
const parsed = pluginHostCallRequestSchema.safeParse(input.request)
if (!parsed.success) {
return { ok: false, code: 'invalid_request', error: 'malformed plugin host call request' }
}
let policy: PluginHostCallPolicy
try {
policy = await input.resolvePolicy(input.pluginKey)
} catch {
return { ok: false, code: 'unavailable', error: 'plugin host policy is not available' }
}
return executePluginHostCall({
pluginId: input.pluginKey,
method: parsed.data.method,
params: parsed.data.params,
viaPanel: input.viaPanel,
...policy
})
}
@@ -0,0 +1,366 @@
import { describe, expect, it, vi } from 'vitest'
import { PLUGIN_HOST_API_V0 } from '../../shared/plugins/plugin-host-api'
import type { PluginCapabilityKind } from '../../shared/plugins/plugin-capabilities'
import {
admitPluginPanelCall,
createPluginPanelCallAdmission
} from '../../shared/plugins/plugin-panel-call-admission'
import type { PluginPanelActionOutcome } from '../../shared/plugins/plugin-panel-bridge'
import type { MethodHandler } from '../../relay/dispatcher'
import {
RELAY_PLUGIN_PANEL_HOST_CALL_METHOD,
RELAY_PLUGIN_WORKER_HOST_CALL_METHOD,
registerRelayPluginHostCallHandlers
} from '../../relay/plugin-host-call-handler'
import {
executePluginHostCallRequest,
type PluginHostCallPolicy,
type ResolvePluginHostCallPolicy
} from './plugin-host-call-adapter'
import type { PluginHostServices } from './plugin-host-methods'
const PLUGIN_KEY = 'orca-samples.demo'
const WORKTREE_ID = 'repo-id::/Users/private/orca'
const TERMINAL_ID = 'terminal:local:one'
type HostCallAdapter = (request: unknown, viaPanel: boolean) => Promise<PluginPanelActionOutcome>
function createServices(): PluginHostServices {
return {
resolveActiveWorktreeContext: vi.fn().mockResolvedValue({
worktreeId: WORKTREE_ID,
branch: 'main',
displayName: 'Orca',
path: '/Users/private/orca'
}),
listWorktreeTerminals: vi
.fn()
.mockResolvedValue([{ id: TERMINAL_ID, title: '/home/private/orca' }]),
sendTerminalText: vi.fn().mockResolvedValue({ accepted: true }),
dispatchPluginNotification: vi.fn().mockResolvedValue({ delivered: true }),
storage: {
get: vi.fn().mockReturnValue('stored'),
set: vi.fn().mockReturnValue({ ok: true }),
delete: vi.fn(),
keys: vi.fn().mockReturnValue(['alpha'])
},
secrets: {
get: vi.fn().mockReturnValue({ ok: true, value: 'secret' }),
set: vi.fn().mockReturnValue({ ok: true }),
delete: vi.fn()
},
settings: {
getAll: vi.fn().mockReturnValue({ theme: 'dark' }),
set: vi.fn().mockReturnValue({ ok: true })
},
subscribeEvents: vi.fn().mockImplementation((_pluginKey, events) => events)
}
}
function createPolicy(
grantedCapabilities: readonly PluginCapabilityKind[] | null,
services: PluginHostServices = createServices(),
audit = { record: vi.fn().mockResolvedValue(undefined) }
): PluginHostCallPolicy {
return { grantedCapabilities, services, audit }
}
function createAdapters(
resolvePolicy: ResolvePluginHostCallPolicy,
limits?: { maxBytes?: number; maxMessages?: number; perMs?: number }
): Record<string, HostCallAdapter> {
const relayHandlers = new Map<string, MethodHandler>()
registerRelayPluginHostCallHandlers(
{ onRequest: (method, handler) => relayHandlers.set(method, handler) },
(context) => (context.clientId === 1 ? PLUGIN_KEY : null),
resolvePolicy,
{ panelAdmission: createPluginPanelCallAdmission({ limits, now: () => 0 }) }
)
const desktopAdmission = createPluginPanelCallAdmission({ limits, now: () => 0 })
return {
'desktop-main': async (request, viaPanel) => {
if (viaPanel) {
const admissionRefusal = admitPluginPanelCall(desktopAdmission, PLUGIN_KEY, request)
if (admissionRefusal) {
return admissionRefusal
}
}
return executePluginHostCallRequest({
pluginKey: PLUGIN_KEY,
request,
viaPanel,
resolvePolicy
})
},
relay: async (request, viaPanel) => {
const registeredMethod = viaPanel
? RELAY_PLUGIN_PANEL_HOST_CALL_METHOD
: RELAY_PLUGIN_WORKER_HOST_CALL_METHOD
return (await relayHandlers.get(registeredMethod)!(request as Record<string, unknown>, {
clientId: 1,
isStale: () => false
})) as PluginPanelActionOutcome
}
}
}
const successParams: Record<string, unknown> = {
'workspace.readContext': {},
'terminal.sendText': { terminalId: TERMINAL_ID, text: 'echo hi', enter: true },
'notifications.show': { title: 'Hello' },
'storage.get': { key: 'alpha' },
'storage.set': { key: 'alpha', value: 1 },
'storage.delete': { key: 'alpha' },
'storage.keys': {},
'secrets.get': { key: 'token' },
'secrets.set': { key: 'token', value: 'secret' },
'secrets.delete': { key: 'token' },
'settings.get': {},
'settings.set': { key: 'theme', value: 'dark' },
'events.subscribe': { events: ['worktree.created'] }
}
describe('plugin host main/relay conformance', () => {
it('runs a granted success through both transports for all 13 v0 methods', async () => {
expect(PLUGIN_HOST_API_V0).toHaveLength(13)
expect(Object.keys(successParams).sort()).toEqual(
PLUGIN_HOST_API_V0.map((entry) => entry.name).sort()
)
expect(PLUGIN_HOST_API_V0.every((entry) => entry.stability === 'experimental')).toBe(true)
expect(PLUGIN_HOST_API_V0.every((entry) => entry.scope.length > 0)).toBe(true)
for (const spec of PLUGIN_HOST_API_V0) {
const policy = createPolicy([spec.capability])
const resolvePolicy = vi.fn().mockResolvedValue(policy)
const outcomes = await Promise.all(
Object.values(createAdapters(resolvePolicy)).map((adapter) =>
adapter({ method: spec.name, params: successParams[spec.name] }, spec.panel)
)
)
expect(outcomes, spec.name).toHaveLength(2)
expect(outcomes[0], spec.name).toEqual(outcomes[1])
expect(outcomes[0], spec.name).toMatchObject({ ok: true })
}
})
it('projects workspace context without host paths on main and relay', async () => {
const resolvePolicy = vi.fn().mockResolvedValue(createPolicy(['workspace:read']))
for (const adapter of Object.values(createAdapters(resolvePolicy))) {
const outcome = await adapter({ method: 'workspace.readContext', params: {} }, true)
expect(outcome).toEqual({
ok: true,
value: {
branch: 'main',
displayName: 'Orca',
terminals: [{ id: TERMINAL_ID }]
}
})
expect(outcome).not.toHaveProperty('value.path')
expect(outcome).not.toHaveProperty('value.worktreeId')
}
})
const deniedCases: {
name: string
request: unknown
viaPanel: boolean
policy: () => PluginHostCallPolicy
code: string
}[] = [
{
name: 'missing or stale consent',
request: { method: 'workspace.readContext', params: {} },
viaPanel: true,
policy: () => createPolicy(null),
code: 'consent_required'
},
{
name: 'missing capability',
request: { method: 'workspace.readContext', params: {} },
viaPanel: true,
policy: () => createPolicy([]),
code: 'capability_denied'
},
{
name: 'unknown method',
request: { method: 'workspace.erase', params: {} },
viaPanel: false,
policy: () => createPolicy(['workspace:read']),
code: 'unknown_method'
},
{
name: 'malformed params',
request: {
method: 'terminal.sendText',
params: { terminalId: TERMINAL_ID, text: '' }
},
viaPanel: true,
policy: () => createPolicy(['terminal:send']),
code: 'invalid_params'
},
{
name: 'panel-forbidden method',
request: { method: 'storage.get', params: { key: 'alpha' } },
viaPanel: true,
policy: () => createPolicy(['storage']),
code: 'panel_forbidden'
},
{
name: 'malformed result',
request: {
method: 'notifications.show',
params: { title: 'Hello' }
},
viaPanel: true,
policy: () => {
const services = createServices()
services.dispatchPluginNotification = vi
.fn()
.mockResolvedValue({ delivered: 'yes' } as unknown as { delivered: boolean })
return createPolicy(['notifications:show'], services)
},
code: 'action_failed'
},
{
name: 'mutation audit failure',
request: {
method: 'storage.set',
params: { key: 'alpha', value: 1 }
},
viaPanel: false,
policy: () =>
createPolicy(['storage'], createServices(), {
record: vi.fn().mockRejectedValue(new Error('disk full'))
}),
code: 'action_failed'
}
]
it.each(deniedCases)('returns identical $code codes for $name', async (testCase) => {
const outcomes: PluginPanelActionOutcome[] = []
for (const adapterName of ['desktop-main', 'relay']) {
const resolvePolicy = vi.fn().mockImplementation(() => testCase.policy())
const adapter = createAdapters(resolvePolicy)[adapterName]!
outcomes.push(await adapter(testCase.request, testCase.viaPanel))
}
expect(outcomes[0]).toMatchObject({ ok: false, code: testCase.code })
expect(outcomes[1]).toMatchObject({ ok: false, code: testCase.code })
expect(outcomes[0]).toEqual(outcomes[1])
})
it('enforces the same per-plugin panel budget on desktop main and relay', async () => {
for (const adapterName of ['desktop-main', 'relay']) {
const resolvePolicy = vi.fn().mockResolvedValue(createPolicy(['notifications:show']))
const adapter = createAdapters(resolvePolicy, {
maxMessages: 1,
perMs: 10_000
})[adapterName]!
await expect(
adapter({ method: 'notifications.show', params: { title: 'first' } }, true)
).resolves.toMatchObject({ ok: true })
await expect(
adapter({ method: 'notifications.show', params: { title: 'second' } }, true)
).resolves.toEqual({
ok: false,
code: 'rate_limited',
error: 'too many panel requests'
})
}
})
it('charges malformed and oversized panel traffic before schema parsing', async () => {
for (const adapterName of ['desktop-main', 'relay']) {
const resolvePolicy = vi.fn().mockResolvedValue(createPolicy(['notifications:show']))
const adapter = createAdapters(resolvePolicy, {
maxBytes: 128,
maxMessages: 2,
perMs: 10_000
})[adapterName]!
await expect(
adapter({ method: 'notifications.show', unexpected: true }, true)
).resolves.toMatchObject({ ok: false, code: 'invalid_request' })
await expect(
adapter(
{
method: 'notifications.show',
params: { title: 'x'.repeat(256) }
},
true
)
).resolves.toEqual({
ok: false,
code: 'invalid_request',
error: 'panel message exceeds the size limit'
})
await expect(
adapter({ method: 'notifications.show', params: { title: 'third' } }, true)
).resolves.toEqual({
ok: false,
code: 'rate_limited',
error: 'too many panel requests'
})
expect(resolvePolicy).not.toHaveBeenCalled()
}
})
it('binds relay plugin identity to the requesting connection', async () => {
const relayHandlers = new Map<string, MethodHandler>()
const services = createServices()
const resolvePolicy = vi.fn().mockResolvedValue(createPolicy(['storage'], services))
const resolveIdentity = vi
.fn()
.mockImplementation(({ clientId }: { clientId: number }) =>
clientId === 7 ? PLUGIN_KEY : null
)
registerRelayPluginHostCallHandlers(
{ onRequest: (method, handler) => relayHandlers.set(method, handler) },
resolveIdentity,
resolvePolicy
)
const handler = relayHandlers.get(RELAY_PLUGIN_WORKER_HOST_CALL_METHOD)!
await expect(
handler(
{ method: 'storage.get', params: { key: 'alpha' } },
{ clientId: 7, isStale: () => false }
)
).resolves.toMatchObject({ ok: true })
expect(services.storage.get).toHaveBeenCalledWith(PLUGIN_KEY, 'alpha')
await expect(
handler(
{ method: 'storage.get', params: { key: 'alpha' } },
{ clientId: 8, isStale: () => false }
)
).resolves.toMatchObject({ ok: false, code: 'unavailable' })
expect(resolvePolicy).toHaveBeenCalledTimes(1)
})
it('rejects malformed envelopes and client-supplied authority before policy resolution', async () => {
const requests = [
{ pluginKey: '../evil', method: 'storage.get', params: { key: 'alpha' } },
{
pluginKey: PLUGIN_KEY,
method: 'storage.get',
params: { key: 'alpha' },
grantedCapabilities: ['storage']
},
{
pluginKey: PLUGIN_KEY,
method: 'storage.get',
params: { key: 'alpha' },
viaPanel: false
}
]
for (const request of requests) {
for (const adapterName of ['desktop-main', 'relay']) {
const resolvePolicy = vi.fn().mockResolvedValue(createPolicy(['storage']))
const outcome = await createAdapters(resolvePolicy)[adapterName]!(request, false)
expect(outcome).toMatchObject({ ok: false, code: 'invalid_request' })
expect(resolvePolicy).not.toHaveBeenCalled()
}
}
})
})
+41
View File
@@ -0,0 +1,41 @@
/**
* Child-process entry for the out-of-process plugin worker. Forked with
* ELECTRON_RUN_AS_NODE, so this file must stay plain Node — no electron
* imports (directly or transitively). All logic lives in
* `plugin-host-runtime.ts`; this file only wires the fork IPC channel.
*/
import { createPluginWorkerRuntime } from './plugin-host-runtime'
import type { PluginWorkerChildMessage } from '../../shared/plugins/plugin-host-protocol'
function sendToParent(message: PluginWorkerChildMessage): void {
process.send?.(message)
}
const runtime = createPluginWorkerRuntime({ send: sendToParent })
process.on('message', (raw: unknown) => {
void runtime.handleMessage(raw)
})
// Why: third-party plugin code runs here; an escaped rejection must not leave
// a zombie worker. Report the crash so the parent can supervise/restart.
function dieFatally(error: unknown): void {
try {
sendToParent({
type: 'fatal',
error: error instanceof Error ? (error.stack ?? error.message) : String(error)
})
} catch {
// Channel already gone; nothing left to report to.
}
process.exit(1)
}
process.on('uncaughtException', dieFatally)
process.on('unhandledRejection', dieFatally)
// Why: if the parent dies without sending shutdown, the IPC channel closes;
// exit instead of lingering as an orphaned Node process.
process.on('disconnect', () => {
process.exit(0)
})
@@ -0,0 +1,181 @@
import {
getPluginHostMethodSpec,
PLUGIN_HOST_API_V0,
PLUGIN_TERMINAL_ID_MAX_LENGTH,
PLUGIN_WORKSPACE_LABEL_MAX_LENGTH,
PLUGIN_WORKSPACE_TERMINAL_LIMIT,
type PluginHostMethodSpec
} from '../../shared/plugins/plugin-host-api'
import type { PluginEventName } from '../../shared/plugins/plugin-manifest'
export type PluginWorktreeContext = {
worktreeId: string
branch: string
displayName: string
}
/** Structural service surface the facade delegates to. Desktop main binds it
* over runtime services; relay policy and conformance tests bind fakes. */
export type PluginHostServices = {
resolveActiveWorktreeContext(): Promise<PluginWorktreeContext | null>
listWorktreeTerminals(worktreeId: string): Promise<{ id: string }[]>
sendTerminalText(
terminalId: string,
action: { text: string; enter: boolean }
): Promise<{ accepted: boolean }>
dispatchPluginNotification(input: {
pluginId: string
title: string
body?: string
}): Promise<{ delivered: boolean }>
storage: {
get(pluginId: string, key: string): unknown
set(pluginId: string, key: string, value: unknown): { ok: true } | { ok: false; error: string }
delete(pluginId: string, key: string): void
keys(pluginId: string): string[]
}
secrets: {
get(
pluginId: string,
key: string
): { ok: true; value: string | null } | { ok: false; error: string }
set(pluginId: string, key: string, value: string): { ok: true } | { ok: false; error: string }
delete(pluginId: string, key: string): void
}
settings: {
getAll(pluginId: string): Record<string, unknown>
set(pluginId: string, key: string, value: unknown): { ok: true } | { ok: false; error: string }
}
subscribeEvents(pluginId: string, events: PluginEventName[]): PluginEventName[]
}
export type BoundPluginHostMethod = {
spec: PluginHostMethodSpec
handler: (
params: unknown,
ctx: { pluginId: string; services: PluginHostServices }
) => Promise<unknown>
}
function definePluginMethod(
name: string,
handler: BoundPluginHostMethod['handler']
): [string, BoundPluginHostMethod] {
const spec = getPluginHostMethodSpec(name)
if (!spec) {
throw new Error(`no host API spec for method ${name}`)
}
return [name, { spec, handler }]
}
const HANDLERS = new Map<string, BoundPluginHostMethod>([
definePluginMethod('workspace.readContext', async (_params, { services }) => {
const context = await services.resolveActiveWorktreeContext()
if (!context) {
return null
}
const terminals = await services.listWorktreeTerminals(context.worktreeId)
// Why: Orca worktree ids embed provider paths, so the public projection
// must select safe fields instead of spreading the internal context.
return {
branch: context.branch.slice(0, PLUGIN_WORKSPACE_LABEL_MAX_LENGTH),
displayName: context.displayName.slice(0, PLUGIN_WORKSPACE_LABEL_MAX_LENGTH),
terminals: terminals
.filter(
(terminal) =>
terminal.id.length > 0 && terminal.id.length <= PLUGIN_TERMINAL_ID_MAX_LENGTH
)
.slice(0, PLUGIN_WORKSPACE_TERMINAL_LIMIT)
.map((terminal) => ({ id: terminal.id }))
}
}),
definePluginMethod('terminal.sendText', async (params, { services }) => {
const { terminalId, text, enter } = params as {
terminalId: string
text: string
enter: boolean
}
const context = await services.resolveActiveWorktreeContext()
if (!context) {
throw new Error('no active worktree is available for terminal input')
}
// Why: terminal handles are provider-owned and can outlive focus changes;
// re-list the resolved worktree immediately before routing plugin input.
const terminals = await services.listWorktreeTerminals(context.worktreeId)
if (!terminals.some((terminal) => terminal.id === terminalId)) {
throw new Error('terminal is outside the active worktree')
}
const result = await services.sendTerminalText(terminalId, { text, enter })
return { accepted: result.accepted }
}),
definePluginMethod('notifications.show', async (params, { pluginId, services }) => {
const { title, body } = params as { title: string; body?: string }
return services.dispatchPluginNotification({ pluginId, title, body })
}),
definePluginMethod('storage.get', async (params, { pluginId, services }) => {
const { key } = params as { key: string }
return { value: services.storage.get(pluginId, key) ?? null }
}),
definePluginMethod('storage.set', async (params, { pluginId, services }) => {
const { key, value } = params as { key: string; value: unknown }
const result = services.storage.set(pluginId, key, value)
if (!result.ok) {
throw new Error(result.error)
}
return { ok: true }
}),
definePluginMethod('storage.delete', async (params, { pluginId, services }) => {
const { key } = params as { key: string }
services.storage.delete(pluginId, key)
return { ok: true }
}),
definePluginMethod('storage.keys', async (_params, { pluginId, services }) => {
return { keys: services.storage.keys(pluginId) }
}),
definePluginMethod('secrets.get', async (params, { pluginId, services }) => {
const { key } = params as { key: string }
const result = services.secrets.get(pluginId, key)
if (!result.ok) {
throw new Error(result.error)
}
return { value: result.value }
}),
definePluginMethod('secrets.set', async (params, { pluginId, services }) => {
const { key, value } = params as { key: string; value: string }
const result = services.secrets.set(pluginId, key, value)
if (!result.ok) {
throw new Error(result.error)
}
return { ok: true }
}),
definePluginMethod('secrets.delete', async (params, { pluginId, services }) => {
const { key } = params as { key: string }
services.secrets.delete(pluginId, key)
return { ok: true }
}),
definePluginMethod('settings.get', async (_params, { pluginId, services }) => {
return { settings: services.settings.getAll(pluginId) }
}),
definePluginMethod('settings.set', async (params, { pluginId, services }) => {
const { key, value } = params as { key: string; value: unknown }
const result = services.settings.set(pluginId, key, value)
if (!result.ok) {
throw new Error(result.error)
}
return { ok: true }
}),
definePluginMethod('events.subscribe', async (params, { pluginId, services }) => {
const { events } = params as { events: PluginEventName[] }
return { subscribed: services.subscribeEvents(pluginId, events) }
})
])
// Why: adding a facade schema without a binding must fail at module load,
// before a plugin can observe transport-specific behavior.
if (HANDLERS.size !== PLUGIN_HOST_API_V0.length) {
throw new Error('plugin host API spec table and handler bindings are out of sync')
}
export function getBoundPluginHostMethod(name: string): BoundPluginHostMethod | null {
return HANDLERS.get(name) ?? null
}
@@ -0,0 +1,232 @@
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { describe, expect, it, vi } from 'vitest'
import { PLUGIN_WORKSPACE_TERMINAL_LIMIT } from '../../shared/plugins/plugin-host-api'
import { bindPluginHostServices, type PluginRuntimeDelegate } from './plugin-host-service-bindings'
import { executePluginHostCall, type PluginHostServices } from './plugin-host-methods'
function createServices(storageSet: PluginHostServices['storage']['set']): PluginHostServices {
return {
resolveActiveWorktreeContext: vi.fn().mockResolvedValue(null),
listWorktreeTerminals: vi.fn().mockResolvedValue([]),
sendTerminalText: vi.fn().mockResolvedValue({ accepted: true }),
dispatchPluginNotification: vi.fn().mockResolvedValue({ delivered: true }),
storage: {
get: vi.fn(),
set: storageSet,
delete: vi.fn(),
keys: vi.fn().mockReturnValue([])
},
secrets: {
get: vi.fn().mockReturnValue({ ok: true, value: null }),
set: vi.fn().mockReturnValue({ ok: true }),
delete: vi.fn()
},
settings: {
getAll: vi.fn().mockReturnValue({}),
set: vi.fn().mockReturnValue({ ok: true })
},
subscribeEvents: vi.fn().mockReturnValue([])
}
}
describe('executePluginHostCall mutation auditing', () => {
it('rejects prototype-sensitive storage keys before any host service call', async () => {
const storageSet = vi.fn().mockReturnValue({ ok: true })
const outcome = await executePluginHostCall({
pluginId: 'orca-samples.demo',
method: 'storage.set',
params: { key: '__proto__', value: 42 },
viaPanel: false,
grantedCapabilities: ['storage'],
services: createServices(storageSet),
audit: { record: vi.fn().mockResolvedValue(undefined) }
})
expect(outcome).toMatchObject({ ok: false, code: 'invalid_params' })
expect(storageSet).not.toHaveBeenCalled()
})
it('rejects non-JSON storage values before any host service call', async () => {
const storageSet = vi.fn().mockReturnValue({ ok: true })
const outcome = await executePluginHostCall({
pluginId: 'orca-samples.demo',
method: 'storage.set',
params: { key: 'created', value: new Date() },
viaPanel: false,
grantedCapabilities: ['storage'],
services: createServices(storageSet),
audit: { record: vi.fn().mockResolvedValue(undefined) }
})
expect(outcome).toMatchObject({ ok: false, code: 'invalid_params' })
expect(storageSet).not.toHaveBeenCalled()
})
it('fails closed before a mutation when the audit intent cannot be recorded', async () => {
const storageSet = vi.fn().mockReturnValue({ ok: true })
const outcome = await executePluginHostCall({
pluginId: 'orca-samples.demo',
method: 'storage.set',
params: { key: 'answer', value: 42 },
viaPanel: false,
grantedCapabilities: ['storage'],
services: createServices(storageSet),
audit: { record: vi.fn().mockRejectedValue(new Error('disk full')) }
})
expect(outcome).toMatchObject({ ok: false, code: 'action_failed' })
expect(storageSet).not.toHaveBeenCalled()
})
it('records an intent before the mutation and its outcome afterward', async () => {
const order: string[] = []
const storageSet = vi.fn(() => {
order.push('mutation')
return { ok: true as const }
})
const record = vi.fn(async (entry: { outcome: string }) => {
order.push(`audit:${entry.outcome}`)
})
const outcome = await executePluginHostCall({
pluginId: 'orca-samples.demo',
method: 'storage.set',
params: { key: 'answer', value: 42 },
viaPanel: false,
grantedCapabilities: ['storage'],
services: createServices(storageSet),
audit: { record }
})
expect(outcome).toEqual({ ok: true, value: { ok: true } })
expect(order).toEqual(['audit:attempt', 'mutation', 'audit:ok'])
})
it('refuses mutations when no audit writer is configured', async () => {
const storageSet = vi.fn().mockReturnValue({ ok: true })
const outcome = await executePluginHostCall({
pluginId: 'orca-samples.demo',
method: 'storage.set',
params: { key: 'answer', value: 42 },
viaPanel: false,
grantedCapabilities: ['storage'],
services: createServices(storageSet)
})
expect(outcome).toMatchObject({ ok: false, code: 'unavailable' })
expect(storageSet).not.toHaveBeenCalled()
})
})
function createTerminalHarness(terminalHandles: string[]): {
delegate: PluginRuntimeDelegate
services: PluginHostServices
} {
const delegate: PluginRuntimeDelegate = {
resolveActiveWorktreeContext: vi.fn().mockResolvedValue({
worktreeId: 'worktree-1',
path: '/Users/private/repo',
branch: 'main',
displayName: 'Repo'
}),
listTerminals: vi.fn().mockResolvedValue({
terminals: terminalHandles.map((handle) => ({ handle, title: null }))
}),
sendTerminal: vi.fn().mockResolvedValue({ accepted: true }),
dispatchPluginNotification: vi.fn().mockResolvedValue({ delivered: true })
}
return {
delegate,
services: bindPluginHostServices({
delegate,
pluginsDataDir: join(tmpdir(), 'plugin-host-methods-test'),
subscribeEvents: vi.fn().mockReturnValue([])
})
}
}
async function sendTerminalText(
services: PluginHostServices,
terminalId: string
): ReturnType<typeof executePluginHostCall> {
return executePluginHostCall({
pluginId: 'orca-samples.demo',
method: 'terminal.sendText',
params: { terminalId, text: 'echo hi', enter: true },
viaPanel: true,
grantedCapabilities: ['terminal:send'],
services,
audit: { record: vi.fn().mockResolvedValue(undefined) }
})
}
describe('terminal.sendText explicit worktree routing', () => {
it('performs one bounded list and zero sends when the terminal is outside the worktree', async () => {
const { delegate, services } = createTerminalHarness(['terminal:local:other'])
const outcome = await sendTerminalText(services, 'terminal:ssh:requested')
expect(outcome).toMatchObject({ ok: false, code: 'action_failed' })
expect(delegate.resolveActiveWorktreeContext).toHaveBeenCalledTimes(1)
expect(delegate.listTerminals).toHaveBeenCalledTimes(1)
expect(delegate.listTerminals).toHaveBeenCalledWith(
'id:worktree-1',
PLUGIN_WORKSPACE_TERMINAL_LIMIT
)
expect(delegate.sendTerminal).not.toHaveBeenCalled()
})
it.each(['terminal:local:one', 'terminal:ssh:opaque-provider-id'])(
'performs one bounded list and one send for provider-agnostic id %s',
async (terminalId) => {
const { delegate, services } = createTerminalHarness([terminalId])
const outcome = await sendTerminalText(services, terminalId)
expect(outcome).toEqual({ ok: true, value: { accepted: true } })
expect(delegate.resolveActiveWorktreeContext).toHaveBeenCalledTimes(1)
expect(delegate.listTerminals).toHaveBeenCalledTimes(1)
expect(delegate.listTerminals).toHaveBeenCalledWith(
'id:worktree-1',
PLUGIN_WORKSPACE_TERMINAL_LIMIT
)
expect(delegate.sendTerminal).toHaveBeenCalledTimes(1)
expect(delegate.sendTerminal).toHaveBeenCalledWith(terminalId, {
text: 'echo hi',
enter: true
})
expect(vi.mocked(delegate.listTerminals).mock.invocationCallOrder[0]!).toBeLessThan(
vi.mocked(delegate.sendTerminal).mock.invocationCallOrder[0]!
)
}
)
it('bounds workspace.readContext and omits the provider path', async () => {
const handles = Array.from(
{ length: PLUGIN_WORKSPACE_TERMINAL_LIMIT + 10 },
(_, index) => `terminal:local:${index}`
)
const { delegate, services } = createTerminalHarness(handles)
const outcome = await executePluginHostCall({
pluginId: 'orca-samples.demo',
method: 'workspace.readContext',
params: {},
viaPanel: true,
grantedCapabilities: ['workspace:read'],
services
})
expect(outcome).toMatchObject({
ok: true,
value: { branch: 'main', displayName: 'Repo' }
})
expect(outcome).not.toHaveProperty('value.path')
expect(outcome).not.toHaveProperty('value.worktreeId')
expect(outcome.ok && (outcome.value as { terminals: unknown[] }).terminals).toHaveLength(
PLUGIN_WORKSPACE_TERMINAL_LIMIT
)
expect(delegate.listTerminals).toHaveBeenCalledTimes(1)
})
})
+144
View File
@@ -0,0 +1,144 @@
import { getBoundPluginHostMethod, type PluginHostServices } from './plugin-host-method-bindings'
import { isQualifiedPluginKey } from '../../shared/plugins/plugin-manifest'
import { gatePluginHostCall as decidePluginHostCall } from '../../shared/plugins/plugin-capability-gate'
import type { PluginCapabilityKind } from '../../shared/plugins/plugin-capabilities'
import type { PluginPanelActionOutcome } from '../../shared/plugins/plugin-panel-bridge'
import type { PluginAuditLog } from './plugin-audit-log'
/**
* Host API v0 handler bindings — the one place plugin-originated calls
* (panel bridge, worker hostCall, serve RPC relay) execute. Handlers
* delegate to runtime services through the structural `PluginHostServices`
* interface, so this module stays electron-free and the relay conformance
* suite can run the identical chokepoint against a fake service set.
*/
export type { PluginHostServices } from './plugin-host-method-bindings'
export type ExecutePluginHostCallInput = {
/** Qualified plugin key, bound host-side from authenticated identity. */
pluginId: string
method: string
params: unknown
/** True when the call arrives over the sandboxed panel bridge. */
viaPanel: boolean
/** Consented capability kinds; null = unknown/disabled/consent-stale. */
grantedCapabilities: readonly PluginCapabilityKind[] | null
services: PluginHostServices | null
audit?: Pick<PluginAuditLog, 'record'>
}
export async function executePluginHostCall(
input: ExecutePluginHostCallInput
): Promise<PluginPanelActionOutcome> {
if (!isQualifiedPluginKey(input.pluginId)) {
return { ok: false, code: 'invalid_request', error: 'invalid qualified plugin key' }
}
const gate = decidePluginHostCall(
{ grantedCapabilities: input.grantedCapabilities, viaPanel: input.viaPanel },
input.method
)
if (!gate.granted) {
return { ok: false, code: gate.code, error: gate.error }
}
const bound = getBoundPluginHostMethod(input.method)
if (!bound) {
return { ok: false, code: 'unknown_method', error: `unknown host method: ${input.method}` }
}
const parsedParams = bound.spec.params.safeParse(input.params)
if (!parsedParams.success) {
const issue = parsedParams.error.issues[0]
const path = issue?.path.join('.') || '(root)'
return {
ok: false,
code: 'invalid_params',
error: `${path}: ${issue?.message ?? 'invalid params'}`
}
}
if (!input.services) {
return { ok: false, code: 'unavailable', error: 'runtime is not available' }
}
const auditMutation = async (outcome: 'attempt' | 'ok' | 'error'): Promise<void> => {
if (bound.spec.mutation && input.audit) {
await input.audit.record({
ts: Date.now(),
actor: `plugin:${input.pluginId}`,
method: input.method,
summary: summarizeParams(input.method, parsedParams.data),
outcome
})
}
}
if (bound.spec.mutation) {
if (!input.audit) {
return {
ok: false,
code: 'unavailable',
error: 'mutation audit log is not available'
}
}
try {
// The intent is appended before the handler. If this write fails, the
// mutation is never attempted.
await auditMutation('attempt')
} catch {
return {
ok: false,
code: 'action_failed',
error: 'mutation audit log could not be written'
}
}
}
try {
const value = await bound.handler(parsedParams.data, {
pluginId: input.pluginId,
services: input.services
})
const validated = bound.spec.result.safeParse(value)
if (!validated.success) {
await auditMutation('error').catch(() => undefined)
// A result-schema mismatch is a host bug; fail the call rather than
// leaking an unvalidated shape into plugin-facing transports.
return {
ok: false,
code: 'action_failed',
error: `internal: malformed ${input.method} result`
}
}
await auditMutation('ok').catch(() => undefined)
return { ok: true, value: validated.data }
} catch (error) {
await auditMutation('error').catch(() => undefined)
return {
ok: false,
code: 'action_failed',
error: error instanceof Error ? error.message : String(error)
}
}
}
/** Bounded, content-free summaries for the audit log. */
function summarizeParams(method: string, params: unknown): string {
const record = (typeof params === 'object' && params !== null ? params : {}) as Record<
string,
unknown
>
switch (method) {
case 'terminal.sendText': {
const text = typeof record.text === 'string' ? record.text : ''
return `terminal=${String(record.terminalId)} bytes=${Buffer.byteLength(text, 'utf8')} enter=${record.enter === true}`
}
case 'notifications.show': {
const title = typeof record.title === 'string' ? record.title : ''
return `titleChars=${title.length}`
}
case 'storage.set':
case 'storage.delete':
case 'secrets.set':
case 'secrets.delete':
case 'settings.set':
return `key=${String(record.key)}`
default:
return ''
}
}
@@ -0,0 +1,135 @@
import { EventEmitter } from 'node:events'
import { PassThrough } from 'node:stream'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const processMocks = vi.hoisted(() => ({ fork: vi.fn() }))
vi.mock('node:child_process', () => ({ fork: processMocks.fork }))
import { startPluginWorker } from './plugin-host-process'
class FakeChild extends EventEmitter {
connected = true
stdout = new PassThrough()
stderr = new PassThrough()
send = vi.fn()
kill = vi.fn()
}
function start(child: FakeChild, options: { eventTimeoutMs?: number } = {}) {
processMocks.fork.mockReturnValue(child)
return startPluginWorker({
pluginId: 'orca-samples.demo',
rootDir: '/plugin',
mainEntry: 'worker.js',
entryPath: '/host.js',
grantedCapabilities: [],
executeHostCall: async () => ({ ok: true, value: null }),
log: vi.fn(),
...options
})
}
beforeEach(() => {
processMocks.fork.mockReset()
})
afterEach(() => {
vi.useRealTimers()
})
describe('startPluginWorker', () => {
it('does not inherit Orca execArgv', async () => {
const child = new FakeChild()
const pending = start(child)
child.emit('message', { type: 'ready', commands: [] })
await pending
expect(processMocks.fork).toHaveBeenCalledWith(
'/host.js',
[],
expect.objectContaining({ execArgv: [] })
)
})
it('replays an exit that happened before handle registration', async () => {
const child = new FakeChild()
const pending = start(child)
child.emit('message', { type: 'ready', commands: ['run'] })
const handle = await pending
child.emit('exit', 23)
const onExit = vi.fn()
handle.onExit(onExit)
expect(onExit).toHaveBeenCalledOnce()
expect(onExit).toHaveBeenCalledWith(23)
})
it('kills a live worker that disconnects its IPC channel', async () => {
const child = new FakeChild()
const pending = start(child)
child.emit('message', { type: 'ready', commands: ['run'] })
const handle = await pending
const command = handle.invokeCommand('run')
child.connected = false
child.emit('disconnect')
await expect(command).rejects.toThrow('disconnected')
expect(child.kill).toHaveBeenCalledWith('SIGKILL')
})
it('counts delivered events as in flight until their acknowledgement', async () => {
const child = new FakeChild()
const pending = start(child)
child.emit('message', { type: 'ready', commands: [] })
const handle = await pending
handle.deliverEvent('worktree.created', {
worktreeId: 'worktree-1',
path: '/repo',
branch: 'feature'
})
expect(handle.inFlightCount()).toBe(1)
child.emit('message', { type: 'eventAck', eventId: 0 })
expect(handle.inFlightCount()).toBe(0)
})
it('kills a worker whose event handler never acknowledges completion', async () => {
vi.useFakeTimers()
const child = new FakeChild()
const pending = start(child, { eventTimeoutMs: 25 })
child.emit('message', { type: 'ready', commands: [] })
const handle = await pending
handle.deliverEvent('worktree.created', {
worktreeId: 'worktree-1',
path: '/repo',
branch: 'feature'
})
await vi.advanceTimersByTimeAsync(25)
expect(handle.inFlightCount()).toBe(0)
expect(child.kill).toHaveBeenCalledWith('SIGKILL')
})
it('kills a worker that exceeds the pending event cap', async () => {
const child = new FakeChild()
const pending = start(child)
child.emit('message', { type: 'ready', commands: [] })
const handle = await pending
for (let index = 0; index < 65; index += 1) {
handle.deliverEvent('agent.status.changed', {
worktreeId: null,
paneKey: `pane-${index}`,
state: 'working',
receivedAt: Date.now()
})
}
expect(handle.inFlightCount()).toBe(64)
expect(child.kill).toHaveBeenCalledWith('SIGKILL')
})
})
+332
View File
@@ -0,0 +1,332 @@
import { fork, type ChildProcess } from 'node:child_process'
import { existsSync } from 'node:fs'
import { join } from 'node:path'
import {
PLUGIN_WORKER_INVOKE_TIMEOUT_MS,
PLUGIN_WORKER_READY_TIMEOUT_MS,
pluginWorkerChildMessageSchema,
type PluginWorkerParentMessage
} from '../../shared/plugins/plugin-host-protocol'
import type { PluginCapabilityKind } from '../../shared/plugins/plugin-capabilities'
import type { PluginEventName } from '../../shared/plugins/plugin-manifest'
import type { PluginPanelActionOutcome } from '../../shared/plugins/plugin-panel-bridge'
import { buildPluginWorkerEnv } from './plugin-worker-env'
import { pipePluginWorkerOutput } from './plugin-worker-output-buffer'
// Grace between the shutdown message and SIGKILL: long enough for plugin
// cleanup, short enough that disable/quit never feels stuck.
const PLUGIN_WORKER_SHUTDOWN_GRACE_MS = 2_000
const PLUGIN_WORKER_EVENT_TIMEOUT_MS = 5 * 60_000
const PLUGIN_WORKER_MAX_PENDING_EVENTS = 64
export type PluginWorkerLogSink = (level: 'info' | 'warn' | 'error', line: string) => void
/** Executes a worker-originated host API call; the outcome is relayed back
* over the fork channel as a hostResult message. */
export type PluginWorkerHostCallExecutor = (
method: string,
params: unknown
) => Promise<PluginPanelActionOutcome>
export type PluginWorkerHandle = {
/** Command ids the worker registered on activate (⊆ manifest commands). */
commands: readonly string[]
invokeCommand(commandId: string, args?: unknown): Promise<unknown>
deliverEvent(event: PluginEventName, payload: unknown): void
/** Milliseconds timestamp of the last completed work (for idle reap). */
lastActivityAt(): number
inFlightCount(): number
dispose(): Promise<void>
kill(): void
onExit(callback: (code: number | null) => void): void
}
export type StartPluginWorkerOptions = {
pluginId: string
rootDir: string
mainEntry: string
/** Absolute path to the compiled plugin-host-entry.js, resolved by caller. */
entryPath: string
grantedCapabilities: readonly PluginCapabilityKind[]
executeHostCall: PluginWorkerHostCallExecutor
log: PluginWorkerLogSink
readyTimeoutMs?: number
invokeTimeoutMs?: number
eventTimeoutMs?: number
signal?: AbortSignal
}
/**
* Resolves the compiled child entry from the app path. Mirrors
* getDaemonEntryPath(): packaged apps must fork the asar-unpacked copy
* because fork() cannot execute scripts from inside app.asar.
*/
export function resolvePluginHostEntryPath(appPath: string, isPackaged: boolean): string {
const basePath = isPackaged ? appPath.replace('app.asar', 'app.asar.unpacked') : appPath
const directEntryPath = join(basePath, 'plugin-host-entry.js')
if (existsSync(directEntryPath)) {
return directEntryPath
}
return join(basePath, 'out', 'main', 'plugin-host-entry.js')
}
type PendingCall = {
resolve: (value: unknown) => void
reject: (error: Error) => void
timer: ReturnType<typeof setTimeout>
}
export async function startPluginWorker(
options: StartPluginWorkerOptions
): Promise<PluginWorkerHandle> {
const { pluginId, rootDir, mainEntry, entryPath, log } = options
const readyTimeoutMs = options.readyTimeoutMs ?? PLUGIN_WORKER_READY_TIMEOUT_MS
const invokeTimeoutMs = options.invokeTimeoutMs ?? PLUGIN_WORKER_INVOKE_TIMEOUT_MS
const eventTimeoutMs = options.eventTimeoutMs ?? PLUGIN_WORKER_EVENT_TIMEOUT_MS
const tag = `[plugin:${pluginId}]`
const child: ChildProcess = fork(entryPath, [], {
// Why: ELECTRON_RUN_AS_NODE makes the forked Electron binary behave as
// plain Node. The env is a scrubbed allowlist — never ...process.env,
// which can carry shell-exported secrets into third-party code.
env: buildPluginWorkerEnv(),
// Why: inspector/loader flags from Orca's own launch must never execute
// inside third-party plugin workers.
execArgv: [],
// Why: the protocol permits structured-clone values. Node's default JSON
// fork serialization rejects BigInt, cycles, maps, and typed arrays.
serialization: 'advanced',
stdio: ['ignore', 'pipe', 'pipe', 'ipc']
})
pipePluginWorkerOutput(child.stdout, 'info', log)
pipePluginWorkerOutput(child.stderr, 'error', log)
const pendingCommands = new Map<number, PendingCall>()
const pendingEvents = new Map<number, ReturnType<typeof setTimeout>>()
const exitCallbacks: ((code: number | null) => void)[] = []
let nextCallId = 0
let nextEventId = 0
let exited = false
let exitCode: number | null = null
let disposed = false
let lastActivityAt = Date.now()
function sendToChild(message: PluginWorkerParentMessage): void {
if (child.connected) {
child.send(message)
}
}
function rejectAllPending(reason: string): void {
for (const [callId, entry] of pendingCommands) {
clearTimeout(entry.timer)
pendingCommands.delete(callId)
entry.reject(new Error(reason))
}
for (const timer of pendingEvents.values()) {
clearTimeout(timer)
}
pendingEvents.clear()
}
child.on('exit', (code) => {
exited = true
exitCode = code
rejectAllPending(`${tag} worker exited before responding`)
for (const callback of exitCallbacks) {
callback(code)
}
})
child.on('disconnect', () => {
// Why: a worker can drop fork IPC while its event loop stays alive. Kill
// it so the ensuing exit enters the normal supervision/backoff path.
rejectAllPending(`${tag} worker disconnected before responding`)
if (!exited) {
child.kill('SIGKILL')
}
})
const commands = await new Promise<string[]>((resolve, reject) => {
let settled = false
const timer = setTimeout(() => {
fail(new Error(`${tag} worker did not become ready within ${readyTimeoutMs}ms`))
child.kill('SIGKILL')
}, readyTimeoutMs)
function fail(error: Error): void {
if (!settled) {
settled = true
clearTimeout(timer)
options.signal?.removeEventListener('abort', onAbort)
reject(error)
}
}
const onAbort = (): void => {
fail(new Error(`${tag} worker startup was cancelled`))
child.kill('SIGKILL')
}
options.signal?.addEventListener('abort', onAbort, { once: true })
child.on('error', (error) => {
const failure = new Error(`${tag} worker process error: ${error.message}`)
fail(failure)
child.kill('SIGKILL')
// Why: fail() no-ops once ready; a post-ready channel fault must still
// reject in-flight calls instead of letting each hit its own timeout.
rejectAllPending(failure.message)
})
child.on('exit', (code) => fail(new Error(`${tag} worker exited before ready (code ${code})`)))
child.on('message', (raw) => {
const parsed = pluginWorkerChildMessageSchema.safeParse(raw)
if (!parsed.success) {
log('warn', 'ignoring malformed worker message')
return
}
const message = parsed.data
switch (message.type) {
case 'ready': {
if (!settled) {
settled = true
clearTimeout(timer)
options.signal?.removeEventListener('abort', onAbort)
resolve(message.commands)
}
return
}
case 'commandResult': {
const entry = pendingCommands.get(message.callId)
if (!entry) {
return
}
clearTimeout(entry.timer)
pendingCommands.delete(message.callId)
lastActivityAt = Date.now()
if (message.ok) {
entry.resolve(message.value)
} else {
entry.reject(new Error(message.error ?? 'plugin command failed'))
}
return
}
case 'eventAck': {
const timer = pendingEvents.get(message.eventId)
if (timer) {
clearTimeout(timer)
pendingEvents.delete(message.eventId)
}
lastActivityAt = Date.now()
return
}
case 'hostCall': {
lastActivityAt = Date.now()
// Host API calls from the worker: gate + execute in main, then
// relay the outcome. Never throws — errors become outcomes.
void options.executeHostCall(message.method, message.params).then((outcome) => {
lastActivityAt = Date.now()
sendToChild(
outcome.ok
? { type: 'hostResult', callId: message.callId, ok: true, value: outcome.value }
: {
type: 'hostResult',
callId: message.callId,
ok: false,
errorCode: outcome.code,
error: outcome.error
}
)
})
return
}
case 'log': {
log(message.level, message.message)
return
}
case 'fatal': {
fail(new Error(`${tag} worker crashed: ${message.error}`))
rejectAllPending(`${tag} worker crashed: ${message.error}`)
child.kill('SIGKILL')
}
}
})
sendToChild({
type: 'init',
pluginId,
pluginRoot: rootDir,
mainEntry,
grantedCapabilities: [...options.grantedCapabilities]
})
if (options.signal?.aborted) {
onAbort()
}
})
return {
commands,
invokeCommand(commandId, args) {
if (exited || disposed) {
return Promise.reject(new Error(`${tag} worker is not running`))
}
const callId = nextCallId++
return new Promise<unknown>((resolve, reject) => {
const timer = setTimeout(() => {
pendingCommands.delete(callId)
reject(new Error(`${tag} ${commandId} timed out after ${invokeTimeoutMs}ms`))
}, invokeTimeoutMs)
pendingCommands.set(callId, { resolve, reject, timer })
sendToChild({ type: 'invokeCommand', callId, commandId, args })
})
},
deliverEvent(event, payload) {
if (exited || disposed) {
return
}
if (pendingEvents.size >= PLUGIN_WORKER_MAX_PENDING_EVENTS) {
log('error', `${tag} exceeded the pending event limit`)
child.kill('SIGKILL')
return
}
lastActivityAt = Date.now()
const eventId = nextEventId++
const timer = setTimeout(() => {
pendingEvents.delete(eventId)
log('error', `${tag} ${event} did not finish within ${eventTimeoutMs}ms`)
child.kill('SIGKILL')
}, eventTimeoutMs)
pendingEvents.set(eventId, timer)
sendToChild({ type: 'deliverEvent', eventId, event, payload })
},
lastActivityAt: () => lastActivityAt,
inFlightCount: () => pendingCommands.size + pendingEvents.size,
async dispose() {
if (disposed) {
return
}
disposed = true
if (exited) {
return
}
sendToChild({ type: 'shutdown' })
await new Promise<void>((resolve) => {
const killTimer = setTimeout(() => {
child.kill('SIGKILL')
}, PLUGIN_WORKER_SHUTDOWN_GRACE_MS)
child.once('exit', () => {
clearTimeout(killTimer)
resolve()
})
if (exited) {
clearTimeout(killTimer)
resolve()
}
})
},
kill() {
child.kill('SIGKILL')
},
onExit(callback) {
if (exited) {
callback(exitCode)
} else {
exitCallbacks.push(callback)
}
}
}
}
@@ -0,0 +1,76 @@
import { describe, expect, it, vi } from 'vitest'
import { join } from 'node:path'
import { pathToFileURL } from 'node:url'
import { createPluginWorkerRuntime } from './plugin-host-runtime'
describe('plugin worker shutdown', () => {
it('normalizes either manifest separator before importing the worker', async () => {
const importModule = vi.fn(async () => ({ default: vi.fn() }))
const runtime = createPluginWorkerRuntime({ send: vi.fn(), importModule })
await runtime.handleMessage({
type: 'init',
pluginId: 'orca-samples.demo',
pluginRoot: join('plugin-root'),
mainEntry: 'nested\\worker.js',
grantedCapabilities: []
})
expect(importModule).toHaveBeenCalledWith(
pathToFileURL(join('plugin-root', 'nested', 'worker.js')).href
)
})
it('awaits an optional deactivate export before exiting', async () => {
let finishDeactivate!: () => void
const deactivate = vi.fn(
() =>
new Promise<void>((resolve) => {
finishDeactivate = resolve
})
)
const send = vi.fn()
const exit = vi.fn()
const runtime = createPluginWorkerRuntime({
send,
exit,
importModule: async () => ({ default: vi.fn(), deactivate })
})
await runtime.handleMessage({
type: 'init',
pluginId: 'orca-samples.demo',
pluginRoot: '/plugin',
mainEntry: 'worker.js',
grantedCapabilities: []
})
const shutdown = runtime.handleMessage({ type: 'shutdown' })
await Promise.resolve()
expect(deactivate).toHaveBeenCalledOnce()
expect(exit).not.toHaveBeenCalled()
finishDeactivate()
await shutdown
expect(exit).toHaveBeenCalledWith(0)
})
it('exits immediately when the plugin has no deactivate export', async () => {
const exit = vi.fn()
const runtime = createPluginWorkerRuntime({
send: vi.fn(),
exit,
importModule: async () => ({ default: vi.fn() })
})
await runtime.handleMessage({
type: 'init',
pluginId: 'orca-samples.demo',
pluginRoot: '/plugin',
mainEntry: 'worker.js',
grantedCapabilities: []
})
await runtime.handleMessage({ type: 'shutdown' })
expect(exit).toHaveBeenCalledWith(0)
})
})
+210
View File
@@ -0,0 +1,210 @@
import { join } from 'node:path'
import { pathToFileURL } from 'node:url'
import {
pluginWorkerParentMessageSchema,
type PluginWorkerChildMessage
} from '../../shared/plugins/plugin-host-protocol'
import type { PluginEventName } from '../../shared/plugins/plugin-manifest'
/**
* Message-loop core of the out-of-process plugin worker. Electron-free and
* side-effect-free (send/import/exit are injected) so it unit-tests without
* forking a real child process; `plugin-host-entry.ts` wires it to the fork
* IPC channel.
*/
export type PluginHostCallError = Error & { code?: string }
/** API surface handed to a plugin's `activate(orca)` export. Everything is
* EXPERIMENTAL until pluginApi v1 freezes. */
export type PluginWorkerOrcaApi = {
/** Register the handler for a command declared in the manifest. */
commands: {
register(commandId: string, handler: (args: unknown) => unknown | Promise<unknown>): void
}
/** Handle an event the manifest subscribed to (`contributes.events`). */
events: {
on(event: PluginEventName, handler: (payload: unknown) => void | Promise<void>): void
}
/** Call a host API method (capability-gated host-side). */
host: {
call(method: string, params?: unknown): Promise<unknown>
}
/** Consented capability kinds (informational — the host re-gates). */
grantedCapabilities: readonly string[]
log(message: string): void
}
export type PluginWorkerRuntimeOptions = {
send: (message: PluginWorkerChildMessage) => void
importModule?: (specifier: string) => Promise<unknown>
exit?: (code: number) => void
}
export type PluginWorkerRuntime = {
handleMessage(raw: unknown): Promise<void>
}
function toErrorMessage(error: unknown): string {
return error instanceof Error ? (error.stack ?? error.message) : String(error)
}
export function createPluginWorkerRuntime(
options: PluginWorkerRuntimeOptions
): PluginWorkerRuntime {
const send = options.send
const importModule = options.importModule ?? ((specifier: string) => import(specifier))
const exit = options.exit ?? ((code: number) => process.exit(code))
const commandHandlers = new Map<string, (args: unknown) => unknown | Promise<unknown>>()
const eventHandlers = new Map<string, ((payload: unknown) => void | Promise<void>)[]>()
const pendingHostCalls = new Map<
number,
{ resolve: (value: unknown) => void; reject: (error: PluginHostCallError) => void }
>()
let nextHostCallId = 0
let initialized = false
let shuttingDown = false
let deactivate: (() => unknown | Promise<unknown>) | null = null
async function handleInit(input: {
pluginRoot: string
mainEntry: string
grantedCapabilities: string[]
}): Promise<void> {
if (initialized) {
send({ type: 'log', level: 'warn', message: 'ignoring duplicate init message' })
return
}
initialized = true
// Why: file URL import keeps ESM plugin entries working on Windows paths.
// Why: manifest paths accept either portable separator; split explicitly
// so a Windows-authored plugin also imports on macOS/Linux and vice versa.
const entryUrl = pathToFileURL(join(input.pluginRoot, ...input.mainEntry.split(/[\\/]/))).href
const module = (await importModule(entryUrl)) as { default?: unknown; deactivate?: unknown }
const activate = module?.default
if (typeof activate !== 'function') {
throw new Error(`plugin entry ${input.mainEntry} has no default-exported activate function`)
}
if (module.deactivate !== undefined && typeof module.deactivate !== 'function') {
throw new Error(`plugin entry ${input.mainEntry} has a non-function deactivate export`)
}
deactivate = (module.deactivate as (() => unknown | Promise<unknown>) | undefined) ?? null
const orca: PluginWorkerOrcaApi = {
commands: {
register(commandId, handler) {
commandHandlers.set(commandId, handler)
}
},
events: {
on(event, handler) {
const handlers = eventHandlers.get(event) ?? []
handlers.push(handler)
eventHandlers.set(event, handlers)
}
},
host: {
call(method, params) {
const callId = nextHostCallId++
return new Promise<unknown>((resolve, reject) => {
pendingHostCalls.set(callId, { resolve, reject })
send({ type: 'hostCall', callId, method, params })
})
}
},
grantedCapabilities: input.grantedCapabilities,
log(message) {
send({ type: 'log', level: 'info', message: String(message).slice(0, 8192) })
}
}
await activate(orca)
send({ type: 'ready', commands: [...commandHandlers.keys()] })
}
return {
async handleMessage(raw) {
const parsed = pluginWorkerParentMessageSchema.safeParse(raw)
if (!parsed.success) {
send({ type: 'log', level: 'warn', message: 'ignoring malformed parent message' })
return
}
const message = parsed.data
try {
switch (message.type) {
case 'init': {
await handleInit(message)
return
}
case 'invokeCommand': {
const handler = commandHandlers.get(message.commandId)
if (!handler) {
send({
type: 'commandResult',
callId: message.callId,
ok: false,
error: `no handler registered for command ${message.commandId}`
})
return
}
try {
const value = await handler(message.args)
send({ type: 'commandResult', callId: message.callId, ok: true, value })
} catch (error) {
send({
type: 'commandResult',
callId: message.callId,
ok: false,
error: toErrorMessage(error)
})
}
return
}
case 'deliverEvent': {
const handlers = eventHandlers.get(message.event) ?? []
for (const handler of handlers) {
try {
await handler(message.payload)
} catch (error) {
send({ type: 'log', level: 'error', message: toErrorMessage(error) })
}
}
send({ type: 'eventAck', eventId: message.eventId })
return
}
case 'hostResult': {
const pending = pendingHostCalls.get(message.callId)
if (!pending) {
return
}
pendingHostCalls.delete(message.callId)
if (message.ok) {
pending.resolve(message.value)
} else {
const error: PluginHostCallError = new Error(message.error ?? 'host call failed')
error.code = message.errorCode
pending.reject(error)
}
return
}
case 'shutdown': {
if (shuttingDown) {
return
}
shuttingDown = true
try {
await deactivate?.()
} catch (error) {
send({ type: 'log', level: 'error', message: toErrorMessage(error).slice(0, 8192) })
}
exit(0)
}
}
} catch (error) {
// Why: an init/activation failure leaves the worker useless; report
// and die so the parent surfaces the error instead of hanging on
// the ready timeout.
send({ type: 'fatal', error: toErrorMessage(error) })
exit(1)
}
}
}
}
@@ -0,0 +1,84 @@
import type { PluginEventName } from '../../shared/plugins/plugin-manifest'
import { PLUGIN_WORKSPACE_TERMINAL_LIMIT } from '../../shared/plugins/plugin-host-api'
import type { PluginHostServices } from './plugin-host-methods'
import { PluginSecretsStore } from './plugin-secrets-store'
import { PluginKvStore } from './plugin-storage-store'
/** Structural subset of OrcaRuntimeService exposed to plugin facade bindings. */
export type PluginRuntimeDelegate = {
resolveActiveWorktreeContext(): Promise<{
worktreeId: string
path: string
branch: string
displayName: string
} | null>
listTerminals(
worktreeSelector?: string,
limit?: number
): Promise<{ terminals: { handle: string; title: string | null }[] }>
sendTerminal(
handle: string,
action: { text?: string; enter?: boolean }
): Promise<{ accepted: boolean }>
dispatchPluginNotification(input: {
pluginId: string
title: string
body?: string
}): Promise<{ delivered: boolean }>
}
export function bindPluginHostServices(input: {
delegate: PluginRuntimeDelegate
pluginsDataDir: string
subscribeEvents: (pluginKey: string, events: PluginEventName[]) => PluginEventName[]
}): PluginHostServices {
const { delegate, pluginsDataDir, subscribeEvents } = input
return {
resolveActiveWorktreeContext: async () => {
const context = await delegate.resolveActiveWorktreeContext()
if (!context) {
return null
}
// Why: retain the internal id only for host-side terminal membership;
// the public handler projects it out because it embeds provider paths.
return {
worktreeId: context.worktreeId,
branch: context.branch,
displayName: context.displayName
}
},
listWorktreeTerminals: async (worktreeId) => {
const result = await delegate.listTerminals(
`id:${worktreeId}`,
PLUGIN_WORKSPACE_TERMINAL_LIMIT
)
return result.terminals
.slice(0, PLUGIN_WORKSPACE_TERMINAL_LIMIT)
.map((terminal) => ({ id: terminal.handle }))
},
sendTerminalText: async (terminalId, action) => {
const result = await delegate.sendTerminal(terminalId, action)
return { accepted: result.accepted }
},
dispatchPluginNotification: (notification) => delegate.dispatchPluginNotification(notification),
storage: {
get: (key, itemKey) => new PluginKvStore(pluginsDataDir, key, 'storage.json').get(itemKey),
set: (key, itemKey, value) =>
new PluginKvStore(pluginsDataDir, key, 'storage.json').set(itemKey, value),
delete: (key, itemKey) =>
new PluginKvStore(pluginsDataDir, key, 'storage.json').delete(itemKey),
keys: (key) => new PluginKvStore(pluginsDataDir, key, 'storage.json').keys()
},
secrets: {
get: (key, itemKey) => new PluginSecretsStore(pluginsDataDir, key).get(itemKey),
set: (key, itemKey, value) => new PluginSecretsStore(pluginsDataDir, key).set(itemKey, value),
delete: (key, itemKey) => new PluginSecretsStore(pluginsDataDir, key).delete(itemKey)
},
settings: {
getAll: (key) => new PluginKvStore(pluginsDataDir, key, 'settings.json').getAll(),
set: (key, itemKey, value) =>
new PluginKvStore(pluginsDataDir, key, 'settings.json').set(itemKey, value)
},
subscribeEvents
}
}
@@ -0,0 +1,83 @@
import { createReadStream } from 'node:fs'
import { mkdir } from 'node:fs/promises'
import { join } from 'node:path'
import {
emptyPluginLockfile,
parsePluginLockfile,
serializePluginLockfile,
type PluginLockfile
} from '../../shared/plugins/plugin-install-lockfile'
import { writePluginFileAtomically } from './plugin-atomic-file-write'
import { recoverPluginLockfile } from './plugin-install-provenance'
export const PLUGIN_LOCKFILE_MAX_BYTES = 5 * 1024 * 1024
const lockfileAccessChains = new Map<string, Promise<void>>()
export function pluginLockfilePath(pluginsDir: string): string {
return join(pluginsDir, 'plugins.lock.json')
}
async function serializeLockfileAccess<T>(
pluginsDir: string,
operation: () => Promise<T>
): Promise<T> {
const previous = lockfileAccessChains.get(pluginsDir) ?? Promise.resolve()
const run = previous.catch(() => undefined).then(operation)
const settled = run.then(
() => undefined,
() => undefined
)
lockfileAccessChains.set(pluginsDir, settled)
try {
return await run
} finally {
if (lockfileAccessChains.get(pluginsDir) === settled) {
lockfileAccessChains.delete(pluginsDir)
}
}
}
/** Reads the install index through a byte cap so a corrupt local file cannot
* turn every plugin-list refresh into an unbounded main-process allocation. */
export async function readPluginLockfile(pluginsDir: string): Promise<PluginLockfile> {
return serializeLockfileAccess(pluginsDir, () => readPluginLockfileUnserialized(pluginsDir))
}
async function readPluginLockfileUnserialized(pluginsDir: string): Promise<PluginLockfile> {
let lock = emptyPluginLockfile()
try {
const chunks: Buffer[] = []
let totalBytes = 0
for await (const chunk of createReadStream(pluginLockfilePath(pluginsDir))) {
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
totalBytes += bytes.byteLength
if (totalBytes > PLUGIN_LOCKFILE_MAX_BYTES) {
throw new Error('plugin lockfile exceeds its size limit')
}
chunks.push(bytes)
}
lock = parsePluginLockfile(JSON.parse(Buffer.concat(chunks, totalBytes).toString('utf8')))
} catch {
// Missing/corrupt global indexes can be reconstructed from current-version provenance.
}
const recovered = await recoverPluginLockfile(pluginsDir, lock)
if (recovered.changed) {
await writePluginLockfileUnserialized(pluginsDir, recovered.lock).catch(() => undefined)
}
return recovered.lock
}
export async function writePluginLockfile(pluginsDir: string, lock: PluginLockfile): Promise<void> {
await serializeLockfileAccess(pluginsDir, () => writePluginLockfileUnserialized(pluginsDir, lock))
}
async function writePluginLockfileUnserialized(
pluginsDir: string,
lock: PluginLockfile
): Promise<void> {
await mkdir(pluginsDir, { recursive: true })
await writePluginFileAtomically(
pluginLockfilePath(pluginsDir),
JSON.stringify(serializePluginLockfile(lock), null, 2)
)
}
@@ -0,0 +1,118 @@
import { createReadStream } from 'node:fs'
import { mkdir, readdir, rm } from 'node:fs/promises'
import { join } from 'node:path'
import {
PLUGIN_CONTENT_HASH_PATTERN,
pluginLockEntrySchema,
type PluginLockEntry,
type PluginLockfile
} from '../../shared/plugins/plugin-install-lockfile'
import { isQualifiedPluginKey } from '../../shared/plugins/plugin-manifest'
import { writePluginFileAtomically } from './plugin-atomic-file-write'
import { readPluginCurrentPointer } from './plugin-current-pointer'
const PROVENANCE_DIRECTORY = '.install-provenance'
const PROVENANCE_MAX_BYTES = 64 * 1024
function provenancePath(pluginDir: string, contentHash: string): string {
if (!PLUGIN_CONTENT_HASH_PATTERN.test(contentHash)) {
throw new Error('invalid plugin content hash')
}
return join(pluginDir, PROVENANCE_DIRECTORY, `${contentHash}.json`)
}
/** Prewrites immutable provenance before the executable current pointer moves. */
export async function writePluginInstallProvenance(
pluginDir: string,
entry: PluginLockEntry
): Promise<void> {
const parsedEntry = pluginLockEntrySchema.parse(entry)
const directory = join(pluginDir, PROVENANCE_DIRECTORY)
await mkdir(directory, { recursive: true, mode: 0o700 })
await writePluginFileAtomically(
provenancePath(pluginDir, parsedEntry.contentHash),
JSON.stringify({ version: 1, entry: parsedEntry }, null, 2),
{ mode: 0o600 }
)
}
export async function readPluginInstallProvenance(
pluginDir: string,
contentHash: string
): Promise<PluginLockEntry | null> {
try {
const chunks: Buffer[] = []
let totalBytes = 0
for await (const chunk of createReadStream(provenancePath(pluginDir, contentHash))) {
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
totalBytes += bytes.byteLength
if (totalBytes > PROVENANCE_MAX_BYTES) {
return null
}
chunks.push(bytes)
}
const raw = JSON.parse(Buffer.concat(chunks, totalBytes).toString('utf8')) as {
version?: unknown
entry?: unknown
}
if (raw.version !== 1) {
return null
}
const parsed = pluginLockEntrySchema.safeParse(raw.entry)
return parsed.success ? parsed.data : null
} catch {
return null
}
}
/** Repairs a pointer-new/lock-old interrupted publication from immutable provenance. */
export async function recoverPluginLockfile(
pluginsDir: string,
lock: PluginLockfile
): Promise<{ lock: PluginLockfile; changed: boolean }> {
const plugins = { ...lock.plugins }
let changed = false
const directories = await readdir(pluginsDir, { withFileTypes: true }).catch(() => [])
for (const directory of directories) {
if (!directory.isDirectory() || !isQualifiedPluginKey(directory.name)) {
continue
}
const pluginDir = join(pluginsDir, directory.name)
const contentHash = await readPluginCurrentPointer(pluginDir).catch(() => null)
if (!contentHash || !PLUGIN_CONTENT_HASH_PATTERN.test(contentHash)) {
continue
}
const provenance = await readPluginInstallProvenance(pluginDir, contentHash)
if (
!provenance ||
provenance.pluginKey !== directory.name ||
provenance.contentHash !== contentHash
) {
continue
}
if (JSON.stringify(plugins[directory.name]) !== JSON.stringify(provenance)) {
plugins[directory.name] = provenance
changed = true
}
}
return { lock: { version: 1, plugins }, changed }
}
export async function prunePluginInstallProvenance(
pluginDir: string,
retained: ReadonlySet<string>
): Promise<void> {
const directory = join(pluginDir, PROVENANCE_DIRECTORY)
const entries = await readdir(directory, { withFileTypes: true }).catch(() => [])
await Promise.all(
entries
.filter(
(entry) =>
entry.isFile() &&
entry.name.endsWith('.json') &&
PLUGIN_CONTENT_HASH_PATTERN.test(entry.name.slice(0, -'.json'.length)) &&
!retained.has(entry.name.slice(0, -'.json'.length))
)
.map((entry) => rm(join(directory, entry.name), { force: true }))
)
}
@@ -0,0 +1,94 @@
import { readdir, rm } from 'node:fs/promises'
import { join } from 'node:path'
import {
PLUGIN_CONTENT_HASH_PATTERN,
upsertPluginLock,
type PluginLockEntry
} from '../../shared/plugins/plugin-install-lockfile'
import {
readPluginCurrentPointer,
restorePluginCurrentPointer,
writePluginCurrentPointer
} from './plugin-current-pointer'
import { readPluginLockfile, writePluginLockfile } from './plugin-install-lockfile-store'
import {
prunePluginInstallProvenance,
readPluginInstallProvenance,
writePluginInstallProvenance
} from './plugin-install-provenance'
/** Publishes executable identity and provenance as one recoverable mutation,
* then retains only current plus one rollback version. */
export async function publishPluginInstall(input: {
pluginsDir: string
pluginDir: string
entry: PluginLockEntry
}): Promise<void> {
const previousContentHash = await readPluginCurrentPointer(input.pluginDir)
const currentLock = await readPluginLockfile(input.pluginsDir)
const provenanceCandidate =
previousContentHash === input.entry.contentHash
? await readPluginInstallProvenance(input.pluginDir, input.entry.contentHash)
: null
const matchesCurrentIdentity = (entry: PluginLockEntry | undefined | null): boolean =>
entry?.pluginKey === input.entry.pluginKey && entry.contentHash === input.entry.contentHash
const existingProvenance = matchesCurrentIdentity(provenanceCandidate)
? provenanceCandidate
: null
const legacyLockEntry = currentLock.plugins[input.entry.pluginKey]
const legacyCurrentEntry =
previousContentHash === input.entry.contentHash && matchesCurrentIdentity(legacyLockEntry)
? legacyLockEntry
: null
// Provenance is immutable per executable identity. A same-byte reinstall
// is a no-op so a failed or interrupted source change cannot be recovered
// later as though it had successfully published.
const publishedEntry = existingProvenance ?? legacyCurrentEntry ?? input.entry
const nextLock = upsertPluginLock(currentLock, publishedEntry)
// Why: after a crash between pointer and global-index publication, startup
// can reconstruct exact source/commit identity from this immutable record.
if (!existingProvenance) {
await writePluginInstallProvenance(input.pluginDir, publishedEntry)
}
await writePluginCurrentPointer(input.pluginDir, input.entry.contentHash)
try {
await writePluginLockfile(input.pluginsDir, nextLock)
} catch (publicationError) {
try {
await restorePluginCurrentPointer(input.pluginDir, previousContentHash)
} catch (rollbackError) {
throw new AggregateError(
[publicationError, rollbackError],
'plugin install publication and pointer rollback both failed'
)
}
throw publicationError
}
// Reinstalling B must not collapse an existing A rollback into {B}.
if (previousContentHash !== input.entry.contentHash) {
await pruneHistoricalVersions(
input.pluginDir,
new Set(
[input.entry.contentHash, previousContentHash].filter(
(hash): hash is string =>
typeof hash === 'string' && PLUGIN_CONTENT_HASH_PATTERN.test(hash)
)
)
).catch(() => undefined)
}
}
async function pruneHistoricalVersions(pluginDir: string, retained: ReadonlySet<string>) {
const entries = await readdir(pluginDir, { withFileTypes: true })
await Promise.all(
entries
.filter(
(entry) =>
entry.isDirectory() &&
PLUGIN_CONTENT_HASH_PATTERN.test(entry.name) &&
!retained.has(entry.name)
)
.map((entry) => rm(join(pluginDir, entry.name), { recursive: true, force: true }))
)
await prunePluginInstallProvenance(pluginDir, retained)
}
+253
View File
@@ -0,0 +1,253 @@
import { existsSync } from 'node:fs'
import { cp, mkdir, rm } from 'node:fs/promises'
import { join, relative, resolve, sep } from 'node:path'
import {
PLUGIN_MANIFEST_FILENAME,
parsePluginManifest,
qualifiedPluginKey,
satisfiesOrcaEngineRange,
type PluginManifest
} from '../../shared/plugins/plugin-manifest'
import { fingerprintPluginConsent } from '../../shared/plugins/plugin-consent-fingerprint'
import type {
PluginInstallSource,
PluginLockEntry
} from '../../shared/plugins/plugin-install-lockfile'
import {
validateDeclaredPluginArtifacts,
validatePluginInstallContent,
type PluginArtifactValidationResult
} from './plugin-artifact-validation'
import { renamePluginFileWithWindowsRetry } from './plugin-atomic-file-write'
import { hashPluginTree } from './plugin-content-hash'
import { publishPluginInstall } from './plugin-install-publication'
import { readPluginManifestText } from './plugin-manifest-file'
import { pluginInstallTrustError } from './plugin-install-trust'
export type PluginInstallResult =
| {
ok: true
pluginKey: string
version: string
contentHash: string
consentFingerprint: string
resolvedCommit: string | null
}
| { ok: false; error: string }
export type PluginInstallInspection =
| {
ok: true
manifest: PluginManifest
pluginKey: string
contentHash: string
consentFingerprint: string
}
| { ok: false; error: string }
async function validatePluginInstallTree(
rootDir: string,
manifest: PluginManifest
): Promise<PluginArtifactValidationResult> {
const declared = await validateDeclaredPluginArtifacts(rootDir, manifest)
return declared.ok ? validatePluginInstallContent(rootDir, manifest) : declared
}
async function readInstallManifest(
rootDir: string,
hostVersion: string
): Promise<{ ok: true; manifest: PluginManifest } | { ok: false; error: string }> {
let raw: unknown
try {
raw = JSON.parse(await readPluginManifestText(rootDir))
} catch (error) {
return {
ok: false,
error: `unreadable ${PLUGIN_MANIFEST_FILENAME}: ${error instanceof Error ? error.message : String(error)}`
}
}
const parsed = parsePluginManifest(raw)
if (!parsed.ok) {
return { ok: false, error: `invalid manifest: ${parsed.error}` }
}
if (!satisfiesOrcaEngineRange(hostVersion, parsed.manifest.engines.orca)) {
return {
ok: false,
error: `plugin requires Orca ${parsed.manifest.engines.orca} (this is ${hostVersion})`
}
}
return { ok: true, manifest: parsed.manifest }
}
/** Validates and hashes a source tree without publishing it. Marketplace
* previews use this exact path so the reviewed bytes match install policy. */
export async function inspectPluginInstallTree(input: {
rootDir: string
hostVersion: string
expectedPluginKey?: string
}): Promise<PluginInstallInspection> {
const sourceManifest = await readInstallManifest(input.rootDir, input.hostVersion)
if (!sourceManifest.ok) {
return sourceManifest
}
const pluginKey = qualifiedPluginKey(sourceManifest.manifest)
if (input.expectedPluginKey && pluginKey !== input.expectedPluginKey) {
return {
ok: false,
error: `plugin manifest identity ${pluginKey} does not match marketplace listing ${input.expectedPluginKey}`
}
}
const declaredArtifacts = await validatePluginInstallTree(input.rootDir, sourceManifest.manifest)
if (!declaredArtifacts.ok) {
return { ok: false, error: `invalid declared artifact: ${declaredArtifacts.error}` }
}
const treeHash = await hashPluginTree(input.rootDir)
if (!treeHash.ok) {
return { ok: false, error: treeHash.error }
}
return {
ok: true,
manifest: sourceManifest.manifest,
pluginKey,
contentHash: treeHash.hash,
consentFingerprint: fingerprintPluginConsent(sourceManifest.manifest, treeHash.hash)
}
}
/** Installs a validated staging tree into the hash-addressed layout. */
export async function installStagedPluginTree(input: {
pluginsDir: string
stagingDir: string
hostVersion: string
source: PluginInstallSource
resolvedCommit: string | null
expectedPluginKey?: string
/** Trusted bundled bytes may restore an immutable directory damaged on disk. */
repairCorruptedVersion?: boolean
blockedPluginReason?: (pluginKey: string) => string | null
}): Promise<PluginInstallResult> {
const sourceInspection = await inspectPluginInstallTree({
rootDir: input.stagingDir,
hostVersion: input.hostVersion,
...(input.expectedPluginKey ? { expectedPluginKey: input.expectedPluginKey } : {})
})
if (!sourceInspection.ok) {
return sourceInspection
}
const trustError = pluginInstallTrustError(sourceInspection.pluginKey, input.source)
if (trustError) {
return { ok: false, error: trustError }
}
const blockedReason = input.blockedPluginReason?.(sourceInspection.pluginKey)
if (blockedReason) {
return { ok: false, error: `plugin is blocked by Orca's safety list: ${blockedReason}` }
}
let manifest = sourceInspection.manifest
const pluginKey = sourceInspection.pluginKey
const pluginDir = join(input.pluginsDir, pluginKey)
const versionDir = join(pluginDir, sourceInspection.contentHash)
if (existsSync(versionDir) && input.repairCorruptedVersion) {
const existingHash = await hashPluginTree(versionDir)
if (!existingHash.ok || existingHash.hash !== sourceInspection.contentHash) {
// Why: bundled resources are release-index verified above, so they can
// safely restore a damaged immutable install instead of staying broken.
await rm(versionDir, { recursive: true, force: true })
}
}
if (!existsSync(versionDir)) {
const stagedVersionDir = `${versionDir}.staging`
try {
await rm(stagedVersionDir, { recursive: true, force: true })
await mkdir(pluginDir, { recursive: true })
// Source trees can change while copying. Hashing the destination closes
// that race before the immutable directory becomes current.
const stagingRoot = resolve(input.stagingDir)
await cp(stagingRoot, stagedVersionDir, {
recursive: true,
verbatimSymlinks: true,
// Source-control metadata is not plugin content. Skip it at the copy
// boundary so a large local repository cannot bypass install limits.
filter: (source) => {
const fromRoot = relative(stagingRoot, resolve(source))
return fromRoot !== '.git' && !fromRoot.startsWith(`.git${sep}`)
}
})
const copiedHash = await hashPluginTree(stagedVersionDir)
if (!copiedHash.ok || copiedHash.hash !== sourceInspection.contentHash) {
return {
ok: false,
error: copiedHash.ok
? 'plugin content changed while it was being copied'
: copiedHash.error
}
}
const copiedManifest = await readInstallManifest(stagedVersionDir, input.hostVersion)
if (!copiedManifest.ok) {
return { ok: false, error: `copied ${copiedManifest.error}` }
}
if (qualifiedPluginKey(copiedManifest.manifest) !== pluginKey) {
return { ok: false, error: 'plugin manifest identity changed while it was being staged' }
}
manifest = copiedManifest.manifest
const copiedArtifacts = await validatePluginInstallTree(stagedVersionDir, manifest)
if (!copiedArtifacts.ok) {
return { ok: false, error: `copied artifact validation failed: ${copiedArtifacts.error}` }
}
await renamePluginFileWithWindowsRetry(stagedVersionDir, versionDir)
} catch (error) {
return { ok: false, error: error instanceof Error ? error.message : String(error) }
} finally {
await rm(stagedVersionDir, { recursive: true, force: true })
}
} else {
// Never repoint at an existing hash directory without proving its bytes;
// a previous partial/tampered install must not be revived by reinstall.
const existingHash = await hashPluginTree(versionDir)
if (!existingHash.ok || existingHash.hash !== sourceInspection.contentHash) {
return {
ok: false,
error: existingHash.ok
? 'existing plugin content failed integrity verification'
: existingHash.error
}
}
const existingManifest = await readInstallManifest(versionDir, input.hostVersion)
if (!existingManifest.ok) {
return { ok: false, error: `installed ${existingManifest.error}` }
}
if (qualifiedPluginKey(existingManifest.manifest) !== pluginKey) {
return { ok: false, error: 'installed plugin manifest identity does not match its directory' }
}
manifest = existingManifest.manifest
const existingArtifacts = await validatePluginInstallTree(versionDir, manifest)
if (!existingArtifacts.ok) {
return {
ok: false,
error: `installed artifact validation failed: ${existingArtifacts.error}`
}
}
}
const consentFingerprint = fingerprintPluginConsent(manifest, sourceInspection.contentHash)
const entry: PluginLockEntry = {
pluginKey,
version: manifest.version,
source: input.source,
resolvedCommit: input.resolvedCommit,
contentHash: sourceInspection.contentHash,
consentFingerprint,
installedAt: Date.now()
}
try {
await publishPluginInstall({ pluginsDir: input.pluginsDir, pluginDir, entry })
} catch (error) {
return { ok: false, error: error instanceof Error ? error.message : String(error) }
}
return {
ok: true,
pluginKey,
version: manifest.version,
contentHash: sourceInspection.contentHash,
consentFingerprint,
resolvedCommit: input.resolvedCommit
}
}
@@ -0,0 +1,115 @@
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import type { PluginInstallSource } from '../../shared/plugins/plugin-install-lockfile'
import {
installBundledPlugin,
installPluginFromLocalPath,
readPluginLockfile
} from './plugin-install'
import { pluginInstallTrustError } from './plugin-install-trust'
const roots: string[] = []
async function tempRoot(prefix: string): Promise<string> {
const root = await mkdtemp(join(tmpdir(), prefix))
roots.push(root)
return root
}
async function writePlugin(root: string, publisher: string, id: string): Promise<void> {
await writeFile(
join(root, 'orca-plugin.json'),
JSON.stringify({
manifestVersion: 1,
id,
publisher,
name: 'Plugin',
version: '1.0.0',
engines: { orca: '>=1.0.0' },
pluginApi: 1,
capabilities: []
})
)
}
afterEach(async () => {
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })))
})
describe('plugin install trust', () => {
it.each<[PluginInstallSource, string | null]>([
[
{
kind: 'git',
url: 'https://github.com/attacker/orca-secrets.git',
ref: 'main'
},
'reserved plugin identity community.orca-secrets must resolve to the stablyai organization'
],
[
{
kind: 'git',
url: 'git@github.com:stablyai/orca-secrets.git',
ref: 'main'
},
null
]
])('enforces reserved source organization', (source, expected) => {
expect(pluginInstallTrustError('community.orca-secrets', source)).toBe(expected)
})
it('rejects locally installed reserved identities before publication', async () => {
const sourcePath = await tempRoot('orca-reserved-plugin-')
const pluginsDir = await tempRoot('orca-plugin-installs-')
await writePlugin(sourcePath, 'stablyai', 'orca-skills')
await expect(
installPluginFromLocalPath({ pluginsDir, sourcePath, hostVersion: '1.4.0' })
).resolves.toEqual({
ok: false,
error: 'reserved plugin identity stablyai.orca-skills cannot be installed from a local path'
})
await expect(readPluginLockfile(pluginsDir)).resolves.toEqual({ version: 1, plugins: {} })
})
it('allows the app-bundled path only for the complete official identity', async () => {
const sourcePath = await tempRoot('orca-bundled-plugin-')
const pluginsDir = await tempRoot('orca-plugin-installs-')
await writePlugin(sourcePath, 'stablyai', 'orca-skills')
const result = await installBundledPlugin({
pluginsDir,
sourcePath,
hostVersion: '1.4.0',
expectedPluginKey: 'stablyai.orca-skills'
})
expect(result).toMatchObject({ ok: true, pluginKey: 'stablyai.orca-skills' })
const lock = await readPluginLockfile(pluginsDir)
expect(lock.plugins['stablyai.orca-skills']?.source).toEqual({
kind: 'bundled',
bundleId: 'stablyai.orca-skills'
})
})
it('blocks a killed plugin even when the caller bypasses marketplace UI', async () => {
const sourcePath = await tempRoot('orca-killed-plugin-')
const pluginsDir = await tempRoot('orca-plugin-installs-')
await writePlugin(sourcePath, 'community', 'unsafe')
await expect(
installPluginFromLocalPath({
pluginsDir,
sourcePath,
hostVersion: '1.4.0',
blockedPluginReason: (pluginKey) =>
pluginKey === 'community.unsafe' ? 'Security incident' : null
})
).resolves.toEqual({
ok: false,
error: "plugin is blocked by Orca's safety list: Security incident"
})
})
})
+27
View File
@@ -0,0 +1,27 @@
import type { PluginInstallSource } from '../../shared/plugins/plugin-install-lockfile'
import {
isOfficialOrganizationGitSource,
isOfficialPluginIdentity,
isReservedPluginIdentity
} from '../../shared/plugins/plugin-marketplace'
export function pluginInstallTrustError(
pluginKey: string,
source: PluginInstallSource
): string | null {
if (source.kind === 'bundled') {
return source.bundleId === pluginKey && isOfficialPluginIdentity(pluginKey)
? null
: 'bundled plugins must use an official stablyai.orca-* identity'
}
if (!isReservedPluginIdentity(pluginKey)) {
return null
}
if (source.kind === 'local-path') {
return `reserved plugin identity ${pluginKey} cannot be installed from a local path`
}
const url = source.kind === 'git' ? source.url : source.plugin.url
return isOfficialOrganizationGitSource(url)
? null
: `reserved plugin identity ${pluginKey} must resolve to the stablyai organization`
}
+531
View File
@@ -0,0 +1,531 @@
import { execFile } from 'node:child_process'
import {
mkdtemp,
mkdir,
readFile,
readdir,
rm,
symlink,
truncate,
writeFile
} from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { pathToFileURL } from 'node:url'
import { promisify } from 'node:util'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
installPluginFromLocalPath,
installPluginFromGit,
PLUGIN_LOCKFILE_MAX_BYTES,
readPluginLockfile,
removeInstalledPlugin
} from './plugin-install'
import { PLUGIN_MANIFEST_MAX_BYTES } from './plugin-manifest-file'
import { readPluginCurrentPointer } from './plugin-current-pointer'
import { writePluginLockfile } from './plugin-install-lockfile-store'
import { installStagedPluginTree } from './plugin-install-staging'
import * as manifestFile from './plugin-manifest-file'
const roots: string[] = []
const execFileAsync = promisify(execFile)
async function tempRoot(prefix: string): Promise<string> {
const root = await mkdtemp(join(tmpdir(), prefix))
roots.push(root)
return root
}
async function writePluginSource(
root: string,
options: { id?: string; panelEntry?: string; includePanel?: boolean } = {}
): Promise<void> {
const panelEntry = options.panelEntry ?? 'panel.html'
await writeFile(
join(root, 'orca-plugin.json'),
JSON.stringify({
manifestVersion: 1,
id: options.id ?? 'demo',
publisher: 'orca-samples',
name: 'Demo',
version: '1.0.0',
engines: { orca: '>=1.0.0' },
pluginApi: 1,
contributes: {
panels: [{ id: 'panel', title: 'Panel', entry: panelEntry }],
commands: [],
events: []
},
capabilities: []
})
)
if (options.includePanel !== false) {
await writeFile(join(root, panelEntry), '<h1>Panel</h1>')
}
}
afterEach(async () => {
vi.restoreAllMocks()
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })))
})
describe('installPluginFromLocalPath', () => {
it('refuses to allocate an oversized install lockfile', async () => {
const pluginsDir = await tempRoot('orca-plugin-installs-')
const lockPath = join(pluginsDir, 'plugins.lock.json')
await writeFile(lockPath, '')
await truncate(lockPath, PLUGIN_LOCKFILE_MAX_BYTES + 1)
await expect(readPluginLockfile(pluginsDir)).resolves.toEqual({ version: 1, plugins: {} })
})
it('verifies copied content and writes a rollback-compatible consent field', async () => {
const sourcePath = await tempRoot('orca-plugin-source-')
const pluginsDir = await tempRoot('orca-plugin-installs-')
await writePluginSource(sourcePath)
const result = await installPluginFromLocalPath({
pluginsDir,
sourcePath,
hostVersion: '1.4.0'
})
expect(result.ok).toBe(true)
if (!result.ok) {
return
}
await expect(
readFile(join(pluginsDir, result.pluginKey, result.contentHash, 'panel.html'), 'utf8')
).resolves.toBe('<h1>Panel</h1>')
const lock = JSON.parse(await readFile(join(pluginsDir, 'plugins.lock.json'), 'utf8')) as {
plugins: Record<string, Record<string, unknown>>
}
expect(lock.plugins[result.pluginKey]).toMatchObject({
capabilityHash: result.consentFingerprint
})
expect(lock.plugins[result.pluginKey]).not.toHaveProperty('consentFingerprint')
})
it('publishes metadata from the copied immutable manifest', async () => {
const sourcePath = await tempRoot('orca-plugin-source-')
const pluginsDir = await tempRoot('orca-plugin-installs-')
await writePluginSource(sourcePath)
const firstManifest = await readFile(join(sourcePath, 'orca-plugin.json'), 'utf8')
const changedManifest = {
...(JSON.parse(firstManifest) as Record<string, unknown>),
name: 'Changed During Staging',
version: '2.0.0'
}
await writeFile(join(sourcePath, 'orca-plugin.json'), JSON.stringify(changedManifest))
const manifestRead = vi
.spyOn(manifestFile, 'readPluginManifestText')
.mockResolvedValueOnce(firstManifest)
const result = await installStagedPluginTree({
pluginsDir,
stagingDir: sourcePath,
hostVersion: '1.4.0',
source: { kind: 'local-path', path: sourcePath },
resolvedCommit: null
})
expect(manifestRead).toHaveBeenCalledTimes(2)
expect(result).toMatchObject({ ok: true, version: '2.0.0' })
if (result.ok) {
const lock = await readPluginLockfile(pluginsDir)
expect(lock.plugins[result.pluginKey]?.version).toBe('2.0.0')
}
})
it('skips root Git metadata before copying while still enforcing plugin limits', async () => {
const sourcePath = await tempRoot('orca-plugin-source-')
const pluginsDir = await tempRoot('orca-plugin-installs-')
await writePluginSource(sourcePath)
const gitDir = join(sourcePath, '.git')
await mkdir(gitDir)
await writeFile(join(gitDir, 'large.pack'), '')
await truncate(join(gitDir, 'large.pack'), 50 * 1024 * 1024 + 1)
const result = await installPluginFromLocalPath({
pluginsDir,
sourcePath,
hostVersion: '1.4.0'
})
expect(result).toMatchObject({ ok: true })
if (result.ok) {
await expect(
readFile(join(pluginsDir, result.pluginKey, result.contentHash, '.git', 'large.pack'))
).rejects.toMatchObject({ code: 'ENOENT' })
}
})
it('restores the previous current pointer when lockfile publication fails', async () => {
const sourcePath = await tempRoot('orca-plugin-source-')
const pluginsDir = await tempRoot('orca-plugin-installs-')
await writePluginSource(sourcePath)
const first = await installPluginFromLocalPath({ pluginsDir, sourcePath, hostVersion: '1.4.0' })
expect(first.ok).toBe(true)
if (!first.ok) {
return
}
await writeFile(join(sourcePath, 'panel.html'), '<h1>Updated</h1>')
await rm(join(pluginsDir, 'plugins.lock.json'))
await mkdir(join(pluginsDir, 'plugins.lock.json'))
const failed = await installPluginFromLocalPath({
pluginsDir,
sourcePath,
hostVersion: '1.4.0'
})
expect(failed).toMatchObject({ ok: false })
await expect(readPluginCurrentPointer(join(pluginsDir, first.pluginKey))).resolves.toBe(
first.contentHash
)
})
it('does not replace provenance when a same-content reinstall fails to publish', async () => {
const firstSource = await tempRoot('orca-plugin-source-')
const secondSource = await tempRoot('orca-plugin-source-')
const pluginsDir = await tempRoot('orca-plugin-installs-')
await writePluginSource(firstSource)
await writePluginSource(secondSource)
const first = await installPluginFromLocalPath({
pluginsDir,
sourcePath: firstSource,
hostVersion: '1.4.0'
})
expect(first.ok).toBe(true)
if (!first.ok) {
return
}
const acceptedLock = await readFile(join(pluginsDir, 'plugins.lock.json'), 'utf8')
await rm(join(pluginsDir, 'plugins.lock.json'))
await mkdir(join(pluginsDir, 'plugins.lock.json'))
const failed = await installPluginFromLocalPath({
pluginsDir,
sourcePath: secondSource,
hostVersion: '1.4.0'
})
expect(failed).toMatchObject({ ok: false })
await rm(join(pluginsDir, 'plugins.lock.json'), { recursive: true })
await writeFile(join(pluginsDir, 'plugins.lock.json'), acceptedLock)
const recovered = await readPluginLockfile(pluginsDir)
expect(recovered.plugins[first.pluginKey]?.source).toEqual({
kind: 'local-path',
path: firstSource
})
})
it('preserves legacy lock provenance during a same-content reinstall', async () => {
const firstSource = await tempRoot('orca-plugin-source-')
const secondSource = await tempRoot('orca-plugin-source-')
const pluginsDir = await tempRoot('orca-plugin-installs-')
await writePluginSource(firstSource)
await writePluginSource(secondSource)
const first = await installPluginFromLocalPath({
pluginsDir,
sourcePath: firstSource,
hostVersion: '1.4.0'
})
expect(first.ok).toBe(true)
if (!first.ok) {
return
}
await rm(join(pluginsDir, first.pluginKey, '.install-provenance', `${first.contentHash}.json`))
const reinstalled = await installPluginFromLocalPath({
pluginsDir,
sourcePath: secondSource,
hostVersion: '1.4.0'
})
expect(reinstalled).toMatchObject({ ok: true })
// Recovery from the newly backfilled provenance must retain the accepted
// legacy source rather than the same-byte reinstall's alternate source.
await rm(join(pluginsDir, 'plugins.lock.json'))
const recovered = await readPluginLockfile(pluginsDir)
expect(recovered.plugins[first.pluginKey]?.source).toEqual({
kind: 'local-path',
path: firstSource
})
})
it('retains only the current and immediately previous content versions', async () => {
const sourcePath = await tempRoot('orca-plugin-source-')
const pluginsDir = await tempRoot('orca-plugin-installs-')
await writePluginSource(sourcePath)
const hashes: string[] = []
for (const content of ['one', 'two', 'three']) {
await writeFile(join(sourcePath, 'panel.html'), `<h1>${content}</h1>`)
const result = await installPluginFromLocalPath({
pluginsDir,
sourcePath,
hostVersion: '1.4.0'
})
expect(result.ok).toBe(true)
if (result.ok) {
hashes.push(result.contentHash)
}
}
const versionDirs = (
await readdir(join(pluginsDir, 'orca-samples.demo'), {
withFileTypes: true
})
)
.filter((entry) => entry.isDirectory() && /^[0-9a-f]{64}$/.test(entry.name))
.map((entry) => entry.name)
.sort()
expect(versionDirs).toEqual(hashes.slice(-2).sort())
})
it('keeps the rollback version when current content is reinstalled', async () => {
const sourcePath = await tempRoot('orca-plugin-source-')
const pluginsDir = await tempRoot('orca-plugin-installs-')
await writePluginSource(sourcePath)
const hashes: string[] = []
for (const content of ['one', 'two', 'two']) {
await writeFile(join(sourcePath, 'panel.html'), `<h1>${content}</h1>`)
const result = await installPluginFromLocalPath({
pluginsDir,
sourcePath,
hostVersion: '1.4.0'
})
expect(result.ok).toBe(true)
if (result.ok) {
hashes.push(result.contentHash)
}
}
const versionDirs = (
await readdir(join(pluginsDir, 'orca-samples.demo'), { withFileTypes: true })
)
.filter((entry) => entry.isDirectory() && /^[0-9a-f]{64}$/.test(entry.name))
.map((entry) => entry.name)
.sort()
expect(versionDirs).toEqual([...new Set(hashes)].sort())
})
it('repairs a pointer-new lock-old interrupted publication from provenance', async () => {
const sourcePath = await tempRoot('orca-plugin-source-')
const pluginsDir = await tempRoot('orca-plugin-installs-')
await writePluginSource(sourcePath)
const first = await installPluginFromLocalPath({ pluginsDir, sourcePath, hostVersion: '1.4.0' })
expect(first.ok).toBe(true)
const oldLock = await readFile(join(pluginsDir, 'plugins.lock.json'), 'utf8')
await writeFile(join(sourcePath, 'panel.html'), '<h1>new current</h1>')
const second = await installPluginFromLocalPath({
pluginsDir,
sourcePath,
hostVersion: '1.4.0'
})
expect(second.ok).toBe(true)
if (!first.ok || !second.ok) {
return
}
await writeFile(join(pluginsDir, 'plugins.lock.json'), oldLock)
const repaired = await readPluginLockfile(pluginsDir)
expect(repaired.plugins[second.pluginKey]?.contentHash).toBe(second.contentHash)
const persisted = JSON.parse(await readFile(join(pluginsDir, 'plugins.lock.json'), 'utf8')) as {
plugins: Record<string, { contentHash?: string }>
}
expect(persisted.plugins[second.pluginKey]?.contentHash).toBe(second.contentHash)
})
it('rejects a manifest whose declared panel artifact is missing', async () => {
const sourcePath = await tempRoot('orca-plugin-source-')
const pluginsDir = await tempRoot('orca-plugin-installs-')
await writePluginSource(sourcePath, { includePanel: false })
const result = await installPluginFromLocalPath({
pluginsDir,
sourcePath,
hostVersion: '1.4.0'
})
expect(result).toMatchObject({ ok: false })
})
it('rejects an oversized manifest without reading an unbounded JSON payload', async () => {
const sourcePath = await tempRoot('orca-plugin-source-')
const pluginsDir = await tempRoot('orca-plugin-installs-')
const manifestPath = join(sourcePath, 'orca-plugin.json')
await writeFile(manifestPath, '')
await truncate(manifestPath, PLUGIN_MANIFEST_MAX_BYTES + 1)
const result = await installPluginFromLocalPath({
pluginsDir,
sourcePath,
hostVersion: '1.4.0'
})
expect(result).toMatchObject({ ok: false, error: expect.stringContaining('exceeds') })
})
it('serializes concurrent installs so lockfile entries are not lost', async () => {
const firstSource = await tempRoot('orca-plugin-source-')
const secondSource = await tempRoot('orca-plugin-source-')
const pluginsDir = await tempRoot('orca-plugin-installs-')
await writePluginSource(firstSource, { id: 'first' })
await writePluginSource(secondSource, { id: 'second' })
const results = await Promise.all([
installPluginFromLocalPath({ pluginsDir, sourcePath: firstSource, hostVersion: '1.4.0' }),
installPluginFromLocalPath({ pluginsDir, sourcePath: secondSource, hostVersion: '1.4.0' })
])
expect(results.every((result) => result.ok)).toBe(true)
const lock = JSON.parse(await readFile(join(pluginsDir, 'plugins.lock.json'), 'utf8')) as {
plugins: Record<string, unknown>
}
expect(Object.keys(lock.plugins).sort()).toEqual(['orca-samples.first', 'orca-samples.second'])
})
it('serializes concurrent lockfile publications without temporary-file collisions', async () => {
const pluginsDir = await tempRoot('orca-plugin-installs-')
const lock = { version: 1 as const, plugins: {} }
await expect(
Promise.all([
writePluginLockfile(pluginsDir, lock),
writePluginLockfile(pluginsDir, lock),
writePluginLockfile(pluginsDir, lock)
])
).resolves.toHaveLength(3)
await expect(readPluginLockfile(pluginsDir)).resolves.toEqual(lock)
})
it('refuses to repoint at a tampered existing content directory', async () => {
const sourcePath = await tempRoot('orca-plugin-source-')
const pluginsDir = await tempRoot('orca-plugin-installs-')
await writePluginSource(sourcePath)
const first = await installPluginFromLocalPath({
pluginsDir,
sourcePath,
hostVersion: '1.4.0'
})
expect(first.ok).toBe(true)
if (!first.ok) {
return
}
await writeFile(
join(pluginsDir, first.pluginKey, first.contentHash, 'panel.html'),
'<h1>Tampered</h1>'
)
const second = await installPluginFromLocalPath({
pluginsDir,
sourcePath,
hostVersion: '1.4.0'
})
expect(second).toMatchObject({
ok: false,
error: expect.stringContaining('integrity verification')
})
})
})
describe('installPluginFromGit', () => {
it('uses system Git, resolves the requested ref, and installs its exact bytes', async () => {
const sourcePath = await tempRoot('orca-plugin-git-source-')
const pluginsDir = await tempRoot('orca-plugin-installs-')
await writePluginSource(sourcePath)
await execFileAsync('git', ['init', '--quiet'], { cwd: sourcePath })
await execFileAsync('git', ['config', 'user.email', 'plugins@example.invalid'], {
cwd: sourcePath
})
await execFileAsync('git', ['config', 'user.name', 'Plugin Test'], { cwd: sourcePath })
await execFileAsync('git', ['add', '.'], { cwd: sourcePath })
await execFileAsync('git', ['commit', '--quiet', '-m', 'fixture'], { cwd: sourcePath })
await execFileAsync('git', ['tag', 'v1.0.0'], { cwd: sourcePath })
const { stdout: commitStdout } = await execFileAsync('git', ['rev-parse', 'HEAD'], {
cwd: sourcePath
})
const configKeys = ['GIT_CONFIG_COUNT', 'GIT_CONFIG_KEY_0', 'GIT_CONFIG_VALUE_0'] as const
const previous = Object.fromEntries(configKeys.map((key) => [key, process.env[key]]))
process.env.GIT_CONFIG_COUNT = '1'
process.env.GIT_CONFIG_KEY_0 = `url.${pathToFileURL(sourcePath).href}.insteadOf`
process.env.GIT_CONFIG_VALUE_0 = 'https://plugin.test/demo.git'
try {
const result = await installPluginFromGit({
pluginsDir,
url: 'https://plugin.test/demo.git',
ref: 'v1.0.0',
hostVersion: '1.4.0'
})
expect(result).toMatchObject({ ok: true, resolvedCommit: commitStdout.trim() })
if (result.ok) {
await expect(
readFile(join(pluginsDir, result.pluginKey, result.contentHash, 'panel.html'), 'utf8')
).resolves.toBe('<h1>Panel</h1>')
}
} finally {
for (const key of configKeys) {
const value = previous[key]
if (value === undefined) {
delete process.env[key]
} else {
process.env[key] = value
}
}
}
})
})
describe('removeInstalledPlugin', () => {
it('rejects an unqualified or traversing key before removing anything', async () => {
const pluginsDir = await tempRoot('orca-plugin-installs-')
const pluginsDataDir = await tempRoot('orca-plugin-data-')
const outside = join(await tempRoot('orca-plugin-outside-'), 'keep.txt')
await writeFile(outside, 'keep')
await expect(
removeInstalledPlugin({ pluginsDir, pluginsDataDir, pluginKey: '../outside' })
).rejects.toThrow('invalid qualified plugin key')
await expect(readFile(outside, 'utf8')).resolves.toBe('keep')
})
it('rejects a resolved uninstall target outside its root', async () => {
const pluginsDir = await tempRoot('orca-plugin-installs-')
const pluginsDataDir = await tempRoot('orca-plugin-data-')
const outside = await tempRoot('orca-plugin-outside-')
const marker = join(outside, 'keep.txt')
await writeFile(marker, 'keep')
await symlink(
outside,
join(pluginsDir, 'orca-samples.demo'),
process.platform === 'win32' ? 'junction' : 'dir'
)
await expect(
removeInstalledPlugin({
pluginsDir,
pluginsDataDir,
pluginKey: 'orca-samples.demo'
})
).rejects.toThrow('outside')
await expect(readFile(marker, 'utf8')).resolves.toBe('keep')
})
it('removes qualified install and data directories', async () => {
const pluginsDir = await tempRoot('orca-plugin-installs-')
const pluginsDataDir = await tempRoot('orca-plugin-data-')
const key = 'orca-samples.demo'
await mkdir(join(pluginsDir, key))
await mkdir(join(pluginsDataDir, key))
await writeFile(join(pluginsDir, key, 'content'), 'installed')
await writeFile(join(pluginsDataDir, key, 'storage.json'), '{}')
await removeInstalledPlugin({ pluginsDir, pluginsDataDir, pluginKey: key })
await expect(readFile(join(pluginsDir, key, 'content'))).rejects.toThrow()
await expect(readFile(join(pluginsDataDir, key, 'storage.json'))).rejects.toThrow()
})
})
+319
View File
@@ -0,0 +1,319 @@
import { mkdtemp, readdir, realpath, rm } from 'node:fs/promises'
import { existsSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { isAbsolute, join, relative, resolve, sep } from 'node:path'
import {
PLUGIN_MANIFEST_FILENAME,
isQualifiedPluginKey
} from '../../shared/plugins/plugin-manifest'
import {
isAllowedPluginGitUrl,
PLUGIN_COMMIT_PATTERN,
PLUGIN_CONTENT_HASH_PATTERN,
pluginInstallSourceSchema,
removePluginLock
} from '../../shared/plugins/plugin-install-lockfile'
import { readPluginLockfile, writePluginLockfile } from './plugin-install-lockfile-store'
import {
inspectPluginInstallTree,
installStagedPluginTree,
type PluginInstallResult
} from './plugin-install-staging'
import { checkoutPluginGitSource } from './plugin-git-repository'
import { readPluginCurrentPointer } from './plugin-current-pointer'
import { readPluginInstallProvenance } from './plugin-install-provenance'
import { publishPluginInstall } from './plugin-install-publication'
export type { PluginInstallResult } from './plugin-install-staging'
export {
PLUGIN_LOCKFILE_MAX_BYTES,
pluginLockfilePath,
readPluginLockfile
} from './plugin-install-lockfile-store'
/**
* Plugin installer, v0 sources: local path + git URL `#ref`. Git operations
* shell out to SYSTEM git (execFile, argv arrays — never a shell string, and
* never a vendored checkout: private repos must work with the user's
* existing credential helpers and SSH remotes). No script execution during
* install, ever — the installer copies files, nothing more.
*
* Installs land in immutable hash-addressed dirs behind an atomic pointer
* swap; the previous version dir is kept for one-step rollback.
*/
const pluginMutationChains = new Map<string, Promise<void>>()
async function serializePluginMutation<T>(
pluginsDir: string,
operation: () => Promise<T>
): Promise<T> {
const previous = pluginMutationChains.get(pluginsDir) ?? Promise.resolve()
const run = previous.catch(() => undefined).then(operation)
const settled = run.then(
() => undefined,
() => undefined
)
pluginMutationChains.set(pluginsDir, settled)
try {
return await run
} finally {
if (pluginMutationChains.get(pluginsDir) === settled) {
pluginMutationChains.delete(pluginsDir)
}
}
}
export async function installPluginFromLocalPath(input: {
pluginsDir: string
sourcePath: string
hostVersion: string
blockedPluginReason?: (pluginKey: string) => string | null
}): Promise<PluginInstallResult> {
return serializePluginMutation(input.pluginsDir, async () => {
if (!existsSync(join(input.sourcePath, PLUGIN_MANIFEST_FILENAME))) {
return { ok: false, error: `no ${PLUGIN_MANIFEST_FILENAME} found in ${input.sourcePath}` }
}
return installStagedPluginTree({
pluginsDir: input.pluginsDir,
stagingDir: input.sourcePath,
hostVersion: input.hostVersion,
source: { kind: 'local-path', path: input.sourcePath },
resolvedCommit: null,
blockedPluginReason: input.blockedPluginReason
})
})
}
export async function installBundledPlugin(input: {
pluginsDir: string
sourcePath: string
hostVersion: string
expectedPluginKey: string
blockedPluginReason?: (pluginKey: string) => string | null
}): Promise<PluginInstallResult> {
return serializePluginMutation(input.pluginsDir, () =>
installStagedPluginTree({
pluginsDir: input.pluginsDir,
stagingDir: input.sourcePath,
hostVersion: input.hostVersion,
source: { kind: 'bundled', bundleId: input.expectedPluginKey },
resolvedCommit: null,
expectedPluginKey: input.expectedPluginKey,
repairCorruptedVersion: true,
blockedPluginReason: input.blockedPluginReason
})
)
}
export async function installPluginFromGit(input: {
pluginsDir: string
url: string
/** `#ref` suffix: branch, tag, or full commit SHA. Empty = default branch. */
ref: string
hostVersion: string
blockedPluginReason?: (pluginKey: string) => string | null
}): Promise<PluginInstallResult> {
if (!isAllowedPluginGitUrl(input.url)) {
return { ok: false, error: 'plugin Git URL must use HTTPS or SSH' }
}
return serializePluginMutation(input.pluginsDir, async () => {
const stagingDir = await mkdtemp(join(tmpdir(), 'orca-plugin-install-'))
try {
const ref = input.ref.trim()
const resolvedCommit = await checkoutPluginGitSource({
url: input.url,
ref,
destination: stagingDir,
workingDirectory: tmpdir()
})
return await installStagedPluginTree({
pluginsDir: input.pluginsDir,
stagingDir,
hostVersion: input.hostVersion,
source: { kind: 'git', url: input.url, ref },
resolvedCommit,
blockedPluginReason: input.blockedPluginReason
})
} catch (error) {
return { ok: false, error: error instanceof Error ? error.message : String(error) }
} finally {
await rm(stagingDir, { recursive: true, force: true })
}
})
}
export async function installPluginFromMarketplace(input: {
pluginsDir: string
hostVersion: string
expectedPluginKey: string
expectedResolvedCommit: string
marketplace: { url: string; ref: string; resolvedCommit: string }
plugin: { url: string; ref: string }
blockedPluginReason?: (pluginKey: string) => string | null
}): Promise<PluginInstallResult> {
const source = pluginInstallSourceSchema.parse({
kind: 'marketplace',
marketplace: input.marketplace,
plugin: input.plugin
})
if (!isQualifiedPluginKey(input.expectedPluginKey)) {
return { ok: false, error: 'invalid marketplace plugin identity' }
}
if (!PLUGIN_COMMIT_PATTERN.test(input.expectedResolvedCommit)) {
return { ok: false, error: 'invalid previewed plugin commit' }
}
return serializePluginMutation(input.pluginsDir, async () => {
const stagingDir = await mkdtemp(join(tmpdir(), 'orca-plugin-marketplace-install-'))
try {
const resolvedCommit = await checkoutPluginGitSource({
url: input.plugin.url,
ref: input.plugin.ref,
destination: stagingDir,
workingDirectory: tmpdir()
})
if (resolvedCommit !== input.expectedResolvedCommit) {
return { ok: false, error: 'plugin source changed after preview; review the update again' }
}
return await installStagedPluginTree({
pluginsDir: input.pluginsDir,
stagingDir,
hostVersion: input.hostVersion,
source,
resolvedCommit,
expectedPluginKey: input.expectedPluginKey,
blockedPluginReason: input.blockedPluginReason
})
} catch (error) {
return { ok: false, error: error instanceof Error ? error.message : String(error) }
} finally {
await rm(stagingDir, { recursive: true, force: true })
}
})
}
/** Restores the single retained immutable predecessor. The old consent
* fingerprint becomes current again, so enablement still fails closed until
* the user has approved those exact bytes. */
export async function rollbackInstalledPlugin(input: {
pluginsDir: string
pluginKey: string
hostVersion: string
blockedPluginReason?: (pluginKey: string) => string | null
}): Promise<PluginInstallResult> {
if (!isQualifiedPluginKey(input.pluginKey)) {
return { ok: false, error: 'invalid qualified plugin key' }
}
const blockedReason = input.blockedPluginReason?.(input.pluginKey)
if (blockedReason) {
return { ok: false, error: `plugin is blocked by Orca's safety list: ${blockedReason}` }
}
return serializePluginMutation(input.pluginsDir, async () => {
const pluginDir = join(input.pluginsDir, input.pluginKey)
const currentContentHash = await readPluginCurrentPointer(pluginDir).catch(() => null)
if (!currentContentHash) {
return { ok: false, error: 'installed plugin has no current version' }
}
const candidates = (await readdir(pluginDir, { withFileTypes: true }).catch(() => []))
.filter(
(entry) =>
entry.isDirectory() &&
PLUGIN_CONTENT_HASH_PATTERN.test(entry.name) &&
entry.name !== currentContentHash
)
.map((entry) => entry.name)
if (candidates.length !== 1) {
return {
ok: false,
error:
candidates.length === 0
? 'no rollback version is available'
: 'rollback state is ambiguous'
}
}
const contentHash = candidates[0]!
const provenance = await readPluginInstallProvenance(pluginDir, contentHash)
if (
!provenance ||
provenance.pluginKey !== input.pluginKey ||
provenance.contentHash !== contentHash
) {
return { ok: false, error: 'rollback version has no valid install provenance' }
}
const inspection = await inspectPluginInstallTree({
rootDir: join(pluginDir, contentHash),
hostVersion: input.hostVersion,
expectedPluginKey: input.pluginKey
})
if (!inspection.ok || inspection.contentHash !== contentHash) {
return {
ok: false,
error: inspection.ok ? 'rollback version failed integrity verification' : inspection.error
}
}
try {
await publishPluginInstall({ pluginsDir: input.pluginsDir, pluginDir, entry: provenance })
} catch (error) {
return { ok: false, error: error instanceof Error ? error.message : String(error) }
}
return {
ok: true,
pluginKey: input.pluginKey,
version: inspection.manifest.version,
contentHash,
consentFingerprint: provenance.consentFingerprint,
resolvedCommit: provenance.resolvedCommit
}
})
}
/** Removes the install dir, the plugin's data dir, and the lock entry. */
export async function removeInstalledPlugin(input: {
pluginsDir: string
pluginsDataDir: string
pluginKey: string
}): Promise<void> {
await serializePluginMutation(input.pluginsDir, async () => {
if (!isQualifiedPluginKey(input.pluginKey)) {
throw new Error(`invalid qualified plugin key: ${input.pluginKey}`)
}
await removeResolvedPluginDirectory(input.pluginsDir, input.pluginKey)
await removeResolvedPluginDirectory(input.pluginsDataDir, input.pluginKey)
await writePluginLockfile(
input.pluginsDir,
removePluginLock(await readPluginLockfile(input.pluginsDir), input.pluginKey)
)
})
}
async function removeResolvedPluginDirectory(rootDir: string, pluginKey: string): Promise<void> {
let rootReal: string
let targetReal: string
try {
rootReal = await realpath(resolve(rootDir))
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
return
}
throw error
}
try {
targetReal = await realpath(resolve(rootDir, pluginKey))
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
return
}
throw error
}
const fromRoot = relative(rootReal, targetReal)
if (
fromRoot.length === 0 ||
isAbsolute(fromRoot) ||
fromRoot === '..' ||
fromRoot.startsWith(`..${sep}`)
) {
throw new Error(`refusing to remove plugin path outside ${rootReal}`)
}
await rm(resolve(rootDir, pluginKey), { recursive: true, force: true })
}
@@ -0,0 +1,30 @@
import { hasInstructionalPluginContributions } from '../../shared/plugins/plugin-consent-fingerprint'
import { hashPluginTree } from './plugin-content-hash'
import type { ValidDiscoveredPlugin } from './plugin-discovery'
/** Instructional bytes execute later, so every read must still match the tree
* identity the user reviewed rather than a cached discovery-time snapshot. */
export async function verifyInstructionalPluginContent(
plugin: ValidDiscoveredPlugin
): Promise<void> {
if (!hasInstructionalPluginContributions(plugin.manifest)) {
return
}
if (!plugin.consentContentHash) {
throw new Error(`plugin ${plugin.pluginKey} has no instructional consent content identity`)
}
const actual = await hashPluginTree(plugin.rootDir)
if (!actual.ok) {
throw new Error(
`plugin ${plugin.pluginKey} instructional content is unreadable: ${actual.error}`
)
}
const matches =
actual.hash === plugin.consentContentHash ||
(plugin.consentContentHash.length === 32 && actual.hash.startsWith(plugin.consentContentHash))
if (!matches) {
throw new Error(
`plugin ${plugin.pluginKey} instructional content changed since it was reviewed`
)
}
}
@@ -0,0 +1,111 @@
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { PluginKillList } from '../../shared/plugins/plugin-kill-list'
import { fetchPluginKillList, PluginKillListService } from './plugin-kill-list-service'
import type { PluginKillListStore } from './plugin-kill-list-store'
const roots: string[] = []
async function tempRoot(): Promise<string> {
const root = await mkdtemp(join(tmpdir(), 'orca-plugin-kill-list-'))
roots.push(root)
return root
}
function killList(date = '2026-07-12T20:00:00Z'): PluginKillList {
return {
version: 1,
generatedAt: date,
plugins: [{ pluginKey: 'community.unsafe', reason: 'Malware advisory' }]
}
}
afterEach(async () => {
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })))
})
describe('PluginKillListService', () => {
it('loads cached revocations before any network refresh', async () => {
const root = await tempRoot()
const first = new PluginKillListService({
pluginsDataDir: root,
fetcher: async () => killList()
})
await first.refresh()
const fetcher = vi.fn(async () => killList())
const restarted = new PluginKillListService({ pluginsDataDir: root, fetcher })
await restarted.initialize()
expect(restarted.reason('community.unsafe')).toBe('Malware advisory')
expect(fetcher).not.toHaveBeenCalled()
})
it('publishes valid refreshes and notifies runtime reconciliation', async () => {
const service = new PluginKillListService({
pluginsDataDir: await tempRoot(),
fetcher: async () => killList()
})
const changed = vi.fn()
service.onChanged(changed)
await service.refresh()
expect(service.find('community.unsafe')).toMatchObject({ reason: 'Malware advisory' })
expect(changed).toHaveBeenCalledTimes(1)
})
it('starts with no revocations after a corrupt cache and accepts a valid refresh', async () => {
const store = {
read: vi.fn().mockRejectedValue(new Error('invalid JSON')),
write: vi.fn().mockResolvedValue(undefined)
} as unknown as PluginKillListStore
const warning = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
const service = new PluginKillListService({
pluginsDataDir: await tempRoot(),
store,
fetcher: async () => killList()
})
await expect(service.initialize()).resolves.toBeUndefined()
expect(service.snapshot()).toBeNull()
await expect(service.refresh()).resolves.toEqual(killList())
expect(service.reason('community.unsafe')).toBe('Malware advisory')
expect(warning).toHaveBeenCalledWith(
'[plugins] ignoring invalid cached plugin safety list:',
expect.any(Error)
)
})
it('rejects a replayed older snapshot without replacing cached revocations', async () => {
const fetcher = vi
.fn<() => Promise<PluginKillList>>()
.mockResolvedValueOnce(killList('2026-07-12T20:00:00Z'))
.mockResolvedValueOnce(killList('2026-07-11T20:00:00Z'))
const service = new PluginKillListService({ pluginsDataDir: await tempRoot(), fetcher })
await service.refresh()
await expect(service.refresh()).rejects.toThrow('older snapshot')
expect(service.snapshot()?.generatedAt).toBe('2026-07-12T20:00:00Z')
})
})
describe('fetchPluginKillList', () => {
it('validates a bounded HTTPS response body', async () => {
const fetcher = vi.fn<typeof fetch>().mockResolvedValue(
new Response(JSON.stringify(killList()), {
status: 200,
headers: { 'content-type': 'application/json' }
})
)
await expect(fetchPluginKillList(fetcher)).resolves.toEqual(killList())
})
it('rejects non-success responses', async () => {
const fetcher = vi.fn<typeof fetch>().mockResolvedValue(new Response('no', { status: 503 }))
await expect(fetchPluginKillList(fetcher)).rejects.toThrow('HTTP 503')
})
})
@@ -0,0 +1,140 @@
import {
findKilledPlugin,
pluginKillListSchema,
type PluginKillList,
type PluginKillListEntry
} from '../../shared/plugins/plugin-kill-list'
import { PluginKillListStore } from './plugin-kill-list-store'
export const PLUGIN_KILL_LIST_URL = 'https://onorca.dev/plugins/kill-list.json'
const PLUGIN_KILL_LIST_DOWNLOAD_LIMIT = 4 * 1024 * 1024
type PluginKillListFetcher = () => Promise<PluginKillList>
export class PluginKillListService {
private readonly store: PluginKillListStore
private readonly fetcher: PluginKillListFetcher
private readonly listeners = new Set<() => void>()
private currentList: PluginKillList | null = null
private loadPromise: Promise<void> | null = null
private refreshChain: Promise<PluginKillList> = Promise.resolve({
version: 1,
generatedAt: '1970-01-01T00:00:00Z',
plugins: []
})
constructor(options: {
pluginsDataDir: string
store?: PluginKillListStore
fetcher?: PluginKillListFetcher
}) {
this.store = options.store ?? new PluginKillListStore(options.pluginsDataDir)
this.fetcher = options.fetcher ?? (() => fetchPluginKillList())
}
async initialize(): Promise<void> {
this.loadPromise ??= this.store
.read()
.then((killList) => {
this.currentList = killList
})
.catch((error) => {
// Why: an unusable cache must not prevent Orca from starting; a valid
// network refresh can still restore runtime revocations this session.
console.warn('[plugins] ignoring invalid cached plugin safety list:', error)
this.currentList = null
})
await this.loadPromise
}
onChanged(listener: () => void): () => void {
this.listeners.add(listener)
return () => this.listeners.delete(listener)
}
find(pluginKey: string): PluginKillListEntry | null {
return this.currentList ? findKilledPlugin(this.currentList, pluginKey) : null
}
reason(pluginKey: string): string | null {
return this.find(pluginKey)?.reason ?? null
}
snapshot(): PluginKillList | null {
return this.currentList
}
refresh(): Promise<PluginKillList> {
const refresh = this.refreshChain
.catch(() => this.currentList ?? emptyKillList())
.then(() => this.performRefresh())
this.refreshChain = refresh
return refresh
}
private async performRefresh(): Promise<PluginKillList> {
await this.initialize()
const fetched = pluginKillListSchema.parse(await this.fetcher())
if (
this.currentList &&
Date.parse(fetched.generatedAt) < Date.parse(this.currentList.generatedAt)
) {
throw new Error('refusing to replace the plugin kill list with an older snapshot')
}
await this.store.write(fetched)
this.currentList = fetched
for (const listener of this.listeners) {
listener()
}
return fetched
}
}
export async function fetchPluginKillList(
fetcher: typeof fetch = fetch,
url = PLUGIN_KILL_LIST_URL
): Promise<PluginKillList> {
const response = await fetcher(url, { cache: 'no-store' })
if (!response.ok) {
throw new Error(`plugin kill-list request failed with HTTP ${response.status}`)
}
const declaredBytes = Number(response.headers.get('content-length') ?? '0')
if (Number.isFinite(declaredBytes) && declaredBytes > PLUGIN_KILL_LIST_DOWNLOAD_LIMIT) {
throw new Error('plugin kill-list response exceeds its size limit')
}
if (!response.body) {
throw new Error('plugin kill-list response has no body')
}
const reader = response.body.getReader()
const chunks: Uint8Array[] = []
let totalBytes = 0
while (true) {
const chunk = await reader.read()
if (chunk.done) {
break
}
totalBytes += chunk.value.byteLength
if (totalBytes > PLUGIN_KILL_LIST_DOWNLOAD_LIMIT) {
await reader.cancel()
throw new Error('plugin kill-list response exceeds its size limit')
}
chunks.push(chunk.value)
}
const bytes = new Uint8Array(totalBytes)
let offset = 0
for (const chunk of chunks) {
bytes.set(chunk, offset)
offset += chunk.byteLength
}
try {
return pluginKillListSchema.parse(JSON.parse(new TextDecoder().decode(bytes)))
} catch (error) {
throw new Error(
`invalid plugin kill-list response: ${error instanceof Error ? error.message : String(error)}`
)
}
}
function emptyKillList(): PluginKillList {
return { version: 1, generatedAt: '1970-01-01T00:00:00Z', plugins: [] }
}
@@ -0,0 +1,46 @@
import { createReadStream } from 'node:fs'
import { mkdir } from 'node:fs/promises'
import { dirname, join } from 'node:path'
import { pluginKillListSchema, type PluginKillList } from '../../shared/plugins/plugin-kill-list'
import { writePluginFileAtomically } from './plugin-atomic-file-write'
const PLUGIN_KILL_LIST_MAX_BYTES = 4 * 1024 * 1024
export class PluginKillListStore {
private readonly filePath: string
constructor(pluginsDataDir: string) {
this.filePath = join(pluginsDataDir, 'plugin-kill-list.json')
}
async read(): Promise<PluginKillList | null> {
try {
const chunks: Buffer[] = []
let totalBytes = 0
for await (const chunk of createReadStream(this.filePath)) {
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
totalBytes += bytes.byteLength
if (totalBytes > PLUGIN_KILL_LIST_MAX_BYTES) {
throw new Error('plugin kill list exceeds its size limit')
}
chunks.push(bytes)
}
return pluginKillListSchema.parse(
JSON.parse(Buffer.concat(chunks, totalBytes).toString('utf8'))
)
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
return null
}
throw new Error(
`cached plugin kill list is invalid: ${error instanceof Error ? error.message : String(error)}`
)
}
}
async write(killList: PluginKillList): Promise<void> {
const parsed = pluginKillListSchema.parse(killList)
await mkdir(dirname(this.filePath), { recursive: true })
await writePluginFileAtomically(this.filePath, `${JSON.stringify(parsed, null, 2)}\n`)
}
}
@@ -0,0 +1,78 @@
import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { fingerprintPluginConsent } from '../../shared/plugins/plugin-consent-fingerprint'
import { pluginManifestSchema } from '../../shared/plugins/plugin-manifest'
import { PluginContentVerifier } from './plugin-content-integrity'
import type { ValidDiscoveredPlugin } from './plugin-discovery'
import { PluginLanguagePackRegistry } from './plugin-language-pack-registry'
const roots: string[] = []
async function pluginWithCatalog(catalog: unknown): Promise<ValidDiscoveredPlugin> {
const rootDir = await mkdtemp(join(tmpdir(), 'orca-plugin-language-registry-'))
roots.push(rootDir)
await mkdir(join(rootDir, 'locales'))
await writeFile(join(rootDir, 'locales', 'pt-BR.json'), JSON.stringify(catalog))
const manifest = pluginManifestSchema.parse({
manifestVersion: 1,
id: 'portuguese',
publisher: 'orca-samples',
name: 'Portuguese',
version: '1.0.0',
engines: { orca: '>=1.0.0' },
pluginApi: 1,
contributes: {
languagePacks: [{ locale: 'pt-BR', path: 'locales/pt-BR.json' }]
},
capabilities: []
})
return {
pluginKey: 'orca-samples.portuguese',
rootDir,
manifest,
consentFingerprint: fingerprintPluginConsent(manifest),
contentHash: null,
isDev: true
}
}
afterEach(async () => {
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })))
})
describe('PluginLanguagePackRegistry', () => {
it('loads approved catalogs under an isolated plugin language id', async () => {
const plugin = await pluginWithCatalog({ common: { save: 'Salvar' } })
const registry = new PluginLanguagePackRegistry(new PluginContentVerifier())
await registry.reconcile([plugin], () => true)
expect(registry.list()).toEqual([
{
id: 'plugin:orca-samples.portuguese/pt-BR',
resourceLanguage:
'plugin0070006c007500670069006e003a006f007200630061002d00730061006d0070006c00650073002e0070006f00720074007500670075006500730065002f00700074002d00420052',
pluginKey: 'orca-samples.portuguese',
locale: 'pt-BR',
catalog: { common: { save: 'Salvar' } }
}
])
expect(registry.error(plugin.pluginKey)).toBeNull()
})
it('fails closed for protected security copy and clears state when disabled', async () => {
const plugin = await pluginWithCatalog({
auto: { components: { settings: { PluginConsentDialog: { disclaimer: 'Safe' } } } }
})
const registry = new PluginLanguagePackRegistry(new PluginContentVerifier())
await registry.reconcile([plugin], () => true)
expect(registry.list()).toEqual([])
expect(registry.error(plugin.pluginKey)).toContain('protected security copy')
await registry.reconcile([plugin], () => false)
expect(registry.error(plugin.pluginKey)).toBeNull()
})
})
@@ -0,0 +1,96 @@
import {
parsePluginLanguagePackArtifact,
pluginLanguageResourceId,
type PluginLanguagePackRegistration
} from '../../shared/plugins/plugin-language-pack-artifact'
import {
PLUGIN_LANGUAGE_PACK_MAX_BYTES,
readContainedPluginArtifactText
} from './plugin-artifact-validation'
import type { PluginContentVerifier } from './plugin-content-integrity'
import { mapWithConcurrency } from '../../shared/map-with-concurrency'
import {
isInvalidDiscoveredPlugin,
type DiscoveredPlugin,
type ValidDiscoveredPlugin
} from './plugin-discovery'
const LANGUAGE_PACK_LOAD_CONCURRENCY = 4
type LanguageLoadResult =
| { pluginKey: string; packs: PluginLanguagePackRegistration[] }
| { pluginKey: string; error: string }
export class PluginLanguagePackRegistry {
private packs: PluginLanguagePackRegistration[] = []
private readonly errors = new Map<string, string>()
constructor(private readonly contentVerifier: PluginContentVerifier) {}
list(): readonly PluginLanguagePackRegistration[] {
return this.packs
}
error(pluginKey: string): string | null {
return this.errors.get(pluginKey) ?? null
}
async reconcile(
discovered: readonly DiscoveredPlugin[],
isApproved: (plugin: ValidDiscoveredPlugin) => boolean
): Promise<void> {
const candidates: ValidDiscoveredPlugin[] = []
for (const plugin of discovered) {
if (
!isInvalidDiscoveredPlugin(plugin) &&
isApproved(plugin) &&
plugin.manifest.contributes.languagePacks.length > 0
) {
candidates.push(plugin)
}
}
const results = await mapWithConcurrency(
candidates,
LANGUAGE_PACK_LOAD_CONCURRENCY,
async (plugin): Promise<LanguageLoadResult> => {
try {
await this.contentVerifier.verify(plugin)
const packs = await Promise.all(
plugin.manifest.contributes.languagePacks.map(async (contribution) => {
const text = await readContainedPluginArtifactText(
plugin.rootDir,
contribution.path,
PLUGIN_LANGUAGE_PACK_MAX_BYTES
)
const parsed = parsePluginLanguagePackArtifact(text)
if (!parsed.ok) {
throw new Error(`language pack "${contribution.locale}" ${parsed.error}`)
}
const id = `plugin:${plugin.pluginKey}/${contribution.locale}` as const
return {
id,
resourceLanguage: pluginLanguageResourceId(id),
pluginKey: plugin.pluginKey,
locale: contribution.locale,
catalog: parsed.catalog
}
})
)
return { pluginKey: plugin.pluginKey, packs }
} catch (error) {
return {
pluginKey: plugin.pluginKey,
error: error instanceof Error ? error.message : String(error)
}
}
}
)
this.packs = results.flatMap((result) => ('packs' in result ? result.packs : []))
this.errors.clear()
for (const result of results) {
if ('error' in result) {
this.errors.set(result.pluginKey, result.error)
}
}
}
}
@@ -0,0 +1,113 @@
import { cp, mkdtemp, readFile, readdir, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import {
isOfficialOrganizationGitSource,
isOfficialPluginIdentity,
pluginMarketplaceSchema
} from '../../shared/plugins/plugin-marketplace'
import { bootstrapBundledPlugins, resolveBundledPluginRoot } from './plugin-bundled-bootstrap'
import { inspectPluginInstallTree } from './plugin-install-staging'
const launchRoot = join(process.cwd(), 'resources', 'plugins', 'launch')
const temporaryRoots: string[] = []
async function readJson(path: string): Promise<unknown> {
return JSON.parse(await readFile(path, 'utf8'))
}
afterEach(async () => {
await Promise.all(
temporaryRoots.splice(0).map((root) => rm(root, { recursive: true, force: true }))
)
})
describe('Phase 1 launch plugin content', () => {
it('lists and validates the launch plugin packs', async () => {
const marketplace = pluginMarketplaceSchema.parse(
await readJson(join(launchRoot, 'orca-marketplace.json'))
)
expect(marketplace.plugins.map((plugin) => plugin.id).sort()).toEqual([
'stablyai.orca-multipass-recipes',
'stablyai.orca-navigation-shortcuts',
'stablyai.orca-portuguese'
])
expect(
marketplace.plugins.filter(
(plugin) =>
isOfficialPluginIdentity(plugin.id) && isOfficialOrganizationGitSource(plugin.source.url)
).length
).toBeGreaterThanOrEqual(2)
const localPluginDirectories = (await readdir(launchRoot, { withFileTypes: true }))
.filter((entry) => entry.isDirectory())
.map((entry) => entry.name)
.sort()
expect(marketplace.plugins.map((plugin) => plugin.id).sort()).toEqual(localPluginDirectories)
const contributionKinds = new Set<string>()
for (const listing of marketplace.plugins) {
const inspection = await inspectPluginInstallTree({
rootDir: join(launchRoot, listing.id),
hostVersion: '1.4.0',
expectedPluginKey: listing.id
})
expect(inspection, `${listing.id} must pass the production install inspection`).toMatchObject(
{
ok: true
}
)
if (!inspection.ok) {
continue
}
const contributes = inspection.manifest.contributes
if (contributes.languagePacks.length > 0) {
contributionKinds.add('language')
}
if (contributes.vmRecipes.length > 0) {
contributionKinds.add('vm-recipe')
}
if (contributes.commands.length > 0 && contributes.keybindings.length > 0) {
contributionKinds.add('command-keybinding')
}
}
expect(contributionKinds).toEqual(new Set(['language', 'vm-recipe', 'command-keybinding']))
})
it('publishes every bundled pack only when its release hash matches exact bytes', async () => {
const userDataPath = await mkdtemp(join(tmpdir(), 'orca-launch-content-'))
temporaryRoots.push(userDataPath)
const result = await bootstrapBundledPlugins({
root: launchRoot,
userDataPath,
hostVersion: '1.4.0'
})
expect(result.errors).toEqual([])
expect(result.installed.length).toBeGreaterThanOrEqual(1)
expect(result.installed.every(isOfficialPluginIdentity)).toBe(true)
})
it('boots release-indexed content from the packaged resources layout', async () => {
const resourcesPath = await mkdtemp(join(tmpdir(), 'orca-packaged-resources-'))
const userDataPath = await mkdtemp(join(tmpdir(), 'orca-packaged-user-data-'))
temporaryRoots.push(resourcesPath, userDataPath)
const packagedRoot = join(resourcesPath, 'plugins', 'launch')
await cp(launchRoot, packagedRoot, { recursive: true })
const result = await bootstrapBundledPlugins({
root: resolveBundledPluginRoot({
isPackaged: true,
resourcesPath,
appPath: join(resourcesPath, 'app.asar')
}),
userDataPath,
hostVersion: '1.4.0'
})
expect(result.errors).toEqual([])
expect(result.installed).toEqual(['stablyai.orca-navigation-shortcuts'])
})
})
@@ -0,0 +1,224 @@
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
import { emptyPluginLockfile } from '../../shared/plugins/plugin-install-lockfile'
import { pluginManifestSchema } from '../../shared/plugins/plugin-manifest'
import type { InvalidDiscoveredPlugin, ValidDiscoveredPlugin } from './plugin-discovery'
import { buildPluginList } from './plugin-list-projection'
import type { PluginService } from './plugin-service'
const manifest = pluginManifestSchema.parse({
manifestVersion: 1,
id: 'demo',
publisher: 'orca-samples',
name: 'Demo',
version: '1.0.0',
engines: { orca: '>=1.0.0' },
pluginApi: 1,
contributes: { panels: [], commands: [], events: [] },
capabilities: [{ kind: 'workspace:read' }]
})
function serviceWith(
discovered: ValidDiscoveredPlugin,
options: {
activation?: ReturnType<PluginService['activationState']>
worker?: ReturnType<PluginService['workerState']>
vmRecipes?: ReturnType<PluginService['contentPacks']['vmRecipes']['preview']>
commands?: ReturnType<PluginService['contentPacks']['commands']['preview']>
} = {}
): PluginService {
return {
options: {
getPluginConsents: () => ({}),
getDisabledPlugins: () => []
},
getDiscovered: () => [discovered],
activationState: () => options.activation ?? 'pending',
workerState: () => options.worker ?? { state: 'inactive', restarts: 0 },
activationError: () => null,
contentPacks: {
vmRecipes: { preview: () => options.vmRecipes ?? [] },
commands: { preview: () => options.commands ?? [] }
}
} as unknown as PluginService
}
describe('buildPluginList consent identity', () => {
it('projects the exact current fingerprint for an optimistic consent write', async () => {
const plugin: ValidDiscoveredPlugin = {
pluginKey: 'orca-samples.demo',
rootDir: join(tmpdir(), 'plugins', 'demo'),
manifest,
consentFingerprint: 'sha256-current',
contentHash: null,
isDev: true
}
expect((await buildPluginList(serviceWith(plugin), emptyPluginLockfile()))[0]).toMatchObject({
pluginKey: plugin.pluginKey,
consentFingerprint: 'sha256-current',
status: 'pending'
})
})
it('projects supervised backoff as restarting instead of running', async () => {
const plugin: ValidDiscoveredPlugin = {
pluginKey: 'orca-samples.demo',
rootDir: join(tmpdir(), 'plugins', 'demo'),
manifest,
consentFingerprint: 'sha256-current',
contentHash: null,
isDev: true
}
expect(
(
await buildPluginList(
serviceWith(plugin, {
activation: 'approved',
worker: { state: 'restarting', restarts: 2 }
}),
emptyPluginLockfile()
)
)[0]
).toMatchObject({ status: 'restarting', restarts: 2 })
})
it('does not attribute a shadowing dev plugin to the installed source', async () => {
const plugin: ValidDiscoveredPlugin = {
pluginKey: 'orca-samples.demo',
rootDir: join(tmpdir(), 'development', 'demo'),
manifest,
consentFingerprint: 'sha256-current',
contentHash: null,
isDev: true
}
const lock = {
version: 1 as const,
plugins: {
[plugin.pluginKey]: {
pluginKey: plugin.pluginKey,
version: '1.0.0',
source: { kind: 'git' as const, url: 'https://example.com/demo.git', ref: 'v1' },
resolvedCommit: 'a'.repeat(40),
contentHash: 'b'.repeat(64),
consentFingerprint: 'sha256-installed',
installedAt: 1
}
}
}
expect((await buildPluginList(serviceWith(plugin), lock))[0]).not.toHaveProperty('source')
})
it('does not expose an invalid development plugin absolute path as identity', async () => {
const invalid: InvalidDiscoveredPlugin = {
rootDir: join(tmpdir(), 'private', 'secret-plugin-path'),
error: 'missing orca-plugin.json',
isDev: true
}
const service = {
options: { getPluginConsents: () => ({}), getDisabledPlugins: () => [] },
getDiscovered: () => [invalid]
} as unknown as PluginService
const projected = (await buildPluginList(service, emptyPluginLockfile()))[0]!
expect(projected.pluginKey).toBe('invalid-development-plugin-1')
expect(projected.name).toBe('invalid-development-plugin-1')
expect(JSON.stringify(projected)).not.toContain(invalid.rootDir)
})
it('projects exact VM lifecycle commands for instructional consent', async () => {
const recipeManifest = pluginManifestSchema.parse({
...manifest,
contributes: { vmRecipes: [{ path: 'recipes/cloud.json' }] }
})
const plugin: ValidDiscoveredPlugin = {
pluginKey: 'orca-samples.demo',
rootDir: join(tmpdir(), 'plugins', 'demo'),
manifest: recipeManifest,
consentFingerprint: 'sha256-current',
consentContentHash: 'a'.repeat(64),
contentHash: null,
isDev: true
}
expect(
(
await buildPluginList(
serviceWith(plugin, {
vmRecipes: [
{
pluginKey: plugin.pluginKey,
recipe: {
id: 'cloud',
name: 'Cloud',
create: './create.sh',
destroyDisabled: true
}
}
]
}),
emptyPluginLockfile()
)
)[0]?.vmRecipes
).toEqual([
{
id: 'cloud',
name: 'Cloud',
commands: [
{ phase: 'create', command: './create.sh' },
{ phase: 'destroy', command: 'none' }
]
}
])
})
it('projects command handlers and normalized keybindings for consent and dispatch', async () => {
const commandManifest = pluginManifestSchema.parse({
...manifest,
contributes: {
commands: [{ id: 'tasks', title: 'Open Tasks', context: 'worktree', action: 'view.tasks' }],
keybindings: [{ command: 'tasks', key: 'mod+alt+t' }]
}
})
const plugin: ValidDiscoveredPlugin = {
pluginKey: 'orca-samples.demo',
rootDir: join(tmpdir(), 'plugins', 'demo'),
manifest: commandManifest,
consentFingerprint: 'sha256-current',
consentContentHash: 'a'.repeat(64),
contentHash: null,
isDev: true
}
expect(
(
await buildPluginList(
serviceWith(plugin, {
commands: [
{
pluginKey: plugin.pluginKey,
id: 'tasks',
title: 'Open Tasks',
context: 'worktree',
handler: { type: 'built-in', action: 'view.tasks' },
keybindings: [{ key: 'Mod+Alt+T', when: 'worktree' }]
}
]
}),
emptyPluginLockfile()
)
)[0]?.commands
).toEqual([
{
id: 'tasks',
title: 'Open Tasks',
context: 'worktree',
handler: { type: 'built-in', action: 'view.tasks' },
keybindings: [{ key: 'Mod+Alt+T', when: 'worktree' }]
}
])
})
})
+231
View File
@@ -0,0 +1,231 @@
import {
PLUGIN_CAPABILITY_DESCRIPTIONS,
type PluginCapabilityKind
} from '../../shared/plugins/plugin-capabilities'
import { needsReconsent } from '../../shared/plugins/plugin-consent-state'
import { pluginPanelTabKey } from '../../shared/plugins/plugin-manifest'
import type { PluginLockfile } from '../../shared/plugins/plugin-install-lockfile'
import { isInvalidDiscoveredPlugin } from './plugin-discovery'
import type { PluginService } from './plugin-service'
import { listPluginVmRecipeCommands } from '../../shared/plugins/plugin-vm-recipe-artifact'
import type { PluginCommandAliasActionId } from '../../shared/plugins/plugin-command-actions'
import {
isOfficialMarketplaceGitSource,
isOfficialOrganizationGitSource,
isOfficialPluginIdentity
} from '../../shared/plugins/plugin-marketplace'
import { mapWithConcurrency } from '../../shared/map-with-concurrency'
const PLUGIN_LIST_PROJECTION_CONCURRENCY = 4
/**
* Wire projection of installed plugins for the renderer and serve RPC.
* `invalid` = unreadable/failed manifest; `pending` = awaiting (re-)consent;
* `idle` = enabled with no worker running (lazy); `restarting` = waiting for
* supervised backoff; `errored` = crashed past the budget or failed to activate.
*/
export type PluginListPanelEntry = {
id: string
title: string
icon?: string
tabKey: `plugin:${string}`
}
export type PluginListStatus =
| 'running'
| 'restarting'
| 'idle'
| 'pending'
| 'disabled'
| 'errored'
| 'invalid'
export type PluginListEntry = {
pluginKey: string
/** Opaque identity of the exact capabilities and worker tier shown for review. */
consentFingerprint: string | null
name: string
version: string
publisher: string
description?: string
status: PluginListStatus
needsReconsent: boolean
error?: string
isDev: boolean
official: boolean
bundled: boolean
capabilities: { kind: PluginCapabilityKind; description: string }[]
panels: PluginListPanelEntry[]
commands: {
id: string
title: string
context: 'global' | 'worktree'
handler: { type: 'built-in'; action: PluginCommandAliasActionId } | { type: 'worker' }
keybindings: { key: string; when: 'global' | 'worktree' }[]
}[]
hasWorker: boolean
vmRecipes: {
id: string
name: string
description?: string
commands: { phase: 'create' | 'suspend' | 'resume' | 'destroy'; command: string }[]
}[]
restarts: number
blockedByKillList?: { reason: string; advisoryUrl?: string }
source?: {
kind: 'local-path' | 'git' | 'marketplace' | 'bundled'
reference: string
resolvedCommit: string | null
contentHash: string
marketplace?: { reference: string; resolvedCommit: string }
}
}
export async function buildPluginList(
service: PluginService,
lock: PluginLockfile
): Promise<PluginListEntry[]> {
const consents = {
pluginConsents: service.options.getPluginConsents(),
disabledPlugins: service.options.getDisabledPlugins()
}
return mapWithConcurrency(
service.getDiscovered(),
PLUGIN_LIST_PROJECTION_CONCURRENCY,
async (plugin, index): Promise<PluginListEntry> => {
if (isInvalidDiscoveredPlugin(plugin)) {
// Why: invalid dev paths can contain private absolute desktop paths;
// never project those as identity over desktop/serve transports.
const fallbackKey = plugin.pluginKey ?? `invalid-development-plugin-${index + 1}`
return {
pluginKey: fallbackKey,
consentFingerprint: null,
name: fallbackKey,
version: '0.0.0',
publisher: '',
status: 'invalid' as const,
needsReconsent: false,
error: plugin.error,
isDev: plugin.isDev,
official: false,
bundled: false,
capabilities: [],
panels: [],
commands: [],
hasWorker: false,
vmRecipes: [],
restarts: 0
}
}
const activation = service.activationState(plugin)
const worker = service.workerState(plugin.pluginKey)
const activationError = service.activationError(plugin.pluginKey)
const killListEntry = service.options.getPluginKillListEntry?.(plugin.pluginKey) ?? null
let status: PluginListStatus
if (activation === 'disabled') {
status = 'disabled'
} else if (activation === 'pending') {
status = 'pending'
} else if (worker.state === 'errored' || activationError) {
status = 'errored'
} else if (worker.state === 'restarting') {
status = 'restarting'
} else {
status = worker.state === 'running' ? 'running' : 'idle'
}
const candidateLockEntry = lock.plugins[plugin.pluginKey]
// Why: never show provenance for bytes other than the current executable
// identity. Dev overrides execute outside the immutable installed tree and
// must never inherit the shadowed install's pinned-source attribution.
const lockEntry =
candidateLockEntry &&
!plugin.isDev &&
plugin.contentHash !== null &&
candidateLockEntry.contentHash === plugin.contentHash
? candidateLockEntry
: undefined
const bundled = lockEntry?.source.kind === 'bundled'
const official =
bundled ||
(lockEntry?.source.kind === 'marketplace' &&
isOfficialPluginIdentity(plugin.pluginKey) &&
isOfficialMarketplaceGitSource(lockEntry.source.marketplace.url) &&
isOfficialOrganizationGitSource(lockEntry.source.plugin.url))
return {
pluginKey: plugin.pluginKey,
consentFingerprint: plugin.consentFingerprint,
name: plugin.manifest.name,
version: plugin.manifest.version,
publisher: plugin.manifest.publisher,
...(plugin.manifest.description ? { description: plugin.manifest.description } : {}),
status,
needsReconsent: needsReconsent(plugin.pluginKey, plugin.consentFingerprint, consents),
...(status === 'errored'
? { error: activationError ?? 'plugin worker crashed repeatedly' }
: {}),
isDev: plugin.isDev,
official,
bundled,
capabilities: plugin.manifest.capabilities.map((capability) => ({
kind: capability.kind,
description: PLUGIN_CAPABILITY_DESCRIPTIONS[capability.kind]
})),
panels: plugin.manifest.contributes.panels.map((panel) => ({
id: panel.id,
title: panel.title,
...(panel.icon ? { icon: panel.icon } : {}),
tabKey: pluginPanelTabKey(plugin.pluginKey, panel.id)
})),
commands: service.contentPacks.commands.preview(plugin.pluginKey).map((command) => ({
id: command.id,
title: command.title,
context: command.context,
handler: command.handler,
keybindings: command.keybindings
})),
hasWorker: Boolean(plugin.manifest.main),
vmRecipes: service.contentPacks.vmRecipes.preview(plugin.pluginKey).map(({ recipe }) => ({
id: recipe.id,
name: recipe.name,
...(recipe.description ? { description: recipe.description } : {}),
commands: listPluginVmRecipeCommands(recipe)
})),
restarts: worker.restarts,
...(killListEntry
? {
blockedByKillList: {
reason: killListEntry.reason,
...(killListEntry.advisoryUrl ? { advisoryUrl: killListEntry.advisoryUrl } : {})
}
}
: {}),
...(lockEntry
? {
source: {
kind: lockEntry.source.kind,
reference:
lockEntry.source.kind === 'local-path'
? lockEntry.source.path
: lockEntry.source.kind === 'git'
? lockEntry.source.url
: lockEntry.source.kind === 'marketplace'
? lockEntry.source.plugin.url
: `bundled:${lockEntry.source.bundleId}`,
resolvedCommit: lockEntry.resolvedCommit,
contentHash: lockEntry.contentHash,
...(lockEntry.source.kind === 'marketplace'
? {
marketplace: {
reference: lockEntry.source.marketplace.url,
resolvedCommit: lockEntry.source.marketplace.resolvedCommit
}
}
: {})
}
}
: {})
}
}
)
}
+20
View File
@@ -0,0 +1,20 @@
export type PluginLogLine = { ts: number; level: 'info' | 'warn' | 'error'; line: string }
const LOG_RING_LIMIT = 200
export class PluginLogBuffer {
private readonly logs = new Map<string, PluginLogLine[]>()
get(pluginKey: string): PluginLogLine[] {
return this.logs.get(pluginKey) ?? []
}
append(pluginKey: string, level: PluginLogLine['level'], line: string): void {
const ring = this.logs.get(pluginKey) ?? []
ring.push({ ts: Date.now(), level, line })
if (ring.length > LOG_RING_LIMIT) {
ring.splice(0, ring.length - LOG_RING_LIMIT)
}
this.logs.set(pluginKey, ring)
}
}
+22
View File
@@ -0,0 +1,22 @@
import { createReadStream } from 'node:fs'
import { join } from 'node:path'
import { PLUGIN_MANIFEST_FILENAME } from '../../shared/plugins/plugin-manifest'
/** A manifest is startup metadata, not an artifact payload. Bounding it keeps
* discovery and install preview from allocating an attacker-sized JSON file. */
export const PLUGIN_MANIFEST_MAX_BYTES = 1024 * 1024
export async function readPluginManifestText(rootDir: string): Promise<string> {
const chunks: Buffer[] = []
let totalBytes = 0
const stream = createReadStream(join(rootDir, PLUGIN_MANIFEST_FILENAME))
for await (const chunk of stream) {
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
totalBytes += bytes.byteLength
if (totalBytes > PLUGIN_MANIFEST_MAX_BYTES) {
throw new Error(`${PLUGIN_MANIFEST_FILENAME} exceeds ${PLUGIN_MANIFEST_MAX_BYTES} bytes`)
}
chunks.push(bytes)
}
return Buffer.concat(chunks, totalBytes).toString('utf8')
}
@@ -0,0 +1,3 @@
export function pluginMarketplaceErrorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error)
}
@@ -0,0 +1,63 @@
import { createReadStream } from 'node:fs'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import {
PLUGIN_MARKETPLACE_FILENAME,
pluginMarketplaceSchema,
type PluginMarketplace
} from '../../shared/plugins/plugin-marketplace'
import { checkoutPluginGitSource } from './plugin-git-repository'
import type { PluginMarketplaceRegisteredSource } from './plugin-marketplace-store'
const MARKETPLACE_INDEX_MAX_BYTES = 16 * 1024 * 1024
export type PluginMarketplaceFetchResult = {
marketplaceCommit: string
marketplace: PluginMarketplace
}
/** Fetches a marketplace through system Git so private repositories use the
* same SSH agent and credential helpers as every other Orca Git operation. */
export async function fetchPluginMarketplace(
source: PluginMarketplaceRegisteredSource
): Promise<PluginMarketplaceFetchResult> {
const stagingDirectory = await mkdtemp(join(tmpdir(), 'orca-plugin-marketplace-'))
try {
const marketplaceCommit = await checkoutPluginGitSource({
url: source.source.url,
ref: source.source.ref,
destination: stagingDirectory,
workingDirectory: tmpdir()
})
const marketplace = await readPluginMarketplaceIndex(stagingDirectory)
return { marketplaceCommit, marketplace }
} finally {
await rm(stagingDirectory, { recursive: true, force: true })
}
}
export async function readPluginMarketplaceIndex(
rootDirectory: string
): Promise<PluginMarketplace> {
const path = join(rootDirectory, PLUGIN_MARKETPLACE_FILENAME)
const chunks: Buffer[] = []
let totalBytes = 0
for await (const chunk of createReadStream(path)) {
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
totalBytes += bytes.byteLength
if (totalBytes > MARKETPLACE_INDEX_MAX_BYTES) {
throw new Error(`${PLUGIN_MARKETPLACE_FILENAME} exceeds its size limit`)
}
chunks.push(bytes)
}
try {
return pluginMarketplaceSchema.parse(
JSON.parse(Buffer.concat(chunks, totalBytes).toString('utf8'))
)
} catch (error) {
throw new Error(
`invalid ${PLUGIN_MARKETPLACE_FILENAME}: ${error instanceof Error ? error.message : String(error)}`
)
}
}
@@ -0,0 +1,198 @@
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { PluginMarketplace } from '../../shared/plugins/plugin-marketplace'
import { readPluginLockfile } from './plugin-install'
import { PluginMarketplaceInstaller } from './plugin-marketplace-installer'
import { PluginMarketplaceService } from './plugin-marketplace-service'
const git = vi.hoisted(() => ({
checkout: vi.fn(),
version: '1.0.0',
publisher: 'community',
id: 'notes',
commit: 'a'.repeat(40),
payload: 'first'
}))
vi.mock('./plugin-git-repository', () => ({
checkoutPluginGitSource: git.checkout
}))
const roots: string[] = []
async function tempRoot(): Promise<string> {
const root = await mkdtemp(join(tmpdir(), 'orca-marketplace-installer-'))
roots.push(root)
return root
}
function marketplace(): PluginMarketplace {
return {
name: 'Community',
owner: 'community',
plugins: [
{
id: 'community.notes',
source: {
kind: 'git',
url: 'https://github.com/community/notes.git',
ref: 'stable'
},
categories: ['productivity']
}
]
}
}
async function writeCurrentPlugin(destination: string): Promise<void> {
await mkdir(destination, { recursive: true })
await writeFile(
join(destination, 'orca-plugin.json'),
JSON.stringify({
manifestVersion: 1,
id: git.id,
publisher: git.publisher,
name: 'Notes',
version: git.version,
engines: { orca: '>=1.0.0' },
pluginApi: 1,
capabilities: []
})
)
await writeFile(join(destination, 'payload.txt'), git.payload)
}
async function setup(): Promise<{
root: string
marketplace: PluginMarketplaceService
installer: PluginMarketplaceInstaller
sourceId: string
}> {
const root = await tempRoot()
const service = new PluginMarketplaceService({
pluginsDataDir: join(root, 'plugins-data'),
fetcher: async () => ({ marketplaceCommit: 'f'.repeat(40), marketplace: marketplace() })
})
const added = await service.addSource({
kind: 'git',
url: 'https://github.com/community/plugins.git',
ref: 'main'
})
return {
root,
marketplace: service,
installer: new PluginMarketplaceInstaller({
marketplace: service,
userDataPath: root,
hostVersion: '1.4.0'
}),
sourceId: added.id
}
}
beforeEach(() => {
git.version = '1.0.0'
git.publisher = 'community'
git.id = 'notes'
git.commit = 'a'.repeat(40)
git.payload = 'first'
git.checkout.mockReset()
git.checkout.mockImplementation(async ({ destination }: { destination: string }) => {
await writeCurrentPlugin(destination)
return git.commit
})
})
afterEach(async () => {
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })))
})
describe('PluginMarketplaceInstaller', () => {
it('previews exact validated bytes and records marketplace provenance on install', async () => {
const { root, installer, sourceId } = await setup()
const preview = await installer.preview(sourceId, 'community.notes')
expect(preview).toMatchObject({
pluginKey: 'community.notes',
resolvedCommit: 'a'.repeat(40),
marketplaceCommit: 'f'.repeat(40),
manifest: { version: '1.0.0' }
})
const result = await installer.install(preview)
if (!result.ok) {
throw new Error(result.error)
}
expect(result).toMatchObject({ ok: true, resolvedCommit: 'a'.repeat(40) })
const lock = await readPluginLockfile(join(root, 'plugins'))
expect(lock.plugins['community.notes']?.source).toEqual({
kind: 'marketplace',
marketplace: {
url: 'https://github.com/community/plugins.git',
ref: 'main',
resolvedCommit: 'f'.repeat(40)
},
plugin: {
url: 'https://github.com/community/notes.git',
ref: 'stable'
}
})
})
it('requires a fresh review when the plugin ref moves after preview', async () => {
const { root, installer, sourceId } = await setup()
const preview = await installer.preview(sourceId, 'community.notes')
git.commit = 'b'.repeat(40)
git.version = '2.0.0'
await expect(installer.install(preview)).resolves.toEqual({
ok: false,
error: 'plugin source changed after preview; review the update again'
})
await expect(readFile(join(root, 'plugins', 'plugins.lock.json'))).rejects.toMatchObject({
code: 'ENOENT'
})
})
it('rejects a source whose manifest identity differs from its listing', async () => {
const { installer, sourceId } = await setup()
git.publisher = 'attacker'
await expect(installer.preview(sourceId, 'community.notes')).rejects.toThrow(
'attacker.notes does not match marketplace listing community.notes'
)
})
it('updates from recorded marketplace provenance and rolls back one immutable version', async () => {
const { root, installer, sourceId } = await setup()
const firstPreview = await installer.preview(sourceId, 'community.notes')
const firstInstall = await installer.install(firstPreview)
expect(firstInstall.ok).toBe(true)
if (!firstInstall.ok) {
return
}
git.commit = 'b'.repeat(40)
git.version = '2.0.0'
git.payload = 'second'
const updatePreview = await installer.previewInstalledUpdate('community.notes')
expect(updatePreview).toMatchObject({ resolvedCommit: 'b'.repeat(40) })
await expect(installer.install(updatePreview)).resolves.toMatchObject({
ok: true,
version: '2.0.0'
})
await expect(installer.rollback('community.notes')).resolves.toMatchObject({
ok: true,
version: '1.0.0',
contentHash: firstInstall.contentHash
})
const lock = await readPluginLockfile(join(root, 'plugins'))
expect(lock.plugins['community.notes']).toMatchObject({
version: '1.0.0',
resolvedCommit: 'a'.repeat(40)
})
})
})
@@ -0,0 +1,164 @@
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import type { PluginManifest } from '../../shared/plugins/plugin-manifest'
import { getUserPluginsDir } from './plugin-discovery'
import { checkoutPluginGitSource } from './plugin-git-repository'
import {
installPluginFromMarketplace,
readPluginLockfile,
rollbackInstalledPlugin,
type PluginInstallResult
} from './plugin-install'
import { inspectPluginInstallTree } from './plugin-install-staging'
import type {
PluginMarketplaceListing,
PluginMarketplaceService
} from './plugin-marketplace-service'
import { marketplaceSourceId } from './plugin-marketplace-store'
export type PluginMarketplaceInstallPreview = {
marketplaceSourceId: string
marketplaceName: string
marketplaceOwner: string
marketplaceCommit: string
pluginKey: string
source: PluginMarketplaceListing['source']
resolvedCommit: string
contentHash: string
consentFingerprint: string
manifest: PluginManifest
official: boolean
bundled: boolean
blockedByKillList?: { reason: string; advisoryUrl?: string }
}
export type PluginMarketplacePreviewIdentity = Pick<
PluginMarketplaceInstallPreview,
'marketplaceSourceId' | 'marketplaceCommit' | 'pluginKey' | 'resolvedCommit'
>
export class PluginMarketplaceInstaller {
private readonly marketplace: PluginMarketplaceService
private readonly userDataPath: string
private readonly hostVersion: string
private readonly blockedPluginReason: (pluginKey: string) => string | null
constructor(options: {
marketplace: PluginMarketplaceService
userDataPath: string
hostVersion: string
blockedPluginReason?: (pluginKey: string) => string | null
}) {
this.marketplace = options.marketplace
this.userDataPath = options.userDataPath
this.hostVersion = options.hostVersion
this.blockedPluginReason = options.blockedPluginReason ?? (() => null)
}
async preview(
marketplaceSourceId: string,
pluginKey: string
): Promise<PluginMarketplaceInstallPreview> {
const listing = await this.requireListing(marketplaceSourceId, pluginKey)
const stagingDirectory = await mkdtemp(join(tmpdir(), 'orca-plugin-marketplace-preview-'))
try {
const resolvedCommit = await checkoutPluginGitSource({
url: listing.source.url,
ref: listing.source.ref,
destination: stagingDirectory,
workingDirectory: tmpdir()
})
const inspection = await inspectPluginInstallTree({
rootDir: stagingDirectory,
hostVersion: this.hostVersion,
expectedPluginKey: pluginKey
})
if (!inspection.ok) {
throw new Error(inspection.error)
}
return {
marketplaceSourceId,
marketplaceName: listing.marketplaceName,
marketplaceOwner: listing.marketplaceOwner,
marketplaceCommit: listing.marketplaceCommit,
pluginKey,
source: listing.source,
resolvedCommit,
contentHash: inspection.contentHash,
consentFingerprint: inspection.consentFingerprint,
manifest: inspection.manifest,
official: listing.official,
bundled: listing.bundled,
...(listing.blockedByKillList ? { blockedByKillList: listing.blockedByKillList } : {})
}
} finally {
await rm(stagingDirectory, { recursive: true, force: true })
}
}
async install(preview: PluginMarketplacePreviewIdentity): Promise<PluginInstallResult> {
const listing = await this.requireListing(preview.marketplaceSourceId, preview.pluginKey)
const blockedReason =
listing.blockedByKillList?.reason ?? this.blockedPluginReason(preview.pluginKey)
if (blockedReason) {
return { ok: false, error: `plugin is blocked by Orca's safety list: ${blockedReason}` }
}
if (listing.marketplaceCommit !== preview.marketplaceCommit) {
return { ok: false, error: 'marketplace changed after preview; review the plugin again' }
}
const sourceState = (await this.marketplace.listSources()).find(
(source) => source.id === preview.marketplaceSourceId
)
if (!sourceState) {
return { ok: false, error: 'marketplace source is no longer configured' }
}
return installPluginFromMarketplace({
pluginsDir: getUserPluginsDir(this.userDataPath),
hostVersion: this.hostVersion,
expectedPluginKey: preview.pluginKey,
expectedResolvedCommit: preview.resolvedCommit,
marketplace: {
url: sourceState.source.url,
ref: sourceState.source.ref,
resolvedCommit: preview.marketplaceCommit
},
plugin: { url: listing.source.url, ref: listing.source.ref },
blockedPluginReason: this.blockedPluginReason
})
}
async previewInstalledUpdate(pluginKey: string): Promise<PluginMarketplaceInstallPreview> {
const lock = await readPluginLockfile(getUserPluginsDir(this.userDataPath))
const entry = lock.plugins[pluginKey]
if (!entry || entry.source.kind !== 'marketplace') {
throw new Error(`plugin ${pluginKey} was not installed from a marketplace`)
}
const sourceId = marketplaceSourceId({
kind: 'git',
url: entry.source.marketplace.url,
ref: entry.source.marketplace.ref
})
return this.preview(sourceId, pluginKey)
}
async rollback(pluginKey: string): Promise<PluginInstallResult> {
return rollbackInstalledPlugin({
pluginsDir: getUserPluginsDir(this.userDataPath),
pluginKey,
hostVersion: this.hostVersion,
blockedPluginReason: this.blockedPluginReason
})
}
private async requireListing(
marketplaceSourceId: string,
pluginKey: string
): Promise<PluginMarketplaceListing> {
const listing = await this.marketplace.findPlugin(marketplaceSourceId, pluginKey)
if (!listing) {
throw new Error(`plugin ${pluginKey} is not listed by marketplace ${marketplaceSourceId}`)
}
return listing
}
}
@@ -0,0 +1,33 @@
import type {
PluginMarketplaceEntry,
PluginMarketplaceGitSource
} from '../../shared/plugins/plugin-marketplace'
export type PluginMarketplaceSourceState = {
id: string
source: PluginMarketplaceGitSource
addedAt: number
marketplace: {
name: string
owner: string
resolvedCommit: string
fetchedAt: number
} | null
stale: boolean
official: boolean
error?: string
}
export type PluginMarketplaceListing = {
marketplaceSourceId: string
marketplaceName: string
marketplaceOwner: string
marketplaceCommit: string
pluginKey: string
source: PluginMarketplaceEntry['source']
description?: string
categories: string[]
official: boolean
bundled: boolean
blockedByKillList?: { reason: string; advisoryUrl?: string }
}
@@ -0,0 +1,27 @@
import {
OFFICIAL_MARKETPLACE_OWNER,
isOfficialMarketplaceGitSource,
isOfficialOrganizationGitSource,
isReservedPluginIdentity
} from '../../shared/plugins/plugin-marketplace'
import type { PluginMarketplaceFetchResult } from './plugin-marketplace-fetch'
import type { PluginMarketplaceRegisteredSource } from './plugin-marketplace-store'
export function validateMarketplaceProvenance(
source: PluginMarketplaceRegisteredSource,
fetched: PluginMarketplaceFetchResult
): void {
if (
isOfficialMarketplaceGitSource(source.source.url) &&
fetched.marketplace.owner.toLowerCase() !== OFFICIAL_MARKETPLACE_OWNER
) {
throw new Error('official marketplace metadata has an unexpected owner')
}
for (const entry of fetched.marketplace.plugins) {
if (isReservedPluginIdentity(entry.id) && !isOfficialOrganizationGitSource(entry.source.url)) {
throw new Error(
`reserved plugin identity ${entry.id} must resolve to the stablyai organization`
)
}
}
}
@@ -0,0 +1,336 @@
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import type {
PluginMarketplace,
PluginMarketplaceGitSource
} from '../../shared/plugins/plugin-marketplace'
import { OFFICIAL_MARKETPLACE_GIT_SOURCE } from '../../shared/plugins/plugin-marketplace'
import type { PluginMarketplaceFetchResult } from './plugin-marketplace-fetch'
import { PluginMarketplaceService } from './plugin-marketplace-service'
import {
marketplaceSourceId,
PLUGIN_MARKETPLACE_SOURCE_LIMIT,
PluginMarketplaceStore,
type PluginMarketplaceRegisteredSource
} from './plugin-marketplace-store'
const roots: string[] = []
async function tempRoot(): Promise<string> {
const root = await mkdtemp(join(tmpdir(), 'orca-marketplace-service-'))
roots.push(root)
return root
}
function source(url = 'https://github.com/community/plugins.git'): PluginMarketplaceGitSource {
return { kind: 'git', url, ref: 'main' }
}
function marketplace(
name = 'Community',
pluginKey = 'community.notes',
pluginUrl = 'https://github.com/community/notes.git'
): PluginMarketplace {
return {
name,
owner: name.toLowerCase(),
plugins: [
{
id: pluginKey,
source: { kind: 'git', url: pluginUrl, ref: 'v1' },
description: 'Notes for active worktrees.',
categories: ['productivity']
}
]
}
}
function fetched(value = marketplace(), commit = 'a'.repeat(40)): PluginMarketplaceFetchResult {
return { marketplaceCommit: commit, marketplace: value }
}
afterEach(async () => {
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })))
})
describe('PluginMarketplaceService', () => {
it('fetches before registration, then serves browse data from the local snapshot', async () => {
const fetcher = vi
.fn<
(registration: PluginMarketplaceRegisteredSource) => Promise<PluginMarketplaceFetchResult>
>()
.mockResolvedValue(fetched())
const service = new PluginMarketplaceService({ pluginsDataDir: await tempRoot(), fetcher })
const added = await service.addSource(source())
expect(added).toMatchObject({ marketplace: { name: 'Community' }, stale: false })
expect(fetcher).toHaveBeenCalledTimes(1)
await expect(service.listPlugins()).resolves.toEqual([
expect.objectContaining({
marketplaceSourceId: added.id,
pluginKey: 'community.notes',
official: false,
bundled: false
})
])
await service.listSources()
expect(fetcher).toHaveBeenCalledTimes(1)
})
it('keeps and labels the last valid snapshot when a refresh is offline', async () => {
const fetcher = vi
.fn<
(registration: PluginMarketplaceRegisteredSource) => Promise<PluginMarketplaceFetchResult>
>()
.mockResolvedValueOnce(fetched())
.mockRejectedValueOnce(new Error('offline'))
const service = new PluginMarketplaceService({ pluginsDataDir: await tempRoot(), fetcher })
const added = await service.addSource(source())
await expect(service.refreshSource(added.id)).resolves.toMatchObject({
marketplace: { name: 'Community', resolvedCommit: 'a'.repeat(40) },
stale: true,
error: 'offline'
})
await expect(service.listPlugins()).resolves.toEqual([
expect.objectContaining({ pluginKey: 'community.notes' })
])
})
it('atomically replaces the cache only after a valid refreshed index', async () => {
const fetcher = vi
.fn<
(registration: PluginMarketplaceRegisteredSource) => Promise<PluginMarketplaceFetchResult>
>()
.mockResolvedValueOnce(fetched())
.mockResolvedValueOnce(fetched(marketplace('Updated'), 'b'.repeat(40)))
const root = await tempRoot()
const service = new PluginMarketplaceService({ pluginsDataDir: root, fetcher })
const added = await service.addSource(source())
await expect(service.refreshSource(added.id)).resolves.toMatchObject({
marketplace: { name: 'Updated', resolvedCommit: 'b'.repeat(40) },
stale: false
})
await expect(
new PluginMarketplaceService({ pluginsDataDir: root, fetcher }).listPlugins()
).resolves.toEqual([expect.objectContaining({ marketplaceName: 'Updated' })])
})
it('does not persist a source whose first fetch fails', async () => {
const service = new PluginMarketplaceService({
pluginsDataDir: await tempRoot(),
fetcher: async () => {
throw new Error('authentication failed')
}
})
await expect(service.addSource(source())).rejects.toThrow('authentication failed')
await expect(service.listSources()).resolves.toEqual([])
})
it('rejects reserved identities outside the official organization', async () => {
const service = new PluginMarketplaceService({
pluginsDataDir: await tempRoot(),
fetcher: async () =>
fetched(
marketplace('Attack', 'community.orca-secrets', 'https://github.com/attacker/x.git')
)
})
await expect(service.addSource(source())).rejects.toThrow(
'reserved plugin identity community.orca-secrets'
)
await expect(service.listSources()).resolves.toEqual([])
})
it('derives the Official badge only from the canonical marketplace and source organization', async () => {
const officialMarketplace: PluginMarketplace = {
name: 'Orca Plugins',
owner: 'stablyai',
plugins: [
{
id: 'stablyai.orca-shortcuts',
source: {
kind: 'git',
url: 'git@github.com:stablyai/orca-shortcuts.git',
ref: 'main'
},
categories: ['keybindings']
}
]
}
const service = new PluginMarketplaceService({
pluginsDataDir: await tempRoot(),
fetcher: async () => fetched(officialMarketplace)
})
await service.addSource(source('https://github.com/stablyai/orca-plugins.git'))
await expect(service.listPlugins()).resolves.toEqual([
expect.objectContaining({ pluginKey: 'stablyai.orca-shortcuts', official: true })
])
})
it('hides listings whose contribution kind this build no longer supports', async () => {
const mixed: PluginMarketplace = {
name: 'Community',
owner: 'community',
plugins: [
{
id: 'community.midnight',
source: { kind: 'git', url: 'https://github.com/community/midnight.git', ref: 'v1' },
categories: ['themes', 'official']
},
{
id: 'community.recipes',
source: { kind: 'git', url: 'https://github.com/community/recipes.git', ref: 'v1' },
categories: ['vm-recipes']
}
]
}
const service = new PluginMarketplaceService({
pluginsDataDir: await tempRoot(),
fetcher: async () => fetched(mixed)
})
const added = await service.addSource(source())
// The theme pack is filtered out; only the supported recipe listing remains.
await expect(service.listPlugins()).resolves.toEqual([
expect.objectContaining({ pluginKey: 'community.recipes' })
])
// Preview and install resolve by key, so an unsupported pack must be
// unreachable that way too — otherwise the dead install just moves later.
await expect(service.findPlugin(added.id, 'community.midnight')).resolves.toBeNull()
await expect(service.findPlugin(added.id, 'community.recipes')).resolves.toEqual(
expect.objectContaining({ pluginKey: 'community.recipes' })
)
})
it('seeds the official marketplace once and keeps it configured across restarts', async () => {
const root = await tempRoot()
const officialMarketplace = marketplace(
'Orca Plugins',
'stablyai.orca-notes',
'https://github.com/stablyai/orca-notes.git'
)
officialMarketplace.owner = 'stablyai'
const fetcher = vi.fn(async () => fetched(officialMarketplace))
const first = new PluginMarketplaceService({ pluginsDataDir: root, fetcher })
await expect(first.seedOfficialSource()).resolves.toMatchObject({
official: true,
marketplace: { name: 'Orca Plugins' }
})
await expect(first.seedOfficialSource()).resolves.toMatchObject({ official: true })
expect(fetcher).toHaveBeenCalledTimes(1)
const restarted = new PluginMarketplaceService({ pluginsDataDir: root, fetcher })
await expect(restarted.seedOfficialSource()).resolves.toMatchObject({ official: true })
expect(fetcher).toHaveBeenCalledTimes(1)
await expect(restarted.listSources()).resolves.toHaveLength(1)
})
it('persists an offline official source for a later refresh and does not remove it', async () => {
const service = new PluginMarketplaceService({
pluginsDataDir: await tempRoot(),
fetcher: async () => {
throw new Error('offline')
}
})
const seeded = await service.seedOfficialSource()
expect(seeded).toMatchObject({ official: true, stale: true, marketplace: null })
await expect(service.removeSource(seeded.id)).rejects.toThrow('cannot be removed')
await expect(service.listSources()).resolves.toEqual([seeded])
})
it('keeps reads usable and allows retry after official seeding rejects', async () => {
const registered: PluginMarketplaceRegisteredSource = {
id: marketplaceSourceId(OFFICIAL_MARKETPLACE_GIT_SOURCE),
source: OFFICIAL_MARKETPLACE_GIT_SOURCE,
addedAt: 1
}
const officialMarketplace = marketplace(
'Orca Plugins',
'stablyai.orca-notes',
'https://github.com/stablyai/orca-notes.git'
)
officialMarketplace.owner = 'stablyai'
const listSources = vi
.fn<() => Promise<readonly PluginMarketplaceRegisteredSource[]>>()
.mockRejectedValueOnce(new Error('source store temporarily unavailable'))
.mockResolvedValue([registered])
const store = {
listSources,
readSnapshot: vi.fn().mockResolvedValue(null),
writeSnapshot: vi.fn(async ({ source: snapshotSource, ...snapshot }) => ({
schemaVersion: 1 as const,
sourceId: snapshotSource.id,
source: snapshotSource.source,
fetchedAt: 2,
...snapshot
}))
} as unknown as PluginMarketplaceStore
const service = new PluginMarketplaceService({
pluginsDataDir: await tempRoot(),
store,
fetcher: async () => fetched(officialMarketplace)
})
await expect(service.seedOfficialSource()).rejects.toThrow('temporarily unavailable')
await expect(service.listSources()).resolves.toEqual([
expect.objectContaining({ id: registered.id, official: true })
])
await expect(service.seedOfficialSource()).resolves.toMatchObject({
marketplace: { name: 'Orca Plugins' },
official: true
})
})
it('recovers the managed source after a full existing store frees a slot', async () => {
const root = await tempRoot()
const store = new PluginMarketplaceStore(root)
const registrations = await Promise.all(
Array.from({ length: PLUGIN_MARKETPLACE_SOURCE_LIMIT }, (_, index) =>
store.addSource(source(`https://example.com/community-${index}.git`), index + 1)
)
)
const officialMarketplace = marketplace(
'Orca Plugins',
'stablyai.orca-notes',
'https://github.com/stablyai/orca-notes.git'
)
officialMarketplace.owner = 'stablyai'
const service = new PluginMarketplaceService({
pluginsDataDir: root,
store,
fetcher: async () => fetched(officialMarketplace)
})
await expect(service.seedOfficialSource()).rejects.toThrow('source limit')
await expect(service.removeSource(registrations[0]!.id)).resolves.toBe(true)
const sources = await service.listSources()
expect(sources).toHaveLength(PLUGIN_MARKETPLACE_SOURCE_LIMIT)
expect(sources).toContainEqual(expect.objectContaining({ official: true }))
})
it('removes source metadata and browse listings together', async () => {
const service = new PluginMarketplaceService({
pluginsDataDir: await tempRoot(),
fetcher: async () => fetched()
})
const added = await service.addSource(source())
await expect(service.removeSource(added.id)).resolves.toBe(true)
await expect(service.listSources()).resolves.toEqual([])
await expect(service.listPlugins()).resolves.toEqual([])
})
})
@@ -0,0 +1,320 @@
import {
OFFICIAL_MARKETPLACE_OWNER,
OFFICIAL_MARKETPLACE_GIT_SOURCE,
isOfficialMarketplaceGitSource,
isOfficialOrganizationGitSource,
isOfficialPluginIdentity,
isMarketplaceListingSupported,
pluginMarketplaceGitSourceSchema,
type PluginMarketplaceEntry,
type PluginMarketplaceGitSource
} from '../../shared/plugins/plugin-marketplace'
import {
fetchPluginMarketplace,
type PluginMarketplaceFetchResult
} from './plugin-marketplace-fetch'
import {
marketplaceSourceId,
PluginMarketplaceStore,
type PluginMarketplaceCachedSnapshot,
type PluginMarketplaceRegisteredSource
} from './plugin-marketplace-store'
import type { PluginKillListEntry } from '../../shared/plugins/plugin-kill-list'
import { validateMarketplaceProvenance } from './plugin-marketplace-provenance'
import { pluginMarketplaceErrorMessage } from './plugin-marketplace-error-message'
import type {
PluginMarketplaceListing,
PluginMarketplaceSourceState
} from './plugin-marketplace-projection'
export type {
PluginMarketplaceListing,
PluginMarketplaceSourceState
} from './plugin-marketplace-projection'
type MarketplaceFetcher = (
source: PluginMarketplaceRegisteredSource
) => Promise<PluginMarketplaceFetchResult>
export class PluginMarketplaceService {
private readonly store: PluginMarketplaceStore
private readonly fetcher: MarketplaceFetcher
private readonly getKillListEntry: (pluginKey: string) => PluginKillListEntry | null
private readonly refreshChains = new Map<string, Promise<PluginMarketplaceSourceState>>()
private readonly sourceErrors = new Map<string, string>()
private officialSeedPromise: Promise<PluginMarketplaceSourceState> | null = null
private officialSeedRequested = false
constructor(options: {
pluginsDataDir: string
fetcher?: MarketplaceFetcher
store?: PluginMarketplaceStore
getKillListEntry?: (pluginKey: string) => PluginKillListEntry | null
}) {
this.store = options.store ?? new PluginMarketplaceStore(options.pluginsDataDir)
this.fetcher = options.fetcher ?? fetchPluginMarketplace
this.getKillListEntry = options.getKillListEntry ?? (() => null)
}
async listSources(): Promise<PluginMarketplaceSourceState[]> {
await this.waitForOfficialSeed()
const sources = await this.store.listSources()
return Promise.all(
sources.map(async (source) => {
try {
const error = this.sourceErrors.get(source.id)
return this.stateFromSnapshot(
source,
await this.store.readSnapshot(source.id),
Boolean(error),
error
)
} catch (error) {
return this.stateFromSnapshot(source, null, true, pluginMarketplaceErrorMessage(error))
}
})
)
}
async addSource(source: PluginMarketplaceGitSource): Promise<PluginMarketplaceSourceState> {
const parsedSource = pluginMarketplaceGitSourceSchema.parse(source)
const sourceId = marketplaceSourceId(parsedSource)
const existing = (await this.store.listSources()).find((candidate) => candidate.id === sourceId)
const candidate: PluginMarketplaceRegisteredSource = existing ?? {
id: sourceId,
source: parsedSource,
addedAt: Date.now()
}
const fetched = await this.fetchAndValidate(candidate)
const registered = existing ?? (await this.store.addSource(parsedSource, candidate.addedAt))
try {
const snapshot = await this.store.writeSnapshot({ source: registered, ...fetched })
this.sourceErrors.delete(registered.id)
return this.stateFromSnapshot(registered, snapshot, false)
} catch (error) {
if (!existing) {
await this.store.removeSource(registered.id).catch(() => undefined)
}
throw error
}
}
async removeSource(sourceId: string): Promise<boolean> {
const source = (await this.store.listSources()).find((candidate) => candidate.id === sourceId)
if (source && isOfficialMarketplaceGitSource(source.source.url)) {
throw new Error('the official marketplace is managed by Orca and cannot be removed')
}
const removed = await this.store.removeSource(sourceId)
if (removed) {
this.sourceErrors.delete(sourceId)
if (this.officialSeedRequested) {
// Why: an existing profile may already occupy every source slot. Once
// the user frees one, recover the managed source without a restart.
await this.seedOfficialSource().catch(() => undefined)
}
}
return removed
}
seedOfficialSource(): Promise<PluginMarketplaceSourceState> {
this.officialSeedRequested = true
if (!this.officialSeedPromise) {
const seed = this.performOfficialSeed()
this.officialSeedPromise = seed
void seed.catch(() => {
if (this.officialSeedPromise === seed) {
// Why: a transient store failure or full source list must not poison
// every marketplace read or prevent a later recovery attempt.
this.officialSeedPromise = null
}
})
}
return this.officialSeedPromise
}
async refreshSource(sourceId: string): Promise<PluginMarketplaceSourceState> {
const previous = this.refreshChains.get(sourceId) ?? Promise.resolve(null)
const refresh = previous.catch(() => null).then(() => this.performRefresh(sourceId))
this.refreshChains.set(sourceId, refresh)
try {
return await refresh
} finally {
if (this.refreshChains.get(sourceId) === refresh) {
this.refreshChains.delete(sourceId)
}
}
}
async refreshAll(): Promise<PluginMarketplaceSourceState[]> {
await this.waitForOfficialSeed()
const sources = await this.store.listSources()
return Promise.all(sources.map((source) => this.refreshSource(source.id)))
}
async listPlugins(): Promise<PluginMarketplaceListing[]> {
await this.waitForOfficialSeed()
const states = await this.listSnapshots()
return states
.flatMap(({ source, snapshot }) =>
snapshot.marketplace.plugins
// Why: hide packs whose contribution kind this build no longer
// supports (themes/icons/skills) so users never reach a dead install.
.filter((entry) => isMarketplaceListingSupported(entry.categories))
.map((entry) => this.listingFromEntry(source, snapshot, entry))
)
.sort((left, right) =>
`${left.pluginKey}\0${left.marketplaceSourceId}`.localeCompare(
`${right.pluginKey}\0${right.marketplaceSourceId}`
)
)
}
async findPlugin(
marketplaceSourceId: string,
pluginKey: string
): Promise<PluginMarketplaceListing | null> {
const source = (await this.store.listSources()).find(
(candidate) => candidate.id === marketplaceSourceId
)
if (!source) {
return null
}
const snapshot = await this.store.readSnapshot(source.id)
// Why: preview and install resolve listings through here, so an unsupported
// pack must be unreachable by key too — hiding only the catalog card would
// move the dead install one click later instead of removing it.
const entry = snapshot?.marketplace.plugins.find(
(plugin) => plugin.id === pluginKey && isMarketplaceListingSupported(plugin.categories)
)
return snapshot && entry ? this.listingFromEntry(source, snapshot, entry) : null
}
private async performRefresh(sourceId: string): Promise<PluginMarketplaceSourceState> {
const source = (await this.store.listSources()).find((candidate) => candidate.id === sourceId)
if (!source) {
throw new Error(`unknown marketplace source: ${sourceId}`)
}
try {
const fetched = await this.fetchAndValidate(source)
const snapshot = await this.store.writeSnapshot({ source, ...fetched })
this.sourceErrors.delete(source.id)
return this.stateFromSnapshot(source, snapshot, false)
} catch (error) {
const cached = await this.store.readSnapshot(source.id).catch(() => null)
if (!cached) {
throw error
}
const message = pluginMarketplaceErrorMessage(error)
this.sourceErrors.set(source.id, message)
return this.stateFromSnapshot(source, cached, true, message)
}
}
private async performOfficialSeed(): Promise<PluginMarketplaceSourceState> {
const sources = await this.store.listSources()
const existing = sources.find((source) => isOfficialMarketplaceGitSource(source.source.url))
const source =
existing ?? (await this.store.addSource(OFFICIAL_MARKETPLACE_GIT_SOURCE, Date.now()))
const snapshot = await this.store.readSnapshot(source.id).catch(() => null)
if (snapshot) {
return this.stateFromSnapshot(source, snapshot, false)
}
try {
return await this.performRefresh(source.id)
} catch (error) {
// Why: the official source remains configured offline so a later manual
// or startup refresh can recover without asking the user for its URL.
const message = pluginMarketplaceErrorMessage(error)
this.sourceErrors.set(source.id, message)
return this.stateFromSnapshot(source, null, true, message)
}
}
private async waitForOfficialSeed(): Promise<void> {
await this.officialSeedPromise?.catch(() => undefined)
}
private async fetchAndValidate(
source: PluginMarketplaceRegisteredSource
): Promise<PluginMarketplaceFetchResult> {
const fetched = await this.fetcher(source)
validateMarketplaceProvenance(source, fetched)
return fetched
}
private async listSnapshots(): Promise<
{ source: PluginMarketplaceRegisteredSource; snapshot: PluginMarketplaceCachedSnapshot }[]
> {
const sources = await this.store.listSources()
const snapshots = await Promise.all(
sources.map(async (source) => ({
source,
snapshot: await this.store.readSnapshot(source.id)
}))
)
return snapshots.filter(
(
candidate
): candidate is {
source: PluginMarketplaceRegisteredSource
snapshot: PluginMarketplaceCachedSnapshot
} => candidate.snapshot !== null
)
}
private listingFromEntry(
source: PluginMarketplaceRegisteredSource,
snapshot: PluginMarketplaceCachedSnapshot,
entry: PluginMarketplaceEntry
): PluginMarketplaceListing {
const official =
isOfficialMarketplaceGitSource(source.source.url) &&
snapshot.marketplace.owner.toLowerCase() === OFFICIAL_MARKETPLACE_OWNER &&
isOfficialPluginIdentity(entry.id) &&
isOfficialOrganizationGitSource(entry.source.url)
const blocked = this.getKillListEntry(entry.id)
return {
marketplaceSourceId: source.id,
marketplaceName: snapshot.marketplace.name,
marketplaceOwner: snapshot.marketplace.owner,
marketplaceCommit: snapshot.marketplaceCommit,
pluginKey: entry.id,
source: entry.source,
...(entry.description ? { description: entry.description } : {}),
categories: entry.categories,
official,
bundled: false,
...(blocked
? {
blockedByKillList: {
reason: blocked.reason,
...(blocked.advisoryUrl ? { advisoryUrl: blocked.advisoryUrl } : {})
}
}
: {})
}
}
private stateFromSnapshot(
source: PluginMarketplaceRegisteredSource,
snapshot: PluginMarketplaceCachedSnapshot | null,
stale: boolean,
error?: string
): PluginMarketplaceSourceState {
return {
id: source.id,
source: source.source,
addedAt: source.addedAt,
marketplace: snapshot
? {
name: snapshot.marketplace.name,
owner: snapshot.marketplace.owner,
resolvedCommit: snapshot.marketplaceCommit,
fetchedAt: snapshot.fetchedAt
}
: null,
stale,
official: isOfficialMarketplaceGitSource(source.source.url),
...(error ? { error } : {})
}
}
}
@@ -0,0 +1,85 @@
import { mkdtemp, readdir, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import type { PluginMarketplaceGitSource } from '../../shared/plugins/plugin-marketplace'
import { marketplaceSourceId, PluginMarketplaceStore } from './plugin-marketplace-store'
const roots: string[] = []
async function tempRoot(): Promise<string> {
const root = await mkdtemp(join(tmpdir(), 'orca-marketplace-store-'))
roots.push(root)
return root
}
function source(ref = 'main'): PluginMarketplaceGitSource {
return { kind: 'git', url: 'https://github.com/community/plugins.git', ref }
}
afterEach(async () => {
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })))
})
describe('PluginMarketplaceStore', () => {
it('persists bounded source registrations under a deterministic opaque id', async () => {
const root = await tempRoot()
const first = new PluginMarketplaceStore(root)
const registered = await first.addSource(source(), 123)
expect(registered).toEqual({
id: marketplaceSourceId(source()),
source: source(),
addedAt: 123
})
await expect(new PluginMarketplaceStore(root).listSources()).resolves.toEqual([registered])
await expect(first.addSource(source(), 999)).resolves.toEqual(registered)
})
it('atomically publishes a strict cached snapshot and removes it with its source', async () => {
const root = await tempRoot()
const store = new PluginMarketplaceStore(root)
const registered = await store.addSource(source(), 123)
const snapshot = await store.writeSnapshot({
source: registered,
marketplaceCommit: 'a'.repeat(40),
fetchedAt: 456,
marketplace: {
name: 'Community',
owner: 'community',
plugins: [
{
id: 'community.theme',
source: {
kind: 'git',
url: 'https://github.com/community/theme.git',
ref: 'v1'
},
categories: ['themes']
}
]
}
})
await expect(new PluginMarketplaceStore(root).readSnapshot(registered.id)).resolves.toEqual(
snapshot
)
expect(
(await readdir(join(root, 'marketplaces', 'snapshots'))).filter((entry) =>
entry.endsWith('.tmp')
)
).toEqual([])
await expect(store.removeSource(registered.id)).resolves.toBe(true)
await expect(store.readSnapshot(registered.id)).resolves.toBeNull()
})
it('keeps distinct refs as distinct marketplace sources', () => {
expect(marketplaceSourceId(source('main'))).not.toBe(marketplaceSourceId(source('stable')))
})
it('rejects path-like source ids before reading or deleting cache files', async () => {
const store = new PluginMarketplaceStore(await tempRoot())
await expect(store.readSnapshot('../outside')).rejects.toThrow()
await expect(store.removeSource('../outside')).rejects.toThrow()
})
})
@@ -0,0 +1,212 @@
import { createHash } from 'node:crypto'
import { createReadStream } from 'node:fs'
import { mkdir, rm } from 'node:fs/promises'
import { dirname, join } from 'node:path'
import { z } from 'zod'
import { PLUGIN_COMMIT_PATTERN } from '../../shared/plugins/plugin-install-lockfile'
import {
pluginMarketplaceGitSourceSchema,
pluginMarketplaceSchema,
type PluginMarketplace,
type PluginMarketplaceGitSource
} from '../../shared/plugins/plugin-marketplace'
import { writePluginFileAtomically } from './plugin-atomic-file-write'
export const PLUGIN_MARKETPLACE_SOURCE_LIMIT = 64
export const PLUGIN_MARKETPLACE_SOURCE_ID_PATTERN = /^[0-9a-f]{32}$/
const sourceIdSchema = z.string().regex(PLUGIN_MARKETPLACE_SOURCE_ID_PATTERN)
const registeredSourceSchema = z.strictObject({
id: sourceIdSchema,
source: pluginMarketplaceGitSourceSchema,
addedAt: z.number().finite().nonnegative()
})
const sourceFileSchema = z.strictObject({
schemaVersion: z.literal(1),
sources: z.array(registeredSourceSchema).max(PLUGIN_MARKETPLACE_SOURCE_LIMIT)
})
const cachedSnapshotSchema = z.strictObject({
schemaVersion: z.literal(1),
sourceId: sourceIdSchema,
source: pluginMarketplaceGitSourceSchema,
marketplaceCommit: z.string().regex(PLUGIN_COMMIT_PATTERN),
fetchedAt: z.number().finite().nonnegative(),
marketplace: pluginMarketplaceSchema
})
export type PluginMarketplaceRegisteredSource = z.infer<typeof registeredSourceSchema>
export type PluginMarketplaceCachedSnapshot = z.infer<typeof cachedSnapshotSchema>
const SOURCE_FILE_MAX_BYTES = 2 * 1024 * 1024
const SNAPSHOT_FILE_MAX_BYTES = 16 * 1024 * 1024
export function marketplaceSourceId(source: PluginMarketplaceGitSource): string {
const parsed = pluginMarketplaceGitSourceSchema.parse(source)
return createHash('sha256')
.update(`orca-plugin-marketplace-source-v1\0${parsed.url}\0${parsed.ref}`)
.digest('hex')
.slice(0, 32)
}
export class PluginMarketplaceStore {
private readonly sourcesPath: string
private readonly snapshotDirectory: string
private sources: PluginMarketplaceRegisteredSource[] | null = null
private writeChain: Promise<void> = Promise.resolve()
constructor(pluginsDataDir: string) {
const root = join(pluginsDataDir, 'marketplaces')
this.sourcesPath = join(root, 'sources.json')
this.snapshotDirectory = join(root, 'snapshots')
}
async listSources(): Promise<readonly PluginMarketplaceRegisteredSource[]> {
await this.loadSources()
return this.sources!
}
async addSource(
source: PluginMarketplaceGitSource,
addedAt = Date.now()
): Promise<PluginMarketplaceRegisteredSource> {
const parsedSource = pluginMarketplaceGitSourceSchema.parse(source)
const registration = registeredSourceSchema.parse({
id: marketplaceSourceId(parsedSource),
source: parsedSource,
addedAt
})
await this.mutateSources((sources) => {
if (sources.some((candidate) => candidate.id === registration.id)) {
return [...sources]
}
if (sources.length >= PLUGIN_MARKETPLACE_SOURCE_LIMIT) {
throw new Error(`marketplace source limit (${PLUGIN_MARKETPLACE_SOURCE_LIMIT}) reached`)
}
return [...sources, registration]
})
return this.sources!.find((candidate) => candidate.id === registration.id)!
}
async removeSource(sourceId: string): Promise<boolean> {
const parsedId = sourceIdSchema.parse(sourceId)
let removed = false
await this.mutateSources((sources) => {
const next = sources.filter((source) => source.id !== parsedId)
removed = next.length !== sources.length
return next
})
if (removed) {
await rm(this.snapshotPath(parsedId), { force: true })
}
return removed
}
async writeSnapshot(input: {
source: PluginMarketplaceRegisteredSource
marketplaceCommit: string
fetchedAt?: number
marketplace: PluginMarketplace
}): Promise<PluginMarketplaceCachedSnapshot> {
const snapshot = cachedSnapshotSchema.parse({
schemaVersion: 1,
sourceId: input.source.id,
source: input.source.source,
marketplaceCommit: input.marketplaceCommit,
fetchedAt: input.fetchedAt ?? Date.now(),
marketplace: input.marketplace
})
await writeAtomicJson(this.snapshotPath(input.source.id), snapshot)
return snapshot
}
async readSnapshot(sourceId: string): Promise<PluginMarketplaceCachedSnapshot | null> {
const parsedId = sourceIdSchema.parse(sourceId)
try {
const raw = JSON.parse(
await readBoundedText(this.snapshotPath(parsedId), SNAPSHOT_FILE_MAX_BYTES)
)
const parsed = cachedSnapshotSchema.parse(raw)
if (parsed.sourceId !== parsedId) {
throw new Error('marketplace snapshot source identity does not match its cache path')
}
return parsed
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
return null
}
throw new Error(
`marketplace snapshot is invalid: ${error instanceof Error ? error.message : String(error)}`
)
}
}
private async loadSources(): Promise<void> {
if (this.sources !== null) {
return
}
try {
const parsed = sourceFileSchema.parse(
JSON.parse(await readBoundedText(this.sourcesPath, SOURCE_FILE_MAX_BYTES))
)
const ids = new Set<string>()
for (const source of parsed.sources) {
if (source.id !== marketplaceSourceId(source.source) || ids.has(source.id)) {
throw new Error('marketplace source identity is inconsistent or duplicated')
}
ids.add(source.id)
}
this.sources = parsed.sources
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
this.sources = []
return
}
throw new Error(
`marketplace sources are invalid: ${error instanceof Error ? error.message : String(error)}`
)
}
}
private async mutateSources(
mutation: (
sources: readonly PluginMarketplaceRegisteredSource[]
) => PluginMarketplaceRegisteredSource[]
): Promise<void> {
const update = this.writeChain
.catch(() => undefined)
.then(async () => {
await this.loadSources()
const next = sourceFileSchema.parse({
schemaVersion: 1,
sources: mutation(this.sources!)
}).sources
await writeAtomicJson(this.sourcesPath, { schemaVersion: 1, sources: next })
this.sources = next
})
this.writeChain = update
await update
}
private snapshotPath(sourceId: string): string {
return join(this.snapshotDirectory, `${sourceId}.json`)
}
}
async function readBoundedText(path: string, limit: number): Promise<string> {
const chunks: Buffer[] = []
let totalBytes = 0
for await (const chunk of createReadStream(path)) {
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
totalBytes += bytes.byteLength
if (totalBytes > limit) {
throw new Error(`file exceeds its ${limit}-byte limit`)
}
chunks.push(bytes)
}
return Buffer.concat(chunks, totalBytes).toString('utf8')
}
async function writeAtomicJson(path: string, value: unknown): Promise<void> {
await mkdir(dirname(path), { recursive: true })
await writePluginFileAtomically(path, `${JSON.stringify(value, null, 2)}\n`)
}
@@ -0,0 +1,179 @@
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { pluginManifestSchema } from '../../shared/plugins/plugin-manifest'
import { createPluginPanelCallAdmission } from '../../shared/plugins/plugin-panel-call-admission'
import type { ValidDiscoveredPlugin } from './plugin-discovery'
import { PluginPanelController } from './plugin-panel-controller'
const roots: string[] = []
afterEach(async () => {
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })))
})
async function createPlugin(): Promise<ValidDiscoveredPlugin> {
const rootDir = await mkdtemp(join(tmpdir(), 'orca-plugin-panel-controller-'))
roots.push(rootDir)
await writeFile(join(rootDir, 'panel.html'), '<h1>Panel</h1>')
return {
pluginKey: 'orca-samples.demo',
rootDir,
manifest: pluginManifestSchema.parse({
manifestVersion: 1,
id: 'demo',
publisher: 'orca-samples',
name: 'Demo',
version: '1.0.0',
engines: { orca: '>=1.0.0' },
pluginApi: 1,
contributes: {
panels: [{ id: 'dashboard', title: 'Dashboard', entry: 'panel.html' }],
commands: [],
events: []
},
capabilities: [{ kind: 'notifications:show' }]
}),
consentFingerprint: 'sha256-consented',
contentHash: null,
isDev: true
}
}
describe('PluginPanelController identity binding', () => {
it('uses the session identity and rejects caller-supplied plugin claims', async () => {
const plugin = await createPlugin()
const executeHostCall = vi.fn().mockResolvedValue({ ok: true, value: { delivered: true } })
const controller = new PluginPanelController({
resolveApprovedPlugin: (pluginKey) => (pluginKey === plugin.pluginKey ? plugin : null),
contentVerifier: { verify: vi.fn().mockResolvedValue(undefined) },
executeHostCall,
log: vi.fn()
})
const entry = await controller.open('runtime:one', plugin.pluginKey, 'dashboard')
expect(entry).not.toBeNull()
await expect(
controller.execute('runtime:one', {
sessionToken: entry!.sessionToken,
pluginId: 'orca-samples.other',
action: 'notifications.show',
params: { title: 'Hello' }
})
).resolves.toMatchObject({ ok: false, code: 'invalid_request' })
expect(executeHostCall).not.toHaveBeenCalled()
await expect(
controller.execute('runtime:one', {
sessionToken: entry!.sessionToken,
action: 'notifications.show',
params: { title: 'Hello' }
})
).resolves.toMatchObject({ ok: true })
expect(executeHostCall).toHaveBeenCalledWith(plugin.pluginKey, 'notifications.show', {
title: 'Hello'
})
await expect(
controller.execute('runtime:other', {
sessionToken: entry!.sessionToken,
action: 'notifications.show',
params: { title: 'Hello' }
})
).resolves.toMatchObject({ ok: false, code: 'invalid_request' })
})
it('charges raw malformed and oversized calls before strict parsing', async () => {
const plugin = await createPlugin()
const executeHostCall = vi.fn()
const controller = new PluginPanelController({
resolveApprovedPlugin: () => plugin,
contentVerifier: { verify: vi.fn().mockResolvedValue(undefined) },
executeHostCall,
log: vi.fn(),
panelAdmission: createPluginPanelCallAdmission({
limits: { maxBytes: 128, maxMessages: 2, perMs: 10_000 },
now: () => 0
})
})
const entry = await controller.open('runtime:one', plugin.pluginKey, 'dashboard')
await expect(
controller.execute('runtime:one', {
sessionToken: entry!.sessionToken,
action: 'notifications.show',
unexpected: true
})
).resolves.toMatchObject({ ok: false, code: 'invalid_request' })
await expect(
controller.execute('runtime:one', {
sessionToken: entry!.sessionToken,
action: 'notifications.show',
params: { title: 'x'.repeat(256) }
})
).resolves.toEqual({
ok: false,
code: 'invalid_request',
error: 'panel message exceeds the size limit'
})
await expect(
controller.execute('runtime:one', {
sessionToken: entry!.sessionToken,
action: 'notifications.show',
params: { title: 'third' }
})
).resolves.toEqual({
ok: false,
code: 'rate_limited',
error: 'too many panel requests'
})
expect(executeHostCall).not.toHaveBeenCalled()
})
it('does not publish stale panel code after approval changes during verification', async () => {
const plugin = await createPlugin()
let approved = true
let finishVerification!: () => void
const verification = new Promise<void>((resolve) => {
finishVerification = resolve
})
const controller = new PluginPanelController({
resolveApprovedPlugin: () => (approved ? plugin : null),
contentVerifier: { verify: () => verification },
executeHostCall: vi.fn(),
log: vi.fn()
})
const opening = controller.open('runtime:one', plugin.pluginKey, 'dashboard')
approved = false
finishVerification()
await expect(opening).resolves.toBeNull()
})
it('invalidates an open dev-panel session when its manifest revision changes', async () => {
const plugin = await createPlugin()
let current = plugin
const executeHostCall = vi.fn().mockResolvedValue({ ok: true, value: { delivered: true } })
const controller = new PluginPanelController({
resolveApprovedPlugin: () => current,
contentVerifier: { verify: vi.fn().mockResolvedValue(undefined) },
executeHostCall,
log: vi.fn()
})
const entry = await controller.open('runtime:one', plugin.pluginKey, 'dashboard')
current = {
...plugin,
manifest: pluginManifestSchema.parse({ ...plugin.manifest, version: '1.0.1' })
}
await expect(
controller.execute('runtime:one', {
sessionToken: entry!.sessionToken,
action: 'notifications.show',
params: { title: 'Hello' }
})
).resolves.toMatchObject({ ok: false, code: 'unavailable' })
expect(executeHostCall).not.toHaveBeenCalled()
})
})
+170
View File
@@ -0,0 +1,170 @@
import type {
PluginPanelActionOutcome,
PluginPanelEntry
} from '../../shared/plugins/plugin-panel-bridge'
import { panelActionCallSchema } from '../../shared/plugins/plugin-panel-bridge'
import {
admitPluginPanelCall,
createPluginPanelCallAdmission,
type PluginPanelCallAdmission
} from '../../shared/plugins/plugin-panel-call-admission'
import { buildPluginPanelShellHtml } from '../../shared/plugins/plugin-panel-shell'
import type { ValidDiscoveredPlugin } from './plugin-discovery'
import type { PluginContentVerifier } from './plugin-content-integrity'
import {
PLUGIN_PANEL_ENTRY_MAX_BYTES,
readContainedPluginArtifactText
} from './plugin-artifact-validation'
import { PluginPanelSessions, type PluginPanelSessionBinding } from './plugin-panel-sessions'
type PluginPanelControllerOptions = {
resolveApprovedPlugin: (pluginKey: string) => ValidDiscoveredPlugin | null
contentVerifier: Pick<PluginContentVerifier, 'verify'>
executeHostCall: (
pluginKey: string,
method: string,
params: unknown
) => Promise<PluginPanelActionOutcome>
log: (pluginKey: string, line: string) => void
panelAdmission?: PluginPanelCallAdmission
}
type LoadedPluginPanel = {
entry: { html: string }
binding: PluginPanelSessionBinding
}
export class PluginPanelController {
private readonly sessions = new PluginPanelSessions()
private readonly boundOwnerSignals = new WeakSet<AbortSignal>()
private readonly panelAdmission: PluginPanelCallAdmission
constructor(private readonly options: PluginPanelControllerOptions) {
this.panelAdmission = options.panelAdmission ?? createPluginPanelCallAdmission()
}
async readEntry(pluginKey: string, panelId: string): Promise<{ html: string } | null> {
return (await this.load(pluginKey, panelId))?.entry ?? null
}
async open(
ownerKey: string,
pluginKey: string,
panelId: string
): Promise<PluginPanelEntry | null> {
const loaded = await this.load(pluginKey, panelId)
if (!loaded) {
return null
}
return {
...loaded.entry,
sessionToken: this.sessions.issue(ownerKey, loaded.binding)
}
}
async execute(ownerKey: string, call: unknown): Promise<PluginPanelActionOutcome> {
const sessionToken = this.extractSessionToken(call)
if (!sessionToken) {
return { ok: false, code: 'invalid_request', error: 'invalid panel session' }
}
const binding = this.sessions.resolve(ownerKey, sessionToken)
if (!binding) {
return { ok: false, code: 'invalid_request', error: 'invalid panel session' }
}
const admissionRefusal = admitPluginPanelCall(this.panelAdmission, binding.pluginKey, call)
if (admissionRefusal) {
return admissionRefusal
}
const parsed = panelActionCallSchema.safeParse(call)
if (!parsed.success) {
return { ok: false, code: 'invalid_request', error: 'malformed panel action call' }
}
const plugin = this.options.resolveApprovedPlugin(binding.pluginKey)
const panelExists = plugin?.manifest.contributes.panels.some(
(panel) => panel.id === binding.panelId
)
if (
!plugin ||
plugin.rootDir !== binding.rootDir ||
JSON.stringify(plugin.manifest) !== binding.manifestRevision ||
!panelExists
) {
return { ok: false, code: 'unavailable', error: 'panel session is no longer available' }
}
return this.options.executeHostCall(binding.pluginKey, parsed.data.action, parsed.data.params)
}
revokeOwner(ownerKey: string): void {
this.sessions.revokeOwner(ownerKey)
}
bindOwnerSignal(ownerKey: string, signal: AbortSignal | undefined): void {
if (!signal || this.boundOwnerSignals.has(signal)) {
return
}
this.boundOwnerSignals.add(signal)
if (signal.aborted) {
this.revokeOwner(ownerKey)
return
}
signal.addEventListener('abort', () => this.revokeOwner(ownerKey), { once: true })
}
revokeAll(): void {
this.sessions.clear()
this.panelAdmission.clear()
}
dispose(): void {
this.revokeAll()
}
private extractSessionToken(call: unknown): string | null {
if (typeof call !== 'object' || call === null) {
return null
}
try {
const token = (call as { sessionToken?: unknown }).sessionToken
return typeof token === 'string' && token.length >= 32 && token.length <= 128 ? token : null
} catch {
return null
}
}
private async load(pluginKey: string, panelId: string): Promise<LoadedPluginPanel | null> {
const plugin = this.options.resolveApprovedPlugin(pluginKey)
const panel = plugin?.manifest.contributes.panels.find((entry) => entry.id === panelId)
if (!plugin || !panel) {
return null
}
try {
await this.options.contentVerifier.verify(plugin)
const html = buildPluginPanelShellHtml(
await readContainedPluginArtifactText(
plugin.rootDir,
panel.entry,
PLUGIN_PANEL_ENTRY_MAX_BYTES
)
)
const current = this.options.resolveApprovedPlugin(pluginKey)
if (current !== plugin || current.rootDir !== plugin.rootDir) {
return null
}
return {
entry: { html },
binding: {
pluginKey,
panelId,
rootDir: plugin.rootDir,
manifestRevision: JSON.stringify(plugin.manifest)
}
}
} catch (error) {
this.options.log(
pluginKey,
`panel entry ${panel.entry} rejected: ${error instanceof Error ? error.message : String(error)}`
)
return null
}
}
}
@@ -0,0 +1,41 @@
import { describe, expect, it } from 'vitest'
import { PLUGIN_PANEL_FRAME_NAME_PREFIX } from '../../shared/plugins/plugin-panel-bridge'
import { PluginPanelNavigationRegistry } from './plugin-panel-navigation-guard'
function frame(input: { id: number; name?: string; url?: string }) {
let destroyed = false
return {
frameTreeNodeId: input.id,
name: input.name ?? '',
isDestroyed: () => destroyed,
destroy: () => {
destroyed = true
}
}
}
describe('PluginPanelNavigationRegistry', () => {
it('blocks only host-marked plugin srcdoc frames', () => {
const registry = new PluginPanelNavigationRegistry()
const plugin = frame({ id: 1, name: `${PLUGIN_PANEL_FRAME_NAME_PREFIX}demo` })
const notebook = frame({ id: 2 })
registry.register(plugin)
registry.register(notebook)
expect(registry.shouldBlock(plugin, null, 'about:srcdoc')).toBe(false)
expect(registry.shouldBlock(plugin, plugin, 'https://example.com')).toBe(true)
expect(registry.shouldBlock(notebook, notebook, 'https://example.com')).toBe(false)
})
it('keeps pre-parse identity after name mutation and prunes destroyed frames', () => {
const registry = new PluginPanelNavigationRegistry()
const plugin = frame({ id: 1, name: `${PLUGIN_PANEL_FRAME_NAME_PREFIX}demo` })
registry.register(plugin)
plugin.name = ''
expect(registry.shouldBlock(plugin, null, 'about:srcdoc')).toBe(false)
expect(registry.shouldBlock(plugin, plugin, 'https://example.com')).toBe(true)
plugin.destroy()
expect(registry.shouldBlock(plugin, plugin, 'https://example.com')).toBe(false)
})
})
@@ -0,0 +1,75 @@
import type { WebContents, WebFrameMain } from 'electron'
import { PLUGIN_PANEL_FRAME_NAME_PREFIX } from '../../shared/plugins/plugin-panel-bridge'
type NavigationFrame = Pick<WebFrameMain, 'frameTreeNodeId' | 'isDestroyed' | 'name'>
type RegisteredFrame = {
frame: NavigationFrame
initialSrcdocPending: boolean
}
/** Records host-marked panel frame identities at browsing-context creation,
* before plugin parsing can mutate window.name. */
export class PluginPanelNavigationRegistry {
private readonly frames = new Map<number, RegisteredFrame>()
register(frame: NavigationFrame): void {
this.prune()
if (frame.name.startsWith(PLUGIN_PANEL_FRAME_NAME_PREFIX)) {
this.frames.set(frame.frameTreeNodeId, { frame, initialSrcdocPending: true })
}
}
shouldBlock(
frame: NavigationFrame | null,
initiator: NavigationFrame | null,
destinationUrl: string
): boolean {
this.prune()
const registeredTarget = frame ? this.frames.get(frame.frameTreeNodeId) : undefined
if (registeredTarget) {
// Why: registration happens before the host-provided srcdoc commits;
// allow exactly that initial document, then contain every navigation.
if (registeredTarget.initialSrcdocPending && destinationUrl === 'about:srcdoc') {
registeredTarget.initialSrcdocPending = false
return false
}
return true
}
return Boolean(initiator && this.frames.has(initiator.frameTreeNodeId))
}
clear(): void {
this.frames.clear()
}
private prune(): void {
for (const [id, registered] of this.frames) {
if (registered.frame.isDestroyed()) {
this.frames.delete(id)
}
}
}
}
export function registerPluginPanelNavigationGuard(webContents: WebContents): void {
const registry = new PluginPanelNavigationRegistry()
webContents.on('frame-created', (_event, { frame }) => {
if (frame) {
registry.register(frame)
}
})
webContents.on('did-start-navigation', (event) => {
if (!event.isMainFrame && event.url === 'about:srcdoc' && event.frame) {
// Some Chromium builds populate the frame name only when navigation
// starts; this event still precedes document parsing and plugin code.
registry.register(event.frame)
}
})
webContents.on('will-frame-navigate', (event) => {
if (registry.shouldBlock(event.frame, event.initiator ?? null, event.url)) {
event.preventDefault()
}
})
webContents.on('destroyed', () => registry.clear())
}
@@ -0,0 +1,33 @@
import { EventEmitter } from 'node:events'
import { describe, expect, it, vi } from 'vitest'
import {
bindPluginPanelOwnerLifecycle,
type PluginPanelOwnerSender
} from './plugin-panel-owner-lifecycle'
describe('bindPluginPanelOwnerLifecycle', () => {
it('deduplicates hooks, revokes on renderer loss, and invalidates in-flight loads', () => {
const sender = new EventEmitter() as PluginPanelOwnerSender & EventEmitter
const revoke = vi.fn()
const first = bindPluginPanelOwnerLifecycle(sender, revoke)
const duplicate = bindPluginPanelOwnerLifecycle(sender, revoke)
expect(sender.listenerCount('destroyed')).toBe(1)
expect(sender.listenerCount('render-process-gone')).toBe(1)
expect(first.isCurrent()).toBe(true)
expect(duplicate.isCurrent()).toBe(true)
sender.emit('render-process-gone')
expect(revoke).toHaveBeenCalledTimes(1)
expect(first.isCurrent()).toBe(false)
expect(duplicate.isCurrent()).toBe(false)
expect(sender.listenerCount('destroyed')).toBe(0)
const restarted = bindPluginPanelOwnerLifecycle(sender, revoke)
expect(restarted.isCurrent()).toBe(true)
sender.emit('destroyed')
expect(revoke).toHaveBeenCalledTimes(2)
expect(restarted.isCurrent()).toBe(false)
})
})
@@ -0,0 +1,42 @@
import type { WebContents } from 'electron'
export type PluginPanelOwnerSender = Pick<WebContents, 'once' | 'removeListener'>
type OwnerState = {
bound: boolean
generation: number
}
const ownerStates = new WeakMap<PluginPanelOwnerSender, OwnerState>()
/** Deduplicates WebContents lifecycle hooks and returns a generation lease so
* an async panel load cannot publish a session after its renderer died. */
export function bindPluginPanelOwnerLifecycle(
sender: PluginPanelOwnerSender,
revoke: () => void
): { isCurrent: () => boolean } {
let state = ownerStates.get(sender)
if (!state) {
state = { bound: false, generation: 0 }
ownerStates.set(sender, state)
}
if (!state.bound) {
state.bound = true
let finished = false
const cleanup = (): void => {
if (finished) {
return
}
finished = true
sender.removeListener('destroyed', cleanup)
sender.removeListener('render-process-gone', cleanup)
state!.bound = false
state!.generation += 1
revoke()
}
sender.once('destroyed', cleanup)
sender.once('render-process-gone', cleanup)
}
const generation = state.generation
return { isCurrent: () => state!.bound && state!.generation === generation }
}
@@ -0,0 +1,38 @@
import { describe, expect, it } from 'vitest'
import { PluginPanelSessions } from './plugin-panel-sessions'
const binding = {
pluginKey: 'orca-samples.demo',
panelId: 'dashboard',
rootDir: '/plugins/orca-samples.demo/hash-one',
manifestRevision: 'manifest-v1'
}
describe('PluginPanelSessions', () => {
it('binds an opaque token to its transport owner and panel revision', () => {
const sessions = new PluginPanelSessions()
const token = sessions.issue('renderer:1', binding)
expect(token).toHaveLength(43)
expect(sessions.resolve('renderer:1', token)).toEqual(binding)
expect(sessions.resolve('renderer:2', token)).toBeNull()
expect(sessions.issue('renderer:1', binding)).toBe(token)
expect(sessions.issue('renderer:1', { ...binding, rootDir: '/plugins/new' })).not.toBe(token)
expect(sessions.issue('renderer:1', { ...binding, manifestRevision: 'manifest-v2' })).not.toBe(
token
)
})
it('revokes every session owned by a disconnected transport', () => {
const sessions = new PluginPanelSessions()
const first = sessions.issue('connection:one', binding)
const second = sessions.issue('connection:one', { ...binding, panelId: 'secondary' })
const other = sessions.issue('connection:two', binding)
sessions.revokeOwner('connection:one')
expect(sessions.resolve('connection:one', first)).toBeNull()
expect(sessions.resolve('connection:one', second)).toBeNull()
expect(sessions.resolve('connection:two', other)).toEqual(binding)
})
})
+84
View File
@@ -0,0 +1,84 @@
import { randomBytes } from 'node:crypto'
export type PluginPanelSessionBinding = {
pluginKey: string
panelId: string
rootDir: string
manifestRevision: string
}
type PluginPanelSession = PluginPanelSessionBinding & {
ownerKey: string
}
const MAX_PANEL_SESSIONS = 1_024
function bindingKey(ownerKey: string, binding: PluginPanelSessionBinding): string {
return JSON.stringify([
ownerKey,
binding.pluginKey,
binding.panelId,
binding.rootDir,
binding.manifestRevision
])
}
/** Opaque bearer sessions bind a loaded panel to its transport owner without
* accepting a plugin identity on later action calls. */
export class PluginPanelSessions {
private readonly sessions = new Map<string, PluginPanelSession>()
private readonly tokensByBinding = new Map<string, string>()
issue(ownerKey: string, binding: PluginPanelSessionBinding): string {
const key = bindingKey(ownerKey, binding)
const existing = this.tokensByBinding.get(key)
if (existing) {
return existing
}
while (this.sessions.size >= MAX_PANEL_SESSIONS) {
const oldest = this.sessions.entries().next().value as
| [string, PluginPanelSession]
| undefined
if (!oldest) {
break
}
this.delete(oldest[0], oldest[1])
}
const token = randomBytes(32).toString('base64url')
const session = { ownerKey, ...binding }
this.sessions.set(token, session)
this.tokensByBinding.set(key, token)
return token
}
resolve(ownerKey: string, token: string): PluginPanelSessionBinding | null {
const session = this.sessions.get(token)
if (!session || session.ownerKey !== ownerKey) {
return null
}
return {
pluginKey: session.pluginKey,
panelId: session.panelId,
rootDir: session.rootDir,
manifestRevision: session.manifestRevision
}
}
revokeOwner(ownerKey: string): void {
for (const [token, session] of this.sessions) {
if (session.ownerKey === ownerKey) {
this.delete(token, session)
}
}
}
clear(): void {
this.sessions.clear()
this.tokensByBinding.clear()
}
private delete(token: string, session: PluginPanelSession): void {
this.sessions.delete(token)
this.tokensByBinding.delete(bindingKey(session.ownerKey, session))
}
}
@@ -0,0 +1,12 @@
const { spawnSync } = require('node:child_process')
const command = process.argv.at(-1) ?? ''
const match = /^git-upload-pack '([^']+)'$/.exec(command)
const repositories = JSON.parse(process.env.ORCA_TEST_SSH_REPOSITORIES ?? '{}')
const repository = match ? repositories[match[1]] : undefined
if (!repository) {
process.stderr.write(`unknown test SSH repository: ${command}\n`)
process.exit(1)
}
const result = spawnSync('git', ['upload-pack', repository], { stdio: 'inherit' })
process.exit(result.status ?? 1)
@@ -0,0 +1,153 @@
import { execFile } from 'node:child_process'
import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { promisify } from 'node:util'
import { afterEach, describe, expect, it } from 'vitest'
import type { PluginMarketplaceGitSource } from '../../shared/plugins/plugin-marketplace'
import { getUserPluginsDir } from './plugin-discovery'
import { readPluginLockfile } from './plugin-install'
import { PluginMarketplaceInstaller } from './plugin-marketplace-installer'
import { PluginMarketplaceService } from './plugin-marketplace-service'
const execFileAsync = promisify(execFile)
const temporaryRoots: string[] = []
const savedEnvironment = {
GIT_SSH_COMMAND: process.env.GIT_SSH_COMMAND,
GIT_SSH_VARIANT: process.env.GIT_SSH_VARIANT,
ORCA_TEST_SSH_REPOSITORIES: process.env.ORCA_TEST_SSH_REPOSITORIES
}
async function runGit(cwd: string, args: string[]): Promise<void> {
await execFileAsync('git', args, { cwd })
}
async function createGitRepository(
root: string,
name: string,
files: Record<string, string>
): Promise<string> {
const repository = join(root, name)
await mkdir(repository, { recursive: true })
for (const [relativePath, contents] of Object.entries(files)) {
const path = join(repository, relativePath)
await mkdir(join(path, '..'), { recursive: true })
await writeFile(path, contents, 'utf8')
}
await runGit(repository, ['init', '--quiet'])
await runGit(repository, ['checkout', '--quiet', '-b', 'main'])
await runGit(repository, ['add', '--all'])
await runGit(repository, [
'-c',
'user.name=Orca Test',
'-c',
'user.email=orca-test@example.invalid',
'commit',
'--quiet',
'-m',
'fixture'
])
return repository
}
function shellQuote(value: string): string {
return `'${value.replaceAll("'", "'\\''")}'`
}
afterEach(async () => {
for (const [key, value] of Object.entries(savedEnvironment)) {
if (value === undefined) {
delete process.env[key]
} else {
process.env[key] = value
}
}
await Promise.all(
temporaryRoots.splice(0).map((root) => rm(root, { recursive: true, force: true }))
)
})
describe('private Git marketplace integration', () => {
it('uses the caller SSH environment for marketplace preview and install', async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-private-marketplace-'))
temporaryRoots.push(root)
const pluginKey = 'private.private-locale'
const pluginUrl = 'ssh://git@example.invalid/private/locale.git'
const marketplaceUrl = 'ssh://git@example.invalid/private/marketplace.git'
const pluginRepository = await createGitRepository(root, 'locale-source', {
'orca-plugin.json': JSON.stringify({
manifestVersion: 1,
id: 'private-locale',
publisher: 'private',
name: 'Private Locale',
version: '1.0.0',
engines: { orca: '>=1.4.0' },
pluginApi: 1,
contributes: {
languagePacks: [{ locale: 'pt-BR', path: 'locale.json' }]
},
capabilities: []
}),
'locale.json': JSON.stringify({
settings: { title: 'Ajustes' }
})
})
const marketplaceRepository = await createGitRepository(root, 'marketplace-source', {
'orca-marketplace.json': JSON.stringify({
name: 'Private Team Plugins',
owner: 'private-team',
plugins: [
{
id: pluginKey,
source: { kind: 'git', url: pluginUrl, ref: 'main' },
categories: ['languages']
}
]
})
})
const sshShim = join(root, 'git-ssh-shim.cjs')
await writeFile(
sshShim,
await readFile(join(import.meta.dirname, 'plugin-private-marketplace-ssh-shim.cjs'), 'utf8'),
'utf8'
)
process.env.GIT_SSH_COMMAND = `${shellQuote(process.execPath.replaceAll('\\', '/'))} ${shellQuote(sshShim.replaceAll('\\', '/'))}`
process.env.GIT_SSH_VARIANT = 'ssh'
process.env.ORCA_TEST_SSH_REPOSITORIES = JSON.stringify({
'/private/locale.git': pluginRepository,
'/private/marketplace.git': marketplaceRepository
})
const userDataPath = join(root, 'user-data')
const marketplace = new PluginMarketplaceService({
pluginsDataDir: join(userDataPath, 'plugins-data')
})
const source: PluginMarketplaceGitSource = {
kind: 'git',
url: marketplaceUrl,
ref: 'main'
}
const registered = await marketplace.addSource(source)
const installer = new PluginMarketplaceInstaller({
marketplace,
userDataPath,
hostVersion: '1.4.0'
})
const preview = await installer.preview(registered.id, pluginKey)
const installed = await installer.install(preview)
expect(registered).toMatchObject({
stale: false,
marketplace: { name: 'Private Team Plugins' }
})
expect(preview).toMatchObject({ pluginKey, official: false, source: { url: pluginUrl } })
expect(installed).toMatchObject({ ok: true, pluginKey })
const lock = await readPluginLockfile(getUserPluginsDir(userDataPath))
expect(lock.plugins[pluginKey]?.source).toMatchObject({
kind: 'marketplace',
marketplace: { url: marketplaceUrl },
plugin: { url: pluginUrl }
})
})
})
@@ -0,0 +1,11 @@
export async function waitForPluginRefreshSettlement(
getCurrent: () => Promise<void>
): Promise<void> {
while (true) {
const pending = getCurrent()
await pending.catch(() => undefined)
if (pending === getCurrent()) {
return
}
}
}
@@ -0,0 +1,117 @@
import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const storageMocks = vi.hoisted(() => ({
available: true,
encryptString: vi.fn((value: string) => Buffer.from(`encrypted:${value}`, 'utf8')),
decryptString: vi.fn((value: Buffer) => {
const text = value.toString('utf8')
if (!text.startsWith('encrypted:')) {
throw new Error('wrong key or corrupt ciphertext')
}
return text.slice('encrypted:'.length)
})
}))
vi.mock('electron', () => ({
safeStorage: {
isEncryptionAvailable: () => storageMocks.available,
encryptString: storageMocks.encryptString,
decryptString: storageMocks.decryptString
}
}))
import { PluginSecretsStore } from './plugin-secrets-store'
const roots: string[] = []
async function tempRoot(): Promise<string> {
const root = await mkdtemp(join(tmpdir(), 'orca-plugin-secrets-'))
roots.push(root)
return root
}
beforeEach(() => {
storageMocks.available = true
storageMocks.encryptString.mockImplementation((value) =>
Buffer.from(`encrypted:${value}`, 'utf8')
)
storageMocks.decryptString.mockImplementation((value) => {
const text = value.toString('utf8')
if (!text.startsWith('encrypted:')) {
throw new Error('wrong key or corrupt ciphertext')
}
return text.slice('encrypted:'.length)
})
})
afterEach(async () => {
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })))
})
describe('PluginSecretsStore', () => {
it('encrypts, persists, decrypts, deletes, and isolates plugin namespaces', async () => {
const root = await tempRoot()
const first = new PluginSecretsStore(root, 'acme.first')
const second = new PluginSecretsStore(root, 'acme.second')
expect(first.set('token', 'top-secret')).toEqual({ ok: true, value: true })
expect(first.get('token')).toEqual({ ok: true, value: 'top-secret' })
expect(second.get('token')).toEqual({ ok: true, value: null })
const persisted = await readFile(join(root, 'acme.first', 'secrets.json.enc'), 'utf8')
expect(persisted).not.toContain('top-secret')
if (process.platform !== 'win32') {
expect((await stat(join(root, 'acme.first', 'secrets.json.enc'))).mode & 0o077).toBe(0)
}
first.delete('token')
expect(first.get('token')).toEqual({ ok: true, value: null })
})
it('fails closed without OS encryption and writes no plaintext file', async () => {
const root = await tempRoot()
storageMocks.available = false
const store = new PluginSecretsStore(root, 'acme.demo')
expect(store.set('token', 'plaintext')).toMatchObject({ ok: false })
expect(store.get('token')).toMatchObject({ ok: true, value: null })
await expect(readFile(join(root, 'acme.demo', 'secrets.json.enc'))).rejects.toMatchObject({
code: 'ENOENT'
})
})
it('reports corrupt or wrong-key ciphertext without returning bytes', async () => {
const root = await tempRoot()
const pluginDir = join(root, 'acme.demo')
await mkdir(pluginDir, { recursive: true })
await writeFile(
join(pluginDir, 'secrets.json.enc'),
JSON.stringify({
version: 1,
format: 'electron-safe-storage-v1',
ciphertexts: { token: Buffer.from('not-encrypted').toString('base64') }
})
)
const store = new PluginSecretsStore(root, 'acme.demo')
expect(store.get('token')).toEqual({ ok: false, error: 'failed to decrypt stored secret' })
})
it('refuses ciphertext that would exceed the bounded vault', async () => {
const root = await tempRoot()
storageMocks.encryptString.mockReturnValue(Buffer.alloc(6 * 1024 * 1024))
const store = new PluginSecretsStore(root, 'acme.demo')
expect(store.set('token', 'small-input')).toMatchObject({ ok: false })
await expect(readFile(join(root, 'acme.demo', 'secrets.json.enc'))).rejects.toMatchObject({
code: 'ENOENT'
})
})
it('rejects unsafe plugin namespaces', async () => {
const root = await tempRoot()
expect(() => new PluginSecretsStore(root, 'constructor.demo')).toThrow('unsafe plugin key')
})
})
+108
View File
@@ -0,0 +1,108 @@
import { existsSync, readFileSync, statSync } from 'node:fs'
import { join } from 'node:path'
import { safeStorage } from 'electron'
import { writeSecureFile } from '../../shared/secure-file'
import {
PLUGIN_STORAGE_KEY_LIMIT,
PLUGIN_STORAGE_TOTAL_MAX_BYTES
} from '../../shared/plugins/plugin-host-api'
import { pluginDataDir } from './plugin-storage-store'
/**
* Per-plugin secret vault, following the repo's safeStorage-backed
* credential-file pattern (versioned envelope + base64 ciphertext via the
* atomic secure-file writer). No plaintext fallback: when OS encryption is
* unavailable, writes fail loudly instead of silently downgrading — plugin
* secrets are API-token grade.
*/
type PersistedSecretsFile = {
version: 1
format: 'electron-safe-storage-v1'
/** key → base64 ciphertext of the secret value. */
ciphertexts: Record<string, string>
}
export type PluginSecretsResult<T> = { ok: true; value: T } | { ok: false; error: string }
export class PluginSecretsStore {
private readonly filePath: string
constructor(pluginsDataDir: string, qualifiedKey: string) {
this.filePath = join(pluginDataDir(pluginsDataDir, qualifiedKey), 'secrets.json.enc')
}
private read(): PersistedSecretsFile {
const empty: PersistedSecretsFile = {
version: 1,
format: 'electron-safe-storage-v1',
ciphertexts: {}
}
try {
if (!existsSync(this.filePath)) {
return empty
}
if (statSync(this.filePath).size > PLUGIN_STORAGE_TOTAL_MAX_BYTES) {
return empty
}
const parsed = JSON.parse(readFileSync(this.filePath, 'utf8')) as PersistedSecretsFile
if (
parsed &&
parsed.version === 1 &&
parsed.format === 'electron-safe-storage-v1' &&
parsed.ciphertexts &&
typeof parsed.ciphertexts === 'object' &&
!Array.isArray(parsed.ciphertexts)
) {
return parsed
}
} catch {
// Corrupt vaults read as empty; set() rewrites a valid file.
}
return empty
}
get(key: string): PluginSecretsResult<string | null> {
const file = this.read()
const ciphertext = file.ciphertexts[key]
if (typeof ciphertext !== 'string') {
return { ok: true, value: null }
}
if (!safeStorage.isEncryptionAvailable()) {
return { ok: false, error: 'OS-backed encryption is unavailable' }
}
try {
return { ok: true, value: safeStorage.decryptString(Buffer.from(ciphertext, 'base64')) }
} catch {
return { ok: false, error: 'failed to decrypt stored secret' }
}
}
set(key: string, value: string): PluginSecretsResult<true> {
if (!safeStorage.isEncryptionAvailable()) {
return { ok: false, error: 'OS-backed encryption is unavailable; secret not stored' }
}
const file = this.read()
if (
!Object.hasOwn(file.ciphertexts, key) &&
Object.keys(file.ciphertexts).length >= PLUGIN_STORAGE_KEY_LIMIT
) {
return { ok: false, error: `secret vault exceeds the ${PLUGIN_STORAGE_KEY_LIMIT}-key limit` }
}
file.ciphertexts[key] = safeStorage.encryptString(value).toString('base64')
const nextFile = JSON.stringify(file, null, 2)
if (Buffer.byteLength(nextFile, 'utf8') > PLUGIN_STORAGE_TOTAL_MAX_BYTES) {
return { ok: false, error: `secret vault exceeds ${PLUGIN_STORAGE_TOTAL_MAX_BYTES} bytes` }
}
writeSecureFile(this.filePath, nextFile)
return { ok: true, value: true }
}
delete(key: string): void {
const file = this.read()
if (Object.hasOwn(file.ciphertexts, key)) {
delete file.ciphertexts[key]
writeSecureFile(this.filePath, JSON.stringify(file, null, 2))
}
}
}
@@ -0,0 +1,47 @@
import { PluginDevWatcher } from './plugin-dev-watcher'
/** Starts and stops lifecycle maintenance as the feature flag and dev paths change. */
export class PluginServiceHousekeeping {
private readonly devWatcher = new PluginDevWatcher()
private reapTimer: ReturnType<typeof setInterval> | null = null
private watchedPathsKey: string | null = null
sync(options: {
enabled: boolean
devPaths: readonly string[]
reapIdle: () => void
refresh: () => void
}): void {
if (!options.enabled) {
this.stop()
return
}
if (!this.reapTimer) {
this.reapTimer = setInterval(options.reapIdle, 60_000)
this.reapTimer.unref?.()
}
const pathsKey = JSON.stringify(options.devPaths)
if (pathsKey !== this.watchedPathsKey) {
this.devWatcher.dispose()
this.devWatcher.start(options.devPaths, options.refresh, () => {
// The next refresh retries a failed watcher even when the configured
// path list itself did not change.
this.watchedPathsKey = null
})
this.watchedPathsKey = pathsKey
}
}
dispose(): void {
this.stop()
}
private stop(): void {
if (this.reapTimer) {
clearInterval(this.reapTimer)
this.reapTimer = null
}
this.devWatcher.dispose()
this.watchedPathsKey = null
}
}
@@ -0,0 +1,125 @@
import { mkdtemp, mkdir, rename, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { basename, join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { fingerprintPluginConsent } from '../../shared/plugins/plugin-consent-fingerprint'
import { pluginManifestSchema, type PluginManifest } from '../../shared/plugins/plugin-manifest'
import { hashPluginTree } from './plugin-content-hash'
import { PluginContentVerifier } from './plugin-content-integrity'
import { PluginService } from './plugin-service'
import type { PluginWorkerFactory } from './plugin-worker-manager'
const roots: string[] = []
async function createInstalledPlugin(options: { worker: boolean }): Promise<{
userDataPath: string
pluginKey: string
rootDir: string
manifest: PluginManifest
}> {
const userDataPath = await mkdtemp(join(tmpdir(), 'orca-plugin-service-integrity-'))
roots.push(userDataPath)
const pluginKey = 'orca-samples.demo'
const pluginDir = join(userDataPath, 'plugins', pluginKey)
const stagingDir = join(pluginDir, 'staging')
await mkdir(stagingDir, { recursive: true })
const manifest = pluginManifestSchema.parse({
manifestVersion: 1,
id: 'demo',
publisher: 'orca-samples',
name: 'Demo',
version: '1.0.0',
engines: { orca: '>=1.0.0' },
pluginApi: 1,
...(options.worker ? { main: 'worker.js' } : {}),
contributes: {
panels: [{ id: 'panel', title: 'Panel', entry: 'panel.html' }],
commands: options.worker ? [{ id: 'run', title: 'Run' }] : [],
events: []
},
capabilities: []
})
await writeFile(join(stagingDir, 'orca-plugin.json'), JSON.stringify(manifest))
await writeFile(join(stagingDir, 'panel.html'), '<h1>Panel</h1>')
await writeFile(join(stagingDir, 'payload.txt'), 'original')
if (options.worker) {
await writeFile(join(stagingDir, 'worker.js'), 'export default async function () {}')
}
const content = await hashPluginTree(stagingDir)
if (!content.ok) {
throw new Error(content.error)
}
const rootDir = join(pluginDir, content.hash)
await rename(stagingDir, rootDir)
await writeFile(join(pluginDir, 'current'), content.hash)
return { userDataPath, pluginKey, rootDir, manifest }
}
function createService(
plugin: Awaited<ReturnType<typeof createInstalledPlugin>>,
workerFactory?: PluginWorkerFactory
): PluginService {
const consentFingerprint = fingerprintPluginConsent(plugin.manifest)
return new PluginService({
userDataPath: plugin.userDataPath,
hostVersion: '1.4.0',
isPluginSystemEnabled: () => true,
getDisabledPlugins: () => [],
getPluginConsents: () => ({ [plugin.pluginKey]: consentFingerprint }),
getDevPluginPaths: () => [],
workerFactory
})
}
afterEach(async () => {
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })))
})
describe('PluginService lazy content verification', () => {
it('does not share an in-flight verification across same-key content revisions', async () => {
const oldPlugin = await createInstalledPlugin({ worker: false })
const newPlugin = await createInstalledPlugin({ worker: false })
await writeFile(join(oldPlugin.rootDir, 'payload.txt'), 'tampered old revision')
const verifier = new PluginContentVerifier()
const oldVerification = verifier.verify({
pluginKey: oldPlugin.pluginKey,
rootDir: oldPlugin.rootDir,
contentHash: basename(oldPlugin.rootDir)
})
const newVerification = verifier.verify({
pluginKey: newPlugin.pluginKey,
rootDir: newPlugin.rootDir,
contentHash: basename(newPlugin.rootDir)
})
await expect(oldVerification).rejects.toThrow('integrity verification')
await expect(newVerification).resolves.toBeUndefined()
})
it('detects tampering only when panel code is first consumed', async () => {
const plugin = await createInstalledPlugin({ worker: false })
const service = createService(plugin)
await service.initialize()
expect(service.findValidPlugin(plugin.pluginKey)).not.toBeNull()
await writeFile(join(plugin.rootDir, 'payload.txt'), 'tampered after discovery')
await expect(service.panels.readEntry(plugin.pluginKey, 'panel')).resolves.toBeNull()
await service.dispose()
})
it('blocks a worker fork when installed content changed after discovery', async () => {
const plugin = await createInstalledPlugin({ worker: true })
const workerFactory = vi.fn<PluginWorkerFactory>()
const service = createService(plugin, workerFactory)
await service.initialize()
await writeFile(join(plugin.rootDir, 'payload.txt'), 'tampered after discovery')
await expect(service.invokeCommand(plugin.pluginKey, 'run')).rejects.toThrow(
'integrity verification'
)
expect(workerFactory).not.toHaveBeenCalled()
await service.dispose()
})
})
@@ -0,0 +1,18 @@
import type { PluginWorkerFactory } from './plugin-worker-manager'
import type { KeybindingOverrides } from '../../shared/keybindings'
import type { PluginKillListEntry } from '../../shared/plugins/plugin-kill-list'
export type PluginServiceOptions = {
userDataPath: string
hostVersion: string
isPluginSystemEnabled: () => boolean
getDisabledPlugins: () => string[]
getPluginConsents: () => Record<string, string>
getDevPluginPaths: () => string[]
getKeybindings?: () => KeybindingOverrides
getPluginKillListEntry?: (pluginKey: string) => PluginKillListEntry | null
hostEntryPath?: string
workerFactory?: PluginWorkerFactory
maxActiveWorkers?: number
idleReapMs?: number
}
@@ -0,0 +1,462 @@
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { KeybindingOverrides } from '../../shared/keybindings'
import { fingerprintPluginConsent } from '../../shared/plugins/plugin-consent-fingerprint'
import { pluginManifestSchema, type PluginManifest } from '../../shared/plugins/plugin-manifest'
import type { PluginWorkerHandle } from './plugin-host-process'
import { PluginService } from './plugin-service'
import type { PluginWorkerFactory } from './plugin-worker-manager'
import { hashPluginTree } from './plugin-content-hash'
const roots: string[] = []
const services: PluginService[] = []
const pluginKey = 'orca-samples.demo'
function manifest(options: { main?: string; capabilities?: PluginManifest['capabilities'] } = {}) {
return pluginManifestSchema.parse({
manifestVersion: 1,
id: 'demo',
publisher: 'orca-samples',
name: 'Demo',
version: '1.0.0',
engines: { orca: '>=1.0.0' },
pluginApi: 1,
main: options.main ?? 'worker.js',
contributes: {
panels: [{ id: 'panel', title: 'Panel', entry: 'panel.html' }],
commands: [{ id: 'run', title: 'Run' }],
events: []
},
capabilities: options.capabilities ?? []
})
}
async function pluginRoot(pluginManifest = manifest()): Promise<string> {
const root = await mkdtemp(join(tmpdir(), 'orca-plugin-reconcile-'))
roots.push(root)
await writeFile(join(root, 'orca-plugin.json'), JSON.stringify(pluginManifest))
await writeFile(join(root, 'worker.js'), 'export default async function () {}')
await writeFile(join(root, 'worker-v2.js'), 'export default async function () {}')
await writeFile(join(root, 'panel.html'), '<h1>Panel</h1>')
return root
}
function testWorker(): PluginWorkerHandle & { dispose: ReturnType<typeof vi.fn> } {
return {
commands: ['run'],
invokeCommand: vi.fn(async () => null),
deliverEvent: vi.fn(),
lastActivityAt: () => Date.now(),
inFlightCount: () => 0,
dispose: vi.fn(async () => undefined),
kill: vi.fn(),
onExit: vi.fn()
}
}
function createHarness(root: string) {
let enabled = true
let disabled: string[] = []
let devPaths = [root]
let killed = false
const consent = fingerprintPluginConsent(manifest())
const workers: ReturnType<typeof testWorker>[] = []
const factory = vi.fn<PluginWorkerFactory>(async () => {
const handle = testWorker()
workers.push(handle)
return handle
})
const service = new PluginService({
userDataPath: root,
hostVersion: '1.4.0',
isPluginSystemEnabled: () => enabled,
getDisabledPlugins: () => disabled,
getPluginConsents: () => ({ [pluginKey]: consent }),
getDevPluginPaths: () => devPaths,
getPluginKillListEntry: (key) =>
killed && key === pluginKey
? { pluginKey, reason: 'Security incident', advisoryUrl: 'https://orca.example/advisory' }
: null,
workerFactory: factory
})
services.push(service)
return {
service,
factory,
workers,
setEnabled: (value: boolean) => {
enabled = value
},
setDisabled: (value: string[]) => {
disabled = value
},
setDevPaths: (value: string[]) => {
devPaths = value
},
setKilled: (value: boolean) => {
killed = value
}
}
}
async function activate(service: PluginService): Promise<void> {
await service.initialize()
await service.invokeCommand(pluginKey, 'run')
}
afterEach(async () => {
vi.useRealTimers()
await Promise.all(services.splice(0).map((service) => service.dispose()))
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })))
})
describe('PluginService worker reconciliation', () => {
it('blocks every runtime surface until a saved override resolves a content conflict', async () => {
const conflictingManifest = (id: string): PluginManifest =>
pluginManifestSchema.parse({
manifestVersion: 1,
id,
publisher: 'orca-samples',
name: id,
version: '1.0.0',
engines: { orca: '>=1.0.0' },
pluginApi: 1,
main: 'worker.js',
contributes: {
panels: [{ id: 'panel', title: 'Panel', entry: 'panel.html' }],
commands: [{ id: 'run', title: 'Run' }],
keybindings: [{ command: 'run', key: 'Mod+Alt+T' }],
events: [{ on: 'worktree.created' }]
},
capabilities: [{ kind: 'events:subscribe' }]
})
const firstManifest = conflictingManifest('first')
const secondManifest = conflictingManifest('second')
const firstRoot = await pluginRoot(firstManifest)
const secondRoot = await pluginRoot(secondManifest)
const firstHash = await hashPluginTree(firstRoot)
const secondHash = await hashPluginTree(secondRoot)
if (!firstHash.ok || !secondHash.ok) {
throw new Error('could not hash conflict fixtures')
}
let keybindings: KeybindingOverrides = {}
const factory = vi.fn<PluginWorkerFactory>(async () => testWorker())
const service = new PluginService({
userDataPath: firstRoot,
hostVersion: '1.4.0',
isPluginSystemEnabled: () => true,
getDisabledPlugins: () => [],
getPluginConsents: () => ({
'orca-samples.first': fingerprintPluginConsent(firstManifest, firstHash.hash),
'orca-samples.second': fingerprintPluginConsent(secondManifest, secondHash.hash)
}),
getDevPluginPaths: () => [firstRoot, secondRoot],
getKeybindings: () => keybindings,
workerFactory: factory
})
services.push(service)
await service.initialize()
expect(service.activationError('orca-samples.first')).toContain('conflicts')
expect(service.getGrantedCapabilities('orca-samples.first')).toBeNull()
await expect(service.invokeCommand('orca-samples.first', 'run')).rejects.toThrow('not enabled')
await expect(service.panels.readEntry('orca-samples.first', 'panel')).resolves.toBeNull()
service.emitEvent('worktree.created', {
worktreeId: 'worktree-1',
path: '/repo',
branch: 'feature'
})
await new Promise((resolve) => setTimeout(resolve, 0))
expect(factory).not.toHaveBeenCalled()
keybindings = { 'plugin:orca-samples.first/run': ['Mod+Shift+T'] }
await service.reconcileActivationState()
expect(service.activationError('orca-samples.first')).toBeNull()
await expect(service.panels.readEntry('orca-samples.first', 'panel')).resolves.toMatchObject({
html: expect.stringContaining('<h1>Panel</h1>')
})
await expect(service.invokeCommand('orca-samples.first', 'run')).resolves.toBeNull()
expect(factory).toHaveBeenCalledOnce()
})
it('rejects declarative aliases at the worker-command boundary without activating code', async () => {
const aliasManifest = pluginManifestSchema.parse({
manifestVersion: 1,
id: 'demo',
publisher: 'orca-samples',
name: 'Demo',
version: '1.0.0',
engines: { orca: '>=1.0.0' },
pluginApi: 1,
contributes: {
commands: [{ id: 'tasks', title: 'Tasks', action: 'view.tasks' }]
},
capabilities: []
})
const root = await pluginRoot(aliasManifest)
const factory = vi.fn<PluginWorkerFactory>()
const service = new PluginService({
userDataPath: root,
hostVersion: '1.4.0',
isPluginSystemEnabled: () => true,
getDisabledPlugins: () => [],
getPluginConsents: () => ({ [pluginKey]: fingerprintPluginConsent(aliasManifest) }),
getDevPluginPaths: () => [root],
workerFactory: factory
})
services.push(service)
await service.initialize()
await expect(service.invokeCommand(pluginKey, 'tasks')).rejects.toThrow(
'is a built-in action alias'
)
expect(factory).not.toHaveBeenCalled()
})
it('denies every authority boundary immediately when the feature flag turns off', async () => {
const root = await pluginRoot()
const harness = createHarness(root)
await activate(harness.service)
const plugin = harness.service.findValidPlugin(pluginKey)!
const opened = await harness.service.panels.open('renderer:1', pluginKey, 'panel')
expect(opened).not.toBeNull()
harness.setEnabled(false)
expect(harness.service.activationState(plugin)).toBe('disabled')
expect(harness.service.getGrantedCapabilities(pluginKey)).toBeNull()
await expect(harness.service.invokeCommand(pluginKey, 'run')).rejects.toThrow('not enabled')
await expect(harness.service.panels.readEntry(pluginKey, 'panel')).resolves.toBeNull()
await harness.service.refresh()
expect(harness.workers[0]!.dispose).toHaveBeenCalledOnce()
harness.setEnabled(true)
await harness.service.refresh()
await expect(
harness.service.panels.execute('renderer:1', {
sessionToken: opened!.sessionToken,
action: 'notifications.show',
params: { title: 'stale' }
})
).resolves.toMatchObject({ ok: false, error: 'invalid panel session' })
})
it('deactivates a worker when its plugin becomes disabled', async () => {
const root = await pluginRoot()
const harness = createHarness(root)
await activate(harness.service)
harness.setDisabled([pluginKey])
await harness.service.refresh()
expect(harness.workers[0]!.dispose).toHaveBeenCalledOnce()
expect(harness.service.workerState(pluginKey).state).toBe('inactive')
})
it('immediately revokes every authority surface and stops a killed plugin', async () => {
const root = await pluginRoot()
const harness = createHarness(root)
await activate(harness.service)
expect(await harness.service.panels.open('renderer:1', pluginKey, 'panel')).not.toBeNull()
harness.setKilled(true)
expect(harness.service.getGrantedCapabilities(pluginKey)).toBeNull()
expect(harness.service.activationError(pluginKey)).toContain('Security incident')
await expect(harness.service.invokeCommand(pluginKey, 'run')).rejects.toThrow('not enabled')
await expect(harness.service.panels.readEntry(pluginKey, 'panel')).resolves.toBeNull()
harness.service.emitEvent('worktree.created', {
worktreeId: 'worktree-1',
path: '/repo',
branch: 'feature'
})
await harness.service.reconcileActivationState()
expect(harness.workers[0]!.dispose).toHaveBeenCalledOnce()
expect(harness.service.options.getPluginKillListEntry?.(pluginKey)).toMatchObject({
reason: 'Security incident'
})
})
it('deactivates a worker when changed capabilities make consent pending', async () => {
const root = await pluginRoot()
const harness = createHarness(root)
await activate(harness.service)
await writeFile(
join(root, 'orca-plugin.json'),
JSON.stringify(manifest({ capabilities: [{ kind: 'storage' }] }))
)
await harness.service.refresh()
expect(harness.workers[0]!.dispose).toHaveBeenCalledOnce()
expect(harness.service.activationState(harness.service.findValidPlugin(pluginKey)!)).toBe(
'pending'
)
})
it('cancels the old generation when a worker spec changes without eager reactivation', async () => {
const root = await pluginRoot()
const harness = createHarness(root)
await activate(harness.service)
await writeFile(
join(root, 'orca-plugin.json'),
JSON.stringify(manifest({ main: 'worker-v2.js' }))
)
await harness.service.refresh()
expect(harness.workers[0]!.dispose).toHaveBeenCalledOnce()
expect(harness.factory).toHaveBeenCalledTimes(1)
await harness.service.invokeCommand(pluginKey, 'run')
expect(harness.factory).toHaveBeenCalledTimes(2)
expect(harness.factory.mock.calls[1]?.[0].mainEntry).toBe('worker-v2.js')
})
it('cannot reactivate the old revision while refresh awaits worker shutdown', async () => {
const root = await pluginRoot()
let finishOldDispose!: () => void
const oldDispose = new Promise<void>((resolve) => {
finishOldDispose = resolve
})
const workers: ReturnType<typeof testWorker>[] = []
const factory = vi.fn<PluginWorkerFactory>(async () => {
const handle = testWorker()
if (workers.length === 0) {
handle.dispose.mockImplementation(() => oldDispose)
}
workers.push(handle)
return handle
})
const consent = fingerprintPluginConsent(manifest())
const service = new PluginService({
userDataPath: root,
hostVersion: '1.4.0',
isPluginSystemEnabled: () => true,
getDisabledPlugins: () => [],
getPluginConsents: () => ({ [pluginKey]: consent }),
getDevPluginPaths: () => [root],
workerFactory: factory
})
services.push(service)
await activate(service)
await writeFile(
join(root, 'orca-plugin.json'),
JSON.stringify(manifest({ main: 'worker-v2.js' }))
)
const refreshing = service.refresh()
await vi.waitFor(() => expect(workers[0]!.dispose).toHaveBeenCalledOnce())
const invoking = service.invokeCommand(pluginKey, 'run')
await vi.waitFor(() => expect(factory).toHaveBeenCalledTimes(2))
expect(factory.mock.calls[1]?.[0].mainEntry).toBe('worker-v2.js')
finishOldDispose()
await expect(invoking).resolves.toBeNull()
await refreshing
})
it('deactivates removed and replaced dev paths without eager activation', async () => {
const firstRoot = await pluginRoot()
const secondRoot = await pluginRoot()
const harness = createHarness(firstRoot)
await activate(harness.service)
harness.setDevPaths([])
await harness.service.refresh()
expect(harness.workers[0]!.dispose).toHaveBeenCalledOnce()
expect(harness.service.findValidPlugin(pluginKey)).toBeNull()
harness.setDevPaths([secondRoot])
await harness.service.refresh()
expect(harness.factory).toHaveBeenCalledTimes(1)
await harness.service.invokeCommand(pluginKey, 'run')
expect(harness.factory.mock.calls[1]?.[0].rootDir).toBe(secondRoot)
})
it('starts and stops housekeeping on feature-flag transitions', async () => {
vi.useFakeTimers()
const root = await pluginRoot()
const harness = createHarness(root)
await harness.service.initialize()
expect(vi.getTimerCount()).toBe(1)
harness.setEnabled(false)
await harness.service.refresh()
expect(vi.getTimerCount()).toBe(0)
expect(harness.service.getDiscovered()).toEqual([])
harness.setEnabled(true)
await harness.service.refresh()
expect(vi.getTimerCount()).toBe(1)
expect(harness.factory).not.toHaveBeenCalled()
})
it('serializes activation reconciliation so the latest disabled state wins', async () => {
const root = await pluginRoot()
const harness = createHarness(root)
await harness.service.initialize()
const originalReconcile = harness.service.contentPacks.reconcile.bind(
harness.service.contentPacks
)
let releaseFirst!: () => void
const firstGate = new Promise<void>((resolve) => {
releaseFirst = resolve
})
let firstStarted!: () => void
const firstStartedPromise = new Promise<void>((resolve) => {
firstStarted = resolve
})
let activeReconciliations = 0
let maximumConcurrentReconciliations = 0
let callCount = 0
const reconcile = vi
.spyOn(harness.service.contentPacks, 'reconcile')
.mockImplementation(async (...args) => {
callCount += 1
activeReconciliations += 1
maximumConcurrentReconciliations = Math.max(
maximumConcurrentReconciliations,
activeReconciliations
)
try {
if (callCount === 1) {
firstStarted()
await firstGate
}
await originalReconcile(...args)
} finally {
activeReconciliations -= 1
}
})
const first = harness.service.reconcileActivationState()
await firstStartedPromise
harness.setDisabled([pluginKey])
const second = harness.service.reconcileActivationState()
let clientsReleased = false
const clientsReady = harness.service.whenReady().then(() => {
clientsReleased = true
})
await Promise.resolve()
expect(reconcile).toHaveBeenCalledTimes(1)
expect(clientsReleased).toBe(false)
releaseFirst()
await Promise.all([first, second, clientsReady])
expect(maximumConcurrentReconciliations).toBe(1)
expect(clientsReleased).toBe(true)
expect(reconcile).toHaveBeenCalledTimes(2)
expect(harness.service.activationState(harness.service.findValidPlugin(pluginKey)!)).toBe(
'disabled'
)
expect(harness.service.workerState(pluginKey).state).toBe('inactive')
})
})
+336
View File
@@ -0,0 +1,336 @@
import type { PluginEventName } from '../../shared/plugins/plugin-manifest'
import {
capabilityKinds,
type PluginCapabilityKind
} from '../../shared/plugins/plugin-capabilities'
import {
getPluginActivationState,
type PluginConsentLists
} from '../../shared/plugins/plugin-consent-state'
import type { PluginPanelActionOutcome } from '../../shared/plugins/plugin-panel-bridge'
import {
createPluginExtensionRegistry,
type PluginExtensionRegistry
} from '../../shared/plugins/plugin-extension-registry'
import {
discoverPlugins,
getPluginsDataDir,
getUserPluginsDir,
isInvalidDiscoveredPlugin,
type DiscoveredPlugin,
type ValidDiscoveredPlugin
} from './plugin-discovery'
import { PluginEventBus } from './plugin-event-bus'
import { PluginAuditLog } from './plugin-audit-log'
import { executePluginHostCallRequest } from './plugin-host-call-adapter'
import { PluginContentVerifier } from './plugin-content-integrity'
import { bindPluginHostServices, type PluginRuntimeDelegate } from './plugin-host-service-bindings'
import { PluginLogBuffer, type PluginLogLine } from './plugin-log-buffer'
import { PluginPanelController } from './plugin-panel-controller'
import { PluginWorkerController } from './plugin-worker-controller'
import { PluginServiceHousekeeping } from './plugin-service-housekeeping'
import { collectApprovedWorkerSpecs } from './plugin-worker-reconciliation'
import type { PluginRunState } from './plugin-supervisor'
import { isPluginApproved, snapshotPluginConsentLists } from './plugin-activation-policy'
import { PluginContentPackRegistry } from './plugin-content-pack-registry'
import type { PluginServiceOptions } from './plugin-service-options'
import type { PluginChangeEvent } from '../../shared/plugins/plugin-change-event'
import { waitForPluginRefreshSettlement } from './plugin-refresh-settlement'
import { assertPluginWorkerCommand } from './plugin-command-invocation'
import { deliverPluginEvent } from './plugin-event-delivery'
export type { PluginRuntimeDelegate } from './plugin-host-service-bindings'
export type { PluginLogLine } from './plugin-log-buffer'
export type { PluginServiceOptions } from './plugin-service-options'
export class PluginService {
readonly options: PluginServiceOptions
private readonly registry: PluginExtensionRegistry = createPluginExtensionRegistry()
private readonly eventBus = new PluginEventBus()
private readonly audit: PluginAuditLog
private readonly workerController: PluginWorkerController
private readonly logBuffer = new PluginLogBuffer()
private readonly contentVerifier = new PluginContentVerifier()
readonly contentPacks: PluginContentPackRegistry
readonly panels: PluginPanelController
private readonly changeListeners = new Set<(event: PluginChangeEvent) => void>()
private readonly housekeeping = new PluginServiceHousekeeping()
private discovered: DiscoveredPlugin[] = []
private runtimeDelegate: PluginRuntimeDelegate | null = null
private initPromise: Promise<void> | null = null
private refreshChain: Promise<void> = Promise.resolve()
private contentPacksReady = false
private disposed = false
constructor(options: PluginServiceOptions) {
this.options = options
this.contentPacks = new PluginContentPackRegistry(this.contentVerifier)
this.audit = new PluginAuditLog(getPluginsDataDir(options.userDataPath))
this.panels = new PluginPanelController({
resolveApprovedPlugin: (pluginKey) => {
const plugin = this.findValidPlugin(pluginKey)
return plugin && this.isRuntimeApproved(plugin) ? plugin : null
},
contentVerifier: this.contentVerifier,
executeHostCall: (pluginKey, method, params) =>
this.executeHostCall(pluginKey, method, params, { viaPanel: true }),
log: (pluginKey, line) => this.logBuffer.append(pluginKey, 'error', line)
})
this.workerController = new PluginWorkerController({
entryPath: options.hostEntryPath ?? '',
maxActive: options.maxActiveWorkers,
idleReapMs: options.idleReapMs,
workerFactory: options.workerFactory,
registry: this.registry,
contentVerifier: this.contentVerifier,
capabilities: (pluginKey) => this.getGrantedCapabilities(pluginKey),
isCurrentApproved: (plugin) =>
this.findValidPlugin(plugin.pluginKey) === plugin && this.isRuntimeApproved(plugin),
invokeCommand: (pluginKey, commandId, args) => this.invokeCommand(pluginKey, commandId, args),
executeHostCall: (pluginKey, method, params) =>
this.executeHostCall(pluginKey, method, params, { viaPanel: false }),
log: (pluginKey, level, line) => this.logBuffer.append(pluginKey, level, line),
onStateChanged: () => this.notifyChanged(false),
onWorkerGone: (pluginKey) => this.eventBus.clear(pluginKey)
})
}
setRuntimeDelegate(delegate: PluginRuntimeDelegate | null): void {
this.runtimeDelegate = delegate
}
onChanged(listener: (event: PluginChangeEvent) => void): () => void {
this.changeListeners.add(listener)
return () => this.changeListeners.delete(listener)
}
private notifyChanged(contentPacksChanged: boolean): void {
for (const listener of this.changeListeners) {
listener({ contentPacksChanged })
}
}
async initialize(): Promise<void> {
this.initPromise ??= this.refresh()
return this.initPromise
}
async whenReady(): Promise<void> {
await (this.initPromise ?? Promise.resolve()).catch(() => undefined)
// Client reads wait for the complete transaction so rollback-based content
// validation cannot expose a partially activated plugin between passes.
await waitForPluginRefreshSettlement(() => this.refreshChain)
}
refresh(): Promise<void> {
// Snapshot settings at request time so a quick off→on sequence still
// processes the off transition and revokes old workers/panel sessions.
const enabled = this.options.isPluginSystemEnabled()
const devPaths = this.options.getDevPluginPaths()
const consentLists = snapshotPluginConsentLists(this.options)
const refresh = this.refreshChain.then(() =>
this.performRefresh(enabled, devPaths, consentLists)
)
this.refreshChain = refresh.catch(() => undefined)
return refresh
}
private async performRefresh(
enabled: boolean,
devPaths: string[],
consentLists: PluginConsentLists
): Promise<void> {
if (this.disposed) {
return
}
this.contentPacksReady = false
this.contentVerifier.clear()
if (!enabled) {
this.panels.revokeAll()
}
const next = enabled
? await discoverPlugins({
pluginsDir: getUserPluginsDir(this.options.userDataPath),
devPluginPaths: devPaths,
hostVersion: this.options.hostVersion
})
: []
if (this.disposed) {
return
}
// Publish identity before shutdown so triggers cannot restart old code.
this.discovered = next
await this.contentPacks.reconcile(
next,
(plugin) => isPluginApproved(enabled, plugin, consentLists),
this.options.getKeybindings?.()
)
this.contentPacksReady = true
const nextSpecs = collectApprovedWorkerSpecs(next, (plugin) => this.isRuntimeApproved(plugin))
// Notify before slow shutdown so feature-off unmounts panels immediately.
this.notifyChanged(true)
await this.workerController.reconcile(nextSpecs)
if (this.disposed) {
return
}
this.housekeeping.sync({
enabled,
devPaths,
reapIdle: () => this.workerController.reapIdle(),
refresh: () => void this.refresh()
})
this.notifyChanged(false)
}
getDiscovered(): readonly DiscoveredPlugin[] {
return this.discovered
}
getLogs(pluginKey: string): PluginLogLine[] {
return this.logBuffer.get(pluginKey)
}
findValidPlugin(pluginKey: string): ValidDiscoveredPlugin | null {
for (const plugin of this.discovered) {
if (!isInvalidDiscoveredPlugin(plugin) && plugin.pluginKey === pluginKey) {
return plugin
}
}
return null
}
activationState(plugin: ValidDiscoveredPlugin): ReturnType<typeof getPluginActivationState> {
// The feature flag is an authority boundary, not only a discovery hint:
// callers fail closed immediately even before async reconciliation ends.
if (!this.options.isPluginSystemEnabled()) {
return 'disabled'
}
return getPluginActivationState(plugin.pluginKey, plugin.consentFingerprint, {
pluginConsents: this.options.getPluginConsents(),
disabledPlugins: this.options.getDisabledPlugins()
})
}
private isRuntimeApproved(plugin: ValidDiscoveredPlugin): boolean {
return (
this.contentPacksReady &&
this.activationState(plugin) === 'approved' &&
!this.contentPacks.error(plugin.pluginKey) &&
!this.options.getPluginKillListEntry?.(plugin.pluginKey)
)
}
workerState(pluginKey: string): { state: PluginRunState; restarts: number } {
return this.workerController.state(pluginKey)
}
activationError(pluginKey: string): string | null {
const blocked = this.options.getPluginKillListEntry?.(pluginKey)
return (
(blocked ? `Blocked by Orca's plugin safety list: ${blocked.reason}` : null) ??
this.contentPacks.error(pluginKey) ??
this.workerController.activationError(pluginKey)
)
}
/** Consented capability kinds for an approved plugin; null otherwise so
* callers deny uniformly (no probe-able distinction). */
getGrantedCapabilities(pluginKey: string): PluginCapabilityKind[] | null {
const plugin = this.findValidPlugin(pluginKey)
if (!plugin || !this.isRuntimeApproved(plugin)) {
return null
}
return capabilityKinds(plugin.manifest.capabilities)
}
/** Host API chokepoint for both transports (worker fork IPC + panel
* bridge); serve RPC reuses it through the same entry points. */
async executeHostCall(
pluginKey: string,
method: string,
params: unknown,
options: { viaPanel: boolean }
): Promise<PluginPanelActionOutcome> {
return executePluginHostCallRequest({
pluginKey,
request: { method, params },
viaPanel: options.viaPanel,
resolvePolicy: (boundPluginKey) => ({
grantedCapabilities: this.getGrantedCapabilities(boundPluginKey),
services: this.runtimeDelegate
? bindPluginHostServices({
delegate: this.runtimeDelegate,
pluginsDataDir: getPluginsDataDir(this.options.userDataPath),
subscribeEvents: (key, events) => this.eventBus.subscribe(key, events)
})
: null,
audit: this.audit
})
})
}
async invokeCommand(pluginKey: string, commandId: string, args?: unknown): Promise<unknown> {
const plugin = this.findValidPlugin(pluginKey)
if (!plugin || !this.isRuntimeApproved(plugin)) {
throw new Error(`plugin ${pluginKey} is not enabled`)
}
assertPluginWorkerCommand(plugin, commandId)
const handle = await this.workerController.ensure(plugin)
if (!handle.commands.includes(commandId)) {
throw new Error(`plugin ${pluginKey} registered no handler for ${commandId}`)
}
return handle.invokeCommand(commandId, args)
}
emitEvent(event: PluginEventName, payload: unknown): void {
if (!this.options.isPluginSystemEnabled() || this.disposed) {
return
}
deliverPluginEvent({
event,
payload,
plugins: this.discovered,
eventBus: this.eventBus,
workerController: this.workerController,
isRuntimeApproved: (plugin) => this.isRuntimeApproved(plugin),
logWarning: (pluginKey, line) => this.logBuffer.append(pluginKey, 'warn', line)
})
}
async deactivatePlugin(pluginKey: string): Promise<void> {
await this.workerController.deactivate(pluginKey)
this.notifyChanged(false)
}
/** Reconciles live workers and client projections after consent or
* enablement changes without re-reading plugin files or starting workers. */
async reconcileActivationState(): Promise<void> {
const reconcile = this.refreshChain.then(() => this.performActivationStateReconciliation())
this.refreshChain = reconcile.catch(() => undefined)
return reconcile
}
private async performActivationStateReconciliation(): Promise<void> {
this.contentPacksReady = false
await this.contentPacks.reconcile(
this.discovered,
(plugin) => this.activationState(plugin) === 'approved',
this.options.getKeybindings?.()
)
this.contentPacksReady = true
const nextSpecs = collectApprovedWorkerSpecs(this.discovered, (plugin) =>
this.isRuntimeApproved(plugin)
)
await this.workerController.reconcile(nextSpecs)
this.notifyChanged(true)
}
async dispose(): Promise<void> {
this.disposed = true
this.housekeeping.dispose()
this.panels.dispose()
await this.refreshChain.catch(() => undefined)
await this.workerController.dispose()
await this.audit.flush()
}
}
@@ -0,0 +1,137 @@
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { performance } from 'node:perf_hooks'
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
import { fingerprintPluginConsent } from '../../shared/plugins/plugin-consent-fingerprint'
import {
PLUGIN_MANIFEST_FILENAME,
pluginManifestSchema,
qualifiedPluginKey,
type PluginManifest
} from '../../shared/plugins/plugin-manifest'
import { PluginService, type PluginServiceOptions } from './plugin-service'
import type { PluginWorkerFactory } from './plugin-worker-manager'
const PLUGIN_COUNT = 20
const SAMPLE_COUNT = 20
// Real disk I/O, so the number moves with machine load: ~16-34ms idle, higher
// when the suite saturates the box. Sized to catch an order-of-magnitude
// regression rather than scheduling noise — the behavioral assertions below
// (no worker spawned, no plugin code run) are what this test really guards.
const STARTUP_P95_BUDGET_MS = 400
let userDataPath = ''
let markerPaths: string[] = []
let consents: Record<string, string> = {}
function dummyManifest(index: number): PluginManifest {
const key = String.fromCharCode('A'.charCodeAt(0) + index)
return pluginManifestSchema.parse({
manifestVersion: 1,
id: `dummy-${index}`,
publisher: 'startup-budget',
name: `Startup Dummy ${index}`,
version: '1.0.0',
engines: { orca: '>=1.0.0' },
pluginApi: 1,
contributes: {
panels: [],
commands: [
{
id: 'open',
title: `Open Startup Dummy ${index}`,
action: 'view.tasks'
}
],
events: [],
keybindings: [{ command: 'open', key: `Mod+Alt+${key}` }],
languagePacks: [{ locale: 'pt-BR', path: 'locale.json' }]
},
capabilities: []
})
}
async function installDummy(index: number): Promise<{ pluginKey: string; markerPath: string }> {
const manifest = dummyManifest(index)
const pluginKey = qualifiedPluginKey(manifest)
const contentHash = (index + 1).toString(16).padStart(64, '0')
const pluginDir = join(userDataPath, 'plugins', pluginKey)
const versionDir = join(pluginDir, contentHash)
const markerPath = join(userDataPath, `activation-${index}.marker`)
await mkdir(versionDir, { recursive: true })
await Promise.all([
writeFile(join(pluginDir, 'current'), contentHash),
writeFile(join(versionDir, PLUGIN_MANIFEST_FILENAME), JSON.stringify(manifest)),
writeFile(
join(versionDir, 'locale.json'),
JSON.stringify({ startup: { label: `Startup Dummy ${index}` } })
)
])
consents[pluginKey] = fingerprintPluginConsent(manifest)
return { pluginKey, markerPath }
}
function nearestRankP95(samples: readonly number[]): number {
const sorted = [...samples].sort((left, right) => left - right)
return sorted[Math.ceil(sorted.length * 0.95) - 1]!
}
describe('plugin startup budget', () => {
beforeAll(async () => {
userDataPath = await mkdtemp(join(tmpdir(), 'orca-plugin-startup-budget-'))
const installed = await Promise.all(
Array.from({ length: PLUGIN_COUNT }, (_, index) => installDummy(index))
)
markerPaths = installed.map(({ markerPath }) => markerPath)
})
afterAll(async () => {
await rm(userDataPath, { recursive: true, force: true })
})
it('stays below 50ms P95 with 20 approved content packs and executes no plugin code', async () => {
const workerFactory = vi.fn<PluginWorkerFactory>(async () => {
throw new Error('startup must not create a plugin worker')
})
const options: PluginServiceOptions = {
userDataPath,
hostVersion: '1.4.0',
isPluginSystemEnabled: () => true,
getDisabledPlugins: () => [],
getPluginConsents: () => consents,
getDevPluginPaths: () => [],
workerFactory
}
const measure = async (): Promise<number> => {
const startedAt = performance.now()
const service = new PluginService(options)
await service.initialize()
const elapsedMs = performance.now() - startedAt
expect(service.getDiscovered()).toHaveLength(PLUGIN_COUNT)
await service.dispose()
return elapsedMs
}
await measure()
const samples: number[] = []
for (let index = 0; index < SAMPLE_COUNT; index += 1) {
samples.push(await measure())
}
const p95 = nearestRankP95(samples)
if (process.env.ORCA_PLUGIN_STARTUP_BUDGET_REPORT === '1') {
process.stdout.write(`plugin startup P95 ${p95.toFixed(2)}ms (${SAMPLE_COUNT} samples)\n`)
}
expect(workerFactory).not.toHaveBeenCalled()
await Promise.all(
markerPaths.map((markerPath) =>
expect(readFile(markerPath, 'utf8')).rejects.toMatchObject({ code: 'ENOENT' })
)
)
expect(
p95,
`plugin startup P95 ${p95.toFixed(2)}ms; samples: ${samples.map((sample) => sample.toFixed(2)).join(', ')}`
).toBeLessThan(STARTUP_P95_BUDGET_MS)
})
})
@@ -0,0 +1,27 @@
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { PLUGIN_STORAGE_VALUE_MAX_BYTES } from '../../shared/plugins/plugin-host-api'
import { PluginKvStore } from './plugin-storage-store'
const roots: string[] = []
afterEach(async () => {
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })))
})
describe('PluginKvStore limits', () => {
it('enforces the value cap in UTF-8 bytes rather than JavaScript code units', async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-plugin-storage-'))
roots.push(root)
const store = new PluginKvStore(root, 'orca-samples.demo', 'storage.json')
const value = '😀'.repeat(Math.ceil(PLUGIN_STORAGE_VALUE_MAX_BYTES / 4) + 1)
expect(store.set('large', value)).toMatchObject({
ok: false,
error: expect.stringContaining('exceeds')
})
expect(store.get('large')).toBeUndefined()
})
})
+102
View File
@@ -0,0 +1,102 @@
import { existsSync, readFileSync, statSync } from 'node:fs'
import { join } from 'node:path'
import { writeSecureFile } from '../../shared/secure-file'
import { isQualifiedPluginKey } from '../../shared/plugins/plugin-manifest'
import {
PLUGIN_STORAGE_KEY_LIMIT,
PLUGIN_STORAGE_TOTAL_MAX_BYTES,
PLUGIN_STORAGE_VALUE_MAX_BYTES
} from '../../shared/plugins/plugin-host-api'
/**
* Per-plugin JSON key-value persistence backing both `storage.*` (plugin
* data) and `settings.*` (settings:own). Each plugin's data lives in its OWN
* file under `<userData>/plugins-data/<publisher>.<id>/` — never a shared
* namespaced blob, so one plugin's path can never resolve into another's.
* Adapted from community PR #5801's per-plugin settings store.
*/
export function pluginDataDir(pluginsDataDir: string, qualifiedKey: string): string {
if (!isQualifiedPluginKey(qualifiedKey)) {
throw new Error(`unsafe plugin key: ${qualifiedKey}`)
}
return join(pluginsDataDir, qualifiedKey)
}
export type PluginKvWriteResult = { ok: true } | { ok: false; error: string }
export class PluginKvStore {
private readonly filePath: string
constructor(
pluginsDataDir: string,
qualifiedKey: string,
fileName: 'storage.json' | 'settings.json'
) {
this.filePath = join(pluginDataDir(pluginsDataDir, qualifiedKey), fileName)
}
private read(): Record<string, unknown> {
try {
if (!existsSync(this.filePath)) {
return {}
}
if (statSync(this.filePath).size > PLUGIN_STORAGE_TOTAL_MAX_BYTES) {
return {}
}
const parsed: unknown = JSON.parse(readFileSync(this.filePath, 'utf8'))
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
return parsed as Record<string, unknown>
}
} catch {
// Corrupt files reset to empty rather than wedging the plugin.
}
return {}
}
get(key: string): unknown {
return this.read()[key]
}
getAll(): Record<string, unknown> {
return this.read()
}
keys(): string[] {
return Object.keys(this.read())
}
set(key: string, value: unknown): PluginKvWriteResult {
let serialized: string
try {
serialized = JSON.stringify(value)
} catch {
return { ok: false, error: 'value is not JSON-serializable' }
}
if (serialized === undefined) {
return { ok: false, error: 'value is not JSON-serializable' }
}
if (Buffer.byteLength(serialized, 'utf8') > PLUGIN_STORAGE_VALUE_MAX_BYTES) {
return { ok: false, error: `value exceeds ${PLUGIN_STORAGE_VALUE_MAX_BYTES} bytes` }
}
const settings = this.read()
if (!Object.hasOwn(settings, key) && Object.keys(settings).length >= PLUGIN_STORAGE_KEY_LIMIT) {
return { ok: false, error: `storage exceeds the ${PLUGIN_STORAGE_KEY_LIMIT}-key limit` }
}
settings[key] = value
const nextFile = JSON.stringify(settings, null, 2)
if (Buffer.byteLength(nextFile, 'utf8') > PLUGIN_STORAGE_TOTAL_MAX_BYTES) {
return { ok: false, error: `storage exceeds ${PLUGIN_STORAGE_TOTAL_MAX_BYTES} bytes` }
}
writeSecureFile(this.filePath, nextFile)
return { ok: true }
}
delete(key: string): void {
const settings = this.read()
if (Object.hasOwn(settings, key)) {
delete settings[key]
writeSecureFile(this.filePath, JSON.stringify(settings, null, 2))
}
}
}
+98
View File
@@ -0,0 +1,98 @@
/**
* Crash/restart supervision policy for plugin workers — the pure decision
* half of the runtime. Decides whether a worker that exited should be
* restarted (with backoff) or marked errored after too many crashes.
*
* Pure + deterministic: callers own the actual timers and forking; this just
* tracks per-plugin state and returns decisions. Ported from community PR
* #5801 (gsxdsm).
*/
export type PluginRunState = 'inactive' | 'running' | 'restarting' | 'errored'
export type PluginExitInfo = {
/** Clean exit from a host-initiated deactivate vs. an unexpected crash. */
crashed: boolean
}
export type PluginRestartDecision =
| { restart: true; delayMs: number; attempt: number }
| { restart: false; state: PluginRunState }
export type PluginSupervisionConfig = {
/** Max crash-restarts before a plugin is marked errored. `0` means no
* restart attempts — the first crash goes straight to errored. */
maxRestarts: number
/** Backoff schedule indexed by attempt; the last entry is reused past its
* end. Must be non-empty (enforced in the constructor). */
backoffMs: number[]
}
const DEFAULT_CONFIG: PluginSupervisionConfig = {
maxRestarts: 3,
backoffMs: [500, 2000, 5000]
}
type Entry = { state: PluginRunState; restarts: number }
export class PluginSupervisor {
private readonly entries = new Map<string, Entry>()
private readonly config: PluginSupervisionConfig
constructor(config: Partial<PluginSupervisionConfig> = {}) {
this.config = { ...DEFAULT_CONFIG, ...config }
// Guard misconfiguration: an empty backoff schedule would index [-1] →
// undefined delay (immediate restart loop); a negative cap is meaningless.
if (this.config.maxRestarts < 0) {
throw new Error('PluginSupervisionConfig.maxRestarts must be >= 0')
}
if (this.config.backoffMs.length === 0) {
throw new Error('PluginSupervisionConfig.backoffMs must be non-empty')
}
}
getState(id: string): PluginRunState {
return this.entries.get(id)?.state ?? 'inactive'
}
restartCount(id: string): number {
return this.entries.get(id)?.restarts ?? 0
}
/** Mark a plugin as running. A fresh activation (not a restart) resets the
* crash counter so a previously-flaky plugin gets a clean slate. */
markRunning(id: string, options: { resetRestarts?: boolean } = {}): void {
const prior = this.entries.get(id)
this.entries.set(id, {
state: 'running',
restarts: options.resetRestarts ? 0 : (prior?.restarts ?? 0)
})
}
/** Record that the worker exited and decide what to do next. */
markExited(id: string, info: PluginExitInfo): PluginRestartDecision {
if (!info.crashed) {
// Host-initiated stop (or idle reap): go inactive, clear history.
this.entries.set(id, { state: 'inactive', restarts: 0 })
return { restart: false, state: 'inactive' }
}
const entry = this.entries.get(id)
// An exit for an untracked plugin is not a running crash to restart.
if (!entry) {
return { restart: false, state: 'inactive' }
}
if (entry.restarts >= this.config.maxRestarts) {
this.entries.set(id, { state: 'errored', restarts: entry.restarts })
return { restart: false, state: 'errored' }
}
const attempt = entry.restarts + 1
const idx = Math.max(0, Math.min(entry.restarts, this.config.backoffMs.length - 1))
this.entries.set(id, { state: 'restarting', restarts: attempt })
return { restart: true, delayMs: this.config.backoffMs[idx]!, attempt }
}
/** Clear all state (deactivate/remove or a manual re-enable). */
reset(id: string): void {
this.entries.delete(id)
}
}
@@ -0,0 +1,169 @@
import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { fingerprintPluginConsent } from '../../shared/plugins/plugin-consent-fingerprint'
import { pluginManifestSchema } from '../../shared/plugins/plugin-manifest'
import { hashPluginTree } from './plugin-content-hash'
import type { ValidDiscoveredPlugin } from './plugin-discovery'
import { PluginVmRecipeRegistry } from './plugin-vm-recipe-registry'
const roots: string[] = []
afterEach(async () => {
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })))
})
async function recipePlugin(
id: string,
artifacts: { path: string; recipe: unknown }[]
): Promise<ValidDiscoveredPlugin> {
const rootDir = await mkdtemp(join(tmpdir(), 'orca-plugin-vm-recipe-'))
roots.push(rootDir)
await mkdir(join(rootDir, 'recipes'))
await Promise.all(
artifacts.map((artifact) =>
writeFile(join(rootDir, artifact.path), JSON.stringify(artifact.recipe), 'utf8')
)
)
const manifest = pluginManifestSchema.parse({
manifestVersion: 1,
id,
publisher: 'orca-samples',
name: id,
version: '1.0.0',
engines: { orca: '>=1.0.0' },
pluginApi: 1,
contributes: { vmRecipes: artifacts.map((artifact) => ({ path: artifact.path })) },
capabilities: []
})
const content = await hashPluginTree(rootDir)
if (!content.ok) {
throw new Error(content.error)
}
return {
pluginKey: `orca-samples.${id}`,
rootDir,
manifest,
consentFingerprint: fingerprintPluginConsent(manifest, content.hash),
consentContentHash: content.hash,
contentHash: null,
isDev: true
}
}
function artifact(id: string): {
schemaVersion: 1
id: string
name: string
create: string
suspend: string
resume: string
destroy: string
} {
return {
schemaVersion: 1,
id,
name: `Recipe ${id}`,
create: `create-${id}`,
suspend: `suspend-${id}`,
resume: `resume-${id}`,
destroy: `destroy-${id}`
}
}
describe('PluginVmRecipeRegistry', () => {
it('retains pending previews and exposes only approved recipes', async () => {
const plugin = await recipePlugin('recipes', [
{ path: 'recipes/cloud.json', recipe: artifact('cloud') }
])
const registry = new PluginVmRecipeRegistry()
await registry.reconcile([plugin], () => false)
expect(registry.list()).toEqual([])
expect(registry.preview(plugin.pluginKey)).toMatchObject([
{ pluginKey: plugin.pluginKey, recipe: { id: 'cloud', create: 'create-cloud' } }
])
await registry.reconcile([plugin], () => true)
expect(registry.list()).toMatchObject([{ recipe: { id: 'cloud' } }])
})
it('rejects malformed artifacts and duplicate ids within one plugin', async () => {
const malformed = await recipePlugin('malformed', [
{
path: 'recipes/bad.json',
recipe: { schemaVersion: 1, id: 'bad', name: 'Bad', create: 'create', suspend: 'stop' }
}
])
const duplicate = await recipePlugin('duplicate', [
{ path: 'recipes/one.json', recipe: artifact('same') },
{ path: 'recipes/two.json', recipe: artifact('same') }
])
const registry = new PluginVmRecipeRegistry()
await registry.reconcile([malformed, duplicate], () => true)
expect(registry.list()).toEqual([])
expect(registry.error(malformed.pluginKey)).toContain('suspend and resume')
expect(registry.error(duplicate.pluginKey)).toContain('duplicate VM recipe id')
})
it('errors every approved plugin that contributes the same global id', async () => {
const first = await recipePlugin('first', [
{ path: 'recipes/shared.json', recipe: artifact('shared') }
])
const second = await recipePlugin('second', [
{ path: 'recipes/shared.json', recipe: artifact('shared') }
])
const registry = new PluginVmRecipeRegistry()
await registry.reconcile([first, second], () => true)
expect(registry.list()).toEqual([])
expect(registry.error(first.pluginKey)).toContain('multiple plugins')
expect(registry.error(second.pluginKey)).toContain('multiple plugins')
})
it('deactivates disabled recipes and removes previews after uninstall', async () => {
const plugin = await recipePlugin('lifecycle', [
{ path: 'recipes/cloud.json', recipe: artifact('cloud') }
])
const registry = new PluginVmRecipeRegistry()
await registry.reconcile([plugin], () => true)
expect(registry.list()).toHaveLength(1)
await registry.reconcile([plugin], () => false)
expect(registry.list()).toEqual([])
expect(registry.preview(plugin.pluginKey)).toHaveLength(1)
await registry.reconcile([], () => false)
expect(registry.preview(plugin.pluginKey)).toEqual([])
expect(registry.error(plugin.pluginKey)).toBeNull()
})
it('refuses recipe bytes changed after the reviewed content identity', async () => {
const plugin = await recipePlugin('mutable', [
{ path: 'recipes/cloud.json', recipe: artifact('cloud') }
])
// Exercise the installed-tree identity as well as mutable dev previews.
plugin.contentHash = plugin.consentContentHash ?? null
const registry = new PluginVmRecipeRegistry()
await registry.reconcile([plugin], () => true)
expect(registry.list()).toHaveLength(1)
await writeFile(
join(plugin.rootDir, 'recipes', 'cloud.json'),
JSON.stringify({ ...artifact('cloud'), create: 'changed-after-review' }),
'utf8'
)
await registry.reconcile([plugin], () => true)
expect(registry.list()).toEqual([])
expect(registry.preview(plugin.pluginKey)).toEqual([])
expect(registry.error(plugin.pluginKey)).toContain('changed since it was reviewed')
})
})
@@ -0,0 +1,127 @@
import type { OrcaVmRecipe } from '../../shared/types'
import { parsePluginVmRecipeArtifact } from '../../shared/plugins/plugin-vm-recipe-artifact'
import {
PLUGIN_VM_RECIPE_MAX_BYTES,
readContainedPluginArtifactText
} from './plugin-artifact-validation'
import { mapWithConcurrency } from '../../shared/map-with-concurrency'
import {
isInvalidDiscoveredPlugin,
type DiscoveredPlugin,
type ValidDiscoveredPlugin
} from './plugin-discovery'
import { verifyInstructionalPluginContent } from './plugin-instructional-content-integrity'
const VM_RECIPE_LOAD_CONCURRENCY = 4
export type PluginVmRecipeRegistration = {
pluginKey: string
recipe: OrcaVmRecipe
}
type VmRecipeLoadResult =
| {
pluginKey: string
approved: boolean
registrations: PluginVmRecipeRegistration[]
}
| { pluginKey: string; error: string }
export class PluginVmRecipeRegistry {
private active: PluginVmRecipeRegistration[] = []
private readonly previews = new Map<string, PluginVmRecipeRegistration[]>()
private readonly errors = new Map<string, string>()
list(): readonly PluginVmRecipeRegistration[] {
return this.active
}
preview(pluginKey: string): readonly PluginVmRecipeRegistration[] {
return this.previews.get(pluginKey) ?? []
}
error(pluginKey: string): string | null {
return this.errors.get(pluginKey) ?? null
}
async reconcile(
discovered: readonly DiscoveredPlugin[],
isApproved: (plugin: ValidDiscoveredPlugin) => boolean
): Promise<void> {
const candidates = discovered.filter(
(plugin): plugin is ValidDiscoveredPlugin =>
!isInvalidDiscoveredPlugin(plugin) && plugin.manifest.contributes.vmRecipes.length > 0
)
const results = await mapWithConcurrency(
candidates,
VM_RECIPE_LOAD_CONCURRENCY,
async (plugin): Promise<VmRecipeLoadResult> => {
try {
const approved = isApproved(plugin)
const registrations: PluginVmRecipeRegistration[] = []
const seen = new Set<string>()
for (const contribution of plugin.manifest.contributes.vmRecipes) {
const recipe = parsePluginVmRecipeArtifact(
await readContainedPluginArtifactText(
plugin.rootDir,
contribution.path,
PLUGIN_VM_RECIPE_MAX_BYTES
)
)
if (seen.has(recipe.id)) {
throw new Error(`duplicate VM recipe id "${recipe.id}"`)
}
seen.add(recipe.id)
registrations.push({ pluginKey: plugin.pluginKey, recipe })
}
// Verify after reading so the in-memory commands shown/activated are
// bound to the exact tree identity the user reviewed.
await verifyInstructionalPluginContent(plugin)
return { pluginKey: plugin.pluginKey, approved, registrations }
} catch (error) {
return {
pluginKey: plugin.pluginKey,
error: error instanceof Error ? error.message : String(error)
}
}
}
)
this.previews.clear()
this.errors.clear()
for (const result of results) {
if ('error' in result) {
this.errors.set(result.pluginKey, result.error)
} else {
this.previews.set(result.pluginKey, result.registrations)
}
}
const approved = results.filter(
(result): result is Extract<VmRecipeLoadResult, { approved: boolean }> =>
'approved' in result && result.approved
)
const owners = new Map<string, Set<string>>()
for (const result of approved) {
for (const registration of result.registrations) {
const recipeOwners = owners.get(registration.recipe.id) ?? new Set<string>()
recipeOwners.add(result.pluginKey)
owners.set(registration.recipe.id, recipeOwners)
}
}
const conflicted = new Set<string>()
for (const [recipeId, recipeOwners] of owners) {
if (recipeOwners.size > 1) {
for (const pluginKey of recipeOwners) {
conflicted.add(pluginKey)
this.errors.set(
pluginKey,
`VM recipe id "${recipeId}" is contributed by multiple plugins`
)
}
}
}
this.active = approved
.filter((result) => !conflicted.has(result.pluginKey))
.flatMap((result) => result.registrations)
}
}
@@ -0,0 +1,166 @@
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { createPluginExtensionRegistry } from '../../shared/plugins/plugin-extension-registry'
import { pluginManifestSchema } from '../../shared/plugins/plugin-manifest'
import type { PluginContentVerifier } from './plugin-content-integrity'
import type { ValidDiscoveredPlugin } from './plugin-discovery'
import type { PluginWorkerHandle } from './plugin-host-process'
import { PluginWorkerController } from './plugin-worker-controller'
import type { PluginWorkerFactory } from './plugin-worker-manager'
const roots: string[] = []
afterEach(async () => {
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })))
})
async function plugin(): Promise<ValidDiscoveredPlugin> {
const rootDir = await mkdtemp(join(tmpdir(), 'orca-plugin-worker-controller-'))
roots.push(rootDir)
await writeFile(join(rootDir, 'main.mjs'), 'export default function activate() {}')
return {
pluginKey: 'orca-samples.demo',
rootDir,
manifest: pluginManifestSchema.parse({
manifestVersion: 1,
id: 'demo',
publisher: 'orca-samples',
name: 'Demo',
version: '1.0.0',
engines: { orca: '>=1.0.0' },
pluginApi: 1,
main: 'main.mjs',
contributes: {
panels: [],
commands: [{ id: 'run', title: 'Run' }],
events: []
},
capabilities: []
}),
consentFingerprint: 'sha256-current',
contentHash: null,
isDev: true
}
}
function worker(commands: string[]): PluginWorkerHandle & { dispose: ReturnType<typeof vi.fn> } {
return {
commands,
invokeCommand: vi.fn(async () => null),
deliverEvent: vi.fn(),
lastActivityAt: () => Date.now(),
inFlightCount: () => 0,
dispose: vi.fn(async () => undefined),
kill: vi.fn(),
onExit: vi.fn()
}
}
function controller(options: {
factory: PluginWorkerFactory
verify: () => Promise<void>
isApproved: () => boolean
}): PluginWorkerController {
return new PluginWorkerController({
entryPath: '/host-entry.js',
workerFactory: options.factory,
registry: createPluginExtensionRegistry(),
contentVerifier: { verify: options.verify } as unknown as PluginContentVerifier,
capabilities: () => (options.isApproved() ? [] : null),
isCurrentApproved: () => options.isApproved(),
invokeCommand: vi.fn(async () => null),
executeHostCall: vi.fn(async () => ({ ok: true as const, value: null })),
log: vi.fn(),
onStateChanged: vi.fn(),
onWorkerGone: vi.fn()
})
}
describe('PluginWorkerController activation authority', () => {
it('does not start code after approval is revoked during integrity verification', async () => {
const subjectPlugin = await plugin()
let approved = true
let finishVerification!: () => void
const verification = new Promise<void>((resolve) => {
finishVerification = resolve
})
const factory = vi.fn<PluginWorkerFactory>()
const subject = controller({ factory, verify: () => verification, isApproved: () => approved })
const activation = subject.ensure(subjectPlugin)
approved = false
finishVerification()
await expect(activation).rejects.toThrow('no longer approved')
expect(factory).not.toHaveBeenCalled()
await subject.dispose()
})
it('disposes a worker whose approval changes while the process starts', async () => {
const subjectPlugin = await plugin()
let approved = true
let finishStart!: (handle: PluginWorkerHandle) => void
const factory = vi.fn<PluginWorkerFactory>(
() => new Promise<PluginWorkerHandle>((resolve) => (finishStart = resolve))
)
const subject = controller({
factory,
verify: async () => undefined,
isApproved: () => approved
})
const startedWorker = worker(['run'])
const activation = subject.ensure(subjectPlugin)
await vi.waitFor(() => expect(factory).toHaveBeenCalledOnce())
approved = false
finishStart(startedWorker)
await expect(activation).rejects.toThrow('disabled during activation')
expect(startedWorker.dispose).toHaveBeenCalledOnce()
await subject.dispose()
})
it('rejects and stops workers that register undeclared commands', async () => {
const subjectPlugin = await plugin()
const startedWorker = worker(['run', 'undeclared'])
const subject = controller({
factory: vi.fn<PluginWorkerFactory>().mockResolvedValue(startedWorker),
verify: async () => undefined,
isApproved: () => true
})
await expect(subject.ensure(subjectPlugin)).rejects.toThrow(
'registered undeclared command undeclared'
)
expect(startedWorker.dispose).toHaveBeenCalledOnce()
await subject.dispose()
})
it('rejects workers that register declarative action aliases', async () => {
const base = await plugin()
const subjectPlugin: ValidDiscoveredPlugin = {
...base,
manifest: pluginManifestSchema.parse({
...base.manifest,
contributes: {
...base.manifest.contributes,
commands: [{ id: 'tasks', title: 'Tasks', action: 'view.tasks' }]
}
})
}
const startedWorker = worker(['tasks'])
const subject = controller({
factory: vi.fn<PluginWorkerFactory>().mockResolvedValue(startedWorker),
verify: async () => undefined,
isApproved: () => true
})
await expect(subject.ensure(subjectPlugin)).rejects.toThrow(
'registered undeclared command tasks'
)
expect(startedWorker.dispose).toHaveBeenCalledOnce()
await subject.dispose()
})
})
@@ -0,0 +1,171 @@
import type { PluginCapabilityKind } from '../../shared/plugins/plugin-capabilities'
import type { PluginEventName } from '../../shared/plugins/plugin-manifest'
import type { PluginPanelActionOutcome } from '../../shared/plugins/plugin-panel-bridge'
import {
PLUGIN_COMMAND_EXTENSION_POINT,
type PluginExtensionRegistry
} from '../../shared/plugins/plugin-extension-registry'
import type { ValidDiscoveredPlugin } from './plugin-discovery'
import { resolveContainedPluginArtifact } from './plugin-artifact-validation'
import type { PluginContentVerifier } from './plugin-content-integrity'
import {
PluginWorkerManager,
type PluginWorkerFactory,
type PluginWorkerSpawnSpec
} from './plugin-worker-manager'
import { buildPluginWorkerSpawnSpec, pluginWorkerSpawnSpecsEqual } from './plugin-worker-spawn-spec'
import type { PluginWorkerHandle } from './plugin-host-process'
import type { PluginRunState } from './plugin-supervisor'
export type PluginWorkerControllerOptions = {
entryPath: string
maxActive?: number
idleReapMs?: number
workerFactory?: PluginWorkerFactory
registry: PluginExtensionRegistry
contentVerifier: PluginContentVerifier
capabilities: (pluginKey: string) => readonly PluginCapabilityKind[] | null
isCurrentApproved: (plugin: ValidDiscoveredPlugin) => boolean
invokeCommand: (pluginKey: string, commandId: string, args: unknown) => Promise<unknown>
executeHostCall: (
pluginKey: string,
method: string,
params: unknown
) => Promise<PluginPanelActionOutcome>
log: (pluginKey: string, level: 'info' | 'warn' | 'error', line: string) => void
onStateChanged: (pluginKey: string) => void
onWorkerGone: (pluginKey: string) => void
}
export class PluginWorkerController {
private readonly manager: PluginWorkerManager
private readonly activationErrors = new Map<string, string>()
private readonly registeredSpecs = new Map<string, PluginWorkerSpawnSpec>()
constructor(private readonly options: PluginWorkerControllerOptions) {
this.manager = new PluginWorkerManager({
entryPath: options.entryPath,
maxActive: options.maxActive,
idleReapMs: options.idleReapMs,
workerFactory: options.workerFactory,
executeHostCall: options.executeHostCall,
log: options.log,
onWorkerStateChange: options.onStateChanged,
onWorkerGone: options.onWorkerGone
})
}
state(pluginKey: string): { state: PluginRunState; restarts: number } {
return {
state: this.manager.runState(pluginKey),
restarts: this.manager.restartCount(pluginKey)
}
}
activationError(pluginKey: string): string | null {
return this.activationErrors.get(pluginKey) ?? null
}
async ensure(plugin: ValidDiscoveredPlugin): Promise<PluginWorkerHandle> {
if (!plugin.manifest.main) {
throw new Error(`plugin ${plugin.pluginKey} has no worker entry`)
}
try {
this.assertCurrentApproved(plugin)
await this.options.contentVerifier.verify(plugin)
await resolveContainedPluginArtifact(plugin.rootDir, plugin.manifest.main)
this.assertCurrentApproved(plugin)
const capabilities = this.options.capabilities(plugin.pluginKey)
if (!capabilities) {
throw new Error(`plugin ${plugin.pluginKey} is no longer approved`)
}
const spec = buildPluginWorkerSpawnSpec(plugin, capabilities)
const handle = await this.manager.ensureActive(spec)
if (!this.options.isCurrentApproved(plugin)) {
await this.manager.deactivate(plugin.pluginKey)
throw new Error(`plugin ${plugin.pluginKey} changed or was disabled during activation`)
}
const declaredCommands = new Set(
plugin.manifest.contributes.commands
.filter((command) => command.action === undefined)
.map((command) => command.id)
)
const undeclaredCommand = handle.commands.find((command) => !declaredCommands.has(command))
if (undeclaredCommand) {
await this.manager.deactivate(plugin.pluginKey)
throw new Error(
`plugin ${plugin.pluginKey} registered undeclared command ${undeclaredCommand}`
)
}
this.activationErrors.delete(plugin.pluginKey)
this.registerCommands(plugin, spec, handle.commands)
return handle
} catch (error) {
this.activationErrors.set(
plugin.pluginKey,
error instanceof Error ? error.message : String(error)
)
this.options.onStateChanged(plugin.pluginKey)
throw error
}
}
private assertCurrentApproved(plugin: ValidDiscoveredPlugin): void {
if (!this.options.isCurrentApproved(plugin)) {
throw new Error(`plugin ${plugin.pluginKey} changed or is no longer approved`)
}
}
async reconcile(nextSpecs: ReadonlyMap<string, PluginWorkerSpawnSpec>): Promise<void> {
const current = new Map([...this.registeredSpecs, ...this.manager.trackedSpecs()])
for (const [pluginKey, spec] of current) {
const next = nextSpecs.get(pluginKey)
if (next && pluginWorkerSpawnSpecsEqual(spec, next)) {
continue
}
this.options.registry.clearPlugin(pluginKey)
this.registeredSpecs.delete(pluginKey)
this.activationErrors.delete(pluginKey)
await this.manager.deactivate(pluginKey)
}
}
async deactivate(pluginKey: string): Promise<void> {
this.options.registry.clearPlugin(pluginKey)
this.registeredSpecs.delete(pluginKey)
this.activationErrors.delete(pluginKey)
await this.manager.deactivate(pluginKey)
}
reapIdle(): void {
this.manager.reapIdle()
}
deliverEventIfRunning(pluginKey: string, event: PluginEventName, payload: unknown): void {
this.manager.deliverEventIfRunning(pluginKey, event, payload)
}
dispose(): Promise<void> {
return this.manager.disposeAll()
}
private registerCommands(
plugin: ValidDiscoveredPlugin,
spec: PluginWorkerSpawnSpec,
commands: readonly string[]
): void {
this.options.registry.clearPlugin(plugin.pluginKey)
for (const commandId of commands) {
this.options.registry.register(
PLUGIN_COMMAND_EXTENSION_POINT,
plugin.pluginKey,
{
commandId,
invoke: (args) => this.options.invokeCommand(plugin.pluginKey, commandId, args)
},
commandId
)
}
this.registeredSpecs.set(plugin.pluginKey, spec)
}
}
@@ -0,0 +1,21 @@
import { describe, expect, it } from 'vitest'
import { buildPluginWorkerEnv } from './plugin-worker-env'
describe('buildPluginWorkerEnv', () => {
it('matches allowlisted keys case-sensitively on POSIX', () => {
expect(
buildPluginWorkerEnv(
{ PATH: '/safe', path: '/wrong', HOME: '/home', NODE_OPTIONS: '--inspect' },
'linux'
)
).toEqual({ PATH: '/safe', HOME: '/home', ELECTRON_RUN_AS_NODE: '1' })
})
it('matches Windows environment keys case-insensitively', () => {
expect(buildPluginWorkerEnv({ Path: 'C:\\safe', systemroot: 'C:\\Windows' }, 'win32')).toEqual({
PATH: 'C:\\safe',
SystemRoot: 'C:\\Windows',
ELECTRON_RUN_AS_NODE: '1'
})
})
})
+52
View File
@@ -0,0 +1,52 @@
/**
* Scrubbed environment for plugin workers. Deliberately an allowlist — the
* app's own environment can carry secrets (tokens exported in the user's
* shell, CI credentials); plugins must not inherit it. This intentionally
* diverges from the sidecar precedent, which spreads the full process.env.
*/
const WORKER_ENV_ALLOWLIST = [
'PATH',
'HOME',
'USERPROFILE',
'LANG',
'LC_ALL',
'LC_CTYPE',
'TZ',
'TMPDIR',
'TEMP',
'TMP',
// Why: Windows Node/libuv need these to resolve DLLs and the machine root.
'SYSTEMROOT',
'SYSTEMDRIVE',
'WINDIR',
'COMSPEC',
'PATHEXT',
'PROCESSOR_ARCHITECTURE',
'NUMBER_OF_PROCESSORS'
] as const
export function buildPluginWorkerEnv(
baseEnv: NodeJS.ProcessEnv = process.env,
platform: NodeJS.Platform = process.platform
): Record<string, string> {
const env: Record<string, string> = {}
const windowsLookup = new Map<string, string>()
if (platform === 'win32') {
// Why: Windows environment keys are case-insensitive, while POSIX keys
// are not; folding on every platform could promote an attacker-set `path`.
for (const [key, value] of Object.entries(baseEnv)) {
if (typeof value === 'string') {
windowsLookup.set(key.toUpperCase(), value)
}
}
}
for (const key of WORKER_ENV_ALLOWLIST) {
const value = platform === 'win32' ? windowsLookup.get(key) : baseEnv[key]
if (value !== undefined) {
env[key === 'SYSTEMROOT' ? 'SystemRoot' : key] = value
}
}
env.ELECTRON_RUN_AS_NODE = '1'
return env
}
@@ -0,0 +1,375 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { PluginWorkerHandle } from './plugin-host-process'
import {
PluginWorkerManager,
type PluginWorkerFactory,
type PluginWorkerSpawnSpec
} from './plugin-worker-manager'
type TestWorker = PluginWorkerHandle & {
exit(code?: number | null): void
dispose: ReturnType<typeof vi.fn<() => Promise<void>>>
}
function worker(lastActivity = Date.now()): TestWorker {
const exitCallbacks: ((code: number | null) => void)[] = []
return {
commands: ['run'],
invokeCommand: vi.fn(async () => null),
deliverEvent: vi.fn(),
lastActivityAt: () => lastActivity,
inFlightCount: () => 0,
dispose: vi.fn(async () => undefined),
kill: vi.fn(),
onExit: (callback) => exitCallbacks.push(callback),
exit: (code = 1) => {
for (const callback of exitCallbacks) {
callback(code)
}
}
}
}
function spec(pluginKey: string): PluginWorkerSpawnSpec {
return {
pluginKey,
rootDir: `/plugins/${pluginKey}`,
mainEntry: 'worker.js',
grantedCapabilities: []
}
}
function manager(
factory: PluginWorkerFactory,
options: { maxActive?: number; idleReapMs?: number } = {}
): PluginWorkerManager {
return new PluginWorkerManager({
entryPath: '/host.js',
workerFactory: factory,
maxActive: options.maxActive,
idleReapMs: options.idleReapMs,
executeHostCall: async () => ({ ok: true, value: null }),
log: vi.fn(),
onWorkerStateChange: vi.fn(),
onWorkerGone: vi.fn()
})
}
async function flush(): Promise<void> {
await Promise.resolve()
await Promise.resolve()
await Promise.resolve()
}
afterEach(() => {
vi.useRealTimers()
})
describe('PluginWorkerManager capacity', () => {
it('atomically counts in-flight starts against maxActive', async () => {
const starts: { key: string; resolve: (handle: TestWorker) => void }[] = []
const factory = vi.fn<PluginWorkerFactory>(
({ pluginId }) => new Promise((resolve) => starts.push({ key: pluginId, resolve }))
)
const subject = manager(factory, { maxActive: 1 })
const first = subject.ensureActive(spec('one'))
const second = subject.ensureActive(spec('two'))
const third = subject.ensureActive(spec('three'))
await flush()
expect(starts.map((start) => start.key)).toEqual(['one'])
starts[0]!.resolve(worker())
await first
await subject.deactivate('one')
await flush()
expect(starts.map((start) => start.key)).toEqual(['one', 'two'])
starts[1]!.resolve(worker())
await second
await subject.deactivate('two')
await flush()
expect(starts.map((start) => start.key)).toEqual(['one', 'two', 'three'])
starts[2]!.resolve(worker())
await third
await subject.disposeAll()
})
it('removes a cancelled waiter without disturbing FIFO order', async () => {
const starts: { key: string; resolve: (handle: TestWorker) => void }[] = []
const factory = vi.fn<PluginWorkerFactory>(
({ pluginId }) => new Promise((resolve) => starts.push({ key: pluginId, resolve }))
)
const subject = manager(factory, { maxActive: 1 })
const first = subject.ensureActive(spec('one'))
const cancelled = subject.ensureActive(spec('two'))
const third = subject.ensureActive(spec('three'))
await flush()
starts[0]!.resolve(worker())
await first
await subject.deactivate('two')
await expect(cancelled).rejects.toThrow('cancelled')
await subject.deactivate('one')
await flush()
expect(starts.map((start) => start.key)).toEqual(['one', 'three'])
starts[1]!.resolve(worker())
await third
await subject.disposeAll()
})
it('releases a failed start so the next FIFO waiter can run', async () => {
vi.useFakeTimers()
const secondWorker = worker()
const factory = vi.fn<PluginWorkerFactory>(async ({ pluginId }) => {
if (pluginId === 'one') {
throw new Error('ready failed')
}
return secondWorker
})
const subject = manager(factory, { maxActive: 1 })
const first = subject.ensureActive(spec('one'))
const firstSettled = first.catch(() => undefined)
const second = subject.ensureActive(spec('two'))
await flush()
await expect(second).resolves.toBe(secondWorker)
expect(factory.mock.calls.map(([options]) => options.pluginId)).toEqual(['one', 'two'])
await subject.deactivate('one')
await firstSettled
await subject.disposeAll()
})
it('cancels an in-flight start without allowing its generation to land', async () => {
const factory = vi.fn<PluginWorkerFactory>(
({ signal }) =>
new Promise((_resolve, reject) => {
signal.addEventListener('abort', () => reject(new Error('factory cancelled')), {
once: true
})
})
)
const subject = manager(factory)
const activation = subject.ensureActive(spec('starting'))
await flush()
await subject.deactivate('starting')
await expect(activation).rejects.toThrow('cancelled')
expect(subject.runState('starting')).toBe('inactive')
expect(subject.trackedSpecs().has('starting')).toBe(false)
await subject.disposeAll()
})
it('disposes running workers and rejects queued waiters', async () => {
const first = worker()
const factory = vi.fn<PluginWorkerFactory>(async ({ pluginId }) => {
if (pluginId === 'one') {
return first
}
return new Promise<PluginWorkerHandle>(() => undefined)
})
const subject = manager(factory, { maxActive: 1 })
await subject.ensureActive(spec('one'))
const queued = subject.ensureActive(spec('two'))
const queuedSettled = queued.catch((error) => error)
await flush()
await subject.disposeAll()
expect(first.dispose).toHaveBeenCalledOnce()
await expect(queuedSettled).resolves.toBeInstanceOf(Error)
expect(factory).toHaveBeenCalledTimes(1)
})
})
describe('PluginWorkerManager restart policy', () => {
it('cancels a stale in-flight revision instead of joining it by plugin key', async () => {
const currentWorker = worker()
const factory = vi.fn<PluginWorkerFactory>(({ rootDir, signal }) => {
if (rootDir === '/plugins/old') {
return new Promise((_resolve, reject) => {
signal.addEventListener('abort', () => reject(new Error('old revision cancelled')), {
once: true
})
})
}
return Promise.resolve(currentWorker)
})
const subject = manager(factory)
const oldSpec = { ...spec('demo'), rootDir: '/plugins/old', manifestRevision: 'old' }
const newSpec = { ...spec('demo'), rootDir: '/plugins/new', manifestRevision: 'new' }
const oldActivation = subject.ensureActive(oldSpec)
await flush()
const currentActivation = subject.ensureActive(newSpec)
await expect(oldActivation).rejects.toThrow('cancelled')
await expect(currentActivation).resolves.toBe(currentWorker)
expect(factory.mock.calls.map(([options]) => options.rootDir)).toEqual([
'/plugins/old',
'/plugins/new'
])
await subject.disposeAll()
})
it('retries startup failures at 500/2000/5000ms before errored', async () => {
vi.useFakeTimers()
const factory = vi.fn<PluginWorkerFactory>(async () => {
throw new Error('not ready')
})
const subject = manager(factory)
const activation = subject.ensureActive(spec('demo'))
let failure: unknown
const settled = activation.catch((error) => {
failure = error
})
await flush()
expect(factory).toHaveBeenCalledTimes(1)
expect(subject.restartCount('demo')).toBe(1)
expect(subject.runState('demo')).toBe('restarting')
await vi.advanceTimersByTimeAsync(499)
expect(factory).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(1)
expect(factory).toHaveBeenCalledTimes(2)
await vi.advanceTimersByTimeAsync(2_000)
expect(factory).toHaveBeenCalledTimes(3)
await vi.advanceTimersByTimeAsync(5_000)
await settled
expect(factory).toHaveBeenCalledTimes(4)
expect(subject.runState('demo')).toBe('errored')
expect(failure).toBeInstanceOf(Error)
await subject.disposeAll()
})
it('joins triggers during backoff without resetting restart history', async () => {
vi.useFakeTimers()
const ready = worker()
const factory = vi.fn<PluginWorkerFactory>(async () => {
if (factory.mock.calls.length === 1) {
throw new Error('first start failed')
}
return ready
})
const subject = manager(factory)
const first = subject.ensureActive(spec('demo'))
await flush()
const joined = subject.ensureActive(spec('demo'))
expect(subject.restartCount('demo')).toBe(1)
expect(factory).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(500)
await expect(Promise.all([first, joined])).resolves.toEqual([ready, ready])
expect(factory).toHaveBeenCalledTimes(2)
expect(subject.restartCount('demo')).toBe(1)
await subject.disposeAll()
})
it('applies the same backoff history to unexpected post-ready exits', async () => {
vi.useFakeTimers()
const workers = [worker(), worker(), worker(), worker()]
const factory = vi.fn<PluginWorkerFactory>(async () => workers[factory.mock.calls.length - 1]!)
const subject = manager(factory)
await subject.ensureActive(spec('demo'))
workers[0]!.exit(11)
expect(subject.runState('demo')).toBe('restarting')
await vi.advanceTimersByTimeAsync(500)
expect(factory).toHaveBeenCalledTimes(2)
workers[1]!.exit(12)
expect(subject.runState('demo')).toBe('restarting')
await vi.advanceTimersByTimeAsync(2_000)
expect(factory).toHaveBeenCalledTimes(3)
workers[2]!.exit(13)
expect(subject.runState('demo')).toBe('restarting')
await vi.advanceTimersByTimeAsync(5_000)
expect(factory).toHaveBeenCalledTimes(4)
workers[3]!.exit(14)
expect(subject.runState('demo')).toBe('errored')
expect(subject.restartCount('demo')).toBe(3)
await subject.disposeAll()
})
it('cancels a pending restart and never resurrects after deactivate', async () => {
vi.useFakeTimers()
const first = worker()
const factory = vi.fn<PluginWorkerFactory>(async () => first)
const subject = manager(factory)
await subject.ensureActive(spec('demo'))
first.exit()
expect(subject.restartCount('demo')).toBe(1)
await subject.deactivate('demo')
await vi.advanceTimersByTimeAsync(10_000)
expect(factory).toHaveBeenCalledTimes(1)
expect(subject.runState('demo')).toBe('inactive')
await subject.disposeAll()
})
})
describe('PluginWorkerManager idle reap', () => {
it('does not reap a worker while an event handler is still in flight', async () => {
const busy = worker(100)
busy.inFlightCount = () => 1
const subject = manager(vi.fn<PluginWorkerFactory>().mockResolvedValue(busy), {
idleReapMs: 100
})
await subject.ensureActive(spec('demo'))
subject.reapIdle(10_000)
expect(busy.dispose).not.toHaveBeenCalled()
expect(subject.runState('demo')).toBe('running')
await subject.disposeAll()
})
it('disposes an idle worker and activates a fresh generation on demand', async () => {
const first = worker(100)
const second = worker(1_000)
const factory = vi
.fn<PluginWorkerFactory>()
.mockResolvedValueOnce(first)
.mockResolvedValueOnce(second)
const subject = manager(factory, { idleReapMs: 100 })
await subject.ensureActive(spec('demo'))
subject.reapIdle(201)
await flush()
expect(first.dispose).toHaveBeenCalledOnce()
expect(subject.runState('demo')).toBe('inactive')
await expect(subject.ensureActive(spec('demo'))).resolves.toBe(second)
await subject.disposeAll()
})
it('waits for an in-progress idle shutdown during manager disposal', async () => {
let finishShutdown!: () => void
const idle = worker(100)
idle.dispose.mockImplementation(
() =>
new Promise<void>((resolve) => {
finishShutdown = resolve
})
)
const subject = manager(vi.fn<PluginWorkerFactory>().mockResolvedValue(idle), {
idleReapMs: 100
})
await subject.ensureActive(spec('demo'))
subject.reapIdle(201)
let disposed = false
const disposal = subject.disposeAll().then(() => {
disposed = true
})
await flush()
expect(disposed).toBe(false)
finishShutdown()
await disposal
expect(disposed).toBe(true)
})
})
+309
View File
@@ -0,0 +1,309 @@
import {
PLUGIN_WORKER_IDLE_REAP_MS,
PLUGIN_WORKER_MAX_ACTIVE_DEFAULT
} from '../../shared/plugins/plugin-host-protocol'
import type { PluginEventName } from '../../shared/plugins/plugin-manifest'
import {
PluginSupervisor,
type PluginRestartDecision,
type PluginRunState
} from './plugin-supervisor'
import type { PluginWorkerHandle, PluginWorkerHostCallExecutor } from './plugin-host-process'
import { PluginWorkerSlotPool } from './plugin-worker-slot-pool'
import {
startPluginWorkerAttempt,
type PluginWorkerFactory,
type PluginWorkerSpawnSpec,
type StartedPluginWorker
} from './plugin-worker-startup'
import { runPluginWorkerRestartLoop } from './plugin-worker-restart-loop'
import { pluginWorkerSpawnSpecsEqual } from './plugin-worker-spawn-spec'
export type { PluginWorkerFactory, PluginWorkerSpawnSpec } from './plugin-worker-startup'
export type PluginWorkerManagerOptions = {
entryPath: string
maxActive?: number
idleReapMs?: number
workerFactory?: PluginWorkerFactory
executeHostCall: (
pluginKey: string,
method: string,
params: unknown
) => ReturnType<PluginWorkerHostCallExecutor>
log: (pluginKey: string, level: 'info' | 'warn' | 'error', line: string) => void
onWorkerStateChange: (pluginKey: string) => void
onWorkerGone: (pluginKey: string) => void
}
type ActivationRecord = {
spec: PluginWorkerSpawnSpec
generation: number
controller: AbortController
task: Promise<PluginWorkerHandle>
}
/** Owns lazy activation, bounded capacity, restart policy, cancellation, and idle reap. */
export class PluginWorkerManager {
private readonly supervisor = new PluginSupervisor()
private readonly workers = new Map<string, StartedPluginWorker>()
private readonly activations = new Map<string, ActivationRecord>()
private readonly knownSpecs = new Map<string, PluginWorkerSpawnSpec>()
private readonly generations = new Map<string, number>()
private readonly stoppingWorkers = new Set<Promise<void>>()
private readonly slots: PluginWorkerSlotPool
private readonly idleReapMs: number
private disposed = false
constructor(private readonly options: PluginWorkerManagerOptions) {
this.slots = new PluginWorkerSlotPool(options.maxActive ?? PLUGIN_WORKER_MAX_ACTIVE_DEFAULT)
this.idleReapMs = options.idleReapMs ?? PLUGIN_WORKER_IDLE_REAP_MS
}
runState(pluginKey: string): PluginRunState {
return this.supervisor.getState(pluginKey)
}
restartCount(pluginKey: string): number {
return this.supervisor.restartCount(pluginKey)
}
trackedSpecs(): ReadonlyMap<string, PluginWorkerSpawnSpec> {
return new Map(this.knownSpecs)
}
async ensureActive(spec: PluginWorkerSpawnSpec): Promise<PluginWorkerHandle> {
if (this.disposed) {
throw new Error('plugin workers are shut down')
}
if (this.supervisor.getState(spec.pluginKey) === 'errored') {
throw new Error(`plugin ${spec.pluginKey} is errored after repeated failures`)
}
for (;;) {
const existing = this.workers.get(spec.pluginKey)
const pending = this.activations.get(spec.pluginKey)
const activeSpec = existing?.spec ?? pending?.spec
if (!activeSpec) {
break
}
if (pluginWorkerSpawnSpecsEqual(activeSpec, spec)) {
return existing?.handle ?? pending!.task
}
// Why: refresh/trigger races can present a new dev manifest while the
// old revision is still starting. Cancel and re-check atomically enough
// that callers never join a stale activation by key alone.
await this.deactivate(spec.pluginKey)
if (this.disposed) {
throw new Error('plugin workers are shut down')
}
}
const generation = this.nextGeneration(spec.pluginKey)
this.knownSpecs.set(spec.pluginKey, spec)
this.supervisor.markRunning(spec.pluginKey, { resetRestarts: true })
return this.beginActivation(spec, generation)
}
private beginActivation(
spec: PluginWorkerSpawnSpec,
generation: number,
firstRestart?: Extract<PluginRestartDecision, { restart: true }>
): Promise<PluginWorkerHandle> {
const controller = new AbortController()
const task = this.activate(spec, generation, controller.signal, firstRestart)
const record: ActivationRecord = { spec, generation, controller, task }
this.activations.set(spec.pluginKey, record)
void task.then(
() => this.finishActivation(spec.pluginKey, record),
() => this.finishActivation(spec.pluginKey, record)
)
return task
}
private finishActivation(pluginKey: string, record: ActivationRecord): void {
if (this.activations.get(pluginKey) === record) {
this.activations.delete(pluginKey)
}
}
private async activate(
spec: PluginWorkerSpawnSpec,
generation: number,
signal: AbortSignal,
firstRestart?: Extract<PluginRestartDecision, { restart: true }>
): Promise<PluginWorkerHandle> {
return runPluginWorkerRestartLoop({
signal,
firstRestart,
assertActive: () => this.throwIfCancelled(spec.pluginKey, generation, signal),
start: async () => {
const worker = await startPluginWorkerAttempt({
spec,
generation,
signal,
slots: this.slots,
entryPath: this.options.entryPath,
factory: this.options.workerFactory,
executeHostCall: (method, params) =>
this.options.executeHostCall(spec.pluginKey, method, params),
log: (level, line) => this.options.log(spec.pluginKey, level, line),
assertActive: () => this.throwIfCancelled(spec.pluginKey, generation, signal),
onExit: (record, code) => this.handleUnexpectedExit(spec.pluginKey, record, code)
})
this.workers.set(spec.pluginKey, worker)
const earlyExit = worker.completeStart()
if (earlyExit.exited) {
this.detachWorker(spec.pluginKey, worker)
throw new Error(`worker exited immediately after ready (code ${earlyExit.code})`)
}
this.supervisor.markRunning(spec.pluginKey)
this.options.onWorkerStateChange(spec.pluginKey)
return worker.handle
},
recordFailure: (error) => this.recordFailure(spec.pluginKey, 'worker failed to start', error),
erroredError: (error) =>
new Error(
`plugin ${spec.pluginKey} is errored after repeated failures: ${this.errorText(error)}`
)
})
}
private handleUnexpectedExit(
pluginKey: string,
record: StartedPluginWorker,
code: number | null
): void {
if (!this.detachWorker(pluginKey, record)) {
return
}
if (this.isCancelled(pluginKey, record.generation)) {
return
}
const decision = this.recordFailure(pluginKey, `worker exited unexpectedly (code ${code})`)
if (decision.restart) {
this.beginActivation(record.spec, record.generation, decision)
}
}
private recordFailure(
pluginKey: string,
context: string,
error?: unknown
): PluginRestartDecision {
this.options.onWorkerGone(pluginKey)
const decision = this.supervisor.markExited(pluginKey, { crashed: true })
this.options.onWorkerStateChange(pluginKey)
if (decision.restart) {
this.options.log(
pluginKey,
'warn',
`${context}${error ? `: ${this.errorText(error)}` : ''}; restart ${decision.attempt} in ${decision.delayMs}ms`
)
} else if (decision.state === 'errored') {
this.options.log(pluginKey, 'error', `${context}; marked errored after repeated failures`)
}
return decision
}
private detachWorker(pluginKey: string, record: StartedPluginWorker): boolean {
if (this.workers.get(pluginKey) !== record) {
return false
}
this.workers.delete(pluginKey)
record.lease.release()
return true
}
deliverEventIfRunning(pluginKey: string, event: PluginEventName, payload: unknown): void {
this.workers.get(pluginKey)?.handle.deliverEvent(event, payload)
}
async deactivate(pluginKey: string): Promise<void> {
this.nextGeneration(pluginKey)
const activation = this.activations.get(pluginKey)
activation?.controller.abort()
const record = this.workers.get(pluginKey)
if (record) {
this.workers.delete(pluginKey)
}
this.options.onWorkerGone(pluginKey)
this.supervisor.reset(pluginKey)
this.knownSpecs.delete(pluginKey)
await Promise.all([
activation?.task.catch(() => undefined),
record?.handle.dispose().catch(() => undefined)
])
record?.lease.release()
}
reapIdle(now = Date.now()): void {
for (const [pluginKey, record] of this.workers) {
if (
record.handle.inFlightCount() !== 0 ||
now - record.handle.lastActivityAt() <= this.idleReapMs
) {
continue
}
this.nextGeneration(pluginKey)
this.knownSpecs.delete(pluginKey)
this.workers.delete(pluginKey)
this.options.onWorkerGone(pluginKey)
this.supervisor.markExited(pluginKey, { crashed: false })
this.options.log(pluginKey, 'info', 'worker reaped after idle period')
this.options.onWorkerStateChange(pluginKey)
const stopping = record.handle
.dispose()
.catch(() => undefined)
.finally(() => record.lease.release())
this.stoppingWorkers.add(stopping)
void stopping.then(() => this.stoppingWorkers.delete(stopping))
}
}
async disposeAll(): Promise<void> {
this.disposed = true
const pluginKeys = new Set([...this.activations.keys(), ...this.workers.keys()])
for (const key of pluginKeys) {
this.nextGeneration(key)
this.options.onWorkerGone(key)
}
const activations = [...this.activations.values()]
for (const activation of activations) {
activation.controller.abort()
}
this.slots.dispose()
const workers = [...this.workers.values()]
this.workers.clear()
this.knownSpecs.clear()
const stoppingWorkers = [...this.stoppingWorkers]
await Promise.all([
...stoppingWorkers,
...activations.map((activation) => activation.task.catch(() => undefined)),
...workers.map(async (record) => {
await record.handle.dispose().catch(() => undefined)
record.lease.release()
})
])
}
private nextGeneration(pluginKey: string): number {
const generation = (this.generations.get(pluginKey) ?? 0) + 1
this.generations.set(pluginKey, generation)
return generation
}
private isCancelled(pluginKey: string, generation: number, signal?: AbortSignal): boolean {
return (
this.disposed || signal?.aborted === true || this.generations.get(pluginKey) !== generation
)
}
private throwIfCancelled(pluginKey: string, generation: number, signal: AbortSignal): void {
if (this.isCancelled(pluginKey, generation, signal)) {
throw new Error('plugin worker activation was cancelled')
}
}
private errorText(error: unknown): string {
return error instanceof Error ? error.message : String(error)
}
}
@@ -0,0 +1,22 @@
import { PassThrough } from 'node:stream'
import { describe, expect, it, vi } from 'vitest'
import {
PLUGIN_WORKER_OUTPUT_LINE_LIMIT,
pipePluginWorkerOutput
} from './plugin-worker-output-buffer'
describe('pipePluginWorkerOutput', () => {
it('bounds an unterminated line and resumes after its newline', () => {
const stream = new PassThrough()
const log = vi.fn()
pipePluginWorkerOutput(stream, 'info', log)
stream.write('x'.repeat(PLUGIN_WORKER_OUTPUT_LINE_LIMIT + 1_000))
stream.write('discarded')
expect(log).toHaveBeenCalledOnce()
expect(log.mock.calls[0]?.[1]).toHaveLength(PLUGIN_WORKER_OUTPUT_LINE_LIMIT)
stream.write('\nok\n')
expect(log).toHaveBeenLastCalledWith('info', 'ok')
})
})

Some files were not shown because too many files have changed in this diff Show More