Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/packages/plugin-runtime/src/capability-grants.ts
T

80 lines
2.9 KiB
TypeScript

import type { PluginCapabilityName } from "./capabilities.js";
import type { PluginCapability, PluginManifest } from "./manifest.js";
export type PluginCapabilityGrant = {
capabilityName: string;
scopeJson: unknown;
};
type CapabilityScope = NonNullable<PluginCapability["scope"]>;
const CAPABILITY_SCOPE_KEYS = new Set(["allowedHosts", "keyPattern", "tablePrefix"]);
function normalizeCapabilityScope(scope: unknown): Partial<CapabilityScope> | null {
if (scope === null || scope === undefined) return null;
if (typeof scope !== "object" || Array.isArray(scope)) return null;
return scope as Partial<CapabilityScope>;
}
function hasScopeValue(scope: Partial<CapabilityScope> | 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<PluginCapabilityGrant>;
}): 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);
}