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:
@@ -0,0 +1,67 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
/**
|
||||
* Plugin capability model v0. The manifest declares capabilities, the user
|
||||
* consents against a fingerprint covering capabilities and worker trust, and the
|
||||
* host enforces at every plugin-callable boundary (panel bridge + worker host
|
||||
* API). Electron-free: shared by desktop main, headless serve, the relay
|
||||
* conformance path, and tests.
|
||||
*
|
||||
* v0 is a closed set of unscoped kinds so a typo (or a capability from a newer
|
||||
* Orca) fails manifest validation instead of silently granting nothing.
|
||||
* Scoped kinds (net:fetch hosts, process:exec globs) arrive in later phases.
|
||||
*/
|
||||
|
||||
export const PLUGIN_CAPABILITY_KINDS = [
|
||||
'workspace:read',
|
||||
'terminal:send',
|
||||
'notifications:show',
|
||||
'storage',
|
||||
'secrets',
|
||||
'events:subscribe',
|
||||
'settings:own'
|
||||
] as const
|
||||
|
||||
export type PluginCapabilityKind = (typeof PLUGIN_CAPABILITY_KINDS)[number]
|
||||
|
||||
// Strict object (not a bare enum) so scoped fields can be added per-kind later
|
||||
// without changing the manifest shape.
|
||||
export const pluginCapabilitySchema = z.object({ kind: z.enum(PLUGIN_CAPABILITY_KINDS) }).strict()
|
||||
|
||||
export type PluginCapability = z.infer<typeof pluginCapabilitySchema>
|
||||
|
||||
export function isPluginCapabilityKind(value: string): value is PluginCapabilityKind {
|
||||
return (PLUGIN_CAPABILITY_KINDS as readonly string[]).includes(value)
|
||||
}
|
||||
|
||||
/** Plain-language consent copy per capability. Shown verbatim in the install
|
||||
* preview / consent dialog; keep each line honest about what is enforced. */
|
||||
export const PLUGIN_CAPABILITY_DESCRIPTIONS: Record<PluginCapabilityKind, string> = {
|
||||
'workspace:read': 'Read the name, branch, and terminal list of your focused worktree',
|
||||
'terminal:send': 'Type text into a terminal you can see (always a specific terminal)',
|
||||
'notifications:show': 'Show desktop notifications labeled with the plugin name',
|
||||
storage: "Store data in the plugin's own storage folder",
|
||||
secrets: "Store and read secrets in the plugin's own encrypted vault",
|
||||
'events:subscribe':
|
||||
'Get notified when worktrees are created or removed and when agent status changes',
|
||||
'settings:own': "Read and change the plugin's own settings"
|
||||
}
|
||||
|
||||
/**
|
||||
* Canonical serialization of a capability set. Order- and duplicate-
|
||||
* insensitive so consent is stable across manifest reformatting;
|
||||
* key-sorted so future scoped fields cannot produce two encodings of the
|
||||
* same grant.
|
||||
*/
|
||||
export function canonicalizeCapabilitySet(capabilities: readonly PluginCapability[]): string {
|
||||
const encoded = capabilities.map((capability) =>
|
||||
JSON.stringify(
|
||||
Object.fromEntries(Object.entries(capability).sort(([a], [b]) => a.localeCompare(b)))
|
||||
)
|
||||
)
|
||||
return JSON.stringify([...new Set(encoded)].sort())
|
||||
}
|
||||
|
||||
export function capabilityKinds(capabilities: readonly PluginCapability[]): PluginCapabilityKind[] {
|
||||
return [...new Set(capabilities.map((capability) => capability.kind))]
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { getPluginHostMethodSpec, isPluginPanelAction } from './plugin-host-api'
|
||||
import type { PluginCapabilityKind } from './plugin-capabilities'
|
||||
|
||||
/**
|
||||
* The capability gate — pure, electron-free, shared by the Electron main
|
||||
* host, the headless serve RPC path, and the relay so a security decision
|
||||
* cannot land on desktop while drifting on the remote path. Deny-by-default:
|
||||
* an empty capability set grants nothing. A conformance test runs identical
|
||||
* cases against the desktop and relay enforcement surfaces.
|
||||
*
|
||||
* Ported from community PR #5801's electron-free gate, rekeyed to the host
|
||||
* API v0 spec table.
|
||||
*/
|
||||
|
||||
export type PluginGateErrorCode =
|
||||
| 'unknown_method'
|
||||
| 'capability_denied'
|
||||
| 'consent_required'
|
||||
| 'panel_forbidden'
|
||||
|
||||
export type PluginGateDecision =
|
||||
| { granted: true }
|
||||
| { granted: false; code: PluginGateErrorCode; error: string }
|
||||
|
||||
export type PluginGateSubject = {
|
||||
/** Capability kinds from the manifest the user consented to; null when the
|
||||
* plugin is unknown, invalid, disabled, or consent is missing/stale. */
|
||||
grantedCapabilities: readonly PluginCapabilityKind[] | null
|
||||
/** True when the call arrives over the sandboxed panel bridge (narrower
|
||||
* method surface than workers). */
|
||||
viaPanel: boolean
|
||||
}
|
||||
|
||||
export function gatePluginHostCall(subject: PluginGateSubject, method: string): PluginGateDecision {
|
||||
const spec = getPluginHostMethodSpec(method)
|
||||
if (!spec) {
|
||||
return { granted: false, code: 'unknown_method', error: `unknown host method: ${method}` }
|
||||
}
|
||||
if (subject.viaPanel && !isPluginPanelAction(method)) {
|
||||
return {
|
||||
granted: false,
|
||||
code: 'panel_forbidden',
|
||||
error: `method ${method} is not available to sandboxed panels`
|
||||
}
|
||||
}
|
||||
// Why: a disabled/unknown/stale-consent plugin must fail exactly like an
|
||||
// ungranted capability — no probe-able distinction for plugin code.
|
||||
if (subject.grantedCapabilities === null) {
|
||||
return {
|
||||
granted: false,
|
||||
code: 'consent_required',
|
||||
error: 'plugin is not enabled with current consent'
|
||||
}
|
||||
}
|
||||
if (!subject.grantedCapabilities.includes(spec.capability)) {
|
||||
return {
|
||||
granted: false,
|
||||
code: 'capability_denied',
|
||||
error: `plugin does not have the "${spec.capability}" capability`
|
||||
}
|
||||
}
|
||||
return { granted: true }
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
export type PluginChangeEvent = {
|
||||
/** True only when declarative contribution catalogs were reconciled. */
|
||||
contentPacksChanged: boolean
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { KeybindingActionId, PluginKeybindingActionId } from '../keybindings'
|
||||
|
||||
/** Built-in actions with a renderer-owned command handler. Keep this closed so
|
||||
* declarative aliases cannot target component-private shortcut implementations. */
|
||||
export const PLUGIN_COMMAND_ALIAS_ACTION_IDS = [
|
||||
'worktree.history.back',
|
||||
'worktree.history.forward',
|
||||
'sidebar.left.toggle',
|
||||
'sidebar.sleepingWorkspaces.toggle',
|
||||
'floatingWorkspace.maximize',
|
||||
'tab.rename',
|
||||
'workspace.rename',
|
||||
'workspace.openBoard',
|
||||
'view.tasks',
|
||||
'sidebar.right.toggle',
|
||||
'sidebar.explorer.toggle',
|
||||
'sidebar.search.toggle',
|
||||
'sidebar.sourceControl.toggle',
|
||||
'sidebar.checks.toggle',
|
||||
'sidebar.ports.toggle'
|
||||
] as const satisfies readonly KeybindingActionId[]
|
||||
|
||||
export type PluginCommandAliasActionId = (typeof PLUGIN_COMMAND_ALIAS_ACTION_IDS)[number]
|
||||
|
||||
const PLUGIN_COMMAND_ALIAS_ACTION_ID_SET = new Set<string>(PLUGIN_COMMAND_ALIAS_ACTION_IDS)
|
||||
|
||||
export function isPluginCommandAliasActionId(value: string): value is PluginCommandAliasActionId {
|
||||
return PLUGIN_COMMAND_ALIAS_ACTION_ID_SET.has(value)
|
||||
}
|
||||
|
||||
export function pluginCommandKeybindingActionId(
|
||||
pluginKey: string,
|
||||
commandId: string
|
||||
): PluginKeybindingActionId {
|
||||
return `plugin:${pluginKey}/${commandId}`
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { canonicalizeCapabilitySet, type PluginCapability } from './plugin-capabilities'
|
||||
import { fingerprintPluginConsent } from './plugin-consent-fingerprint'
|
||||
import {
|
||||
getPluginActivationState,
|
||||
needsReconsent,
|
||||
normalizePluginConsents
|
||||
} from './plugin-consent-state'
|
||||
import {
|
||||
parsePluginLockfile,
|
||||
serializePluginLockfile,
|
||||
type PluginLockfile
|
||||
} from './plugin-install-lockfile'
|
||||
|
||||
const workspaceRead: PluginCapability = { kind: 'workspace:read' }
|
||||
const storage: PluginCapability = { kind: 'storage' }
|
||||
|
||||
describe('fingerprintPluginConsent', () => {
|
||||
it('drops malformed persisted consent identities and oversized fingerprints', () => {
|
||||
expect(
|
||||
normalizePluginConsents({
|
||||
__proto__: 'polluted',
|
||||
constructor: 'polluted',
|
||||
invalid: 'sha256-invalid',
|
||||
'orca-samples.demo': 'sha256-valid',
|
||||
'orca-samples.large': 'x'.repeat(257)
|
||||
})
|
||||
).toEqual({ 'orca-samples.demo': 'sha256-valid' })
|
||||
})
|
||||
|
||||
it('is stable across capability order and duplicate declarations', () => {
|
||||
const first = fingerprintPluginConsent({
|
||||
main: undefined,
|
||||
capabilities: [workspaceRead, storage, workspaceRead]
|
||||
})
|
||||
const second = fingerprintPluginConsent({
|
||||
main: undefined,
|
||||
capabilities: [storage, workspaceRead]
|
||||
})
|
||||
|
||||
expect(first).toBe(second)
|
||||
})
|
||||
|
||||
it('changes when a panel-only plugin gains a trusted Node worker', () => {
|
||||
const panelOnly = fingerprintPluginConsent({ main: undefined, capabilities: [] })
|
||||
const withWorker = fingerprintPluginConsent({ main: 'worker.js', capabilities: [] })
|
||||
|
||||
expect(withWorker).not.toBe(panelOnly)
|
||||
const lists = {
|
||||
pluginConsents: { 'orca-samples.demo': panelOnly },
|
||||
disabledPlugins: []
|
||||
}
|
||||
expect(getPluginActivationState('orca-samples.demo', withWorker, lists)).toBe('pending')
|
||||
expect(needsReconsent('orca-samples.demo', withWorker, lists)).toBe(true)
|
||||
})
|
||||
|
||||
it('preserves capability-only fingerprints for existing panel plugins', () => {
|
||||
const capabilities = [workspaceRead, storage]
|
||||
const legacy = `sha256-${createHash('sha256')
|
||||
.update(canonicalizeCapabilitySet(capabilities))
|
||||
.digest('base64')}`
|
||||
|
||||
expect(fingerprintPluginConsent({ main: undefined, capabilities })).toBe(legacy)
|
||||
})
|
||||
|
||||
it('requires re-consent when instructional content bytes change', () => {
|
||||
const subject = {
|
||||
main: undefined,
|
||||
capabilities: [],
|
||||
contributes: {
|
||||
keybindings: [],
|
||||
vmRecipes: [{ path: 'recipes/cloud.json' }],
|
||||
agents: []
|
||||
}
|
||||
}
|
||||
const first = fingerprintPluginConsent(subject, 'a'.repeat(64))
|
||||
const second = fingerprintPluginConsent(subject, 'b'.repeat(64))
|
||||
|
||||
expect(second).not.toBe(first)
|
||||
expect(
|
||||
getPluginActivationState('orca-samples.recipes', second, {
|
||||
pluginConsents: { 'orca-samples.recipes': first },
|
||||
disabledPlugins: []
|
||||
})
|
||||
).toBe('pending')
|
||||
})
|
||||
|
||||
it('does not invalidate inert content consent when only its content hash changes', () => {
|
||||
const subject = {
|
||||
main: undefined,
|
||||
capabilities: [],
|
||||
contributes: {
|
||||
keybindings: [],
|
||||
vmRecipes: [],
|
||||
agents: []
|
||||
}
|
||||
}
|
||||
|
||||
expect(fingerprintPluginConsent(subject, 'a'.repeat(64))).toBe(
|
||||
fingerprintPluginConsent(subject, 'b'.repeat(64))
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('plugin install lockfile consent fingerprints', () => {
|
||||
const persistedEntry = {
|
||||
pluginKey: 'orca-samples.demo',
|
||||
version: '1.0.0',
|
||||
source: { kind: 'local-path' as const, path: '/plugins/demo' },
|
||||
resolvedCommit: null,
|
||||
contentHash: '0123456789abcdef0123456789abcdef',
|
||||
capabilityHash: 'sha256-legacy-name',
|
||||
installedAt: 1
|
||||
}
|
||||
|
||||
it('reads the legacy capabilityHash field as a consent fingerprint', () => {
|
||||
const parsed = parsePluginLockfile({
|
||||
version: 1,
|
||||
plugins: { 'orca-samples.demo': persistedEntry }
|
||||
})
|
||||
|
||||
expect(parsed.plugins['orca-samples.demo']?.consentFingerprint).toBe('sha256-legacy-name')
|
||||
})
|
||||
|
||||
it('keeps writing the v1 field name for rollback compatibility', () => {
|
||||
const lock: PluginLockfile = {
|
||||
version: 1,
|
||||
plugins: {
|
||||
'orca-samples.demo': {
|
||||
...persistedEntry,
|
||||
consentFingerprint: 'sha256-current'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
expect(serializePluginLockfile(lock)).toMatchObject({
|
||||
version: 1,
|
||||
plugins: {
|
||||
'orca-samples.demo': {
|
||||
capabilityHash: 'sha256-current'
|
||||
}
|
||||
}
|
||||
})
|
||||
expect(
|
||||
(serializePluginLockfile(lock) as { plugins: Record<string, unknown> }).plugins[
|
||||
'orca-samples.demo'
|
||||
]
|
||||
).not.toHaveProperty('consentFingerprint')
|
||||
})
|
||||
|
||||
it('drops a lockfile whose record key disagrees with its embedded identity', () => {
|
||||
const parsed = parsePluginLockfile({
|
||||
version: 1,
|
||||
plugins: {
|
||||
'orca-samples.other': persistedEntry
|
||||
}
|
||||
})
|
||||
|
||||
expect(parsed.plugins).toEqual({})
|
||||
})
|
||||
|
||||
it('accepts SHA-256 Git object ids in lockfile provenance', () => {
|
||||
const parsed = parsePluginLockfile({
|
||||
version: 1,
|
||||
plugins: {
|
||||
'orca-samples.demo': { ...persistedEntry, resolvedCommit: 'a'.repeat(64) }
|
||||
}
|
||||
})
|
||||
|
||||
expect(parsed.plugins['orca-samples.demo']?.resolvedCommit).toBe('a'.repeat(64))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,45 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import { canonicalizeCapabilitySet } from './plugin-capabilities'
|
||||
import type { PluginManifest } from './plugin-manifest'
|
||||
|
||||
type PluginConsentSubject = Pick<PluginManifest, 'capabilities' | 'main'> & {
|
||||
contributes?: Partial<Pick<PluginManifest['contributes'], 'keybindings' | 'vmRecipes' | 'agents'>>
|
||||
}
|
||||
|
||||
export function hasInstructionalPluginContributions(manifest: PluginConsentSubject): boolean {
|
||||
const contributions = manifest.contributes
|
||||
return Boolean(
|
||||
contributions &&
|
||||
((contributions.keybindings?.length ?? 0) > 0 ||
|
||||
(contributions.vmRecipes?.length ?? 0) > 0 ||
|
||||
(contributions.agents?.length ?? 0) > 0)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Consent covers both the declared host capabilities and whether the plugin
|
||||
* executes trusted Node code. A panel-only update that adds `main` crosses a
|
||||
* trust boundary even when its capability list is unchanged.
|
||||
*/
|
||||
export function canonicalizePluginConsent(
|
||||
manifest: PluginConsentSubject,
|
||||
contentIdentity?: string
|
||||
): string {
|
||||
const capabilities = canonicalizeCapabilitySet(manifest.capabilities)
|
||||
const workerIdentity = manifest.main === undefined ? '' : '\0trusted-node-worker'
|
||||
// Instructional bytes execute later under user or agent authority, so
|
||||
// approval is bound to their immutable install/dev-tree identity.
|
||||
const instructionalIdentity = hasInstructionalPluginContributions(manifest)
|
||||
? `\0instructional-content:${contentIdentity ?? 'unresolved'}`
|
||||
: ''
|
||||
return `${capabilities}${workerIdentity}${instructionalIdentity}`
|
||||
}
|
||||
|
||||
export function fingerprintPluginConsent(
|
||||
manifest: PluginConsentSubject,
|
||||
contentIdentity?: string
|
||||
): string {
|
||||
return `sha256-${createHash('sha256')
|
||||
.update(canonicalizePluginConsent(manifest, contentIdentity))
|
||||
.digest('base64')}`
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { pluginConsentRequestSchema } from './plugin-consent-request'
|
||||
|
||||
describe('pluginConsentRequestSchema', () => {
|
||||
it('requires the exact reviewed consent fingerprint', () => {
|
||||
expect(
|
||||
pluginConsentRequestSchema.safeParse({
|
||||
pluginKey: 'orca-samples.demo',
|
||||
decision: 'approve'
|
||||
}).success
|
||||
).toBe(false)
|
||||
expect(
|
||||
pluginConsentRequestSchema.safeParse({
|
||||
pluginKey: 'orca-samples.demo',
|
||||
reviewedFingerprint: '',
|
||||
decision: 'approve'
|
||||
}).success
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('accepts an explicit opaque fingerprint and rejects contract drift', () => {
|
||||
expect(
|
||||
pluginConsentRequestSchema.parse({
|
||||
pluginKey: 'orca-samples.demo',
|
||||
reviewedFingerprint: 'sha256-reviewed',
|
||||
decision: 'keep-disabled'
|
||||
})
|
||||
).toEqual({
|
||||
pluginKey: 'orca-samples.demo',
|
||||
reviewedFingerprint: 'sha256-reviewed',
|
||||
decision: 'keep-disabled'
|
||||
})
|
||||
expect(() =>
|
||||
pluginConsentRequestSchema.parse({
|
||||
pluginKey: 'orca-samples.demo',
|
||||
reviewedFingerprint: 'sha256-reviewed',
|
||||
decision: 'approve',
|
||||
unexpected: true
|
||||
})
|
||||
).toThrow()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,16 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
/**
|
||||
* Experimental consent write contract shared by desktop IPC and serve RPC.
|
||||
* The reviewed fingerprint makes approval conditional on the exact manifest
|
||||
* trust boundary the user saw, rather than whichever same-key plugin is current.
|
||||
*/
|
||||
export const pluginConsentRequestSchema = z
|
||||
.object({
|
||||
pluginKey: z.string().min(1),
|
||||
reviewedFingerprint: z.string().min(1).max(256),
|
||||
decision: z.enum(['approve', 'keep-disabled'])
|
||||
})
|
||||
.strict()
|
||||
|
||||
export type PluginConsentRequest = z.infer<typeof pluginConsentRequestSchema>
|
||||
@@ -0,0 +1,70 @@
|
||||
import { isQualifiedPluginKey } from './plugin-manifest'
|
||||
|
||||
/**
|
||||
* Consent + enablement state derivation. Consent is recorded against the
|
||||
* (qualified plugin key → consent fingerprint) pair, never the bare id. The
|
||||
* fingerprint covers capabilities and the trusted-worker execution tier, so
|
||||
* crossing either trust boundary requires approval before plugin code runs.
|
||||
*/
|
||||
|
||||
export type PluginActivationState = 'approved' | 'pending' | 'disabled'
|
||||
|
||||
export type PluginConsentLists = {
|
||||
/** Qualified key → consent fingerprint. */
|
||||
pluginConsents: Readonly<Record<string, string>>
|
||||
disabledPlugins: readonly string[]
|
||||
}
|
||||
|
||||
export function getPluginActivationState(
|
||||
qualifiedKey: string,
|
||||
currentConsentFingerprint: string,
|
||||
lists: PluginConsentLists
|
||||
): PluginActivationState {
|
||||
if (lists.disabledPlugins.includes(qualifiedKey)) {
|
||||
return 'disabled'
|
||||
}
|
||||
return lists.pluginConsents[qualifiedKey] === currentConsentFingerprint ? 'approved' : 'pending'
|
||||
}
|
||||
|
||||
/** True when the plugin was consented before but its capability set changed —
|
||||
* the UI shows "needs re-approval" instead of a first-install prompt. */
|
||||
export function needsReconsent(
|
||||
qualifiedKey: string,
|
||||
currentConsentFingerprint: string,
|
||||
lists: PluginConsentLists
|
||||
): boolean {
|
||||
const recorded = lists.pluginConsents[qualifiedKey]
|
||||
return recorded !== undefined && recorded !== currentConsentFingerprint
|
||||
}
|
||||
|
||||
export function normalizePluginConsents(value: unknown): Record<string, string> {
|
||||
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
||||
return {}
|
||||
}
|
||||
const consents: Record<string, string> = {}
|
||||
for (const [key, hash] of Object.entries(value)) {
|
||||
if (
|
||||
typeof hash === 'string' &&
|
||||
hash.length > 0 &&
|
||||
hash.length <= 256 &&
|
||||
isQualifiedPluginKey(key)
|
||||
) {
|
||||
consents[key] = hash
|
||||
}
|
||||
}
|
||||
return consents
|
||||
}
|
||||
|
||||
export function normalizePluginIdList(value: unknown): string[] {
|
||||
if (!Array.isArray(value)) {
|
||||
return []
|
||||
}
|
||||
return [
|
||||
...new Set(
|
||||
value.filter(
|
||||
(entry): entry is string =>
|
||||
typeof entry === 'string' && entry.length > 0 && entry.length <= 32 * 1024
|
||||
)
|
||||
)
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parsePluginManifest, pluginManifestSchema } from './plugin-manifest'
|
||||
|
||||
function manifest(contributes: Record<string, unknown>): Record<string, unknown> {
|
||||
return {
|
||||
manifestVersion: 1,
|
||||
id: 'content-pack',
|
||||
publisher: 'orca-samples',
|
||||
name: 'Content pack',
|
||||
version: '1.0.0',
|
||||
engines: { orca: '>=1.0.0' },
|
||||
pluginApi: 1,
|
||||
contributes,
|
||||
capabilities: []
|
||||
}
|
||||
}
|
||||
|
||||
describe('content-pack manifest contributions', () => {
|
||||
it('accepts the documented P1 contribution set without a worker', () => {
|
||||
const parsed = pluginManifestSchema.parse(
|
||||
manifest({
|
||||
languagePacks: [{ locale: 'pt-BR', path: 'locales/pt-BR.json' }],
|
||||
commands: [
|
||||
{
|
||||
id: 'workspace.openTasks',
|
||||
title: 'Open tasks',
|
||||
context: 'worktree',
|
||||
action: 'view.tasks'
|
||||
}
|
||||
],
|
||||
keybindings: [{ command: 'workspace.openTasks', key: 'Mod+Alt+T' }],
|
||||
vmRecipes: [{ path: 'recipes/fly.json' }],
|
||||
agents: [{ path: 'agents/custom.json' }]
|
||||
})
|
||||
)
|
||||
|
||||
expect(parsed.main).toBeUndefined()
|
||||
expect(parsed.contributes.languagePacks[0]?.locale).toBe('pt-BR')
|
||||
expect(parsed.contributes.keybindings[0]?.key).toBe('Mod+Alt+T')
|
||||
})
|
||||
|
||||
it('defaults every contribution registry to an empty array', () => {
|
||||
const parsed = pluginManifestSchema.parse(manifest({}))
|
||||
|
||||
expect(parsed.contributes).toEqual({
|
||||
panels: [],
|
||||
commands: [],
|
||||
events: [],
|
||||
languagePacks: [],
|
||||
keybindings: [],
|
||||
vmRecipes: [],
|
||||
agents: []
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects the removed plugin skills contribution', () => {
|
||||
expect(parsePluginManifest(manifest({ skills: [{ path: 'skills' }] }))).toMatchObject({
|
||||
ok: false,
|
||||
error: expect.stringContaining('Unrecognized key')
|
||||
})
|
||||
})
|
||||
|
||||
it('still requires a worker entry for non-alias commands', () => {
|
||||
expect(
|
||||
parsePluginManifest(
|
||||
manifest({ commands: [{ id: 'content-pack.run', title: 'Run content pack' }] })
|
||||
)
|
||||
).toMatchObject({ ok: false, error: expect.stringContaining('worker command') })
|
||||
})
|
||||
|
||||
it.each([
|
||||
[
|
||||
'unknown alias target',
|
||||
{
|
||||
commands: [{ id: 'open', title: 'Open', action: 'missing.action' }]
|
||||
},
|
||||
'unknown built-in action'
|
||||
],
|
||||
[
|
||||
'unknown command reference',
|
||||
{ keybindings: [{ command: 'missing', key: 'Mod+K' }] },
|
||||
'unknown contributed command'
|
||||
],
|
||||
[
|
||||
'invalid chord',
|
||||
{
|
||||
commands: [{ id: 'open', title: 'Open', action: 'view.tasks' }],
|
||||
keybindings: [{ command: 'open', key: 'Mod+NotAKey' }]
|
||||
},
|
||||
'key'
|
||||
],
|
||||
[
|
||||
'global binding for a worktree command',
|
||||
{
|
||||
commands: [{ id: 'open', title: 'Open', context: 'worktree', action: 'view.tasks' }],
|
||||
keybindings: [{ command: 'open', key: 'Mod+K', when: 'global' }]
|
||||
},
|
||||
'command context'
|
||||
],
|
||||
[
|
||||
'platform-equivalent duplicate chords',
|
||||
{
|
||||
commands: [
|
||||
{ id: 'first', title: 'First', action: 'view.tasks' },
|
||||
{ id: 'second', title: 'Second', action: 'sidebar.left.toggle' }
|
||||
],
|
||||
keybindings: [
|
||||
{ command: 'first', key: 'Mod+K' },
|
||||
{ command: 'second', key: 'Ctrl+K' }
|
||||
]
|
||||
},
|
||||
'duplicate keybinding'
|
||||
]
|
||||
])('rejects %s', (_label, contributes, error) => {
|
||||
expect(parsePluginManifest(manifest(contributes))).toMatchObject({
|
||||
ok: false,
|
||||
error: expect.stringContaining(error)
|
||||
})
|
||||
})
|
||||
|
||||
it.each([
|
||||
['language pack', { languagePacks: [{ locale: 'en_US', path: 'locale.json' }] }],
|
||||
['language pack path', { languagePacks: [{ locale: 'pt-BR', path: '../outside.json' }] }],
|
||||
['VM recipe', { vmRecipes: [{ path: '\\\\server\\recipe.json' }] }],
|
||||
['agent profile', { agents: [{ path: 'agents/../profile.json' }] }]
|
||||
])('rejects unsafe or malformed %s contributions', (_label, contributes) => {
|
||||
expect(parsePluginManifest(manifest(contributes)).ok).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects duplicate ids, locales, paths, and bindings', () => {
|
||||
const parsed = pluginManifestSchema.safeParse(
|
||||
manifest({
|
||||
languagePacks: [
|
||||
{ locale: 'pt-BR', path: 'pt-br.json' },
|
||||
{ locale: 'pt-br', path: 'other.json' }
|
||||
],
|
||||
commands: [{ id: 'open', title: 'Open', action: 'view.tasks' }],
|
||||
keybindings: [
|
||||
{ command: 'open', key: 'Mod+T' },
|
||||
{ command: 'open', key: 'mod+t' }
|
||||
]
|
||||
})
|
||||
)
|
||||
|
||||
expect(parsed.success).toBe(false)
|
||||
if (!parsed.success) {
|
||||
expect(parsed.error.issues.map((issue) => issue.message)).toEqual(
|
||||
expect.arrayContaining([
|
||||
'duplicate language pack locale: pt-br',
|
||||
'duplicate keybinding: mod+t'
|
||||
])
|
||||
)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,55 @@
|
||||
import { z } from 'zod'
|
||||
import { pluginCommandIdSchema, pluginRelativePathSchema } from './plugin-manifest-fields'
|
||||
import { normalizeKeybinding } from '../keybindings'
|
||||
|
||||
export const PLUGIN_LANGUAGE_PACK_LIMIT = 16
|
||||
export const PLUGIN_KEYBINDING_LIMIT = 256
|
||||
export const PLUGIN_VM_RECIPE_LIMIT = 64
|
||||
export const PLUGIN_AGENT_PROFILE_LIMIT = 64
|
||||
|
||||
// Why: locale ids become i18next bundle keys and filenames. This bounded BCP
|
||||
// 47 subset covers current community packs without accepting path syntax.
|
||||
export const pluginLocaleIdSchema = z
|
||||
.string()
|
||||
.min(2)
|
||||
.max(35)
|
||||
.regex(/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/, 'must be a portable locale identifier')
|
||||
|
||||
export const pluginLanguagePackContributionSchema = z
|
||||
.object({
|
||||
locale: pluginLocaleIdSchema,
|
||||
path: pluginRelativePathSchema
|
||||
})
|
||||
.strict()
|
||||
|
||||
export const pluginKeybindingContributionSchema = z
|
||||
.object({
|
||||
command: pluginCommandIdSchema,
|
||||
key: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(128)
|
||||
.transform((value, ctx) => {
|
||||
const normalized = normalizeKeybinding(value)
|
||||
if (!normalized.ok) {
|
||||
ctx.addIssue({ code: 'custom', message: normalized.error })
|
||||
return z.NEVER
|
||||
}
|
||||
return normalized.value
|
||||
}),
|
||||
when: z.enum(['global', 'worktree']).optional()
|
||||
})
|
||||
.strict()
|
||||
|
||||
export const pluginVmRecipeContributionSchema = z
|
||||
.object({ path: pluginRelativePathSchema })
|
||||
.strict()
|
||||
|
||||
export const pluginAgentProfileContributionSchema = z
|
||||
.object({ path: pluginRelativePathSchema })
|
||||
.strict()
|
||||
|
||||
export type PluginLanguagePackContribution = z.infer<typeof pluginLanguagePackContributionSchema>
|
||||
export type PluginKeybindingContribution = z.infer<typeof pluginKeybindingContributionSchema>
|
||||
export type PluginVmRecipeContribution = z.infer<typeof pluginVmRecipeContributionSchema>
|
||||
export type PluginAgentProfileContribution = z.infer<typeof pluginAgentProfileContributionSchema>
|
||||
@@ -0,0 +1,20 @@
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { pathToFileURL } from 'node:url'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { pluginManifestSchema } from './plugin-manifest'
|
||||
|
||||
describe('hello Orca plugin fixture', () => {
|
||||
it('uses an ESM entry that remains loadable outside a type-module package', async () => {
|
||||
const root = join(process.cwd(), 'examples', 'plugins', 'hello-orca')
|
||||
const manifest = pluginManifestSchema.parse(
|
||||
JSON.parse(await readFile(join(root, 'orca-plugin.json'), 'utf8'))
|
||||
)
|
||||
|
||||
expect(manifest.main).toBe('main.mjs')
|
||||
const workerModule = (await import(pathToFileURL(join(root, manifest.main!)).href)) as {
|
||||
default?: unknown
|
||||
}
|
||||
expect(workerModule.default).toBeTypeOf('function')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,43 @@
|
||||
import { z } from 'zod'
|
||||
import type { PluginEventName } from './plugin-manifest'
|
||||
|
||||
/**
|
||||
* Payload contracts for the v0 plugin event set (worktree lifecycle + agent
|
||||
* status only). Payloads are bounded projections — never raw runtime
|
||||
* objects — so nothing sensitive (absolute repo paths beyond the worktree's
|
||||
* own, remotes, credentials) can leak through the event stream.
|
||||
*/
|
||||
|
||||
export const worktreeCreatedPayloadSchema = z.object({
|
||||
worktreeId: z.string().min(1).max(2048),
|
||||
path: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(32 * 1024),
|
||||
branch: z.string().max(1024)
|
||||
})
|
||||
|
||||
export const worktreeRemovedPayloadSchema = z.object({
|
||||
worktreeId: z.string().min(1).max(2048),
|
||||
path: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(32 * 1024)
|
||||
})
|
||||
|
||||
export const agentStatusChangedPayloadSchema = z.object({
|
||||
worktreeId: z.string().min(1).max(2048).nullable(),
|
||||
paneKey: z.string().min(1).max(2048),
|
||||
state: z.string().min(1).max(256),
|
||||
receivedAt: z.number().finite().positive()
|
||||
})
|
||||
|
||||
export const PLUGIN_EVENT_PAYLOAD_SCHEMAS: Record<PluginEventName, z.ZodTypeAny> = {
|
||||
'worktree.created': worktreeCreatedPayloadSchema,
|
||||
'worktree.removed': worktreeRemovedPayloadSchema,
|
||||
'agent.status.changed': agentStatusChangedPayloadSchema
|
||||
}
|
||||
|
||||
export type PluginWorktreeCreatedPayload = z.infer<typeof worktreeCreatedPayloadSchema>
|
||||
export type PluginWorktreeRemovedPayload = z.infer<typeof worktreeRemovedPayloadSchema>
|
||||
export type PluginAgentStatusChangedPayload = z.infer<typeof agentStatusChangedPayloadSchema>
|
||||
@@ -0,0 +1,98 @@
|
||||
/**
|
||||
* Typed extension-point registry. An extension point is a named, typed slot
|
||||
* (like a Go interface value); plugins register implementations and hosts
|
||||
* resolve them without compile-time knowledge of the implementor. Runtime
|
||||
* registration because plugins load (and unload) dynamically.
|
||||
*
|
||||
* All P0 points are EXPERIMENTAL — excluded from compatibility guarantees.
|
||||
*/
|
||||
|
||||
declare const extensionPointBrand: unique symbol
|
||||
|
||||
export type PluginExtensionPoint<T> = {
|
||||
readonly key: string
|
||||
/** Experimental points may change or vanish between releases. */
|
||||
readonly experimental: boolean
|
||||
// Why: phantom field carries T so register/resolve stay type-safe per point
|
||||
// even though the runtime value is just `{ key, experimental }`.
|
||||
readonly [extensionPointBrand]?: T
|
||||
}
|
||||
|
||||
export function definePluginExtensionPoint<T>(
|
||||
key: string,
|
||||
options: { experimental: boolean }
|
||||
): PluginExtensionPoint<T> {
|
||||
return { key, experimental: options.experimental }
|
||||
}
|
||||
|
||||
/** A contributed command whose handler lives in the plugin's worker. The
|
||||
* proxy lazily activates the worker on first invoke. */
|
||||
export type PluginWorkerCommand = {
|
||||
readonly commandId: string
|
||||
invoke(args?: unknown): Promise<unknown>
|
||||
}
|
||||
|
||||
export const PLUGIN_COMMAND_EXTENSION_POINT = definePluginExtensionPoint<PluginWorkerCommand>(
|
||||
'command',
|
||||
{ experimental: true }
|
||||
)
|
||||
|
||||
export type PluginExtensionRegistration<T> = {
|
||||
pluginId: string
|
||||
/** Contribution id within the plugin; addresses one of several providers. */
|
||||
providerId?: string
|
||||
implementation: T
|
||||
}
|
||||
|
||||
export type PluginExtensionRegistry = {
|
||||
register<T>(
|
||||
point: PluginExtensionPoint<T>,
|
||||
pluginId: string,
|
||||
implementation: T,
|
||||
providerId?: string
|
||||
): () => void
|
||||
resolveAll<T>(point: PluginExtensionPoint<T>): PluginExtensionRegistration<T>[]
|
||||
resolve<T>(point: PluginExtensionPoint<T>, pluginId: string, providerId?: string): T | null
|
||||
clearPlugin(pluginId: string): void
|
||||
}
|
||||
|
||||
export function createPluginExtensionRegistry(): PluginExtensionRegistry {
|
||||
const byPoint = new Map<string, PluginExtensionRegistration<unknown>[]>()
|
||||
|
||||
return {
|
||||
register(point, pluginId, implementation, providerId) {
|
||||
const registrations = byPoint.get(point.key) ?? []
|
||||
const entry = { pluginId, providerId, implementation }
|
||||
byPoint.set(point.key, [...registrations, entry])
|
||||
return () => {
|
||||
const current = byPoint.get(point.key) ?? []
|
||||
byPoint.set(
|
||||
point.key,
|
||||
current.filter((registration) => registration !== entry)
|
||||
)
|
||||
}
|
||||
},
|
||||
resolveAll<T>(point: PluginExtensionPoint<T>) {
|
||||
return (byPoint.get(point.key) ?? []) as PluginExtensionRegistration<T>[]
|
||||
},
|
||||
resolve<T>(point: PluginExtensionPoint<T>, pluginId: string, providerId?: string) {
|
||||
const registrations = (byPoint.get(point.key) ?? []) as PluginExtensionRegistration<T>[]
|
||||
// Why: without a providerId the first registration wins — only safe for
|
||||
// single-provider plugins; multi-provider callers must address by id.
|
||||
const match = registrations.find(
|
||||
(registration) =>
|
||||
registration.pluginId === pluginId &&
|
||||
(providerId === undefined || registration.providerId === providerId)
|
||||
)
|
||||
return match?.implementation ?? null
|
||||
},
|
||||
clearPlugin(pluginId) {
|
||||
for (const [key, registrations] of byPoint) {
|
||||
byPoint.set(
|
||||
key,
|
||||
registrations.filter((registration) => registration.pluginId !== pluginId)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
import { z } from 'zod'
|
||||
import { PLUGIN_EVENT_NAMES } from './plugin-manifest'
|
||||
import type { PluginCapabilityKind } from './plugin-capabilities'
|
||||
|
||||
/**
|
||||
* Host API v0 — the separately-versioned public facade plugins call. Every
|
||||
* method carries params AND result schemas plus capability/mutation metadata;
|
||||
* handlers (bound in main) delegate to runtime services. The raw runtime-RPC
|
||||
* registry is never exposed: its methods have no result schemas and evolve at
|
||||
* internal velocity.
|
||||
*
|
||||
* This table is the single source of truth for the capability gate, the panel
|
||||
* bridge action set, and the worker SDK. Electron-free by design: desktop
|
||||
* main, headless serve, the relay conformance path, and tests all import it.
|
||||
*
|
||||
* EXPERIMENTAL: additive-only within pluginApi major 1 once frozen; no
|
||||
* stability promises before then.
|
||||
*/
|
||||
|
||||
export const PANEL_ACTION_TEXT_MAX_LENGTH = 4096
|
||||
export const PLUGIN_WORKSPACE_TERMINAL_LIMIT = 50
|
||||
export const PLUGIN_WORKSPACE_LABEL_MAX_LENGTH = 512
|
||||
export const PLUGIN_TERMINAL_ID_MAX_LENGTH = 1024
|
||||
|
||||
const workspaceReadContextParams = z.object({}).strict().optional()
|
||||
const workspaceReadContextResult = z
|
||||
.object({
|
||||
branch: z.string().max(PLUGIN_WORKSPACE_LABEL_MAX_LENGTH),
|
||||
displayName: z.string().max(PLUGIN_WORKSPACE_LABEL_MAX_LENGTH),
|
||||
/** Terminals of the focused worktree, so callers can address a specific
|
||||
* terminal id — the API has no "active terminal" write target. */
|
||||
terminals: z
|
||||
.array(
|
||||
z
|
||||
.object({
|
||||
id: z.string().min(1).max(PLUGIN_TERMINAL_ID_MAX_LENGTH)
|
||||
})
|
||||
.strict()
|
||||
)
|
||||
.max(PLUGIN_WORKSPACE_TERMINAL_LIMIT)
|
||||
})
|
||||
.strict()
|
||||
.nullable()
|
||||
|
||||
const terminalSendTextParams = z.object({
|
||||
/** Explicit target. Never "the active terminal": a focus change must not
|
||||
* redirect a delayed plugin write into another pane (design-doc rule). */
|
||||
terminalId: z.string().min(1).max(PLUGIN_TERMINAL_ID_MAX_LENGTH),
|
||||
text: z.string().min(1).max(PANEL_ACTION_TEXT_MAX_LENGTH),
|
||||
enter: z.boolean().default(false)
|
||||
})
|
||||
const terminalSendTextResult = z.object({ accepted: z.boolean() })
|
||||
|
||||
const notificationsShowParams = z.object({
|
||||
title: z.string().min(1).max(120),
|
||||
body: z.string().max(1000).optional()
|
||||
})
|
||||
const notificationsShowResult = z.object({ delivered: z.boolean() })
|
||||
|
||||
const RESERVED_STORAGE_KEYS = new Set(['__proto__', 'prototype', 'constructor'])
|
||||
const storageKeySchema = z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(256)
|
||||
.refine((key) => !RESERVED_STORAGE_KEYS.has(key), 'reserved storage key')
|
||||
const pluginJsonValueSchema = z.json()
|
||||
/** Caps keep per-plugin storage an honest key-value store, not a database. */
|
||||
export const PLUGIN_STORAGE_VALUE_MAX_BYTES = 256 * 1024
|
||||
export const PLUGIN_STORAGE_TOTAL_MAX_BYTES = 5 * 1024 * 1024
|
||||
export const PLUGIN_STORAGE_KEY_LIMIT = 1024
|
||||
|
||||
const storageGetParams = z.object({ key: storageKeySchema })
|
||||
const storageGetResult = z.object({ value: pluginJsonValueSchema })
|
||||
const storageSetParams = z.object({ key: storageKeySchema, value: pluginJsonValueSchema })
|
||||
const storageSetResult = z.object({ ok: z.literal(true) })
|
||||
const storageDeleteParams = z.object({ key: storageKeySchema })
|
||||
const storageDeleteResult = z.object({ ok: z.literal(true) })
|
||||
const storageKeysParams = z.object({}).strict().optional()
|
||||
const storageKeysResult = z.object({ keys: z.array(z.string()).max(PLUGIN_STORAGE_KEY_LIMIT) })
|
||||
|
||||
const secretsGetParams = z.object({ key: storageKeySchema })
|
||||
const secretsGetResult = z.object({ value: z.string().nullable() })
|
||||
const secretsSetParams = z.object({ key: storageKeySchema, value: z.string().max(64 * 1024) })
|
||||
const secretsSetResult = z.object({ ok: z.literal(true) })
|
||||
const secretsDeleteParams = z.object({ key: storageKeySchema })
|
||||
const secretsDeleteResult = z.object({ ok: z.literal(true) })
|
||||
|
||||
const settingsGetParams = z.object({}).strict().optional()
|
||||
const settingsGetResult = z.object({ settings: z.record(z.string(), pluginJsonValueSchema) })
|
||||
const settingsSetParams = z.object({ key: storageKeySchema, value: pluginJsonValueSchema })
|
||||
const settingsSetResult = z.object({ ok: z.literal(true) })
|
||||
|
||||
const eventsSubscribeParams = z.object({
|
||||
events: z.array(z.enum(PLUGIN_EVENT_NAMES)).min(1).max(PLUGIN_EVENT_NAMES.length)
|
||||
})
|
||||
const eventsSubscribeResult = z.object({ subscribed: z.array(z.enum(PLUGIN_EVENT_NAMES)) })
|
||||
|
||||
export type PluginHostMethodSpec = {
|
||||
name: string
|
||||
/** pluginApi minor the method appeared in (`1.0` for the v0 set). */
|
||||
since: string
|
||||
/** Machine-readable resource boundary enforced by the host binding. */
|
||||
scope: 'active-worktree' | 'explicit-terminal' | 'plugin-private' | 'desktop' | 'host-events'
|
||||
stability: 'experimental'
|
||||
capability: PluginCapabilityKind
|
||||
/** Mutations are audit-logged with actor `plugin:<id>`. */
|
||||
mutation: boolean
|
||||
/** Whether sandboxed panels may call this over the postMessage bridge.
|
||||
* Workers can call every method. */
|
||||
panel: boolean
|
||||
params: z.ZodTypeAny
|
||||
result: z.ZodTypeAny
|
||||
}
|
||||
|
||||
const spec = <P extends z.ZodTypeAny, R extends z.ZodTypeAny>(
|
||||
entry: Omit<PluginHostMethodSpec, 'params' | 'result' | 'stability'> & {
|
||||
params: P
|
||||
result: R
|
||||
}
|
||||
): PluginHostMethodSpec => ({ ...entry, stability: 'experimental' })
|
||||
|
||||
export const PLUGIN_HOST_API_V0: readonly PluginHostMethodSpec[] = [
|
||||
spec({
|
||||
name: 'workspace.readContext',
|
||||
since: '1.0',
|
||||
scope: 'active-worktree',
|
||||
capability: 'workspace:read',
|
||||
mutation: false,
|
||||
panel: true,
|
||||
params: workspaceReadContextParams,
|
||||
result: workspaceReadContextResult
|
||||
}),
|
||||
spec({
|
||||
name: 'terminal.sendText',
|
||||
since: '1.0',
|
||||
scope: 'explicit-terminal',
|
||||
capability: 'terminal:send',
|
||||
mutation: true,
|
||||
panel: true,
|
||||
params: terminalSendTextParams,
|
||||
result: terminalSendTextResult
|
||||
}),
|
||||
spec({
|
||||
name: 'notifications.show',
|
||||
since: '1.0',
|
||||
scope: 'desktop',
|
||||
capability: 'notifications:show',
|
||||
mutation: true,
|
||||
panel: true,
|
||||
params: notificationsShowParams,
|
||||
result: notificationsShowResult
|
||||
}),
|
||||
spec({
|
||||
name: 'storage.get',
|
||||
since: '1.0',
|
||||
scope: 'plugin-private',
|
||||
capability: 'storage',
|
||||
mutation: false,
|
||||
panel: false,
|
||||
params: storageGetParams,
|
||||
result: storageGetResult
|
||||
}),
|
||||
spec({
|
||||
name: 'storage.set',
|
||||
since: '1.0',
|
||||
scope: 'plugin-private',
|
||||
capability: 'storage',
|
||||
mutation: true,
|
||||
panel: false,
|
||||
params: storageSetParams,
|
||||
result: storageSetResult
|
||||
}),
|
||||
spec({
|
||||
name: 'storage.delete',
|
||||
since: '1.0',
|
||||
scope: 'plugin-private',
|
||||
capability: 'storage',
|
||||
mutation: true,
|
||||
panel: false,
|
||||
params: storageDeleteParams,
|
||||
result: storageDeleteResult
|
||||
}),
|
||||
spec({
|
||||
name: 'storage.keys',
|
||||
since: '1.0',
|
||||
scope: 'plugin-private',
|
||||
capability: 'storage',
|
||||
mutation: false,
|
||||
panel: false,
|
||||
params: storageKeysParams,
|
||||
result: storageKeysResult
|
||||
}),
|
||||
spec({
|
||||
name: 'secrets.get',
|
||||
since: '1.0',
|
||||
scope: 'plugin-private',
|
||||
capability: 'secrets',
|
||||
mutation: false,
|
||||
panel: false,
|
||||
params: secretsGetParams,
|
||||
result: secretsGetResult
|
||||
}),
|
||||
spec({
|
||||
name: 'secrets.set',
|
||||
since: '1.0',
|
||||
scope: 'plugin-private',
|
||||
capability: 'secrets',
|
||||
mutation: true,
|
||||
panel: false,
|
||||
params: secretsSetParams,
|
||||
result: secretsSetResult
|
||||
}),
|
||||
spec({
|
||||
name: 'secrets.delete',
|
||||
since: '1.0',
|
||||
scope: 'plugin-private',
|
||||
capability: 'secrets',
|
||||
mutation: true,
|
||||
panel: false,
|
||||
params: secretsDeleteParams,
|
||||
result: secretsDeleteResult
|
||||
}),
|
||||
spec({
|
||||
name: 'settings.get',
|
||||
since: '1.0',
|
||||
scope: 'plugin-private',
|
||||
capability: 'settings:own',
|
||||
mutation: false,
|
||||
panel: false,
|
||||
params: settingsGetParams,
|
||||
result: settingsGetResult
|
||||
}),
|
||||
spec({
|
||||
name: 'settings.set',
|
||||
since: '1.0',
|
||||
scope: 'plugin-private',
|
||||
capability: 'settings:own',
|
||||
mutation: true,
|
||||
panel: false,
|
||||
params: settingsSetParams,
|
||||
result: settingsSetResult
|
||||
}),
|
||||
spec({
|
||||
name: 'events.subscribe',
|
||||
since: '1.0',
|
||||
scope: 'host-events',
|
||||
capability: 'events:subscribe',
|
||||
mutation: false,
|
||||
panel: false,
|
||||
params: eventsSubscribeParams,
|
||||
result: eventsSubscribeResult
|
||||
})
|
||||
]
|
||||
|
||||
const SPEC_BY_NAME = new Map(PLUGIN_HOST_API_V0.map((entry) => [entry.name, entry]))
|
||||
|
||||
export function getPluginHostMethodSpec(name: string): PluginHostMethodSpec | null {
|
||||
return SPEC_BY_NAME.get(name) ?? null
|
||||
}
|
||||
|
||||
/** Actions sandboxed panels may request over the postMessage bridge. Derived
|
||||
* from the spec table so the panel surface can never drift from the gate. */
|
||||
export const PLUGIN_PANEL_ACTIONS = PLUGIN_HOST_API_V0.filter((entry) => entry.panel).map(
|
||||
(entry) => entry.name
|
||||
)
|
||||
|
||||
export function isPluginPanelAction(action: string): boolean {
|
||||
return PLUGIN_PANEL_ACTIONS.includes(action)
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import { z } from 'zod'
|
||||
import { PLUGIN_COMMAND_LIMIT, PLUGIN_EVENT_NAMES, pluginCommandIdSchema } from './plugin-manifest'
|
||||
import { PLUGIN_CAPABILITY_KINDS } from './plugin-capabilities'
|
||||
|
||||
/**
|
||||
* Message protocol between the Orca process and the out-of-process plugin
|
||||
* worker (child_process.fork channel). Zod-validated on both sides because
|
||||
* the child runs third-party code — nothing it sends is trusted structurally.
|
||||
*/
|
||||
|
||||
export const pluginWorkerInitSchema = z.object({
|
||||
type: z.literal('init'),
|
||||
/** Qualified `<publisher>.<id>` key. */
|
||||
pluginId: z.string().min(1),
|
||||
pluginRoot: z.string().min(1),
|
||||
mainEntry: z.string().min(1),
|
||||
/** Consented capability kinds, so the in-worker SDK can fail fast client-
|
||||
* side; the host re-gates every call regardless. */
|
||||
grantedCapabilities: z.array(z.enum(PLUGIN_CAPABILITY_KINDS))
|
||||
})
|
||||
|
||||
export const pluginWorkerInvokeCommandSchema = z.object({
|
||||
type: z.literal('invokeCommand'),
|
||||
callId: z.number().int().nonnegative(),
|
||||
commandId: z.string().min(1),
|
||||
args: z.unknown().optional()
|
||||
})
|
||||
|
||||
export const pluginWorkerDeliverEventSchema = z.object({
|
||||
type: z.literal('deliverEvent'),
|
||||
eventId: z.number().int().nonnegative(),
|
||||
event: z.enum(PLUGIN_EVENT_NAMES),
|
||||
payload: z.unknown()
|
||||
})
|
||||
|
||||
export const pluginWorkerHostResultSchema = z.object({
|
||||
type: z.literal('hostResult'),
|
||||
callId: z.number().int().nonnegative(),
|
||||
ok: z.boolean(),
|
||||
value: z.unknown().optional(),
|
||||
errorCode: z.string().optional(),
|
||||
error: z.string().optional()
|
||||
})
|
||||
|
||||
export const pluginWorkerShutdownSchema = z.object({ type: z.literal('shutdown') })
|
||||
|
||||
export const pluginWorkerParentMessageSchema = z.discriminatedUnion('type', [
|
||||
pluginWorkerInitSchema,
|
||||
pluginWorkerInvokeCommandSchema,
|
||||
pluginWorkerDeliverEventSchema,
|
||||
pluginWorkerHostResultSchema,
|
||||
pluginWorkerShutdownSchema
|
||||
])
|
||||
|
||||
export const pluginWorkerReadySchema = z.object({
|
||||
type: z.literal('ready'),
|
||||
/** Command ids the worker registered handlers for (⊆ manifest commands). */
|
||||
commands: z.array(pluginCommandIdSchema).max(PLUGIN_COMMAND_LIMIT)
|
||||
})
|
||||
|
||||
export const pluginWorkerCommandResultSchema = z.object({
|
||||
type: z.literal('commandResult'),
|
||||
callId: z.number().int().nonnegative(),
|
||||
ok: z.boolean(),
|
||||
// Why: value crosses a fork() IPC boundary, so it is structured-clone data
|
||||
// by construction; zod treats it as opaque and callers re-validate shape.
|
||||
value: z.unknown().optional(),
|
||||
error: z.string().max(8192).optional()
|
||||
})
|
||||
|
||||
export const pluginWorkerEventAckSchema = z.object({
|
||||
type: z.literal('eventAck'),
|
||||
eventId: z.number().int().nonnegative()
|
||||
})
|
||||
|
||||
/** Worker→host API call (the plugin SDK's transport for host methods). */
|
||||
export const pluginWorkerHostCallSchema = z.object({
|
||||
type: z.literal('hostCall'),
|
||||
callId: z.number().int().nonnegative(),
|
||||
method: z.string().min(1),
|
||||
params: z.unknown().optional()
|
||||
})
|
||||
|
||||
export const pluginWorkerLogSchema = z.object({
|
||||
type: z.literal('log'),
|
||||
level: z.enum(['info', 'warn', 'error']),
|
||||
message: z.string().max(8192)
|
||||
})
|
||||
|
||||
export const pluginWorkerFatalSchema = z.object({
|
||||
type: z.literal('fatal'),
|
||||
error: z.string().max(8192)
|
||||
})
|
||||
|
||||
export const pluginWorkerChildMessageSchema = z.discriminatedUnion('type', [
|
||||
pluginWorkerReadySchema,
|
||||
pluginWorkerCommandResultSchema,
|
||||
pluginWorkerEventAckSchema,
|
||||
pluginWorkerHostCallSchema,
|
||||
pluginWorkerLogSchema,
|
||||
pluginWorkerFatalSchema
|
||||
])
|
||||
|
||||
export type PluginWorkerParentMessage = z.infer<typeof pluginWorkerParentMessageSchema>
|
||||
export type PluginWorkerChildMessage = z.infer<typeof pluginWorkerChildMessageSchema>
|
||||
export type PluginWorkerInit = z.infer<typeof pluginWorkerInitSchema>
|
||||
|
||||
export const PLUGIN_WORKER_READY_TIMEOUT_MS = 10_000
|
||||
export const PLUGIN_WORKER_INVOKE_TIMEOUT_MS = 30_000
|
||||
/** Idle reap: a worker with no in-flight work for this long is disposed and
|
||||
* re-forked on the next trigger. */
|
||||
export const PLUGIN_WORKER_IDLE_REAP_MS = 5 * 60_000
|
||||
/** Default cap on concurrently-active workers; excess activations queue. */
|
||||
export const PLUGIN_WORKER_MAX_ACTIVE_DEFAULT = 5
|
||||
@@ -0,0 +1,29 @@
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { Script } from 'node:vm'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
describe('hostile panel fixture', () => {
|
||||
it('is complete JavaScript and retains every containment probe', async () => {
|
||||
const html = await readFile(
|
||||
join(process.cwd(), 'examples', 'plugins', 'hostile-panel', 'panel.html'),
|
||||
'utf8'
|
||||
)
|
||||
const script = html.match(/<script>([\s\S]*?)<\/script>/)?.[1]
|
||||
|
||||
expect(script).toBeTruthy()
|
||||
if (!script) {
|
||||
throw new Error('hostile fixture script is missing')
|
||||
}
|
||||
expect(() => new Script(script)).not.toThrow()
|
||||
expect(html).toContain('self-navigation')
|
||||
expect(html).toContain('meta-refresh-navigation')
|
||||
expect(html).toContain('Navigation probes are opt-in')
|
||||
expect(html).toContain("window.name = ''")
|
||||
expect(html).toContain('oversized-message')
|
||||
expect(html).toContain('message-flood')
|
||||
expect(html).toContain("data.errorCode === 'rate_limited'")
|
||||
expect(html).toContain('busy-loop')
|
||||
expect(html.trimEnd()).toMatch(/<\/html>$/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { pluginInstallSourceSchema } from './plugin-install-lockfile'
|
||||
|
||||
describe('pluginInstallSourceSchema marketplace provenance', () => {
|
||||
it('records both the marketplace snapshot and plugin Git ref', () => {
|
||||
expect(
|
||||
pluginInstallSourceSchema.parse({
|
||||
kind: 'marketplace',
|
||||
marketplace: {
|
||||
url: 'https://github.com/stablyai/orca-plugins.git',
|
||||
ref: 'main',
|
||||
resolvedCommit: 'a'.repeat(40)
|
||||
},
|
||||
plugin: {
|
||||
url: 'git@github.com:stablyai/orca-skills.git',
|
||||
ref: 'v1.0.0'
|
||||
}
|
||||
})
|
||||
).toEqual({
|
||||
kind: 'marketplace',
|
||||
marketplace: {
|
||||
url: 'https://github.com/stablyai/orca-plugins.git',
|
||||
ref: 'main',
|
||||
resolvedCommit: 'a'.repeat(40)
|
||||
},
|
||||
plugin: {
|
||||
url: 'git@github.com:stablyai/orca-skills.git',
|
||||
ref: 'v1.0.0'
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
it('requires pinned refs and an exact marketplace snapshot commit', () => {
|
||||
expect(
|
||||
pluginInstallSourceSchema.safeParse({
|
||||
kind: 'marketplace',
|
||||
marketplace: {
|
||||
url: 'https://github.com/stablyai/orca-plugins.git',
|
||||
ref: '',
|
||||
resolvedCommit: 'main'
|
||||
},
|
||||
plugin: {
|
||||
url: 'https://github.com/stablyai/orca-skills.git',
|
||||
ref: ''
|
||||
}
|
||||
}).success
|
||||
).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,165 @@
|
||||
import { z } from 'zod'
|
||||
import { isQualifiedPluginKey } from './plugin-manifest'
|
||||
|
||||
/**
|
||||
* Install lockfile: records where each installed plugin came from, the exact
|
||||
* commit it resolved to, the content hash of the installed tree, and the
|
||||
* consent fingerprint the user was shown. A reinstall/update that does not
|
||||
* match is a visible change, never a silent one. Adapted from community PR
|
||||
* #5801's SHA-256 + lockfile installer pieces.
|
||||
*/
|
||||
|
||||
/** Install content hash: legacy 128-bit SHA-256 prefix or the full digest. */
|
||||
export const PLUGIN_CONTENT_HASH_PATTERN = /^(?:[0-9a-f]{32}|[0-9a-f]{64})$/
|
||||
/** Git object id, SHA-1 or SHA-256. */
|
||||
export const PLUGIN_COMMIT_PATTERN = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/
|
||||
|
||||
export const pluginInstallSourceSchema = z.discriminatedUnion('kind', [
|
||||
z.object({
|
||||
kind: z.literal('local-path'),
|
||||
path: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(32 * 1024)
|
||||
}),
|
||||
z.object({
|
||||
kind: z.literal('git'),
|
||||
url: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(32 * 1024)
|
||||
.refine(isAllowedPluginGitUrl, 'git URL must use HTTPS or SSH'),
|
||||
/** Requested ref (`#ref` suffix); empty means the remote default branch. */
|
||||
ref: z.string().max(4096).default('')
|
||||
}),
|
||||
z.object({
|
||||
kind: z.literal('marketplace'),
|
||||
marketplace: z.object({
|
||||
url: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(32 * 1024)
|
||||
.refine(isAllowedPluginGitUrl, 'marketplace Git URL must use HTTPS or SSH'),
|
||||
ref: z.string().min(1).max(4096),
|
||||
resolvedCommit: z.string().regex(PLUGIN_COMMIT_PATTERN)
|
||||
}),
|
||||
plugin: z.object({
|
||||
url: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(32 * 1024)
|
||||
.refine(isAllowedPluginGitUrl, 'plugin Git URL must use HTTPS or SSH'),
|
||||
ref: z.string().min(1).max(4096)
|
||||
})
|
||||
}),
|
||||
z.object({
|
||||
kind: z.literal('bundled'),
|
||||
bundleId: z.string().refine(isQualifiedPluginKey, 'invalid bundled plugin identity')
|
||||
})
|
||||
])
|
||||
|
||||
export type PluginInstallSource = z.infer<typeof pluginInstallSourceSchema>
|
||||
|
||||
/** System Git supports executable remote helpers (`ext::`, custom `foo::`
|
||||
* transports). P0 accepts network Git only over HTTPS or SSH so installing a
|
||||
* source cannot turn URL parsing into arbitrary command execution. */
|
||||
export function isAllowedPluginGitUrl(value: string): boolean {
|
||||
const url = value.trim()
|
||||
if (/^[^\s@/:]+@[A-Za-z0-9.-]+:[^\s]+$/.test(url)) {
|
||||
return true
|
||||
}
|
||||
try {
|
||||
const parsed = new URL(url)
|
||||
if (!parsed.hostname || parsed.password) {
|
||||
return false
|
||||
}
|
||||
if (parsed.protocol === 'https:') {
|
||||
return parsed.username.length === 0
|
||||
}
|
||||
return parsed.protocol === 'ssh:'
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export const pluginLockEntrySchema = z
|
||||
.object({
|
||||
/** Qualified `<publisher>.<id>` key. */
|
||||
pluginKey: z.string().refine(isQualifiedPluginKey, 'invalid qualified plugin key'),
|
||||
version: z.string().min(1).max(128),
|
||||
source: pluginInstallSourceSchema,
|
||||
/** Commit the git source resolved to at install time; null for local. */
|
||||
resolvedCommit: z.string().regex(PLUGIN_COMMIT_PATTERN).nullable(),
|
||||
/** Deterministic hash of the installed file tree (also the install dir name). */
|
||||
contentHash: z.string().regex(PLUGIN_CONTENT_HASH_PATTERN),
|
||||
/** New descriptive name, accepted for forward compatibility. */
|
||||
consentFingerprint: z.string().min(1).max(256).optional(),
|
||||
/** v1 on-disk name retained so existing Orca builds can read new lockfiles. */
|
||||
capabilityHash: z.string().min(1).max(256).optional(),
|
||||
installedAt: z.number().finite().nonnegative()
|
||||
})
|
||||
.refine((entry) => entry.consentFingerprint || entry.capabilityHash, {
|
||||
message: 'consent fingerprint is required'
|
||||
})
|
||||
.transform(({ capabilityHash, consentFingerprint, ...entry }) => ({
|
||||
...entry,
|
||||
consentFingerprint: consentFingerprint ?? capabilityHash!
|
||||
}))
|
||||
|
||||
export type PluginLockEntry = z.infer<typeof pluginLockEntrySchema>
|
||||
|
||||
export const pluginLockfileSchema = z
|
||||
.object({
|
||||
version: z.literal(1),
|
||||
plugins: z.record(z.string(), pluginLockEntrySchema)
|
||||
})
|
||||
.superRefine((lock, ctx) => {
|
||||
for (const [key, entry] of Object.entries(lock.plugins)) {
|
||||
if (!isQualifiedPluginKey(key) || entry.pluginKey !== key) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['plugins', key],
|
||||
message: 'lockfile key must match its qualified plugin identity'
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export type PluginLockfile = z.infer<typeof pluginLockfileSchema>
|
||||
|
||||
/**
|
||||
* Lockfile v1 called this opaque value `capabilityHash`. Keep writing that
|
||||
* field so rollback to an older host does not make the whole lockfile unreadable.
|
||||
*/
|
||||
export function serializePluginLockfile(lock: PluginLockfile): unknown {
|
||||
return {
|
||||
version: 1,
|
||||
plugins: Object.fromEntries(
|
||||
Object.entries(lock.plugins).map(([key, { consentFingerprint, ...entry }]) => [
|
||||
key,
|
||||
{ ...entry, capabilityHash: consentFingerprint }
|
||||
])
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export function emptyPluginLockfile(): PluginLockfile {
|
||||
return { version: 1, plugins: {} }
|
||||
}
|
||||
|
||||
export function upsertPluginLock(lock: PluginLockfile, entry: PluginLockEntry): PluginLockfile {
|
||||
return { version: 1, plugins: { ...lock.plugins, [entry.pluginKey]: entry } }
|
||||
}
|
||||
|
||||
export function removePluginLock(lock: PluginLockfile, pluginKey: string): PluginLockfile {
|
||||
const plugins = { ...lock.plugins }
|
||||
delete plugins[pluginKey]
|
||||
return { version: 1, plugins }
|
||||
}
|
||||
|
||||
export function parsePluginLockfile(raw: unknown): PluginLockfile {
|
||||
const parsed = pluginLockfileSchema.safeParse(raw)
|
||||
// A corrupt lockfile must not brick installs; integrity of installed trees
|
||||
// is independently anchored by their hash-addressed directory names.
|
||||
return parsed.success ? parsed.data : emptyPluginLockfile()
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
PLUGIN_KILL_LIST_ENTRY_LIMIT,
|
||||
findKilledPlugin,
|
||||
killedPluginKeys,
|
||||
pluginKillListSchema
|
||||
} from './plugin-kill-list'
|
||||
|
||||
function entry(pluginKey = 'community.unsafe'): Record<string, unknown> {
|
||||
return {
|
||||
pluginKey,
|
||||
reason: 'Known malicious release',
|
||||
advisoryUrl: 'https://orca.example/security/unsafe'
|
||||
}
|
||||
}
|
||||
|
||||
describe('pluginKillListSchema', () => {
|
||||
it('parses a strict versioned revocation document', () => {
|
||||
const parsed = pluginKillListSchema.parse({
|
||||
version: 1,
|
||||
generatedAt: '2026-07-12T20:00:00Z',
|
||||
plugins: [entry()]
|
||||
})
|
||||
|
||||
expect(findKilledPlugin(parsed, 'community.unsafe')).toEqual(entry())
|
||||
expect(killedPluginKeys(parsed)).toEqual(new Set(['community.unsafe']))
|
||||
})
|
||||
|
||||
it.each([
|
||||
{
|
||||
version: 1,
|
||||
generatedAt: '2026-07-12T20:00:00Z',
|
||||
plugins: [],
|
||||
unexpected: true
|
||||
},
|
||||
{
|
||||
version: 1,
|
||||
generatedAt: '2026-07-12T20:00:00Z',
|
||||
plugins: [{ ...entry(), unexpected: true }]
|
||||
},
|
||||
{
|
||||
version: 1,
|
||||
generatedAt: 'not-a-date',
|
||||
plugins: []
|
||||
},
|
||||
{
|
||||
version: 1,
|
||||
generatedAt: '2026-07-12T20:00:00Z',
|
||||
plugins: [{ ...entry(), pluginKey: 'unsafe' }]
|
||||
},
|
||||
{
|
||||
version: 1,
|
||||
generatedAt: '2026-07-12T20:00:00Z',
|
||||
plugins: [{ ...entry(), advisoryUrl: 'http://orca.example/advisory' }]
|
||||
}
|
||||
])('rejects malformed or untrusted fields', (killList) => {
|
||||
expect(pluginKillListSchema.safeParse(killList).success).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects duplicate killed plugin identities', () => {
|
||||
const parsed = pluginKillListSchema.safeParse({
|
||||
version: 1,
|
||||
generatedAt: '2026-07-12T20:00:00Z',
|
||||
plugins: [entry(), entry()]
|
||||
})
|
||||
|
||||
expect(parsed.success).toBe(false)
|
||||
if (!parsed.success) {
|
||||
expect(parsed.error.issues).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ message: 'duplicate killed plugin: community.unsafe' })
|
||||
])
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
it('caps the revocation document size by entry count', () => {
|
||||
const plugins = Array.from({ length: PLUGIN_KILL_LIST_ENTRY_LIMIT + 1 }, (_, index) =>
|
||||
entry(`publisher.plugin-${index}`)
|
||||
)
|
||||
expect(
|
||||
pluginKillListSchema.safeParse({
|
||||
version: 1,
|
||||
generatedAt: '2026-07-12T20:00:00Z',
|
||||
plugins
|
||||
}).success
|
||||
).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,50 @@
|
||||
import { z } from 'zod'
|
||||
import { isQualifiedPluginKey } from './plugin-manifest'
|
||||
|
||||
export const PLUGIN_KILL_LIST_ENTRY_LIMIT = 4_096
|
||||
|
||||
const advisoryUrlSchema = z
|
||||
.string()
|
||||
.url()
|
||||
.max(2_048)
|
||||
.refine((value) => new URL(value).protocol === 'https:', 'advisory URL must use HTTPS')
|
||||
|
||||
export const pluginKillListEntrySchema = z.strictObject({
|
||||
pluginKey: z.string().refine(isQualifiedPluginKey, 'invalid qualified plugin key'),
|
||||
reason: z.string().min(1).max(1_024),
|
||||
advisoryUrl: advisoryUrlSchema.optional()
|
||||
})
|
||||
|
||||
export const pluginKillListSchema = z
|
||||
.strictObject({
|
||||
version: z.literal(1),
|
||||
generatedAt: z.string().datetime({ offset: true }),
|
||||
plugins: z.array(pluginKillListEntrySchema).max(PLUGIN_KILL_LIST_ENTRY_LIMIT)
|
||||
})
|
||||
.superRefine((killList, context) => {
|
||||
const seen = new Set<string>()
|
||||
for (const [index, plugin] of killList.plugins.entries()) {
|
||||
if (seen.has(plugin.pluginKey)) {
|
||||
context.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['plugins', index, 'pluginKey'],
|
||||
message: `duplicate killed plugin: ${plugin.pluginKey}`
|
||||
})
|
||||
}
|
||||
seen.add(plugin.pluginKey)
|
||||
}
|
||||
})
|
||||
|
||||
export type PluginKillList = z.infer<typeof pluginKillListSchema>
|
||||
export type PluginKillListEntry = z.infer<typeof pluginKillListEntrySchema>
|
||||
|
||||
export function killedPluginKeys(killList: PluginKillList): ReadonlySet<string> {
|
||||
return new Set(killList.plugins.map((plugin) => plugin.pluginKey))
|
||||
}
|
||||
|
||||
export function findKilledPlugin(
|
||||
killList: PluginKillList,
|
||||
pluginKey: string
|
||||
): PluginKillListEntry | null {
|
||||
return killList.plugins.find((plugin) => plugin.pluginKey === pluginKey) ?? null
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
parsePluginLanguagePackArtifact,
|
||||
PLUGIN_LANGUAGE_CATALOG_MAX_DEPTH,
|
||||
pluginLanguageResourceId
|
||||
} from './plugin-language-pack-artifact'
|
||||
|
||||
describe('plugin language-pack artifacts', () => {
|
||||
it('maps qualified IDs to distinct alphanumeric i18next resource languages', () => {
|
||||
const first = pluginLanguageResourceId('plugin:a.bc/d-ef')
|
||||
const second = pluginLanguageResourceId('plugin:ab.c/de-f')
|
||||
|
||||
expect(first).toMatch(/^plugin[0-9a-f]+$/)
|
||||
expect(second).toMatch(/^plugin[0-9a-f]+$/)
|
||||
expect(first).not.toBe(second)
|
||||
})
|
||||
|
||||
it('accepts nested string catalogs and reports their bounded entry count', () => {
|
||||
expect(
|
||||
parsePluginLanguagePackArtifact(
|
||||
JSON.stringify({
|
||||
settings: { appearance: { title: 'Aparência' } },
|
||||
common: { save: 'Salvar' }
|
||||
})
|
||||
)
|
||||
).toEqual({
|
||||
ok: true,
|
||||
catalog: {
|
||||
settings: { appearance: { title: 'Aparência' } },
|
||||
common: { save: 'Salvar' }
|
||||
},
|
||||
entries: 5
|
||||
})
|
||||
})
|
||||
|
||||
it.each([
|
||||
'PluginConsentDialog',
|
||||
'PluginKeybindingConsentPreview',
|
||||
'PluginMarketplaceListingRow',
|
||||
'PluginMarketplacePreviewDialog',
|
||||
'PluginMarketplaceSourceDialog',
|
||||
'PluginVmRecipeConsentPreview'
|
||||
])('prevents language packs from rewriting %s security copy', (component) => {
|
||||
expect(
|
||||
parsePluginLanguagePackArtifact(
|
||||
JSON.stringify({
|
||||
auto: {
|
||||
components: {
|
||||
settings: { [component]: { disclaimer: 'This plugin is perfectly safe.' } }
|
||||
}
|
||||
}
|
||||
})
|
||||
)
|
||||
).toMatchObject({ ok: false, error: expect.stringContaining('protected security copy') })
|
||||
})
|
||||
|
||||
it.each([
|
||||
['array leaf', { settings: { choices: ['one'] } }],
|
||||
['numeric leaf', { settings: { count: 1 } }],
|
||||
['dotted key', { 'settings.title': 'Title' }],
|
||||
['prototype key', JSON.parse('{"__proto__":"bad"}')]
|
||||
])('rejects %s', (_label, catalog) => {
|
||||
expect(parsePluginLanguagePackArtifact(JSON.stringify(catalog)).ok).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects excessive nesting without recursive validation', () => {
|
||||
let catalog: Record<string, unknown> = { value: 'deep' }
|
||||
for (let index = 0; index <= PLUGIN_LANGUAGE_CATALOG_MAX_DEPTH; index += 1) {
|
||||
catalog = { nested: catalog }
|
||||
}
|
||||
expect(parsePluginLanguagePackArtifact(JSON.stringify(catalog))).toMatchObject({
|
||||
ok: false,
|
||||
error: expect.stringContaining('depth')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,118 @@
|
||||
export const PLUGIN_LANGUAGE_CATALOG_MAX_ENTRIES = 20_000
|
||||
export const PLUGIN_LANGUAGE_CATALOG_MAX_DEPTH = 16
|
||||
|
||||
const DANGEROUS_CATALOG_KEYS = new Set(['__proto__', 'prototype', 'constructor'])
|
||||
const PROTECTED_TRANSLATION_PREFIXES = [
|
||||
'auto.components.settings.PluginConsentDialog',
|
||||
'auto.components.settings.PluginInstallDialog',
|
||||
'auto.components.settings.PluginKeybindingConsentPreview',
|
||||
'auto.components.settings.PluginMarketplaceBrowser',
|
||||
'auto.components.settings.PluginMarketplaceListingRow',
|
||||
'auto.components.settings.PluginMarketplacePreviewDialog',
|
||||
'auto.components.settings.PluginMarketplaceSourceDialog',
|
||||
'auto.components.settings.PluginRemoveDialog',
|
||||
'auto.components.settings.PluginRollbackDialog',
|
||||
'auto.components.settings.PluginSettingsRow',
|
||||
'auto.components.settings.PluginVmRecipeConsentPreview',
|
||||
'auto.components.settings.PluginsSettingsSection'
|
||||
]
|
||||
|
||||
export type PluginLanguagePackRegistration = {
|
||||
id: `plugin:${string}`
|
||||
resourceLanguage: `plugin${string}`
|
||||
pluginKey: string
|
||||
locale: string
|
||||
catalog: Record<string, unknown>
|
||||
}
|
||||
|
||||
export function pluginLanguageResourceId(id: `plugin:${string}`): `plugin${string}` {
|
||||
let encoded = ''
|
||||
for (let index = 0; index < id.length; index += 1) {
|
||||
encoded += id.charCodeAt(index).toString(16).padStart(4, '0')
|
||||
}
|
||||
// Why: i18next parses punctuation in language tags during resource lookup;
|
||||
// fixed-width UTF-16 hex preserves a collision-free qualified-ID mapping.
|
||||
return `plugin${encoded}`
|
||||
}
|
||||
|
||||
export type PluginLanguagePackParseResult =
|
||||
| { ok: true; catalog: Record<string, unknown>; entries: number }
|
||||
| { ok: false; error: string }
|
||||
|
||||
type CatalogFrame = {
|
||||
source: Record<string, unknown>
|
||||
target: Record<string, unknown>
|
||||
path: string
|
||||
depth: number
|
||||
}
|
||||
|
||||
function isCatalogObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function protectedTranslation(path: string): boolean {
|
||||
return PROTECTED_TRANSLATION_PREFIXES.some(
|
||||
(prefix) => path === prefix || path.startsWith(`${prefix}.`)
|
||||
)
|
||||
}
|
||||
|
||||
function hasUnsafeCatalogKeyCharacter(key: string): boolean {
|
||||
return key.includes('.') || Array.from(key).some((character) => character.charCodeAt(0) <= 31)
|
||||
}
|
||||
|
||||
export function parsePluginLanguagePackArtifact(raw: string): PluginLanguagePackParseResult {
|
||||
let json: unknown
|
||||
try {
|
||||
json = JSON.parse(raw)
|
||||
} catch {
|
||||
return { ok: false, error: 'language pack must contain one JSON object' }
|
||||
}
|
||||
if (!isCatalogObject(json)) {
|
||||
return { ok: false, error: 'language pack root must be an object' }
|
||||
}
|
||||
|
||||
const catalog: Record<string, unknown> = {}
|
||||
const stack: CatalogFrame[] = [{ source: json, target: catalog, path: '', depth: 0 }]
|
||||
let entries = 0
|
||||
while (stack.length > 0) {
|
||||
const frame = stack.pop()!
|
||||
if (frame.depth > PLUGIN_LANGUAGE_CATALOG_MAX_DEPTH) {
|
||||
return { ok: false, error: `catalog exceeds depth ${PLUGIN_LANGUAGE_CATALOG_MAX_DEPTH}` }
|
||||
}
|
||||
for (const [key, value] of Object.entries(frame.source)) {
|
||||
entries += 1
|
||||
if (entries > PLUGIN_LANGUAGE_CATALOG_MAX_ENTRIES) {
|
||||
return {
|
||||
ok: false,
|
||||
error: `catalog exceeds ${PLUGIN_LANGUAGE_CATALOG_MAX_ENTRIES} entries`
|
||||
}
|
||||
}
|
||||
if (
|
||||
key.length === 0 ||
|
||||
key.length > 128 ||
|
||||
DANGEROUS_CATALOG_KEYS.has(key) ||
|
||||
hasUnsafeCatalogKeyCharacter(key)
|
||||
) {
|
||||
return { ok: false, error: `catalog key ${key || '(empty)'} is not safe` }
|
||||
}
|
||||
const path = frame.path ? `${frame.path}.${key}` : key
|
||||
if (protectedTranslation(path)) {
|
||||
return { ok: false, error: `catalog cannot replace protected security copy at ${path}` }
|
||||
}
|
||||
if (typeof value === 'string') {
|
||||
if (value.length > 8192) {
|
||||
return { ok: false, error: `translation at ${path} exceeds 8192 characters` }
|
||||
}
|
||||
frame.target[key] = value
|
||||
continue
|
||||
}
|
||||
if (!isCatalogObject(value)) {
|
||||
return { ok: false, error: `translation at ${path} must be a string or object` }
|
||||
}
|
||||
const child: Record<string, unknown> = {}
|
||||
frame.target[key] = child
|
||||
stack.push({ source: value, target: child, path, depth: frame.depth + 1 })
|
||||
}
|
||||
}
|
||||
return { ok: true, catalog, entries }
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
import type { RefinementCtx } from 'zod'
|
||||
import { isPluginCommandAliasActionId } from './plugin-command-actions'
|
||||
import { getKeybindingConflictIdentity } from '../keybindings'
|
||||
|
||||
type IdentifiedContribution = { id: string }
|
||||
type PathContribution = { path: string }
|
||||
|
||||
type ContributionValidationManifest = {
|
||||
main?: string
|
||||
contributes: {
|
||||
panels: IdentifiedContribution[]
|
||||
commands: (IdentifiedContribution & { action?: string; context?: 'global' | 'worktree' })[]
|
||||
events: { on: string }[]
|
||||
languagePacks: { locale: string }[]
|
||||
keybindings: { command: string; key: string; when?: 'global' | 'worktree' }[]
|
||||
vmRecipes: PathContribution[]
|
||||
agents: PathContribution[]
|
||||
}
|
||||
capabilities: { kind: string }[]
|
||||
}
|
||||
|
||||
function rejectDuplicateValues(
|
||||
entries: readonly unknown[],
|
||||
valueOf: (entry: unknown) => string,
|
||||
path: string,
|
||||
label: string,
|
||||
ctx: RefinementCtx
|
||||
): void {
|
||||
const seen = new Set<string>()
|
||||
for (const [index, entry] of entries.entries()) {
|
||||
const value = valueOf(entry)
|
||||
if (seen.has(value)) {
|
||||
ctx.addIssue({
|
||||
code: 'custom',
|
||||
path: ['contributes', path, index],
|
||||
message: `duplicate ${label}: ${value}`
|
||||
})
|
||||
}
|
||||
seen.add(value)
|
||||
}
|
||||
}
|
||||
|
||||
export function validatePluginManifestContributions(
|
||||
manifest: ContributionValidationManifest,
|
||||
ctx: RefinementCtx
|
||||
): void {
|
||||
for (const path of ['panels', 'commands'] as const) {
|
||||
rejectDuplicateValues(
|
||||
manifest.contributes[path],
|
||||
(entry) => (entry as IdentifiedContribution).id,
|
||||
path,
|
||||
`${path} id`,
|
||||
ctx
|
||||
)
|
||||
}
|
||||
rejectDuplicateValues(
|
||||
manifest.contributes.languagePacks,
|
||||
(entry) => (entry as { locale: string }).locale.toLowerCase(),
|
||||
'languagePacks',
|
||||
'language pack locale',
|
||||
ctx
|
||||
)
|
||||
for (const path of ['vmRecipes', 'agents'] as const) {
|
||||
rejectDuplicateValues(
|
||||
manifest.contributes[path],
|
||||
(entry) => (entry as PathContribution).path,
|
||||
path,
|
||||
`${path} path`,
|
||||
ctx
|
||||
)
|
||||
}
|
||||
const keybindingIdentities = new Set<string>()
|
||||
for (const [index, keybinding] of manifest.contributes.keybindings.entries()) {
|
||||
const identities = (['darwin', 'linux', 'win32'] as const).map((platform) =>
|
||||
getKeybindingConflictIdentity(keybinding.key, platform)
|
||||
)
|
||||
if (identities.some((identity) => keybindingIdentities.has(identity))) {
|
||||
ctx.addIssue({
|
||||
code: 'custom',
|
||||
path: ['contributes', 'keybindings', index],
|
||||
message: `duplicate keybinding: ${keybinding.key.toLowerCase()}`
|
||||
})
|
||||
}
|
||||
identities.forEach((identity) => keybindingIdentities.add(identity))
|
||||
}
|
||||
|
||||
const commands = new Map(manifest.contributes.commands.map((command) => [command.id, command]))
|
||||
for (const [index, command] of manifest.contributes.commands.entries()) {
|
||||
if (command.action !== undefined && !isPluginCommandAliasActionId(command.action)) {
|
||||
ctx.addIssue({
|
||||
code: 'custom',
|
||||
path: ['contributes', 'commands', index, 'action'],
|
||||
message: `unknown built-in action: ${command.action}`
|
||||
})
|
||||
}
|
||||
}
|
||||
for (const [index, keybinding] of manifest.contributes.keybindings.entries()) {
|
||||
const command = commands.get(keybinding.command)
|
||||
if (!command) {
|
||||
ctx.addIssue({
|
||||
code: 'custom',
|
||||
path: ['contributes', 'keybindings', index, 'command'],
|
||||
message: `unknown contributed command: ${keybinding.command}`
|
||||
})
|
||||
continue
|
||||
}
|
||||
const commandContext = command.context ?? 'global'
|
||||
if (keybinding.when !== undefined && keybinding.when !== commandContext) {
|
||||
ctx.addIssue({
|
||||
code: 'custom',
|
||||
path: ['contributes', 'keybindings', index, 'when'],
|
||||
message: 'keybinding context must match its command context'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
!manifest.main &&
|
||||
manifest.contributes.commands.some((command) => command.action === undefined)
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: 'custom',
|
||||
path: ['main'],
|
||||
message: 'required when contributes.commands contains a worker command'
|
||||
})
|
||||
}
|
||||
if (!manifest.main && manifest.contributes.events.length > 0) {
|
||||
ctx.addIssue({
|
||||
code: 'custom',
|
||||
path: ['main'],
|
||||
message: 'required when contributes.events is non-empty'
|
||||
})
|
||||
}
|
||||
if (
|
||||
manifest.contributes.events.length > 0 &&
|
||||
!manifest.capabilities.some((capability) => capability.kind === 'events:subscribe')
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: 'custom',
|
||||
path: ['capabilities'],
|
||||
message: 'events:subscribe capability required when contributes.events is non-empty'
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { z } from 'zod'
|
||||
import { isSafePluginRelativePath } from './plugin-path-safety'
|
||||
|
||||
const PLUGIN_ID_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
|
||||
const DANGEROUS_PLUGIN_NAMES = new Set(['__proto__', 'prototype', 'constructor'])
|
||||
|
||||
export const PLUGIN_ID_MAX_LENGTH = 64
|
||||
|
||||
export function isSafePluginId(id: string): boolean {
|
||||
return (
|
||||
typeof id === 'string' &&
|
||||
id.length <= PLUGIN_ID_MAX_LENGTH &&
|
||||
PLUGIN_ID_RE.test(id) &&
|
||||
!DANGEROUS_PLUGIN_NAMES.has(id)
|
||||
)
|
||||
}
|
||||
|
||||
export const pluginIdSchema = z
|
||||
.string()
|
||||
.refine(isSafePluginId, 'must be kebab-case (a-z, 0-9, dashes) and not a reserved name')
|
||||
|
||||
// Why: every declared artifact stays inside the immutable plugin root; realpath
|
||||
// containment separately rejects symlink escapes when the artifact is read.
|
||||
export const pluginRelativePathSchema = z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(1024)
|
||||
.refine(isSafePluginRelativePath, 'must be a portable relative path inside the plugin directory')
|
||||
|
||||
// Directory contributions accept the conventional trailing slash but store a
|
||||
// canonical path so hashing, materialization, and cleanup use one identity.
|
||||
export const pluginRelativeDirectorySchema = z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(1024)
|
||||
.transform((value) => value.replace(/[\\/]+$/, ''))
|
||||
.refine(isSafePluginRelativePath, 'must be a portable relative path inside the plugin directory')
|
||||
|
||||
export const pluginCommandIdSchema = z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(256)
|
||||
.regex(/^[A-Za-z0-9]+(?:[._-][A-Za-z0-9]+)*$/, 'must be a portable command id')
|
||||
|
||||
export function isPluginManifestId(value: string): boolean {
|
||||
return PLUGIN_ID_RE.test(value)
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
PLUGIN_COMMAND_LIMIT,
|
||||
PLUGIN_ID_MAX_LENGTH,
|
||||
parsePluginManifest,
|
||||
pluginManifestSchema
|
||||
} from './plugin-manifest'
|
||||
|
||||
function manifest(overrides: Record<string, unknown> = {}): Record<string, unknown> {
|
||||
return {
|
||||
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: [],
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
describe('pluginManifestSchema boundaries', () => {
|
||||
it('accepts documented dotted command namespaces with camel-case actions', () => {
|
||||
const result = parsePluginManifest(
|
||||
manifest({
|
||||
main: 'main.mjs',
|
||||
contributes: {
|
||||
panels: [],
|
||||
commands: [{ id: 'jupyter.restartKernel', title: 'Restart kernel' }],
|
||||
events: []
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
expect(result).toMatchObject({ ok: true })
|
||||
})
|
||||
|
||||
it('rejects oversized identities and invalid semantic versions', () => {
|
||||
expect(parsePluginManifest(manifest({ id: 'a'.repeat(PLUGIN_ID_MAX_LENGTH + 1) })).ok).toBe(
|
||||
false
|
||||
)
|
||||
expect(parsePluginManifest(manifest({ version: '01.0.0' })).ok).toBe(false)
|
||||
expect(parsePluginManifest(manifest({ version: '1.0' })).ok).toBe(false)
|
||||
expect(parsePluginManifest(manifest({ version: '1.0.0-01' })).ok).toBe(false)
|
||||
expect(parsePluginManifest(manifest({ version: '1.0.0-alpha.1+build.5' })).ok).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects duplicate contribution ids', () => {
|
||||
const parsed = pluginManifestSchema.safeParse(
|
||||
manifest({
|
||||
main: 'main.mjs',
|
||||
contributes: {
|
||||
panels: [
|
||||
{ id: 'dashboard', title: 'One', entry: 'one.html' },
|
||||
{ id: 'dashboard', title: 'Two', entry: 'two.html' }
|
||||
],
|
||||
commands: [
|
||||
{ id: 'run', title: 'One' },
|
||||
{ id: 'run', title: 'Two' }
|
||||
],
|
||||
events: []
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
expect(parsed.success).toBe(false)
|
||||
if (!parsed.success) {
|
||||
expect(parsed.error.issues.map((issue) => issue.message)).toEqual(
|
||||
expect.arrayContaining(['duplicate panels id: dashboard', 'duplicate commands id: run'])
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
it('caps contribution arrays before they reach renderer or worker registries', () => {
|
||||
const commands = Array.from({ length: PLUGIN_COMMAND_LIMIT + 1 }, (_, index) => ({
|
||||
id: `command-${index}`,
|
||||
title: `Command ${index}`
|
||||
}))
|
||||
expect(
|
||||
parsePluginManifest(
|
||||
manifest({
|
||||
main: 'main.mjs',
|
||||
contributes: { panels: [], commands, events: [] }
|
||||
})
|
||||
).ok
|
||||
).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,214 @@
|
||||
import { z } from 'zod'
|
||||
import { pluginCapabilitySchema } from './plugin-capabilities'
|
||||
import {
|
||||
PLUGIN_AGENT_PROFILE_LIMIT,
|
||||
PLUGIN_KEYBINDING_LIMIT,
|
||||
PLUGIN_LANGUAGE_PACK_LIMIT,
|
||||
PLUGIN_VM_RECIPE_LIMIT,
|
||||
pluginAgentProfileContributionSchema,
|
||||
pluginKeybindingContributionSchema,
|
||||
pluginLanguagePackContributionSchema,
|
||||
pluginVmRecipeContributionSchema
|
||||
} from './plugin-content-pack-contributions'
|
||||
import {
|
||||
isPluginManifestId,
|
||||
isSafePluginId,
|
||||
pluginCommandIdSchema,
|
||||
pluginIdSchema,
|
||||
pluginRelativePathSchema
|
||||
} from './plugin-manifest-fields'
|
||||
import { validatePluginManifestContributions } from './plugin-manifest-contribution-validation'
|
||||
|
||||
/**
|
||||
* Plugin manifest v1 (`orca-plugin.json` at the plugin root). The
|
||||
* `contributes` key names deliberately mirror common Electron-ecosystem
|
||||
* manifest conventions so future adapters stay cheap.
|
||||
*
|
||||
* Lives in `shared` so the desktop app, the headless `orca serve` runtime,
|
||||
* the relay, and the CLI validate manifests identically (SSH/remote parity).
|
||||
*
|
||||
* Everything here is EXPERIMENTAL: no compatibility promises until pluginApi
|
||||
* v1 freezes (see the plugin roadmap).
|
||||
*/
|
||||
|
||||
const SEMVER_RE =
|
||||
/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/
|
||||
export const PLUGIN_PANEL_LIMIT = 64
|
||||
export const PLUGIN_COMMAND_LIMIT = 256
|
||||
|
||||
// Why: v0 supports only the ">=x.y.z" form. A closed grammar keeps the gate
|
||||
// predictable; richer ranges can be added without breaking old manifests.
|
||||
const orcaEngineRangeSchema = z
|
||||
.string()
|
||||
.max(64)
|
||||
.regex(/^>=\d+\.\d+\.\d+$/, 'must be a ">=x.y.z" version range')
|
||||
|
||||
const panelContributionSchema = z.object({
|
||||
id: pluginIdSchema,
|
||||
title: z.string().min(1).max(256),
|
||||
/** Lucide icon name rendered in the right-sidebar activity bar. */
|
||||
icon: z.string().min(1).max(64).optional(),
|
||||
/** HTML entry rendered inside a sandboxed panel frame. */
|
||||
entry: pluginRelativePathSchema
|
||||
})
|
||||
|
||||
const commandContributionSchema = z.object({
|
||||
id: pluginCommandIdSchema,
|
||||
title: z.string().min(1).max(256),
|
||||
context: z.enum(['global', 'worktree']).optional(),
|
||||
/** Built-in action aliases remain declarative and do not activate a worker. */
|
||||
action: pluginCommandIdSchema.optional()
|
||||
})
|
||||
|
||||
/** Domain events a plugin can subscribe to in v0. Closed set: server-side
|
||||
* filtering means plugins only ever receive what they subscribed to. */
|
||||
export const PLUGIN_EVENT_NAMES = [
|
||||
'worktree.created',
|
||||
'worktree.removed',
|
||||
'agent.status.changed'
|
||||
] as const
|
||||
export const PLUGIN_EVENT_SUBSCRIPTION_LIMIT = PLUGIN_EVENT_NAMES.length
|
||||
|
||||
export type PluginEventName = (typeof PLUGIN_EVENT_NAMES)[number]
|
||||
|
||||
const eventContributionSchema = z.object({
|
||||
on: z.enum(PLUGIN_EVENT_NAMES)
|
||||
})
|
||||
|
||||
export const pluginManifestSchema = z
|
||||
.object({
|
||||
manifestVersion: z.literal(1),
|
||||
id: pluginIdSchema,
|
||||
/** Publisher slug; canonical identity is `<publisher>.<id>` — bare-id
|
||||
* global uniqueness is unverifiable without a registry. */
|
||||
publisher: pluginIdSchema,
|
||||
name: z.string().min(1).max(256),
|
||||
version: z.string().regex(SEMVER_RE, 'must be semver'),
|
||||
description: z.string().max(4096).optional(),
|
||||
author: z
|
||||
.object({ name: z.string().min(1).max(256), url: z.string().max(2048).optional() })
|
||||
.optional(),
|
||||
repository: z.string().max(2048).optional(),
|
||||
icon: pluginRelativePathSchema.optional(),
|
||||
/** Minimum host version gate; the host refuses to load below it. */
|
||||
engines: z.object({ orca: orcaEngineRangeSchema }),
|
||||
/** Host-API major version this plugin targets. */
|
||||
pluginApi: z.literal(1),
|
||||
/** Node entry executed inside the out-of-process plugin worker. */
|
||||
main: pluginRelativePathSchema.optional(),
|
||||
contributes: z
|
||||
.object({
|
||||
panels: z.array(panelContributionSchema).max(PLUGIN_PANEL_LIMIT).default([]),
|
||||
commands: z.array(commandContributionSchema).max(PLUGIN_COMMAND_LIMIT).default([]),
|
||||
events: z.array(eventContributionSchema).max(PLUGIN_EVENT_SUBSCRIPTION_LIMIT).default([]),
|
||||
languagePacks: z
|
||||
.array(pluginLanguagePackContributionSchema)
|
||||
.max(PLUGIN_LANGUAGE_PACK_LIMIT)
|
||||
.default([]),
|
||||
keybindings: z
|
||||
.array(pluginKeybindingContributionSchema)
|
||||
.max(PLUGIN_KEYBINDING_LIMIT)
|
||||
.default([]),
|
||||
vmRecipes: z
|
||||
.array(pluginVmRecipeContributionSchema)
|
||||
.max(PLUGIN_VM_RECIPE_LIMIT)
|
||||
.default([]),
|
||||
agents: z
|
||||
.array(pluginAgentProfileContributionSchema)
|
||||
.max(PLUGIN_AGENT_PROFILE_LIMIT)
|
||||
.default([])
|
||||
})
|
||||
.strict()
|
||||
.default(() => ({
|
||||
panels: [],
|
||||
commands: [],
|
||||
events: [],
|
||||
languagePacks: [],
|
||||
keybindings: [],
|
||||
vmRecipes: [],
|
||||
agents: []
|
||||
})),
|
||||
capabilities: z.array(pluginCapabilitySchema).max(32).default([])
|
||||
})
|
||||
.superRefine(validatePluginManifestContributions)
|
||||
|
||||
export type PluginManifest = z.infer<typeof pluginManifestSchema>
|
||||
export type PluginPanelContribution = z.infer<typeof panelContributionSchema>
|
||||
export type PluginCommandContribution = z.infer<typeof commandContributionSchema>
|
||||
export type PluginEventContribution = z.infer<typeof eventContributionSchema>
|
||||
|
||||
export {
|
||||
isSafePluginId,
|
||||
PLUGIN_ID_MAX_LENGTH,
|
||||
pluginCommandIdSchema
|
||||
} from './plugin-manifest-fields'
|
||||
|
||||
export const PLUGIN_MANIFEST_FILENAME = 'orca-plugin.json'
|
||||
|
||||
/** Canonical install identity: `<publisher>.<id>` (also the install dir name). */
|
||||
export function qualifiedPluginKey(manifest: Pick<PluginManifest, 'publisher' | 'id'>): string {
|
||||
return `${manifest.publisher}.${manifest.id}`
|
||||
}
|
||||
|
||||
export function isQualifiedPluginKey(value: string): boolean {
|
||||
const parts = value.split('.')
|
||||
if (parts.length !== 2) {
|
||||
return false
|
||||
}
|
||||
return isSafePluginId(parts[0]!) && isSafePluginId(parts[1]!)
|
||||
}
|
||||
|
||||
export type PluginManifestParseResult =
|
||||
| { ok: true; manifest: PluginManifest }
|
||||
| { ok: false; error: string }
|
||||
|
||||
export function parsePluginManifest(raw: unknown): PluginManifestParseResult {
|
||||
const parsed = pluginManifestSchema.safeParse(raw)
|
||||
if (parsed.success) {
|
||||
return { ok: true, manifest: parsed.data }
|
||||
}
|
||||
const issue = parsed.error.issues[0]
|
||||
const path = issue?.path.join('.') || '(root)'
|
||||
return { ok: false, error: `${path}: ${issue?.message ?? 'invalid manifest'}` }
|
||||
}
|
||||
|
||||
/** v0 engines gate: supports the ">=x.y.z" grammar the schema enforces.
|
||||
* Prerelease/build suffixes on the host version are ignored for ordering. */
|
||||
export function satisfiesOrcaEngineRange(hostVersion: string, range: string): boolean {
|
||||
const minimum = range.slice(2)
|
||||
const parse = (value: string): number[] =>
|
||||
value
|
||||
.split(/[-+]/)[0]!
|
||||
.split('.')
|
||||
.map((part) => Number.parseInt(part, 10) || 0)
|
||||
const host = parse(hostVersion)
|
||||
const min = parse(minimum)
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const a = host[i] ?? 0
|
||||
const b = min[i] ?? 0
|
||||
if (a !== b) {
|
||||
return a > b
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/** Sidebar tab key for a plugin panel: `plugin:<publisher>.<id>/<panelId>`. */
|
||||
export function pluginPanelTabKey(qualifiedKey: string, panelId: string): `plugin:${string}` {
|
||||
return `plugin:${qualifiedKey}/${panelId}`
|
||||
}
|
||||
|
||||
export function isPluginPanelTabKey(tab: string): tab is `plugin:${string}` {
|
||||
if (!tab.startsWith('plugin:')) {
|
||||
return false
|
||||
}
|
||||
const rest = tab.slice('plugin:'.length)
|
||||
const [qualifiedKey, panelId, ...extra] = rest.split('/')
|
||||
return (
|
||||
extra.length === 0 &&
|
||||
!!qualifiedKey &&
|
||||
!!panelId &&
|
||||
isQualifiedPluginKey(qualifiedKey) &&
|
||||
isPluginManifestId(panelId)
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
OFFICIAL_MARKETPLACE_REPOSITORY,
|
||||
PLUGIN_MARKETPLACE_CATEGORY_LIMIT,
|
||||
PLUGIN_MARKETPLACE_ENTRY_LIMIT,
|
||||
isMarketplaceListingSupported,
|
||||
isOfficialMarketplaceGitSource,
|
||||
isOfficialOrganizationGitSource,
|
||||
isOfficialPluginIdentity,
|
||||
isReservedPluginIdentity,
|
||||
parseGitRepositoryIdentity,
|
||||
pluginMarketplaceSchema,
|
||||
pluginMarketplaceTrustMetadataSchema
|
||||
} from './plugin-marketplace'
|
||||
|
||||
function listing(id = 'community.nord'): Record<string, unknown> {
|
||||
return {
|
||||
id,
|
||||
source: { kind: 'git', url: 'https://github.com/community/nord.git', ref: 'v1.0.0' },
|
||||
description: 'A theme pack',
|
||||
categories: ['themes']
|
||||
}
|
||||
}
|
||||
|
||||
describe('pluginMarketplaceSchema', () => {
|
||||
it('parses a bounded, pinned Git marketplace index', () => {
|
||||
expect(
|
||||
pluginMarketplaceSchema.parse({
|
||||
name: 'Community plugins',
|
||||
owner: 'community',
|
||||
plugins: [listing()]
|
||||
})
|
||||
).toEqual({
|
||||
name: 'Community plugins',
|
||||
owner: 'community',
|
||||
plugins: [listing()]
|
||||
})
|
||||
})
|
||||
|
||||
it.each([
|
||||
['root', { name: 'Plugins', owner: 'team', plugins: [], extra: true }],
|
||||
['entry', { name: 'Plugins', owner: 'team', plugins: [{ ...listing(), official: true }] }],
|
||||
[
|
||||
'source',
|
||||
{
|
||||
name: 'Plugins',
|
||||
owner: 'team',
|
||||
plugins: [
|
||||
{
|
||||
...listing(),
|
||||
source: {
|
||||
kind: 'git',
|
||||
url: 'https://github.com/community/nord.git',
|
||||
ref: 'main',
|
||||
depth: 1
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
])('rejects unknown keys at the %s boundary', (_boundary, marketplace) => {
|
||||
expect(pluginMarketplaceSchema.safeParse(marketplace).success).toBe(false)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['an unqualified id', { ...listing(), id: 'nord' }],
|
||||
[
|
||||
'a missing ref',
|
||||
{
|
||||
...listing(),
|
||||
source: { kind: 'git', url: 'https://github.com/community/nord.git', ref: '' }
|
||||
}
|
||||
],
|
||||
[
|
||||
'an executable Git transport',
|
||||
{
|
||||
...listing(),
|
||||
source: { kind: 'git', url: 'ext::sh -c exploit', ref: 'main' }
|
||||
}
|
||||
],
|
||||
['a duplicate category', { ...listing(), categories: ['themes', 'themes'] }],
|
||||
[
|
||||
'too many categories',
|
||||
{
|
||||
...listing(),
|
||||
categories: Array.from(
|
||||
{ length: PLUGIN_MARKETPLACE_CATEGORY_LIMIT + 1 },
|
||||
(_, index) => `category-${index}`
|
||||
)
|
||||
}
|
||||
]
|
||||
])('rejects %s', (_label, entry) => {
|
||||
expect(
|
||||
pluginMarketplaceSchema.safeParse({ name: 'Plugins', owner: 'team', plugins: [entry] })
|
||||
.success
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects duplicate plugin identities', () => {
|
||||
const parsed = pluginMarketplaceSchema.safeParse({
|
||||
name: 'Plugins',
|
||||
owner: 'team',
|
||||
plugins: [listing(), listing()]
|
||||
})
|
||||
|
||||
expect(parsed.success).toBe(false)
|
||||
if (!parsed.success) {
|
||||
expect(parsed.error.issues).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ message: 'duplicate plugin id: community.nord' })
|
||||
])
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
it('caps the marketplace entry count', () => {
|
||||
const plugins = Array.from({ length: PLUGIN_MARKETPLACE_ENTRY_LIMIT + 1 }, (_, index) =>
|
||||
listing(`publisher.plugin-${index}`)
|
||||
)
|
||||
expect(
|
||||
pluginMarketplaceSchema.safeParse({ name: 'Plugins', owner: 'team', plugins }).success
|
||||
).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('marketplace provenance contracts', () => {
|
||||
it.each([
|
||||
['stablyai.orca-skills', true, true],
|
||||
['stablyai.skills', true, false],
|
||||
['community.orca-skills', true, false],
|
||||
['community.skills', false, false],
|
||||
['invalid', false, false]
|
||||
])('classifies %s', (pluginKey, reserved, official) => {
|
||||
expect(isReservedPluginIdentity(pluginKey)).toBe(reserved)
|
||||
expect(isOfficialPluginIdentity(pluginKey)).toBe(official)
|
||||
})
|
||||
|
||||
it.each([
|
||||
'https://github.com/stablyai/orca-skills.git',
|
||||
'ssh://git@github.com/stablyai/orca-skills.git',
|
||||
'git@github.com:stablyai/orca-skills.git'
|
||||
])('accepts official organization source %s', (source) => {
|
||||
expect(isOfficialOrganizationGitSource(source)).toBe(true)
|
||||
})
|
||||
|
||||
it('does not trust lookalike organizations or hosts', () => {
|
||||
expect(isOfficialOrganizationGitSource('https://github.com/stablyai-fakes/orca-skills')).toBe(
|
||||
false
|
||||
)
|
||||
expect(isOfficialOrganizationGitSource('https://gitlab.com/stablyai/orca-skills')).toBe(false)
|
||||
})
|
||||
|
||||
it('recognizes only the canonical official marketplace repository', () => {
|
||||
expect(
|
||||
isOfficialMarketplaceGitSource(
|
||||
`git@github.com:stablyai/${OFFICIAL_MARKETPLACE_REPOSITORY}.git`
|
||||
)
|
||||
).toBe(true)
|
||||
expect(isOfficialMarketplaceGitSource('git@github.com:stablyai/plugins.git')).toBe(false)
|
||||
})
|
||||
|
||||
it('parses nested repository paths without confusing the repository name', () => {
|
||||
expect(parseGitRepositoryIdentity('https://gitlab.com/team/subgroup/plugin.git')).toEqual({
|
||||
host: 'gitlab.com',
|
||||
owner: 'team',
|
||||
repository: 'plugin'
|
||||
})
|
||||
})
|
||||
|
||||
it('prevents an untrusted listing from self-awarding trust metadata', () => {
|
||||
expect(pluginMarketplaceTrustMetadataSchema.parse({ official: true, bundled: true })).toEqual({
|
||||
official: true,
|
||||
bundled: true
|
||||
})
|
||||
expect(
|
||||
pluginMarketplaceTrustMetadataSchema.safeParse({ official: false, bundled: true }).success
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('marks listings with a deferred contribution category as unsupported', () => {
|
||||
expect(isMarketplaceListingSupported(['vm-recipes', 'official'])).toBe(true)
|
||||
expect(isMarketplaceListingSupported(['keybindings'])).toBe(true)
|
||||
expect(isMarketplaceListingSupported([])).toBe(true)
|
||||
for (const deferred of ['themes', 'icons', 'icon-themes', 'terminal-themes', 'skills']) {
|
||||
expect(isMarketplaceListingSupported([deferred, 'official'])).toBe(false)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,207 @@
|
||||
import { z } from 'zod'
|
||||
import { isAllowedPluginGitUrl } from './plugin-install-lockfile'
|
||||
import { isQualifiedPluginKey } from './plugin-manifest'
|
||||
|
||||
export const PLUGIN_MARKETPLACE_FILENAME = 'orca-marketplace.json'
|
||||
export const PLUGIN_MARKETPLACE_ENTRY_LIMIT = 2_048
|
||||
export const PLUGIN_MARKETPLACE_CATEGORY_LIMIT = 16
|
||||
|
||||
export const OFFICIAL_PLUGIN_PUBLISHER = 'stablyai'
|
||||
export const OFFICIAL_PLUGIN_ID_PREFIX = 'orca-'
|
||||
export const OFFICIAL_MARKETPLACE_OWNER = 'stablyai'
|
||||
export const OFFICIAL_MARKETPLACE_REPOSITORY = 'orca-plugins'
|
||||
|
||||
// Why: theme/icon/skill contributions were deferred, so `contributes` now
|
||||
// rejects them and any plugin declaring one fails to install wholesale. The
|
||||
// shared marketplace index (which this build does not control) still advertises
|
||||
// such packs; hide listings that carry these categories so users never hit a
|
||||
// dead "install" path until the marketplace catches up.
|
||||
export const UNSUPPORTED_MARKETPLACE_CATEGORIES: readonly string[] = [
|
||||
'themes',
|
||||
'icons',
|
||||
'icon-themes',
|
||||
'terminal-themes',
|
||||
'skills'
|
||||
]
|
||||
|
||||
export function isMarketplaceListingSupported(categories: readonly string[]): boolean {
|
||||
return !categories.some((category) => UNSUPPORTED_MARKETPLACE_CATEGORIES.includes(category))
|
||||
}
|
||||
|
||||
const marketplaceOwnerSchema = z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(128)
|
||||
.regex(/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/, 'invalid marketplace owner')
|
||||
|
||||
const marketplaceCategorySchema = z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(64)
|
||||
.regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, 'categories must be lowercase slugs')
|
||||
|
||||
export const pluginMarketplaceGitSourceSchema = z.strictObject({
|
||||
kind: z.literal('git'),
|
||||
url: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.max(32 * 1024)
|
||||
.refine(isAllowedPluginGitUrl, 'git URL must use HTTPS or SSH'),
|
||||
// Why: marketplace installs must first resolve a named ref to an exact
|
||||
// commit; an omitted remote default would make the listing irreproducible.
|
||||
ref: z.string().trim().min(1).max(4_096)
|
||||
})
|
||||
|
||||
export const pluginMarketplaceEntrySchema = z
|
||||
.strictObject({
|
||||
/** Canonical `<publisher>.<id>` identity expected in the source manifest. */
|
||||
id: z.string().refine(isQualifiedPluginKey, 'invalid qualified plugin key'),
|
||||
source: pluginMarketplaceGitSourceSchema,
|
||||
description: z.string().min(1).max(4_096).optional(),
|
||||
categories: z
|
||||
.array(marketplaceCategorySchema)
|
||||
.max(PLUGIN_MARKETPLACE_CATEGORY_LIMIT)
|
||||
.default([])
|
||||
})
|
||||
.superRefine((entry, context) => {
|
||||
const seen = new Set<string>()
|
||||
for (const [index, category] of entry.categories.entries()) {
|
||||
if (seen.has(category)) {
|
||||
context.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['categories', index],
|
||||
message: `duplicate category: ${category}`
|
||||
})
|
||||
}
|
||||
seen.add(category)
|
||||
}
|
||||
})
|
||||
|
||||
export const pluginMarketplaceSchema = z
|
||||
.strictObject({
|
||||
name: z.string().min(1).max(256),
|
||||
owner: marketplaceOwnerSchema,
|
||||
plugins: z.array(pluginMarketplaceEntrySchema).max(PLUGIN_MARKETPLACE_ENTRY_LIMIT)
|
||||
})
|
||||
.superRefine((marketplace, context) => {
|
||||
const seen = new Set<string>()
|
||||
for (const [index, plugin] of marketplace.plugins.entries()) {
|
||||
if (seen.has(plugin.id)) {
|
||||
context.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['plugins', index, 'id'],
|
||||
message: `duplicate plugin id: ${plugin.id}`
|
||||
})
|
||||
}
|
||||
seen.add(plugin.id)
|
||||
}
|
||||
})
|
||||
|
||||
/** Host-derived trust metadata. Marketplace JSON cannot self-award either bit. */
|
||||
export const pluginMarketplaceTrustMetadataSchema = z
|
||||
.strictObject({
|
||||
official: z.boolean(),
|
||||
bundled: z.boolean()
|
||||
})
|
||||
.refine((metadata) => !metadata.bundled || metadata.official, {
|
||||
message: 'bundled plugins must be official',
|
||||
path: ['bundled']
|
||||
})
|
||||
|
||||
export type PluginMarketplace = z.infer<typeof pluginMarketplaceSchema>
|
||||
export type PluginMarketplaceEntry = z.infer<typeof pluginMarketplaceEntrySchema>
|
||||
export type PluginMarketplaceGitSource = z.infer<typeof pluginMarketplaceGitSourceSchema>
|
||||
export type PluginMarketplaceTrustMetadata = z.infer<typeof pluginMarketplaceTrustMetadataSchema>
|
||||
|
||||
export const OFFICIAL_MARKETPLACE_GIT_SOURCE: PluginMarketplaceGitSource = {
|
||||
kind: 'git',
|
||||
url: 'https://github.com/stablyai/orca-plugins.git',
|
||||
ref: 'main'
|
||||
}
|
||||
|
||||
export function splitQualifiedPluginKey(pluginKey: string): {
|
||||
publisher: string
|
||||
id: string
|
||||
} | null {
|
||||
if (!isQualifiedPluginKey(pluginKey)) {
|
||||
return null
|
||||
}
|
||||
const separator = pluginKey.indexOf('.')
|
||||
return {
|
||||
publisher: pluginKey.slice(0, separator),
|
||||
id: pluginKey.slice(separator + 1)
|
||||
}
|
||||
}
|
||||
|
||||
export function isReservedPluginIdentity(pluginKey: string): boolean {
|
||||
const identity = splitQualifiedPluginKey(pluginKey)
|
||||
return (
|
||||
identity !== null &&
|
||||
(identity.publisher === OFFICIAL_PLUGIN_PUBLISHER ||
|
||||
identity.id.startsWith(OFFICIAL_PLUGIN_ID_PREFIX))
|
||||
)
|
||||
}
|
||||
|
||||
export function isOfficialPluginIdentity(pluginKey: string): boolean {
|
||||
const identity = splitQualifiedPluginKey(pluginKey)
|
||||
return (
|
||||
identity !== null &&
|
||||
identity.publisher === OFFICIAL_PLUGIN_PUBLISHER &&
|
||||
identity.id.startsWith(OFFICIAL_PLUGIN_ID_PREFIX)
|
||||
)
|
||||
}
|
||||
|
||||
type GitRepositoryIdentity = {
|
||||
host: string
|
||||
owner: string
|
||||
repository: string
|
||||
}
|
||||
|
||||
/** Extracts the host and first owner segment from the HTTPS/SSH Git forms the
|
||||
* installer accepts. It is intentionally only a provenance parser. */
|
||||
export function parseGitRepositoryIdentity(url: string): GitRepositoryIdentity | null {
|
||||
const trimmed = url.trim()
|
||||
const scp = /^[^\s@/:]+@([^\s:]+):(.+)$/.exec(trimmed)
|
||||
if (scp) {
|
||||
return repositoryIdentity(scp[1]!, scp[2]!)
|
||||
}
|
||||
try {
|
||||
const parsed = new URL(trimmed)
|
||||
if (parsed.protocol !== 'https:' && parsed.protocol !== 'ssh:') {
|
||||
return null
|
||||
}
|
||||
return repositoryIdentity(parsed.hostname, parsed.pathname)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function repositoryIdentity(host: string, repositoryPath: string): GitRepositoryIdentity | null {
|
||||
const segments = repositoryPath
|
||||
.replace(/^\/+|\/+$/g, '')
|
||||
.split('/')
|
||||
.filter(Boolean)
|
||||
if (segments.length < 2) {
|
||||
return null
|
||||
}
|
||||
const repository = segments.at(-1)!.replace(/\.git$/i, '')
|
||||
if (!repository) {
|
||||
return null
|
||||
}
|
||||
return { host: host.toLowerCase(), owner: segments[0]!, repository }
|
||||
}
|
||||
|
||||
export function isOfficialOrganizationGitSource(url: string): boolean {
|
||||
const source = parseGitRepositoryIdentity(url)
|
||||
return source?.host === 'github.com' && source.owner.toLowerCase() === OFFICIAL_PLUGIN_PUBLISHER
|
||||
}
|
||||
|
||||
export function isOfficialMarketplaceGitSource(url: string): boolean {
|
||||
const source = parseGitRepositoryIdentity(url)
|
||||
return (
|
||||
source?.host === 'github.com' &&
|
||||
source.owner.toLowerCase() === OFFICIAL_MARKETPLACE_OWNER &&
|
||||
source.repository.toLowerCase() === OFFICIAL_MARKETPLACE_REPOSITORY
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import { z } from 'zod'
|
||||
import { getPluginHostMethodSpec, isPluginPanelAction } from './plugin-host-api'
|
||||
|
||||
/**
|
||||
* postMessage protocol between a sandboxed plugin panel iframe and the host
|
||||
* renderer, plus the action call shape relayed to main. The frame has an
|
||||
* opaque origin (sandbox="allow-scripts"), so neither side can use origins
|
||||
* for trust: the host verifies the sending window's identity and re-validates
|
||||
* every payload here; main re-checks capabilities before executing.
|
||||
*
|
||||
* Param/result schemas come from the host API v0 spec table — the panel
|
||||
* bridge is a transport, not a second contract.
|
||||
*/
|
||||
|
||||
export const PANEL_ACTION_REQUEST_TYPE = 'orca-panel-action'
|
||||
export const PANEL_ACTION_RESULT_TYPE = 'orca-panel-action-result'
|
||||
export const PANEL_PING_TYPE = 'orca-panel-ping'
|
||||
export const PANEL_PONG_TYPE = 'orca-panel-pong'
|
||||
export const PLUGIN_PANEL_FRAME_NAME_PREFIX = 'orca-plugin-panel:'
|
||||
|
||||
/** Per-plugin bridge budgets, enforced host-side. */
|
||||
export const PANEL_MESSAGE_MAX_BYTES = 64 * 1024
|
||||
export const PANEL_MESSAGE_RATE_LIMIT = { maxMessages: 30, perMs: 10_000 }
|
||||
|
||||
/** Watchdog cadence: a panel that misses a pong deadline is demoted to an
|
||||
* errored badge. Busy-loop detection is valid only while the runtime frame-
|
||||
* process gate confirms the sandbox stays outside the host renderer. */
|
||||
export const PANEL_WATCHDOG_PING_INTERVAL_MS = 10_000
|
||||
export const PANEL_WATCHDOG_PONG_TIMEOUT_MS = 5_000
|
||||
|
||||
export const panelActionRequestSchema = z.object({
|
||||
type: z.literal(PANEL_ACTION_REQUEST_TYPE),
|
||||
/** Plugin-chosen correlation id echoed back on the result message. */
|
||||
requestId: z.string().min(1).max(128),
|
||||
action: z.string().min(1).refine(isPluginPanelAction, 'not a panel-callable action'),
|
||||
params: z.unknown().optional()
|
||||
})
|
||||
|
||||
export type PluginPanelActionRequest = z.infer<typeof panelActionRequestSchema>
|
||||
|
||||
export const panelPongSchema = z.object({
|
||||
type: z.literal(PANEL_PONG_TYPE),
|
||||
pingId: z.number().int().nonnegative()
|
||||
})
|
||||
|
||||
export type PluginPanelActionErrorCode =
|
||||
| 'invalid_request'
|
||||
| 'unknown_method'
|
||||
| 'capability_denied'
|
||||
| 'consent_required'
|
||||
| 'panel_forbidden'
|
||||
| 'invalid_params'
|
||||
| 'rate_limited'
|
||||
| 'unavailable'
|
||||
| 'action_failed'
|
||||
|
||||
/** Result message posted back into the panel iframe. */
|
||||
export type PluginPanelActionResultMessage = {
|
||||
type: typeof PANEL_ACTION_RESULT_TYPE
|
||||
requestId: string
|
||||
ok: boolean
|
||||
value?: unknown
|
||||
errorCode?: PluginPanelActionErrorCode
|
||||
error?: string
|
||||
}
|
||||
|
||||
/** Outcome of executing a panel action in main (wire shape of
|
||||
* `plugins:panelAction` / `plugins.panelAction`). */
|
||||
export type PluginPanelActionOutcome =
|
||||
| { ok: true; value: unknown }
|
||||
| { ok: false; code: PluginPanelActionErrorCode; error: string }
|
||||
|
||||
export const panelSessionTokenSchema = z.string().min(32).max(128)
|
||||
|
||||
/** Call shape relayed by a trusted panel host. The opaque session is issued
|
||||
* while loading one approved panel, so the caller never supplies identity. */
|
||||
export const panelActionCallSchema = z
|
||||
.object({
|
||||
sessionToken: panelSessionTokenSchema,
|
||||
action: z.string().min(1),
|
||||
params: z.unknown().optional()
|
||||
})
|
||||
.strict()
|
||||
|
||||
export type PluginPanelActionCall = z.infer<typeof panelActionCallSchema>
|
||||
|
||||
export type PluginPanelEntry = {
|
||||
html: string
|
||||
sessionToken: string
|
||||
}
|
||||
|
||||
export type PanelActionRequestParseResult =
|
||||
| { ok: true; request: PluginPanelActionRequest }
|
||||
| { ok: false; requestId: string | null; error: string }
|
||||
|
||||
/** Validates a raw `message` event payload from the panel iframe. On failure
|
||||
* still surfaces a best-effort requestId so the host can answer with an
|
||||
* error instead of silently dropping the request. */
|
||||
export function parsePanelActionRequest(data: unknown): PanelActionRequestParseResult {
|
||||
const parsed = panelActionRequestSchema.safeParse(data)
|
||||
if (parsed.success) {
|
||||
return { ok: true, request: parsed.data }
|
||||
}
|
||||
let requestId: string | null = null
|
||||
if (typeof data === 'object' && data !== null && 'requestId' in data) {
|
||||
const raw = (data as { requestId?: unknown }).requestId
|
||||
if (typeof raw === 'string' && raw.length > 0 && raw.length <= 128) {
|
||||
requestId = raw
|
||||
}
|
||||
}
|
||||
const issue = parsed.error.issues[0]
|
||||
const path = issue?.path.join('.') || '(root)'
|
||||
return {
|
||||
ok: false,
|
||||
requestId,
|
||||
error: `${path}: ${issue?.message ?? 'invalid panel action request'}`
|
||||
}
|
||||
}
|
||||
|
||||
/** True when `data` even looks like a bridge request (right `type`). Used to
|
||||
* ignore unrelated window messages without replying to them. */
|
||||
export function looksLikePanelActionRequest(data: unknown): boolean {
|
||||
return (
|
||||
typeof data === 'object' &&
|
||||
data !== null &&
|
||||
(data as { type?: unknown }).type === PANEL_ACTION_REQUEST_TYPE
|
||||
)
|
||||
}
|
||||
|
||||
export function looksLikePanelPong(data: unknown): boolean {
|
||||
return panelPongSchema.safeParse(data).success
|
||||
}
|
||||
|
||||
/** Validates action params against the host API spec (shared with workers). */
|
||||
export function parsePanelActionParams(
|
||||
action: string,
|
||||
params: unknown
|
||||
): { ok: true; params: unknown } | { ok: false; error: string } {
|
||||
const spec = getPluginHostMethodSpec(action)
|
||||
if (!spec) {
|
||||
return { ok: false, error: `unknown action: ${action}` }
|
||||
}
|
||||
const parsed = spec.params.safeParse(params)
|
||||
if (!parsed.success) {
|
||||
const issue = parsed.error.issues[0]
|
||||
const path = issue?.path.join('.') || '(root)'
|
||||
return { ok: false, error: `${path}: ${issue?.message ?? 'invalid action params'}` }
|
||||
}
|
||||
return { ok: true, params: parsed.data }
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { createPluginPanelCallAdmission } from './plugin-panel-call-admission'
|
||||
|
||||
describe('createPluginPanelCallAdmission', () => {
|
||||
it('shares the rate budget across panel sessions for one plugin', () => {
|
||||
let now = 0
|
||||
const admission = createPluginPanelCallAdmission({
|
||||
limits: { maxMessages: 2, perMs: 1_000 },
|
||||
now: () => now
|
||||
})
|
||||
|
||||
expect(admission.admit('orca-samples.one', { method: 'one' })).toBeNull()
|
||||
expect(admission.admit('orca-samples.one', { method: 'two' })).toBeNull()
|
||||
expect(admission.admit('orca-samples.one', { method: 'three' })).toBe('rate_limited')
|
||||
expect(admission.admit('orca-samples.two', { method: 'one' })).toBeNull()
|
||||
|
||||
now = 1_000
|
||||
expect(admission.admit('orca-samples.one', { method: 'four' })).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects oversized calls and can revoke a plugin budget', () => {
|
||||
const admission = createPluginPanelCallAdmission({
|
||||
limits: { maxBytes: 32, maxMessages: 1, perMs: 10_000 },
|
||||
now: () => 0
|
||||
})
|
||||
|
||||
expect(admission.admit('orca-samples.one', { payload: 'x'.repeat(64) })).toBe('oversized')
|
||||
expect(admission.admit('orca-samples.one', {})).toBe('rate_limited')
|
||||
admission.clear('orca-samples.one')
|
||||
expect(admission.admit('orca-samples.one', {})).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,63 @@
|
||||
import {
|
||||
createPanelMessageBudget,
|
||||
structuredCloneMessageBytes,
|
||||
type PanelMessageBudget
|
||||
} from './plugin-panel-message-budget'
|
||||
import type { PluginPanelActionOutcome } from './plugin-panel-bridge'
|
||||
|
||||
export type PluginPanelCallRefusal = 'oversized' | 'rate_limited'
|
||||
|
||||
export type PluginPanelCallAdmission = {
|
||||
admit(pluginKey: string, message: unknown): PluginPanelCallRefusal | null
|
||||
clear(pluginKey?: string): void
|
||||
}
|
||||
|
||||
export function admitPluginPanelCall(
|
||||
admission: PluginPanelCallAdmission,
|
||||
pluginKey: string,
|
||||
message: unknown
|
||||
): PluginPanelActionOutcome | null {
|
||||
const refusal = admission.admit(pluginKey, message)
|
||||
if (refusal === 'oversized') {
|
||||
return { ok: false, code: 'invalid_request', error: 'panel message exceeds the size limit' }
|
||||
}
|
||||
if (refusal === 'rate_limited') {
|
||||
return { ok: false, code: 'rate_limited', error: 'too many panel requests' }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
type PluginPanelCallAdmissionOptions = {
|
||||
limits?: { maxBytes?: number; maxMessages?: number; perMs?: number }
|
||||
now?: () => number
|
||||
}
|
||||
|
||||
/** One budget per qualified plugin identity, shared by every panel session
|
||||
* using this transport boundary. */
|
||||
export function createPluginPanelCallAdmission(
|
||||
options: PluginPanelCallAdmissionOptions = {}
|
||||
): PluginPanelCallAdmission {
|
||||
const budgets = new Map<string, PanelMessageBudget>()
|
||||
const now = options.now ?? (() => Date.now())
|
||||
const budgetFor = (pluginKey: string): PanelMessageBudget => {
|
||||
let budget = budgets.get(pluginKey)
|
||||
if (!budget) {
|
||||
budget = createPanelMessageBudget(options.limits)
|
||||
budgets.set(pluginKey, budget)
|
||||
}
|
||||
return budget
|
||||
}
|
||||
return {
|
||||
admit(pluginKey, message) {
|
||||
const budget = budgetFor(pluginKey)
|
||||
return budget.admit(now(), structuredCloneMessageBytes(message, budget.maxBytes))
|
||||
},
|
||||
clear(pluginKey) {
|
||||
if (pluginKey === undefined) {
|
||||
budgets.clear()
|
||||
} else {
|
||||
budgets.delete(pluginKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
createPanelMessageBudget,
|
||||
structuredCloneMessageBytes
|
||||
} from './plugin-panel-message-budget'
|
||||
|
||||
describe('structuredCloneMessageBytes', () => {
|
||||
it('counts strings as UTF-8 bytes', () => {
|
||||
expect(structuredCloneMessageBytes('é')).toBe(2)
|
||||
expect(structuredCloneMessageBytes('🐋')).toBe(4)
|
||||
})
|
||||
|
||||
it('counts binary backing stores instead of JSON object projections', () => {
|
||||
const buffer = new ArrayBuffer(128)
|
||||
const tinyView = new Uint8Array(buffer, 0, 1)
|
||||
|
||||
expect(structuredCloneMessageBytes(tinyView, 256)).toBeGreaterThanOrEqual(128)
|
||||
expect(structuredCloneMessageBytes(new Blob([new Uint8Array(80)]), 256)).toBe(80)
|
||||
})
|
||||
|
||||
it('handles cycles and stops walking once the cap is exceeded', () => {
|
||||
const cyclic: { self?: unknown; text: string } = { text: 'x'.repeat(100) }
|
||||
cyclic.self = cyclic
|
||||
|
||||
expect(structuredCloneMessageBytes(cyclic, 32)).toBe(33)
|
||||
})
|
||||
})
|
||||
|
||||
describe('createPanelMessageBudget', () => {
|
||||
it('charges oversized traffic against the message-rate budget', () => {
|
||||
const budget = createPanelMessageBudget({ maxBytes: 10, maxMessages: 2, perMs: 1_000 })
|
||||
|
||||
expect(budget.admit(0, 11)).toBe('oversized')
|
||||
expect(budget.admit(1, 1)).toBeNull()
|
||||
expect(budget.admit(2, 1)).toBe('rate_limited')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,181 @@
|
||||
import { PANEL_MESSAGE_MAX_BYTES, PANEL_MESSAGE_RATE_LIMIT } from './plugin-panel-bridge'
|
||||
|
||||
/**
|
||||
* Per-plugin bridge budgets: message size cap and a sliding-window rate
|
||||
* limit. Pure (caller supplies the clock) so both the renderer bridge host
|
||||
* and tests exercise identical decisions.
|
||||
*/
|
||||
|
||||
export type PanelMessageBudget = {
|
||||
readonly maxBytes?: number
|
||||
/** Returns null when the message may proceed, or a refusal reason. */
|
||||
admit(now: number, messageBytes: number): 'oversized' | 'rate_limited' | null
|
||||
}
|
||||
|
||||
export function createPanelMessageBudget(
|
||||
limits: { maxBytes?: number; maxMessages?: number; perMs?: number } = {}
|
||||
): PanelMessageBudget {
|
||||
const maxBytes = limits.maxBytes ?? PANEL_MESSAGE_MAX_BYTES
|
||||
const maxMessages = limits.maxMessages ?? PANEL_MESSAGE_RATE_LIMIT.maxMessages
|
||||
const perMs = limits.perMs ?? PANEL_MESSAGE_RATE_LIMIT.perMs
|
||||
const timestamps: number[] = []
|
||||
return {
|
||||
maxBytes,
|
||||
admit(now, messageBytes) {
|
||||
while (timestamps.length > 0 && timestamps[0]! <= now - perMs) {
|
||||
timestamps.shift()
|
||||
}
|
||||
const rateLimited = timestamps.length >= maxMessages
|
||||
// Oversized and malformed traffic still spends rate budget; otherwise
|
||||
// it can force unbounded size-estimation work for free.
|
||||
if (rateLimited) {
|
||||
return 'rate_limited'
|
||||
}
|
||||
timestamps.push(now)
|
||||
if (messageBytes > maxBytes) {
|
||||
return 'oversized'
|
||||
}
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const textEncoder = new TextEncoder()
|
||||
|
||||
function utf8Bytes(value: string, stopAfter: number): number {
|
||||
// UTF-8 is never shorter than the JS code-unit count, so avoid allocating
|
||||
// a large encoded copy once the cap is already proven exceeded.
|
||||
if (value.length > stopAfter) {
|
||||
return stopAfter + 1
|
||||
}
|
||||
return textEncoder.encode(value).byteLength
|
||||
}
|
||||
|
||||
/**
|
||||
* Bounded byte estimate for values accepted by structured clone. It counts
|
||||
* strings as UTF-8 and binary backing stores by byteLength, handles cycles,
|
||||
* and stops walking as soon as the host cap is exceeded.
|
||||
*/
|
||||
export function structuredCloneMessageBytes(
|
||||
data: unknown,
|
||||
stopAfter = PANEL_MESSAGE_MAX_BYTES
|
||||
): number {
|
||||
const seen = new WeakSet<object>()
|
||||
let total = 0
|
||||
let visitedNodes = 0
|
||||
|
||||
const add = (bytes: number): void => {
|
||||
total = Math.min(stopAfter + 1, total + bytes)
|
||||
}
|
||||
|
||||
const visit = (value: unknown, depth: number): void => {
|
||||
if (total > stopAfter) {
|
||||
return
|
||||
}
|
||||
if (value === null) {
|
||||
add(1)
|
||||
return
|
||||
}
|
||||
switch (typeof value) {
|
||||
case 'undefined':
|
||||
case 'boolean':
|
||||
add(1)
|
||||
return
|
||||
case 'number':
|
||||
add(8)
|
||||
return
|
||||
case 'bigint':
|
||||
add(utf8Bytes(value.toString(), stopAfter - total))
|
||||
return
|
||||
case 'string':
|
||||
add(utf8Bytes(value, stopAfter - total))
|
||||
return
|
||||
case 'symbol':
|
||||
case 'function':
|
||||
total = stopAfter + 1
|
||||
return
|
||||
case 'object':
|
||||
break
|
||||
}
|
||||
const object = value as object
|
||||
if (seen.has(object)) {
|
||||
add(8)
|
||||
return
|
||||
}
|
||||
seen.add(object)
|
||||
visitedNodes += 1
|
||||
if (visitedNodes > 10_000 || depth > 100) {
|
||||
total = stopAfter + 1
|
||||
return
|
||||
}
|
||||
|
||||
if (object instanceof ArrayBuffer) {
|
||||
add(object.byteLength)
|
||||
return
|
||||
}
|
||||
if (typeof SharedArrayBuffer !== 'undefined' && object instanceof SharedArrayBuffer) {
|
||||
add(object.byteLength)
|
||||
return
|
||||
}
|
||||
if (ArrayBuffer.isView(object)) {
|
||||
add(16)
|
||||
visit(object.buffer, depth + 1)
|
||||
return
|
||||
}
|
||||
if (typeof Blob !== 'undefined' && object instanceof Blob) {
|
||||
add(object.size)
|
||||
return
|
||||
}
|
||||
if (object instanceof Date) {
|
||||
add(8)
|
||||
return
|
||||
}
|
||||
if (object instanceof RegExp) {
|
||||
visit(object.source, depth + 1)
|
||||
visit(object.flags, depth + 1)
|
||||
return
|
||||
}
|
||||
if (object instanceof Map) {
|
||||
add(8)
|
||||
for (const [key, entry] of object) {
|
||||
add(4)
|
||||
visit(key, depth + 1)
|
||||
visit(entry, depth + 1)
|
||||
}
|
||||
return
|
||||
}
|
||||
if (object instanceof Set) {
|
||||
add(8)
|
||||
for (const entry of object) {
|
||||
add(4)
|
||||
visit(entry, depth + 1)
|
||||
}
|
||||
return
|
||||
}
|
||||
if (Array.isArray(object)) {
|
||||
add(8)
|
||||
for (const entry of object) {
|
||||
add(4)
|
||||
visit(entry, depth + 1)
|
||||
}
|
||||
return
|
||||
}
|
||||
try {
|
||||
const prototype = Object.getPrototypeOf(object)
|
||||
if (prototype !== Object.prototype && prototype !== null) {
|
||||
total = stopAfter + 1
|
||||
return
|
||||
}
|
||||
for (const key of Object.keys(object)) {
|
||||
add(4)
|
||||
add(utf8Bytes(key, stopAfter - total))
|
||||
visit((object as Record<string, unknown>)[key], depth + 1)
|
||||
}
|
||||
} catch {
|
||||
total = stopAfter + 1
|
||||
}
|
||||
}
|
||||
|
||||
visit(data, 0)
|
||||
return total
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
buildPluginPanelShellHtml,
|
||||
PANEL_DESIGN_TOKEN_ALLOWLIST,
|
||||
PLUGIN_PANEL_CSP
|
||||
} from './plugin-panel-shell'
|
||||
|
||||
describe('buildPluginPanelShellHtml', () => {
|
||||
it('keeps destructive surface and foreground tokens paired', () => {
|
||||
expect(PANEL_DESIGN_TOKEN_ALLOWLIST).toEqual(
|
||||
expect.arrayContaining(['--destructive', '--destructive-foreground'])
|
||||
)
|
||||
})
|
||||
|
||||
it('places CSP and navigation guards before plugin content', () => {
|
||||
const html = buildPluginPanelShellHtml('<main id="plugin-content">Plugin</main>')
|
||||
const pluginOffset = html.indexOf('plugin-content')
|
||||
|
||||
expect(PLUGIN_PANEL_CSP).toContain("form-action 'none'")
|
||||
expect(html.indexOf('Content-Security-Policy')).toBeLessThan(pluginOffset)
|
||||
expect(html.indexOf("window.navigation.addEventListener('navigate'")).toBeLessThan(pluginOffset)
|
||||
expect(html.indexOf("window.addEventListener('click'")).toBeLessThan(pluginOffset)
|
||||
expect(html.indexOf("window.addEventListener('submit'")).toBeLessThan(pluginOffset)
|
||||
expect(html.indexOf("Object.defineProperty(window, 'open'")).toBeLessThan(pluginOffset)
|
||||
})
|
||||
|
||||
it('cancels anchor and form default navigation in the fallback path', () => {
|
||||
const html = buildPluginPanelShellHtml('<main>Plugin</main>')
|
||||
const script = html.match(/<script>\n([\s\S]*?)<\/script>/)?.[1]
|
||||
expect(script).toBeTruthy()
|
||||
// Keep happy-dom's global removable for Vitest teardown; production shell
|
||||
// keeps the override non-configurable inside the disposable iframe.
|
||||
window.eval(script!.replace('configurable: false', 'configurable: true'))
|
||||
|
||||
const anchor = document.createElement('a')
|
||||
anchor.href = 'https://example.com/'
|
||||
document.body.appendChild(anchor)
|
||||
const clickAccepted = anchor.dispatchEvent(
|
||||
new MouseEvent('click', { bubbles: true, cancelable: true })
|
||||
)
|
||||
const form = document.createElement('form')
|
||||
document.body.appendChild(form)
|
||||
const submitAccepted = form.dispatchEvent(
|
||||
new Event('submit', { bubbles: true, cancelable: true })
|
||||
)
|
||||
|
||||
expect(clickAccepted).toBe(false)
|
||||
expect(submitAccepted).toBe(false)
|
||||
expect(window.open('https://example.com/')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,101 @@
|
||||
import { PANEL_PING_TYPE, PANEL_PONG_TYPE } from './plugin-panel-bridge'
|
||||
|
||||
/**
|
||||
* Host-generated shell wrapped around plugin panel HTML before it is handed
|
||||
* to the sandboxed iframe. The shell's job is to make the CSP parse BEFORE
|
||||
* any plugin content does: an opaque-origin sandboxed iframe without a CSP
|
||||
* can still fetch() CORS-permissive endpoints and beacon data out via <img>.
|
||||
*
|
||||
* Prepending works because (a) a CSP <meta> applies from the moment it
|
||||
* parses and cannot be un-applied by later markup or DOM removal, and (b) a
|
||||
* second CSP meta from the plugin can only intersect (tighten), never loosen.
|
||||
* The plugin document merges into the shell's open <head>/<html>, so design
|
||||
* tokens defined here are visible to plugin CSS as ordinary custom
|
||||
* properties.
|
||||
*
|
||||
* Electron-free string builder: desktop main and headless serve both wrap
|
||||
* panel HTML through this one function.
|
||||
*/
|
||||
|
||||
export const PLUGIN_PANEL_CSP =
|
||||
"default-src 'none'; connect-src 'none'; script-src 'unsafe-inline'; " +
|
||||
"style-src 'unsafe-inline'; img-src data:; font-src data:; base-uri 'none'; form-action 'none'"
|
||||
|
||||
/** Renderer-substituted placeholders. Main cannot know the renderer's theme
|
||||
* or token values; the renderer replaces these with a color-scheme class and
|
||||
* CSS custom-property declarations before mounting the srcdoc. */
|
||||
export const PANEL_SHELL_TOKENS_PLACEHOLDER = '/*__ORCA_PANEL_TOKENS__*/'
|
||||
export const PANEL_SHELL_COLOR_SCHEME_PLACEHOLDER = '__ORCA_COLOR_SCHEME__'
|
||||
|
||||
/** Curated design-token subset injected into panel documents. Deliberately
|
||||
* NOT all of main.css (~257 custom properties): freezing every token as
|
||||
* public API would lock future refactors. Grow additively; renaming or
|
||||
* dropping an entry here is a plugin-facing breaking change. */
|
||||
export const PANEL_DESIGN_TOKEN_ALLOWLIST = [
|
||||
'--background',
|
||||
'--foreground',
|
||||
'--card',
|
||||
'--card-foreground',
|
||||
'--popover',
|
||||
'--popover-foreground',
|
||||
'--primary',
|
||||
'--primary-foreground',
|
||||
'--secondary',
|
||||
'--secondary-foreground',
|
||||
'--muted',
|
||||
'--muted-foreground',
|
||||
'--accent',
|
||||
'--accent-foreground',
|
||||
'--destructive',
|
||||
'--destructive-foreground',
|
||||
'--border',
|
||||
'--input',
|
||||
'--ring',
|
||||
'--radius'
|
||||
] as const
|
||||
|
||||
export function buildPluginPanelShellHtml(pluginHtml: string): string {
|
||||
// The inline ping responder proves the frame's event loop is alive; the
|
||||
// renderer watchdog demotes the panel when pongs stop arriving.
|
||||
const prelude =
|
||||
'<!doctype html>\n' +
|
||||
`<html class="${PANEL_SHELL_COLOR_SCHEME_PLACEHOLDER}">\n` +
|
||||
'<head>\n' +
|
||||
'<meta charset="utf-8">\n' +
|
||||
`<meta http-equiv="Content-Security-Policy" content="${PLUGIN_PANEL_CSP}">\n` +
|
||||
`<style>:root{${PANEL_SHELL_TOKENS_PLACEHOLDER}}</style>\n` +
|
||||
'<script>\n' +
|
||||
"'use strict'\n" +
|
||||
'// Host policy: plugin panels are documents, never browsing contexts.\n' +
|
||||
"if (window.navigation && typeof window.navigation.addEventListener === 'function') {\n" +
|
||||
" window.navigation.addEventListener('navigate', function (event) {\n" +
|
||||
' if (event.cancelable) event.preventDefault()\n' +
|
||||
' })\n' +
|
||||
'}\n' +
|
||||
"try { Object.defineProperty(window, 'open', { value: function () { return null }, writable: false, configurable: false }) }\n" +
|
||||
'catch (_) { try { window.open = function () { return null } } catch (_) {} }\n' +
|
||||
"window.addEventListener('click', function (event) {\n" +
|
||||
' var node = event.target\n' +
|
||||
' while (node && node !== document) {\n' +
|
||||
" if (node.nodeType === 1 && node.tagName === 'A' && node.hasAttribute('href')) {\n" +
|
||||
' event.preventDefault()\n' +
|
||||
' event.stopImmediatePropagation()\n' +
|
||||
' return\n' +
|
||||
' }\n' +
|
||||
' node = node.parentNode\n' +
|
||||
' }\n' +
|
||||
'}, true)\n' +
|
||||
"window.addEventListener('submit', function (event) {\n" +
|
||||
' event.preventDefault()\n' +
|
||||
' event.stopImmediatePropagation()\n' +
|
||||
'}, true)\n' +
|
||||
"window.addEventListener('message', function (event) {\n" +
|
||||
' var data = event.data\n' +
|
||||
` if (event.source === window.parent && data && data.type === '${PANEL_PING_TYPE}') {\n` +
|
||||
` window.parent.postMessage({ type: '${PANEL_PONG_TYPE}', pingId: data.pingId }, '*')\n` +
|
||||
' }\n' +
|
||||
'})\n' +
|
||||
'</script>\n' +
|
||||
'</head>\n'
|
||||
return prelude + pluginHtml
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parsePluginManifest } from './plugin-manifest'
|
||||
import { isSafePluginRelativePath } from './plugin-path-safety'
|
||||
|
||||
describe('plugin path portability', () => {
|
||||
it.each([
|
||||
'CON',
|
||||
'assets/aux.txt',
|
||||
'dist/panel.html.',
|
||||
'dist/panel.html ',
|
||||
'dist/panel.html:payload',
|
||||
'dist\\LPT1.js',
|
||||
'../worker.js',
|
||||
'dist//panel.html'
|
||||
])('rejects %s on every host platform', (path) => {
|
||||
expect(isSafePluginRelativePath(path)).toBe(false)
|
||||
})
|
||||
|
||||
it.each(['dist/panel.html', 'assets/.icon.svg', 'nested\\worker.js'])('accepts %s', (path) => {
|
||||
expect(isSafePluginRelativePath(path)).toBe(true)
|
||||
})
|
||||
|
||||
it('applies portable path validation to every declared artifact kind', () => {
|
||||
const base = {
|
||||
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: []
|
||||
}
|
||||
|
||||
expect(parsePluginManifest({ ...base, icon: 'assets/NUL.svg' }).ok).toBe(false)
|
||||
expect(parsePluginManifest({ ...base, main: 'dist/worker.js.' }).ok).toBe(false)
|
||||
expect(
|
||||
parsePluginManifest({
|
||||
...base,
|
||||
contributes: {
|
||||
...base.contributes,
|
||||
panels: [{ id: 'panel', title: 'Panel', entry: 'dist/panel.html:ads' }]
|
||||
}
|
||||
}).ok
|
||||
).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,42 @@
|
||||
/** Windows normalizes these names even when the host doing validation does not. */
|
||||
const WINDOWS_DEVICE_NAME_RE =
|
||||
/^(?:con|prn|aux|nul|clock\$|conin\$|conout\$|com[1-9¹²³]|lpt[1-9¹²³])(?:\..*)?$/i
|
||||
|
||||
const WINDOWS_FORBIDDEN_CHAR_RE = /[<>:"|?*]/
|
||||
|
||||
export function pluginPathSegmentError(segment: string): string | null {
|
||||
if (segment.length === 0 || segment === '.' || segment === '..') {
|
||||
return 'empty and dot path segments are not allowed'
|
||||
}
|
||||
if (segment.endsWith('.') || segment.endsWith(' ')) {
|
||||
return 'path segments may not end with a dot or space'
|
||||
}
|
||||
if (
|
||||
WINDOWS_FORBIDDEN_CHAR_RE.test(segment) ||
|
||||
[...segment].some((character) => character.charCodeAt(0) <= 31)
|
||||
) {
|
||||
return 'path segment contains a Windows-forbidden character or alternate-data-stream colon'
|
||||
}
|
||||
if (WINDOWS_DEVICE_NAME_RE.test(segment)) {
|
||||
return 'path segment is a Windows reserved device name'
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function pluginRelativePathError(value: string): string | null {
|
||||
if (value.length === 0 || value.startsWith('/') || value.startsWith('\\')) {
|
||||
return 'must be a non-empty relative path'
|
||||
}
|
||||
const segments = value.split(/[\\/]/)
|
||||
for (const segment of segments) {
|
||||
const error = pluginPathSegmentError(segment)
|
||||
if (error) {
|
||||
return error
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function isSafePluginRelativePath(value: string): boolean {
|
||||
return pluginRelativePathError(value) === null
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
listPluginVmRecipeCommands,
|
||||
parsePluginVmRecipeArtifact
|
||||
} from './plugin-vm-recipe-artifact'
|
||||
|
||||
describe('plugin VM recipe artifacts', () => {
|
||||
it('parses bounded lifecycle commands for verbatim consent', () => {
|
||||
const recipe = parsePluginVmRecipeArtifact(
|
||||
JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
id: 'cloud-sandbox',
|
||||
name: 'Cloud Sandbox',
|
||||
create: './scripts/create.sh',
|
||||
suspend: './scripts/suspend.sh',
|
||||
resume: './scripts/resume.sh',
|
||||
destroy: './scripts/destroy.sh'
|
||||
})
|
||||
)
|
||||
|
||||
expect(recipe).toMatchObject({ id: 'cloud-sandbox', name: 'Cloud Sandbox' })
|
||||
expect(listPluginVmRecipeCommands(recipe)).toEqual([
|
||||
{ phase: 'create', command: './scripts/create.sh' },
|
||||
{ phase: 'suspend', command: './scripts/suspend.sh' },
|
||||
{ phase: 'resume', command: './scripts/resume.sh' },
|
||||
{ phase: 'destroy', command: './scripts/destroy.sh' }
|
||||
])
|
||||
})
|
||||
|
||||
it('requires paired suspend/resume commands and rejects unknown fields', () => {
|
||||
expect(() =>
|
||||
parsePluginVmRecipeArtifact(
|
||||
JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
id: 'broken',
|
||||
name: 'Broken',
|
||||
create: 'create',
|
||||
suspend: 'suspend'
|
||||
})
|
||||
)
|
||||
).toThrow('suspend and resume')
|
||||
expect(() =>
|
||||
parsePluginVmRecipeArtifact(
|
||||
JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
id: 'broken',
|
||||
name: 'Broken',
|
||||
create: 'create',
|
||||
environment: { SECRET: 'value' }
|
||||
})
|
||||
)
|
||||
).toThrow()
|
||||
})
|
||||
|
||||
it('represents an explicitly disabled destroy action without executing text', () => {
|
||||
const recipe = parsePluginVmRecipeArtifact(
|
||||
JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
id: 'managed',
|
||||
name: 'Managed',
|
||||
create: 'create',
|
||||
destroy: 'none'
|
||||
})
|
||||
)
|
||||
|
||||
expect(recipe).toMatchObject({ destroyDisabled: true })
|
||||
expect(recipe.destroy).toBeUndefined()
|
||||
})
|
||||
|
||||
it('rejects NUL bytes and commands beyond the bounded artifact contract', () => {
|
||||
for (const create of ['bad\0command', 'x'.repeat(32 * 1024 + 1)]) {
|
||||
expect(() =>
|
||||
parsePluginVmRecipeArtifact(
|
||||
JSON.stringify({ schemaVersion: 1, id: 'bounded', name: 'Bounded', create })
|
||||
)
|
||||
).toThrow()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,65 @@
|
||||
import { z } from 'zod'
|
||||
import { ORCA_VM_RECIPE_ID_PATTERN, ORCA_VM_RECIPE_ID_RULE } from '../orca-yaml'
|
||||
import type { OrcaVmRecipe } from '../types'
|
||||
|
||||
const recipeCommandSchema = z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.max(32 * 1024)
|
||||
.refine((value) => !value.includes('\0'), 'must not contain NUL bytes')
|
||||
|
||||
const pluginVmRecipeArtifactSchema = z
|
||||
.object({
|
||||
schemaVersion: z.literal(1),
|
||||
id: z.string().regex(ORCA_VM_RECIPE_ID_PATTERN, ORCA_VM_RECIPE_ID_RULE),
|
||||
name: z.string().trim().min(1).max(128),
|
||||
description: z.string().trim().min(1).max(1024).optional(),
|
||||
create: recipeCommandSchema,
|
||||
suspend: recipeCommandSchema.optional(),
|
||||
resume: recipeCommandSchema.optional(),
|
||||
destroy: z.union([recipeCommandSchema, z.literal('none')]).optional()
|
||||
})
|
||||
.strict()
|
||||
.superRefine((recipe, ctx) => {
|
||||
if (Boolean(recipe.suspend) !== Boolean(recipe.resume)) {
|
||||
ctx.addIssue({
|
||||
code: 'custom',
|
||||
path: recipe.suspend ? ['resume'] : ['suspend'],
|
||||
message: 'suspend and resume must be declared together'
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
export type PluginVmRecipeCommand = {
|
||||
phase: 'create' | 'suspend' | 'resume' | 'destroy'
|
||||
command: string
|
||||
}
|
||||
|
||||
export function parsePluginVmRecipeArtifact(raw: string): OrcaVmRecipe {
|
||||
const parsed = pluginVmRecipeArtifactSchema.parse(JSON.parse(raw))
|
||||
const destroyDisabled = parsed.destroy === 'none'
|
||||
return {
|
||||
id: parsed.id,
|
||||
name: parsed.name,
|
||||
create: parsed.create,
|
||||
...(parsed.description ? { description: parsed.description } : {}),
|
||||
...(parsed.suspend ? { suspend: parsed.suspend } : {}),
|
||||
...(parsed.resume ? { resume: parsed.resume } : {}),
|
||||
...(parsed.destroy && !destroyDisabled ? { destroy: parsed.destroy } : {}),
|
||||
...(destroyDisabled ? { destroyDisabled: true } : {})
|
||||
}
|
||||
}
|
||||
|
||||
export function listPluginVmRecipeCommands(recipe: OrcaVmRecipe): PluginVmRecipeCommand[] {
|
||||
return [
|
||||
{ phase: 'create', command: recipe.create },
|
||||
...(recipe.suspend ? [{ phase: 'suspend' as const, command: recipe.suspend }] : []),
|
||||
...(recipe.resume ? [{ phase: 'resume' as const, command: recipe.resume }] : []),
|
||||
...(recipe.destroy
|
||||
? [{ phase: 'destroy' as const, command: recipe.destroy }]
|
||||
: recipe.destroyDisabled
|
||||
? [{ phase: 'destroy' as const, command: 'none' }]
|
||||
: [])
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user