mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-20 18:26:40 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Agents use external services through connectors: a catalog of connector types, connections (accounts) per type, and per-agent installs, policies and audit in the tool gateway > - Today only core can add a connector type. Every type is a JSON definition compiled into `@paperclipai/shared` > - Plugins can add agent tools, but those tools skip connections, grants, per-agent installs and the Connectors page > - This pull request lets a plugin add connector types with the same definition schema, and makes them behave exactly like built-in connectors > - The benefit is that a connector can ship as a plugin, and an operator controls it with the same Connectors page and the same access rules ## Linked Issues or Issue Description **Subsystem affected** Plugins, Connectors (tool access), tool gateway **Problem or motivation** A plugin cannot add a connector type to the Connectors catalog. Plugin tools (`tools` in the manifest) do not use connections, credentials per account, agent installs, policies or the Connectors page. **Proposed solution** Add a manifest field `apps` (gated by a new `connectors.provide` capability). Each entry uses the built-in app-definition schema. The host namespaces the slug by plugin key and runs setup, OAuth, discovery, grants, policies and audit through the existing code. This is the first of two pull requests. The second adds a `plugin` transport so a plugin worker can serve the tools itself. **Activation rules (product requirements)** 1. Installing or enabling a plugin grants no tools. It only adds connector types to the catalog. 2. Connecting an account grants no tools. 3. An agent gets the tools only from an agent install or a company install of an active connection. Discovery and invocation both enforce this. 4. A disabled or uninstalled plugin (or an upgrade that removes the app) hides its connector types and connections from the Connectors APIs and they reach no agent. Saved setup survives disable and comes back on re-enable. Uninstall keeps rows archived for audit and revokes credentials. **Alternatives considered** Keep plugin tools (`tools`) as the only plugin path. Rejected: they bypass connections, per-account credentials, per-agent installs and the Connectors page. ## What Changed - `packages/shared`: new capability `connectors.provide`; manifest `apps` validated with `appDefinitionSchema`. The validator rejects apps without the capability, duplicate slugs, host-derived fields (`plugin`, `aiConnectionRouter`, `experimentalFeatureKey`, `availability`), and methods that need provider code in the host (REST adapters, chat channels, AI runtimes). - `packages/shared/src/plugin-apps.ts`: reversible namespaced slugs (`plugin-<hex plugin key>-<slug>`), the catalog entry builder, and `reviewedToolRisk`. - `packages/shared/src/app-definitions.ts`: catalog lookups (`getConnectableAppDefinition`, `getAppStoreDefinition`, ...) also resolve the current plugin apps. The set is replaced on each read of plugin state, so a built-in app is never shadowed. - App definitions can declare `reviewedTools` (reviewed read/write/destructive names and the risk for unlisted tools). Circleback's reviewed risk moves from `server/src/services/connectors/circleback/risk.ts` into `circleback.json`, with the same classification. A copy of the definition now classifies tools the same way. - `validators/json-schema.ts`: `jsonSchemaSchema` moves to its own module to break an import cycle between the plugin and app-definition validators (still re-exported from `validators/plugin.ts`). - `server/src/services/plugin-app-catalog.ts`: reads ready plugins from the `plugins` table and answers "is this connection's connector available". It does not trust in-memory lifecycle events, because several lifecycle managers and processes can share one database. - Gateway: connected-tool discovery and `resolveConnectionGrant` drop connections from an unavailable plugin connector. Built-in connections do not read the plugins table. - Connectors APIs: the gallery lists ready plugin apps (with the same Cloud connector profile filter as core); `listConnections` and `listApplications` hide unavailable plugin connections; setup entry points refresh plugin apps first. - Plugin uninstall archives the plugin's connections through the standard connection removal (grants revoked, owned credentials deleted, rows kept). - UI: the gallery response registers plugin apps for the setup screens; `/apps/connect?source=plugin-…` loads the gallery first and shows an unavailable state when the plugin is disabled. - Docs: `doc/plugins/PLUGIN_SPEC.md` section 11A and the capability list. Design choices where the spec left room (picked to match "a plugin connector behaves like a built-in connector"): - Only `ready` plugins provide connectors. `error` and `upgrade_pending` hide them, the same as the AI connection router plugins. - `rest_api` is rejected for plugin apps in this PR. Core REST connectors need reviewed adapter code in the host, so a definition alone cannot work. The `plugin` transport in the next PR covers that case. - Disabled plugin connections are hidden from list endpoints. Reading one connection by id still works, so audit links keep resolving. ## Verification - `packages/shared`: `npx vitest run src/plugin-apps.test.ts src/validators/ src/app-definitions.test.ts` (416 passed). New tests: manifest validation, slug namespacing, no shadowing of built-in apps, reviewed risk. - `server`: `npx vitest run src/__tests__/plugin-connectors-circleback-parity.test.ts` (new). A test-only plugin (`server/src/__tests__/fixtures/plugin-connectors/circleback-parity/`) ships an unmodified copy of `circleback.json`. The same journey runs against built-in Circleback and the plugin copy with a recorded DCR OAuth + MCP fixture, and must give identical catalog risk/status, suggested defaults and per-agent tool sets. It covers each rule: - Rule 1: the gallery adds only the namespaced type; no connections exist; no agent tool changes. - Rule 2: two signed-in accounts, no agent sees a tool. - Rule 3: an install for agent A gives only A the tools of that connection; agent B is denied on invocation; each account calls the provider with its own credential. - Rule 4: disable hides the type, both connections and applications, removes tools from discovery and invocation (404) and blocks new setup, while built-in Circleback is unchanged; installs and grants are byte-identical; re-enable restores tools with the same names; an upgrade that removes the app hides it; uninstall archives both connections, revokes grants and deletes owned secrets. - Red/green: removing the gateway gate or the declared review makes the test fail. - An env-gated live check (`PAPERCLIP_CIRCLEBACK_LIVE=1`) starts the real Circleback sign-in for both connectors and compares the requests. It never runs in CI. I did not run it for this PR. - Regression: `ai-connection-router`, `connector-tool-policy`, `mcp-apps`, `plugin-lifecycle-restart`, `tool-access-service`, `braintrust-connection`, `remote-mcp-connectors`, `connection-intents-service`, `tool-gateway` (796 passed). - `ui`: `app-connect-policy.test.ts`, `AppsConnect.test.tsx` (new plugin cases) pass. - `tsc --noEmit` for shared, server, ui (only pre-existing ungenerated Storybook catalog errors), plugin SDK and CLI. - `pnpm verify --explain` selects a broad plan because a doc under `doc/plugins` changed; CI supplies that coverage. ## Risks - No migration. Built-in connectors only gain one string check per discovery; the plugins table is read only when a plugin connection is present. - Circleback's reviewed risk is now data. The behavior is the same, and the existing policy tests and new tests cover it. - Connection intents (agent connection requests in chat) still search only built-in apps. Plugin connectors can be set up from the Connectors page. This is a follow-up. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file editing, test execution). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
533 lines
18 KiB
TypeScript
533 lines
18 KiB
TypeScript
/**
|
||
* PluginCapabilityValidator — enforces the capability model at both
|
||
* install-time and runtime.
|
||
*
|
||
* Every plugin declares the capabilities it requires in its manifest
|
||
* (`manifest.capabilities`). This service checks those declarations
|
||
* against a mapping of operations → required capabilities so that:
|
||
*
|
||
* 1. **Install-time validation** — `validateManifestCapabilities()`
|
||
* ensures that declared features (tools, jobs, webhooks, UI slots)
|
||
* have matching capability entries, giving operators clear feedback
|
||
* before a plugin is activated.
|
||
*
|
||
* 2. **Runtime gating** — `checkOperation()` / `assertOperation()` are
|
||
* called on every worker→host bridge call to enforce least-privilege
|
||
* access. If a plugin attempts an operation it did not declare, the
|
||
* call is rejected with a 403 error.
|
||
*
|
||
* @see PLUGIN_SPEC.md §15 — Capability Model
|
||
* @see host-client-factory.ts — SDK-side capability gating
|
||
*/
|
||
import type {
|
||
PluginCapability,
|
||
PaperclipPluginManifestV1,
|
||
PluginUiSlotType,
|
||
PluginLauncherPlacementZone,
|
||
} from "@paperclipai/shared";
|
||
import { forbidden } from "../errors.js";
|
||
import { logger } from "../middleware/logger.js";
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Capability requirement mappings
|
||
// ---------------------------------------------------------------------------
|
||
|
||
/**
|
||
* Maps high-level operations to the capabilities they require.
|
||
*
|
||
* When the bridge receives a call from a plugin worker, the host looks up
|
||
* the operation in this map and checks the plugin's declared capabilities.
|
||
* If any required capability is missing, the call is rejected.
|
||
*
|
||
* @see PLUGIN_SPEC.md §15 — Capability Model
|
||
*/
|
||
const OPERATION_CAPABILITIES: Record<string, readonly PluginCapability[]> = {
|
||
// Data read operations
|
||
"companies.list": ["companies.read"],
|
||
"companies.get": ["companies.read"],
|
||
"projects.list": ["projects.read"],
|
||
"projects.get": ["projects.read"],
|
||
"projects.resolveGitCredential": ["projects.git-credentials"],
|
||
"projects.getInstanceSecrets": ["projects.instance-secrets"],
|
||
"projects.managed.get": ["projects.managed"],
|
||
"projects.managed.reconcile": ["projects.managed"],
|
||
"projects.managed.reset": ["projects.managed"],
|
||
"routines.managed.get": ["routines.managed"],
|
||
"routines.managed.reconcile": ["routines.managed"],
|
||
"routines.managed.reset": ["routines.managed"],
|
||
"project.workspaces.list": ["project.workspaces.read"],
|
||
"project.workspaces.get": ["project.workspaces.read"],
|
||
"execution.workspaces.get": ["execution.workspaces.read"],
|
||
"issues.list": ["issues.read"],
|
||
"issues.get": ["issues.read"],
|
||
"issues.relations.get": ["issue.relations.read"],
|
||
"issue.comments.list": ["issue.comments.read"],
|
||
"issue.comments.get": ["issue.comments.read"],
|
||
"issue.interactions.list": ["issue.interactions.read"],
|
||
"issue.interactions.read": ["issue.interactions.read"],
|
||
"issue.attachments.list": ["issue.attachments.read"],
|
||
"issue.attachments.get": ["issue.attachments.read"],
|
||
"approvals.list": ["approvals.read"],
|
||
"approvals.get": ["approvals.read"],
|
||
"agents.list": ["agents.read"],
|
||
"agents.get": ["agents.read"],
|
||
"agents.managed.get": ["agents.managed"],
|
||
"agents.managed.reconcile": ["agents.managed"],
|
||
"agents.managed.reset": ["agents.managed"],
|
||
"goals.list": ["goals.read"],
|
||
"goals.get": ["goals.read"],
|
||
"activity.list": ["activity.read"],
|
||
"activity.get": ["activity.read"],
|
||
"costs.list": ["costs.read"],
|
||
"costs.get": ["costs.read"],
|
||
"issues.summaries.getOrchestration": ["issues.orchestration.read"],
|
||
"db.namespace": ["database.namespace.read"],
|
||
"db.query": ["database.namespace.read"],
|
||
"localFolders.declarations": [],
|
||
"localFolders.configure": ["local.folders"],
|
||
"localFolders.status": ["local.folders"],
|
||
"localFolders.list": ["local.folders"],
|
||
"localFolders.readText": ["local.folders"],
|
||
"localFolders.writeTextAtomic": ["local.folders"],
|
||
|
||
// Data write operations
|
||
"issues.create": ["issues.create"],
|
||
"issues.update": ["issues.update"],
|
||
"issues.relations.setBlockedBy": ["issue.relations.write"],
|
||
"issues.relations.addBlockers": ["issue.relations.write"],
|
||
"issues.relations.removeBlockers": ["issue.relations.write"],
|
||
"issues.assertCheckoutOwner": ["issues.checkout"],
|
||
"issues.getSubtree": ["issue.subtree.read"],
|
||
"issues.requestWakeup": ["issues.wakeup"],
|
||
"issues.requestWakeups": ["issues.wakeup"],
|
||
"issue.comments.create": ["issue.comments.create"],
|
||
"issue.comments.create_human_attributed": ["issue.comments.create_human_attributed"],
|
||
"issue.interactions.create": ["issue.interactions.create"],
|
||
"issue.interactions.respond": ["issue.interactions.respond"],
|
||
"approvals.respond": ["approvals.respond"],
|
||
"approvals.decide": ["approvals.respond"],
|
||
"activity.log": ["activity.log.write"],
|
||
"metrics.write": ["metrics.write"],
|
||
"telemetry.track": ["telemetry.track"],
|
||
"db.migrate": ["database.namespace.migrate"],
|
||
"db.execute": ["database.namespace.write"],
|
||
"external.objects.detect": ["external.objects.detect"],
|
||
"external.objects.read": ["external.objects.read"],
|
||
"external.objects.write": ["external.objects.write"],
|
||
"external.objects.refresh": ["external.objects.refresh"],
|
||
|
||
// Plugin state operations
|
||
"plugin.state.get": ["plugin.state.read"],
|
||
"plugin.state.list": ["plugin.state.read"],
|
||
"plugin.state.set": ["plugin.state.write"],
|
||
"plugin.state.delete": ["plugin.state.write"],
|
||
|
||
// Runtime / Integration operations
|
||
"events.subscribe": ["events.subscribe"],
|
||
"events.emit": ["events.emit"],
|
||
"jobs.schedule": ["jobs.schedule"],
|
||
"jobs.cancel": ["jobs.schedule"],
|
||
"webhooks.receive": ["webhooks.receive"],
|
||
"http.request": ["http.outbound"],
|
||
"secrets.resolve": ["secrets.read-ref"],
|
||
|
||
// Agent tools
|
||
"agent.tools.register": ["agent.tools.register"],
|
||
"agent.tools.execute": ["agent.tools.register"],
|
||
|
||
// Environment runtime drivers
|
||
"workspace.operation": ["workspaces.manage"],
|
||
"environment.validateConfig": ["environment.drivers.register"],
|
||
"environment.probe": ["environment.drivers.register"],
|
||
"environment.acquireLease": ["environment.drivers.register"],
|
||
"environment.resumeLease": ["environment.drivers.register"],
|
||
"environment.releaseLease": ["environment.drivers.register"],
|
||
"environment.destroyLease": ["environment.drivers.register"],
|
||
"environment.realizeWorkspace": ["environment.drivers.register"],
|
||
"environment.execute": ["environment.drivers.register"],
|
||
"environment.startInteractiveSetup": ["environment.drivers.register"],
|
||
"environment.getInteractiveSetup": ["environment.drivers.register"],
|
||
"environment.captureTemplate": ["environment.drivers.register"],
|
||
"environment.cancelInteractiveSetup": ["environment.drivers.register"],
|
||
"environment.deleteTemplate": ["environment.drivers.register"],
|
||
};
|
||
|
||
/**
|
||
* Maps UI slot types to the capability required to register them.
|
||
*
|
||
* @see PLUGIN_SPEC.md §19 — UI Extension Model
|
||
*/
|
||
const UI_SLOT_CAPABILITIES: Record<PluginUiSlotType, PluginCapability> = {
|
||
sidebar: "ui.sidebar.register",
|
||
sidebarPanel: "ui.sidebar.register",
|
||
projectSidebarItem: "ui.sidebar.register",
|
||
page: "ui.page.register",
|
||
detailTab: "ui.detailTab.register",
|
||
taskDetailView: "ui.detailTab.register",
|
||
dashboardWidget: "ui.dashboardWidget.register",
|
||
globalToolbarButton: "ui.action.register",
|
||
appShellOverlay: "ui.action.register",
|
||
organizationSwitcher: "ui.sidebar.register",
|
||
toolbarButton: "ui.action.register",
|
||
contextMenuItem: "ui.action.register",
|
||
commentAnnotation: "ui.commentAnnotation.register",
|
||
commentContextMenuItem: "ui.action.register",
|
||
settingsPage: "instance.settings.register",
|
||
companySettingsPage: "instance.settings.register",
|
||
routeSidebar: "ui.sidebar.register",
|
||
};
|
||
|
||
/**
|
||
* Launcher placement zones align with host UI surfaces and therefore inherit
|
||
* the same capability requirements as the equivalent slot type.
|
||
*/
|
||
const LAUNCHER_PLACEMENT_CAPABILITIES: Record<
|
||
PluginLauncherPlacementZone,
|
||
PluginCapability
|
||
> = {
|
||
page: "ui.page.register",
|
||
detailTab: "ui.detailTab.register",
|
||
taskDetailView: "ui.detailTab.register",
|
||
dashboardWidget: "ui.dashboardWidget.register",
|
||
sidebar: "ui.sidebar.register",
|
||
sidebarPanel: "ui.sidebar.register",
|
||
projectSidebarItem: "ui.sidebar.register",
|
||
globalToolbarButton: "ui.action.register",
|
||
toolbarButton: "ui.action.register",
|
||
contextMenuItem: "ui.action.register",
|
||
commentAnnotation: "ui.commentAnnotation.register",
|
||
commentContextMenuItem: "ui.action.register",
|
||
settingsPage: "instance.settings.register",
|
||
};
|
||
|
||
/**
|
||
* Maps feature declarations in the manifest to their required capabilities.
|
||
*/
|
||
const FEATURE_CAPABILITIES: Record<string, PluginCapability> = {
|
||
tools: "agent.tools.register",
|
||
apps: "connectors.provide",
|
||
jobs: "jobs.schedule",
|
||
webhooks: "webhooks.receive",
|
||
database: "database.namespace.migrate",
|
||
environmentDrivers: "environment.drivers.register",
|
||
workspaceProvider: "workspaces.manage",
|
||
agents: "agents.managed",
|
||
projects: "projects.managed",
|
||
routines: "routines.managed",
|
||
objectReferences: "external.objects.detect",
|
||
};
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Result types
|
||
// ---------------------------------------------------------------------------
|
||
|
||
/**
|
||
* Result of a capability check. When `allowed` is false, `missing` contains
|
||
* the capabilities that the plugin does not declare but the operation requires.
|
||
*/
|
||
export interface CapabilityCheckResult {
|
||
allowed: boolean;
|
||
missing: PluginCapability[];
|
||
operation?: string;
|
||
pluginId?: string;
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// PluginCapabilityValidator interface
|
||
// ---------------------------------------------------------------------------
|
||
|
||
export interface PluginCapabilityValidator {
|
||
/**
|
||
* Check whether a plugin has a specific capability.
|
||
*/
|
||
hasCapability(
|
||
manifest: PaperclipPluginManifestV1,
|
||
capability: PluginCapability,
|
||
): boolean;
|
||
|
||
/**
|
||
* Check whether a plugin has all of the specified capabilities.
|
||
*/
|
||
hasAllCapabilities(
|
||
manifest: PaperclipPluginManifestV1,
|
||
capabilities: PluginCapability[],
|
||
): CapabilityCheckResult;
|
||
|
||
/**
|
||
* Check whether a plugin has at least one of the specified capabilities.
|
||
*/
|
||
hasAnyCapability(
|
||
manifest: PaperclipPluginManifestV1,
|
||
capabilities: PluginCapability[],
|
||
): boolean;
|
||
|
||
/**
|
||
* Check whether a plugin is allowed to perform the named operation.
|
||
*
|
||
* Operations are mapped to required capabilities via OPERATION_CAPABILITIES.
|
||
* Unknown operations are rejected by default.
|
||
*/
|
||
checkOperation(
|
||
manifest: PaperclipPluginManifestV1,
|
||
operation: string,
|
||
): CapabilityCheckResult;
|
||
|
||
/**
|
||
* Assert that a plugin is allowed to perform an operation.
|
||
* Throws a 403 HttpError if the capability check fails.
|
||
*/
|
||
assertOperation(
|
||
manifest: PaperclipPluginManifestV1,
|
||
operation: string,
|
||
): void;
|
||
|
||
/**
|
||
* Assert that a plugin has a specific capability.
|
||
* Throws a 403 HttpError if the capability is missing.
|
||
*/
|
||
assertCapability(
|
||
manifest: PaperclipPluginManifestV1,
|
||
capability: PluginCapability,
|
||
): void;
|
||
|
||
/**
|
||
* Check whether a plugin can register the given UI slot type.
|
||
*/
|
||
checkUiSlot(
|
||
manifest: PaperclipPluginManifestV1,
|
||
slotType: PluginUiSlotType,
|
||
): CapabilityCheckResult;
|
||
|
||
/**
|
||
* Validate that a manifest's declared capabilities are consistent with its
|
||
* declared features (tools, jobs, webhooks, UI slots).
|
||
*
|
||
* Returns all missing capabilities rather than failing on the first one.
|
||
* This is useful for install-time validation to give comprehensive feedback.
|
||
*/
|
||
validateManifestCapabilities(
|
||
manifest: PaperclipPluginManifestV1,
|
||
): CapabilityCheckResult;
|
||
|
||
/**
|
||
* Get the capabilities required for a named operation.
|
||
* Returns an empty array if the operation is unknown.
|
||
*/
|
||
getRequiredCapabilities(operation: string): readonly PluginCapability[];
|
||
|
||
/**
|
||
* Get the capability required for a UI slot type.
|
||
*/
|
||
getUiSlotCapability(slotType: PluginUiSlotType): PluginCapability;
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Factory
|
||
// ---------------------------------------------------------------------------
|
||
|
||
/**
|
||
* Create a PluginCapabilityValidator.
|
||
*
|
||
* This service enforces capability gates for plugin operations. The host
|
||
* uses it to verify that a plugin's declared capabilities permit the
|
||
* operation it is attempting, both at install time (manifest validation)
|
||
* and at runtime (bridge call gating).
|
||
*
|
||
* Usage:
|
||
* ```ts
|
||
* const validator = pluginCapabilityValidator();
|
||
*
|
||
* // Runtime: gate a bridge call
|
||
* validator.assertOperation(plugin.manifestJson, "issues.create");
|
||
*
|
||
* // Install time: validate manifest consistency
|
||
* const result = validator.validateManifestCapabilities(manifest);
|
||
* if (!result.allowed) {
|
||
* throw badRequest("Missing capabilities", result.missing);
|
||
* }
|
||
* ```
|
||
*/
|
||
export function pluginCapabilityValidator(): PluginCapabilityValidator {
|
||
const log = logger.child({ service: "plugin-capability-validator" });
|
||
|
||
// -----------------------------------------------------------------------
|
||
// Internal helpers
|
||
// -----------------------------------------------------------------------
|
||
|
||
function capabilitySet(manifest: PaperclipPluginManifestV1): Set<PluginCapability> {
|
||
return new Set(manifest.capabilities);
|
||
}
|
||
|
||
function buildForbiddenMessage(
|
||
manifest: PaperclipPluginManifestV1,
|
||
operation: string,
|
||
missing: PluginCapability[],
|
||
): string {
|
||
return (
|
||
`Plugin '${manifest.id}' is not allowed to perform '${operation}'. ` +
|
||
`Missing required capabilities: ${missing.join(", ")}`
|
||
);
|
||
}
|
||
|
||
// -----------------------------------------------------------------------
|
||
// Public API
|
||
// -----------------------------------------------------------------------
|
||
|
||
return {
|
||
hasCapability(manifest, capability) {
|
||
return manifest.capabilities.includes(capability);
|
||
},
|
||
|
||
hasAllCapabilities(manifest, capabilities) {
|
||
const declared = capabilitySet(manifest);
|
||
const missing = capabilities.filter((cap) => !declared.has(cap));
|
||
return {
|
||
allowed: missing.length === 0,
|
||
missing,
|
||
pluginId: manifest.id,
|
||
};
|
||
},
|
||
|
||
hasAnyCapability(manifest, capabilities) {
|
||
const declared = capabilitySet(manifest);
|
||
return capabilities.some((cap) => declared.has(cap));
|
||
},
|
||
|
||
checkOperation(manifest, operation) {
|
||
const required = OPERATION_CAPABILITIES[operation];
|
||
|
||
if (!required) {
|
||
log.warn(
|
||
{ pluginId: manifest.id, operation },
|
||
"capability check for unknown operation – rejecting by default",
|
||
);
|
||
return {
|
||
allowed: false,
|
||
missing: [],
|
||
operation,
|
||
pluginId: manifest.id,
|
||
};
|
||
}
|
||
|
||
const declared = capabilitySet(manifest);
|
||
const missing = required.filter((cap) => !declared.has(cap));
|
||
|
||
if (missing.length > 0) {
|
||
log.debug(
|
||
{ pluginId: manifest.id, operation, missing },
|
||
"capability check failed",
|
||
);
|
||
}
|
||
|
||
return {
|
||
allowed: missing.length === 0,
|
||
missing,
|
||
operation,
|
||
pluginId: manifest.id,
|
||
};
|
||
},
|
||
|
||
assertOperation(manifest, operation) {
|
||
const result = this.checkOperation(manifest, operation);
|
||
if (!result.allowed) {
|
||
const msg = result.missing.length > 0
|
||
? buildForbiddenMessage(manifest, operation, result.missing)
|
||
: `Plugin '${manifest.id}' attempted unknown operation '${operation}'`;
|
||
throw forbidden(msg);
|
||
}
|
||
},
|
||
|
||
assertCapability(manifest, capability) {
|
||
if (!this.hasCapability(manifest, capability)) {
|
||
throw forbidden(
|
||
`Plugin '${manifest.id}' lacks required capability '${capability}'`,
|
||
);
|
||
}
|
||
},
|
||
|
||
checkUiSlot(manifest, slotType) {
|
||
const required = UI_SLOT_CAPABILITIES[slotType];
|
||
if (!required) {
|
||
return {
|
||
allowed: false,
|
||
missing: [],
|
||
operation: `ui.${slotType}.register`,
|
||
pluginId: manifest.id,
|
||
};
|
||
}
|
||
|
||
const has = manifest.capabilities.includes(required);
|
||
return {
|
||
allowed: has,
|
||
missing: has ? [] : [required],
|
||
operation: `ui.${slotType}.register`,
|
||
pluginId: manifest.id,
|
||
};
|
||
},
|
||
|
||
validateManifestCapabilities(manifest) {
|
||
const declared = capabilitySet(manifest);
|
||
const allMissing: PluginCapability[] = [];
|
||
|
||
// Check feature declarations → required capabilities
|
||
for (const [feature, requiredCap] of Object.entries(FEATURE_CAPABILITIES)) {
|
||
const featureValue = manifest[feature as keyof PaperclipPluginManifestV1];
|
||
if (Array.isArray(featureValue) && featureValue.length > 0) {
|
||
if (!declared.has(requiredCap)) {
|
||
allMissing.push(requiredCap);
|
||
}
|
||
}
|
||
}
|
||
|
||
if ((manifest.objectReferences?.length ?? 0) > 0) {
|
||
for (const requiredCap of ["external.objects.detect", "external.objects.read"] as const) {
|
||
if (!declared.has(requiredCap) && !allMissing.includes(requiredCap)) {
|
||
allMissing.push(requiredCap);
|
||
}
|
||
}
|
||
}
|
||
|
||
// Check UI slots → required capabilities
|
||
const uiSlots = manifest.ui?.slots ?? [];
|
||
if (uiSlots.length > 0) {
|
||
for (const slot of uiSlots) {
|
||
const requiredCap = UI_SLOT_CAPABILITIES[slot.type];
|
||
if (requiredCap && !declared.has(requiredCap)) {
|
||
if (!allMissing.includes(requiredCap)) {
|
||
allMissing.push(requiredCap);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// Check launcher declarations → required capabilities
|
||
const launchers = [
|
||
...(manifest.launchers ?? []),
|
||
...(manifest.ui?.launchers ?? []),
|
||
];
|
||
if (launchers.length > 0) {
|
||
for (const launcher of launchers) {
|
||
const requiredCap = LAUNCHER_PLACEMENT_CAPABILITIES[launcher.placementZone];
|
||
if (requiredCap && !declared.has(requiredCap) && !allMissing.includes(requiredCap)) {
|
||
allMissing.push(requiredCap);
|
||
}
|
||
}
|
||
}
|
||
|
||
return {
|
||
allowed: allMissing.length === 0,
|
||
missing: allMissing,
|
||
pluginId: manifest.id,
|
||
};
|
||
},
|
||
|
||
getRequiredCapabilities(operation) {
|
||
return OPERATION_CAPABILITIES[operation] ?? [];
|
||
},
|
||
|
||
getUiSlotCapability(slotType) {
|
||
return UI_SLOT_CAPABILITIES[slotType];
|
||
},
|
||
};
|
||
}
|