import type { PluginCapabilityName } from "./capabilities.js"; import type { PluginCapability, PluginManifest } from "./manifest.js"; export type PluginCapabilityGrant = { capabilityName: string; scopeJson: unknown; }; type CapabilityScope = NonNullable; const CAPABILITY_SCOPE_KEYS = new Set(["allowedHosts", "keyPattern", "tablePrefix"]); function normalizeCapabilityScope(scope: unknown): Partial | null { if (scope === null || scope === undefined) return null; if (typeof scope !== "object" || Array.isArray(scope)) return null; return scope as Partial; } function hasScopeValue(scope: Partial | null): boolean { if (!scope) return false; return Boolean((Array.isArray(scope.allowedHosts) && scope.allowedHosts.length > 0) || scope.keyPattern || scope.tablePrefix); } export function isCapabilityGrantScopeSatisfied(args: { declaredScope: PluginCapability["scope"] | null | undefined; grantedScopeJson: unknown; }): boolean { const declaredScope = normalizeCapabilityScope(args.declaredScope); const grantedScope = normalizeCapabilityScope(args.grantedScopeJson); if (args.grantedScopeJson !== null && args.grantedScopeJson !== undefined && !grantedScope) return false; const grantedKeys = grantedScope ? Object.keys(grantedScope) : []; if (grantedKeys.some((key) => !CAPABILITY_SCOPE_KEYS.has(key))) return false; if (!hasScopeValue(declaredScope)) { return grantedKeys.length === 0; } if (!grantedScope) return false; if (declaredScope?.allowedHosts?.length) { if (!Array.isArray(grantedScope.allowedHosts) || grantedScope.allowedHosts.length === 0) return false; const declaredHosts = new Set(declaredScope.allowedHosts); if (grantedScope.allowedHosts.some((host) => !declaredHosts.has(host))) return false; } else if (grantedScope.allowedHosts?.length) { return false; } if (declaredScope?.keyPattern) { if (grantedScope.keyPattern !== declaredScope.keyPattern) return false; } else if (grantedScope.keyPattern) { return false; } if (declaredScope?.tablePrefix) { if (grantedScope.tablePrefix !== declaredScope.tablePrefix) return false; } else if (grantedScope.tablePrefix) { return false; } return true; } export function getMissingCapabilityGrantNames(args: { manifest: PluginManifest; grants: ReadonlyArray; }): PluginCapabilityName[] { const grantByCapability = new Map(args.grants.map((grant) => [grant.capabilityName, grant])); return (args.manifest.capabilities ?? []) .filter((capability) => { const grant = grantByCapability.get(capability.name); return ( !grant || !isCapabilityGrantScopeSatisfied({ declaredScope: capability.scope ?? null, grantedScopeJson: grant.scopeJson, }) ); }) .map((capability) => capability.name); }