import type { PluginCapabilityName } from "./capabilities.js"; import { isPluginCapabilityHostBindingAvailable } from "./capabilities.js"; import { isCapabilityGrantScopeSatisfied, type PluginCapabilityGrant } from "./capability-grants.js"; import { isCapabilityCallWithinScope } from "./capability-scope.js"; import { hashCapabilityPayload } from "./audit.js"; import { manifestDeclaresCapability, type PluginManifest } from "./manifest.js"; /** * Capability gateway — Phase 06 #21 foundation. * * Wraps a record of host functions so that a plugin can only invoke * the ones it declared in its manifest. Calls to undeclared host * functions throw `CapabilityDeniedError`. The gateway also charges a * configurable fuel cost on every successful host-fn invocation, which * is what the sandbox uses to enforce a CPU-budget-by-proxy on plugins * (since V8 has no public hook for per-instruction metering). * * Defaults are deny-by-default: capabilities not in `PLUGIN_CAPABILITY_NAMES` * (the closed enum from `capabilities.ts`) cannot be registered. */ export type CapabilityHostFn = (...args: unknown[]) => unknown | Promise; export type CapabilityHostFnMap = Partial>; export type CapabilityGatewayOptions = { manifest: PluginManifest; hostFns: CapabilityHostFnMap; /** * Tenant-approved grants for this invocation. When provided, the gateway * requires every host-fn call to be both manifest-declared and granted. */ approvedGrants?: ReadonlyArray; /** Charged on every successful host-fn call. Default: 100. */ fuelCostPerCall?: number; /** Called when a denied capability is invoked — for audit logging. */ onDenied?: (info: { capability: PluginCapabilityName; reason: CapabilityDenyReason }) => void; /** * Phase 06 #23 — called after every host-fn call (success / error / * denied). Wire to a `PluginCapabilityUseRecorder` to feed the audit * log. Synchronous and best-effort: errors thrown here are swallowed * so audit-sink trouble never aborts a plugin invocation. */ onCall?: (info: CapabilityCallInfo) => void; }; export type CapabilityCallInfo = { capability: PluginCapabilityName; outcome: "success" | "denied" | "error"; durationMs: number; errorCode?: string; payloadHash?: string; }; export type CapabilityDenyReason = | "not_declared_in_manifest" | "not_granted_for_tenant" | "scope_violation" | "unknown_capability" | "no_host_implementation"; export class CapabilityDeniedError extends Error { override readonly name = "CapabilityDeniedError"; readonly capability: string; readonly reason: CapabilityDenyReason; constructor(capability: string, reason: CapabilityDenyReason) { super(`capability denied: ${capability} (${reason})`); this.capability = capability; this.reason = reason; } } export type CapabilityGateway = { /** Invoke a host-fn through the gateway. Throws on denial. */ invoke(capability: PluginCapabilityName, ...args: unknown[]): Promise; /** * Invoke a synchronous host-fn through the gateway. Intended for WASM * imports that cannot await promises. */ invokeSync(capability: PluginCapabilityName, ...args: unknown[]): T; /** Cumulative fuel cost charged across all calls so far. */ fuelCharged(): number; /** Reset the fuel counter — used between invocations. */ resetFuel(): void; }; const DEFAULT_FUEL_COST = 100; /** * Build a gateway. The gateway is invocation-scoped (one per plugin * call); callers `resetFuel()` between calls when reusing the same * sandbox instance. */ export function createCapabilityGateway(options: CapabilityGatewayOptions): CapabilityGateway { const { manifest, hostFns } = options; const fuelCostPerCall = options.fuelCostPerCall ?? DEFAULT_FUEL_COST; const approvedGrantByName = options.approvedGrants ? new Map(options.approvedGrants.map((grant) => [grant.capabilityName, grant])) : null; let fuel = 0; function notifyCall(info: CapabilityCallInfo): void { if (!options.onCall) return; try { options.onCall(info); } catch { // Audit sink must never abort a plugin invocation. Drop and // continue — the sink's own logger reports the failure. } } return { invoke: async (capability: PluginCapabilityName, ...args: unknown[]): Promise => { const startedAt = Date.now(); if (!manifestDeclaresCapability(manifest, capability)) { options.onDenied?.({ capability, reason: "not_declared_in_manifest" }); notifyCall({ capability, outcome: "denied", durationMs: Date.now() - startedAt, errorCode: "not_declared_in_manifest", }); throw new CapabilityDeniedError(capability, "not_declared_in_manifest"); } const approvedGrant = approvedGrantByName ? getCapabilityApprovedGrantForManifestScope(manifest, approvedGrantByName, capability) : null; if (approvedGrantByName && !approvedGrant) { options.onDenied?.({ capability, reason: "not_granted_for_tenant" }); notifyCall({ capability, outcome: "denied", durationMs: Date.now() - startedAt, errorCode: "not_granted_for_tenant", }); throw new CapabilityDeniedError(capability, "not_granted_for_tenant"); } if (!isPluginCapabilityHostBindingAvailable(capability)) { options.onDenied?.({ capability, reason: "no_host_implementation" }); notifyCall({ capability, outcome: "denied", durationMs: Date.now() - startedAt, errorCode: "no_host_implementation", }); throw new CapabilityDeniedError(capability, "no_host_implementation"); } const fn = hostFns[capability]; if (typeof fn !== "function") { options.onDenied?.({ capability, reason: "no_host_implementation" }); notifyCall({ capability, outcome: "denied", durationMs: Date.now() - startedAt, errorCode: "no_host_implementation", }); throw new CapabilityDeniedError(capability, "no_host_implementation"); } if ( approvedGrant && !isCapabilityCallWithinScope({ capability, callArgs: args, scope: approvedGrant.scopeJson, }) ) { options.onDenied?.({ capability, reason: "scope_violation" }); notifyCall({ capability, outcome: "denied", durationMs: Date.now() - startedAt, errorCode: "scope_violation", payloadHash: hashCapabilityPayload(createCapabilityPayloadDescriptor(capability, args)), }); throw new CapabilityDeniedError(capability, "scope_violation"); } // Always charge fuel before invoking, so a host-fn that throws // still counts against the plugin's budget — matches Wasmtime // semantics where consumed fuel survives a trap. fuel += fuelCostPerCall; try { const result = await fn(...args); notifyCall({ capability, outcome: "success", durationMs: Date.now() - startedAt, payloadHash: hashCapabilityPayload(createCapabilityPayloadDescriptor(capability, args)), }); return result as T; } catch (err) { notifyCall({ capability, outcome: "error", durationMs: Date.now() - startedAt, errorCode: err instanceof Error ? err.name : "unknown", payloadHash: hashCapabilityPayload(createCapabilityPayloadDescriptor(capability, args)), }); throw err; } }, invokeSync: (capability: PluginCapabilityName, ...args: unknown[]): T => { const startedAt = Date.now(); if (!manifestDeclaresCapability(manifest, capability)) { options.onDenied?.({ capability, reason: "not_declared_in_manifest" }); notifyCall({ capability, outcome: "denied", durationMs: Date.now() - startedAt, errorCode: "not_declared_in_manifest", }); throw new CapabilityDeniedError(capability, "not_declared_in_manifest"); } const approvedGrant = approvedGrantByName ? getCapabilityApprovedGrantForManifestScope(manifest, approvedGrantByName, capability) : null; if (approvedGrantByName && !approvedGrant) { options.onDenied?.({ capability, reason: "not_granted_for_tenant" }); notifyCall({ capability, outcome: "denied", durationMs: Date.now() - startedAt, errorCode: "not_granted_for_tenant", }); throw new CapabilityDeniedError(capability, "not_granted_for_tenant"); } if (!isPluginCapabilityHostBindingAvailable(capability)) { options.onDenied?.({ capability, reason: "no_host_implementation" }); notifyCall({ capability, outcome: "denied", durationMs: Date.now() - startedAt, errorCode: "no_host_implementation", }); throw new CapabilityDeniedError(capability, "no_host_implementation"); } const fn = hostFns[capability]; if (typeof fn !== "function") { options.onDenied?.({ capability, reason: "no_host_implementation" }); notifyCall({ capability, outcome: "denied", durationMs: Date.now() - startedAt, errorCode: "no_host_implementation", }); throw new CapabilityDeniedError(capability, "no_host_implementation"); } if ( approvedGrant && !isCapabilityCallWithinScope({ capability, callArgs: args, scope: approvedGrant.scopeJson, }) ) { options.onDenied?.({ capability, reason: "scope_violation" }); notifyCall({ capability, outcome: "denied", durationMs: Date.now() - startedAt, errorCode: "scope_violation", payloadHash: hashCapabilityPayload(createCapabilityPayloadDescriptor(capability, args)), }); throw new CapabilityDeniedError(capability, "scope_violation"); } fuel += fuelCostPerCall; try { const result = fn(...args); if (result && typeof (result as Promise).then === "function") { throw new Error("async_host_fn_not_supported"); } notifyCall({ capability, outcome: "success", durationMs: Date.now() - startedAt, payloadHash: hashCapabilityPayload(createCapabilityPayloadDescriptor(capability, args)), }); return result as T; } catch (err) { notifyCall({ capability, outcome: "error", durationMs: Date.now() - startedAt, errorCode: err instanceof Error ? err.name : "unknown", payloadHash: hashCapabilityPayload(createCapabilityPayloadDescriptor(capability, args)), }); throw err; } }, fuelCharged: () => fuel, resetFuel: () => { fuel = 0; }, }; } function getCapabilityApprovedGrantForManifestScope( manifest: PluginManifest, approvedGrantByName: ReadonlyMap, capability: PluginCapabilityName ): PluginCapabilityGrant | null { const grant = approvedGrantByName.get(capability); const declaredCapability = manifest.capabilities.find((candidate) => candidate.name === capability); return grant && declaredCapability && isCapabilityGrantScopeSatisfied({ declaredScope: declaredCapability.scope ?? null, grantedScopeJson: grant.scopeJson, }) ? grant : null; } function createCapabilityPayloadDescriptor(capability: PluginCapabilityName, args: readonly unknown[]): string { return JSON.stringify({ capability, args: args.map((arg) => describeCapabilityArgument(arg)), }); } function describeCapabilityArgument(arg: unknown): unknown { if (arg === null) return null; if (Array.isArray(arg)) return { type: "array", length: arg.length }; if (typeof arg === "object") { return { type: "object", keys: Object.keys(arg).sort() }; } return { type: typeof arg, value: arg }; }