UNPKG

@adonis-agora/agent

Version:

Governed, durable-backed AI agent (chat + tool-calling + governance) for AdonisJS — part of the Agora ecosystem.

191 lines • 8.48 kB
import { authorizeByToken as sharedAuthorizeByToken, normalizeConsoleAuthorizeResult as sharedNormalize, } from './dashboard/console_authorize.js'; /** * Normalise any value an authorize hook returned (the shared contract's rules, fail closed: a * malformed `capabilities` allows nothing, a malformed `apps`/`tenants` none), mapped to the agent's * {@link ConsoleAuthorizeDecision}. Anything unrecognised denies (`403`). */ export function normalizeConsoleAuthorizeResult(result) { // `{ allowed: false, redirectTo }` (a denial that names the sign-in page) is a sign-in, as // `{ redirectTo }` alone is: a page navigation is redirected, an API call answered `401`. if (typeof result === 'object' && result !== null) { const { allowed, redirectTo } = result; if (allowed !== true && typeof redirectTo === 'string' && redirectTo !== '') { return { allowed: false, status: 401, redirectTo }; } } const decision = sharedNormalize(result); if (decision.allowed) return decision; if (decision.status === 302) return { allowed: false, status: 401, redirectTo: decision.redirectTo }; if (decision.status === 401) return { allowed: false, status: 401 }; return { allowed: false, status: 403 }; } function isAuthorizerClass(value) { return (typeof value === 'function' && typeof value.prototype?.authorize === 'function'); } function lazyAuthorizerClass(value) { if (typeof value !== 'object' || value === null) return undefined; const candidate = value.default; return isAuthorizerClass(candidate) ? candidate : undefined; } async function instantiate(Authorizer, ctx) { const resolver = ctx .containerResolver; if (resolver !== undefined && typeof resolver.make === 'function') { return (await resolver.make(Authorizer)); } return new Authorizer(); } /** * Turn a console `authorize` (any of the three forms) into one function returning a normalised * decision. A class is built through `ctx.containerResolver` on each request; a lazy import is * imported once and its class remembered. A thrown error is a `403` denial, never an allow. */ export function resolveConsoleAuthorize(authorize) { let lazyClass; return async (ctx, actor, request) => { // Every hook is told what the request intends; a caller that does not say is reading. const intent = request ?? { action: 'read' }; try { if (lazyClass !== undefined) { return normalizeConsoleAuthorizeResult(await (await instantiate(lazyClass, ctx)).authorize(ctx, actor, intent)); } if (isAuthorizerClass(authorize)) { return normalizeConsoleAuthorizeResult(await (await instantiate(authorize, ctx)).authorize(ctx, actor, intent)); } const result = await authorize(ctx, actor, intent); const imported = lazyAuthorizerClass(result); if (imported !== undefined) { lazyClass = imported; return normalizeConsoleAuthorizeResult(await (await instantiate(imported, ctx)).authorize(ctx, actor, intent)); } return normalizeConsoleAuthorizeResult(result); } catch (error) { return { allowed: false, status: 403, error }; } }; } const resolvedByConfig = new WeakMap(); /** * {@link resolveConsoleAuthorize}, memoised per configured value — so a lazy import configured once * in `config/agent.ts` is imported once, however many routes and requests run it. */ export function consoleAuthorizeFor(authorize) { let resolved = resolvedByConfig.get(authorize); if (resolved === undefined) { resolved = resolveConsoleAuthorize(authorize); resolvedByConfig.set(authorize, resolved); } return resolved; } /** * Whether the request is a browser page navigation (it accepts HTML) — the only kind of request a * `{ redirectTo }` decision is answered with a redirect; everything else gets a `401`. */ export function isPageNavigation(ctx) { const header = ctx.request ?.header; if (typeof header !== 'function') return false; const accept = header.call(ctx.request, 'accept') ?? ''; return accept.includes('text/html'); } /** * An `authorize` check for machine access: allows a request whose `Authorization` header is * `Bearer <token>`, and answers `{ allowed: false, reason: 'unauthenticated' }` (`401`) otherwise. * The shared check, with the agent's default: the token reads (`access: 'read'`); pass * `access: 'write'` for one that may also change prices or settle other actors' approvals. * * ```ts * dashboard: { authorize: authorizeByToken({ token: env.get('CONSOLE_TOKEN') }) }, * ``` * * Throws at config time when `token` is empty or undefined, or `access` is not `'read'`/`'write'`. */ export function authorizeByToken(options) { const access = options?.access ?? 'read'; if (access !== 'read' && access !== 'write') { throw new Error("[@adonis-agora/agent] authorizeByToken: `access` must be 'read' or 'write'"); } return sharedAuthorizeByToken({ ...options, access }); } /** * An `authorize` that allows a request when ANY of `authorizers` allows it, tried in order — e.g. a * machine token for MCP clients OR a signed-in admin for the browser: * * ```ts * dashboard: { * authorize: anyAuthorize( * authorizeByToken({ token: env.get('CONSOLE_TOKEN') }), * (ctx) => ctx.auth.user?.isAdmin === true, * ), * }, * ``` * * When none allows: `401` if any of them said "unauthenticated" (redirecting when one asked to), * `403` otherwise. A throwing authorizer counts as a `403` and the next one is still tried. For a * change (`action: 'write'`), an allow limited to reading does not stop the search: a later one * that grants writing wins, and only when none does is the read-only allow returned (so the change * answers `403`). */ export function anyAuthorize(...authorizers) { if (authorizers.length === 0) { throw new Error('[@adonis-agora/agent] anyAuthorize: pass at least one authorize'); } const resolved = authorizers.map((authorize) => resolveConsoleAuthorize(authorize)); return async (ctx, actor, request) => { let unauthenticated = false; let redirectTo; let readOnly; for (const authorize of resolved) { const decision = await authorize(ctx, actor, request); if (decision.allowed) { const { allowed: _allowed, ...grant } = decision; if (decision.access === 'read' && request?.action === 'write') { readOnly ??= { allowed: true, ...grant }; continue; } return { allowed: true, ...grant }; } if (decision.status !== 401) continue; if (decision.redirectTo !== undefined && redirectTo === undefined) { redirectTo = decision.redirectTo; } unauthenticated = true; } if (readOnly !== undefined) return readOnly; if (redirectTo !== undefined) return { redirectTo }; return unauthenticated ? { allowed: false, reason: 'unauthenticated' } : { allowed: false, reason: 'forbidden' }; }; } /** The boot warning logged once when the console has no `authorize`. Same wording in every console. */ export const NO_CONSOLE_AUTHORIZE_WARNING = '[@adonis-agora/agent] console has no `authorize` configured: it is open outside production and denies every request in production. Set `authorize` in config/agent.ts.'; const warnedApps = new WeakSet(); /** * Log {@link NO_CONSOLE_AUTHORIZE_WARNING} once per application, however many providers (the agent's * governance routes, the console shell) find `authorize` missing. */ export function warnNoConsoleAuthorizeOnce(app, warn) { if (warnedApps.has(app)) return; warnedApps.add(app); warn(NO_CONSOLE_AUTHORIZE_WARNING); } /** * Whether the console refuses the request before anything else runs: `authorize` is omitted and the * app is in production. (Omitted outside production, the console is open.) */ export function consoleClosedByDefault(authorize, inProduction) { return authorize === undefined && inProduction; } //# sourceMappingURL=console-authorize.js.map