@adonis-agora/agent
Version:
Governed, durable-backed AI agent (chat + tool-calling + governance) for AdonisJS — part of the Agora ecosystem.
131 lines • 5.54 kB
JavaScript
import { createHash, timingSafeEqual } from 'node:crypto';
import { resolveAuthorizeResult } from './authorize-decision.js';
/** Normalise any value an authorize hook returned. Anything unrecognised denies (`403`). */
export function normalizeConsoleAuthorizeResult(result) {
if (typeof result === 'object' && result !== null) {
const redirectTo = result.redirectTo;
if (result.allowed !== true && typeof redirectTo === 'string') {
return { allowed: false, status: 401, redirectTo };
}
}
return resolveAuthorizeResult(result);
}
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) => {
try {
if (lazyClass !== undefined) {
return normalizeConsoleAuthorizeResult(await (await instantiate(lazyClass, ctx)).authorize(ctx, actor));
}
if (isAuthorizerClass(authorize)) {
return normalizeConsoleAuthorizeResult(await (await instantiate(authorize, ctx)).authorize(ctx, actor));
}
const result = await authorize(ctx, actor);
const imported = lazyAuthorizerClass(result);
if (imported !== undefined) {
lazyClass = imported;
return normalizeConsoleAuthorizeResult(await (await instantiate(imported, ctx)).authorize(ctx, actor));
}
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');
}
function digest(value) {
return createHash('sha256').update(value).digest();
}
/**
* An `authorize` check for machine access: allows a request whose `Authorization` header is
* `Bearer <token>`, and answers `{ allowed: false, reason: 'unauthenticated' }` (`401`) otherwise.
*
* ```ts
* dashboard: { authorize: authorizeByToken({ token: env.get('CONSOLE_TOKEN') }) },
* ```
*
* Throws at config time when `token` is empty or undefined.
*/
export function authorizeByToken(options) {
const token = options?.token;
if (typeof token !== 'string' || token === '') {
throw new Error('authorizeByToken: `token` must be a non-empty string');
}
const expected = digest(token);
return (ctx) => {
const header = ctx.request.header('authorization');
const match = typeof header === 'string' ? /^Bearer\s+(.+)$/i.exec(header.trim()) : null;
if (match?.[1] && timingSafeEqual(digest(match[1]), expected))
return { allowed: true };
return { allowed: false, reason: 'unauthenticated' };
};
}
/** 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