import { YonexusError } from '../models/errors'; import type { Action, Actor, Scope } from "../models/types"; import { JsonStore } from "../store/jsonStore"; function hasRole(store: JsonStore, actor: Actor, role: string): boolean { const me = store.findAgent(actor.agentId); return Boolean(me?.roles.includes(role as never)); } function inDeptScope(scope: Scope): boolean { return Boolean(scope.deptId); } function inTeamScope(scope: Scope): boolean { return Boolean(scope.teamId); } export function authorize(action: Action, actor: Actor, scope: Scope, store: JsonStore): void { const orgAdmin = hasRole(store, actor, "org_admin"); const deptAdmin = hasRole(store, actor, "dept_admin") && inDeptScope(scope); const teamLead = hasRole(store, actor, "team_lead") && inTeamScope(scope); const agent = hasRole(store, actor, "agent"); const allowed = (action === "create_organization" && orgAdmin) || (action === "create_department" && orgAdmin) || (action === "create_team" && (orgAdmin || deptAdmin)) || (action === "assign_identity" && (orgAdmin || deptAdmin || teamLead)) || (action === "register_agent" && (orgAdmin || deptAdmin || teamLead)) || (action === "set_supervisor" && (orgAdmin || deptAdmin)) || (action === "query_agents" && (orgAdmin || deptAdmin || teamLead || agent)); if (!allowed) { throw new YonexusError('PERMISSION_DENIED', `permission_denied: ${action}`, { action, actorId: actor.agentId, scope }); } }