import type { Identity } from '@astrale-os/sdk/auth' import type { KernelClient } from '@astrale-os/shell' import type { ReactElement, ReactNode } from 'react' import { createContext, useContext, useEffect, useMemo, useState } from 'react' import { ShellContext } from '../session/session.context.js' export type NodeValue = Identity export type SessionView = KernelClient export interface IdentityBinding { readonly kernel: KernelClient readonly self: Identity } export const IdentityContext = createContext(null) IdentityContext.displayName = 'AstraleIdentityContext' export function useIdentityBinding(): IdentityBinding { const override = useContext(IdentityContext) if (override !== null) return override const runtime = useContext(ShellContext) if (runtime === null) throw new Error('identity hooks must be used within a ') if (runtime.self === null) throw new Error('the active Shell has no authenticated identity') return { kernel: runtime.shell.kernel, self: runtime.self } } export interface ActAsProps { /** * A separately authenticated Kernel capability. Raw credentials are deliberately not accepted; * construct the delegated Client Session at the trust boundary that owns credential resolution. */ readonly client: KernelClient readonly fallback?: ReactNode readonly children: ReactNode } /** Bind a subtree to an explicitly supplied authenticated Kernel capability. */ export function ActAs({ client, fallback, children }: ActAsProps): ReactElement | null { const [state, setState] = useState< | { readonly status: 'pending' } | { readonly status: 'ready'; readonly self: Identity } | { readonly status: 'failed'; readonly error: unknown } >({ status: 'pending' }) useEffect(() => { let active = true setState({ status: 'pending' }) void client.auth.whoami().then( (self) => { if (active) setState({ status: 'ready', self }) }, (error: unknown) => { if (active) setState({ status: 'failed', error }) }, ) return () => { active = false } }, [client]) const value = useMemo( () => (state.status === 'ready' ? { kernel: client, self: state.self } : null), [client, state], ) if (state.status === 'failed') throw state.error if (value === null) return fallback === undefined ? null : <>{fallback} return {children} }