import type { NodeId } from '@astrale-os/sdk/graph/node' import type { PathLike } from '@astrale-os/sdk/graph/path' import type { PolicyRef } from '@astrale-os/sdk/schema' import { Path } from '@astrale-os/sdk/graph/path' import { useEffect, useState } from 'react' import { useIdentityBinding } from './act-as.context.js' export type PolicyObject = NodeId | { readonly id: NodeId } /** * Evaluate one declared Kernel policy for one exact graph object. This is a UI affordance; the * invoked callable remains the authorization enforcement point. */ export function useCan( policy: PathLike | PolicyRef | null | undefined, object: PolicyObject | null | undefined, ): boolean | undefined { const { kernel } = useIdentityBinding() const objectId = objectIdOf(object) const policyTarget = policyPath(policy) const [decision, setDecision] = useState(undefined) useEffect(() => { if (policyTarget === null || objectId === null) { setDecision(undefined) return } let active = true setDecision(undefined) void kernel.auth.can({ policy: policyTarget, object: objectId }).then( (allowed) => { if (active) setDecision(allowed) }, () => { if (active) setDecision(undefined) }, ) return () => { active = false } }, [kernel, policyTarget, objectId]) return decision } function policyPath(policy: PathLike | PolicyRef | null | undefined) { if (policy === null || policy === undefined) return null return policy instanceof Path || typeof policy === 'string' ? Path.from(policy).raw : Path.project(policy).raw } function objectIdOf(value: PolicyObject | null | undefined): NodeId | null { if (value === null || value === undefined) return null return typeof value === 'object' ? value.id : value }