@adonis-agora/agent
Version:
Governed, durable-backed AI agent (chat + tool-calling + governance) for AdonisJS — part of the Agora ecosystem.
213 lines • 9.82 kB
JavaScript
import { McpAuthError } from '../mcp/auth.js';
import { absoluteUrl, actorFromClaims, createJwtVerifier, rolesFrom, sameIssuer, scopesFrom, } from '../mcp/jwt-verifier.js';
import { bridgeAuthkitClaims } from './authkit-bridge.js';
export { actorFromClaims, discoverJwksUri, issuerMetadataUrls } from '../mcp/jwt-verifier.js';
const principals = new WeakMap();
/**
* The principal `devTools.auth` verified for this request, or `undefined` (no token, a token the
* hub's auth did not recognize, or not a dev tools request). Read it in an `authorize`:
*
* ```ts
* authorize: (ctx) => devToolsPrincipal(ctx)?.roles?.includes('admin') === true
* ```
*/
export function devToolsPrincipal(ctx) {
return principals.get(ctx);
}
/**
* Put the principal on the request: {@link devToolsPrincipal}, and with a `user`, `ctx.auth` answers
* for it (`user`, `check()`, `authenticate()`, `checkUsing()`…) the way a guard that signed it in
* would, so `authorizeByRoles(…)` and `(ctx) => ctx.auth.user?.isAdmin` work unchanged.
*/
export function bindDevToolsPrincipal(ctx, principal) {
principals.set(ctx, principal);
if (principal.user === undefined || principal.user === null)
return;
const user = principal.user;
const holder = ctx;
const original = holder.auth;
const overrides = {
user,
isAuthenticated: true,
authenticationAttempted: true,
check: async () => true,
checkUsing: async () => true,
authenticate: async () => user,
authenticateUsing: async () => user,
getUserOrFail: () => user,
};
if (original === undefined || original === null) {
holder.auth = { ...overrides, use: () => overrides };
return;
}
holder.auth = new Proxy(original, {
get(target, key) {
if (typeof key === 'string' && Object.hasOwn(overrides, key))
return overrides[key];
// `target` as `this`: @adonisjs/auth's Authenticator keeps its state in private fields.
const value = Reflect.get(target, key);
return typeof value === 'function' ? value.bind(target) : value;
},
});
}
async function principalOf(claims, options, context) {
const subject = claims.sub;
if (typeof subject !== 'string' || subject === '') {
throw new McpAuthError('invalid_token: the token has no subject');
}
const scopes = scopesFrom(claims);
const missing = (options.requiredScopes ?? []).filter((s) => !scopes.includes(s));
if (missing.length > 0) {
throw new McpAuthError(`insufficient_scope: the dev tools need the scope "${missing.join(' ')}"`, {
status: 403,
});
}
const roles = rolesFrom(claims[options.rolesClaim ?? 'roles']);
const actor = actorFromClaims(claims);
const principal = {
subject,
claims,
scopes,
...(roles !== undefined ? { roles } : {}),
...(actor !== undefined ? { actor } : {}),
};
if (options.resolveUser !== undefined) {
const user = await options.resolveUser(claims, context);
if (user === null || user === undefined) {
throw new McpAuthError('invalid_token: the account no longer exists');
}
principal.user = user;
}
return principal;
}
function audiencesOf(audience, context) {
if (audience === undefined)
return [context.resource];
return Array.isArray(audience) ? audience : [audience];
}
/**
* Verify JWT access tokens of an OAuth / OIDC authorization server (authkit with JWT access tokens,
* Sésame with `accessTokenFormat: 'jwt'`, Auth0, Keycloak, Entra ID…) against its JWKS: signature,
* `iss`, `aud` (the hub's URL by default) and `exp`/`nbf`. The JWKS URL is discovered from the
* issuer's metadata on first use and its keys are cached (refetched when a token names an unknown key).
*
* A token with another `iss`, or that is not a JWT, is not this auth's: it is left on the request
* for an `authorizeByToken` console.
*
* With `@adonis-agora/authkit-client` installed (or `authkit: true`), a verified user token is also
* put on the request as an authkit identity (`ctx.authkit`, and `ctx.auth` with `authkitClientGuard`),
* so a console gated by `authkitDashboardAuthorize` accepts the caller.
*/
export function jwtAuth(options) {
absoluteUrl(options.issuer, 'jwtAuth `issuer`');
if (options.jwksUri !== undefined)
absoluteUrl(options.jwksUri, 'jwtAuth `jwksUri`');
const verifyJwt = createJwtVerifier(options);
return {
authorizationServers: [options.issuer],
...(options.scopes !== undefined ? { scopes: options.scopes } : {}),
...(options.resourceName !== undefined ? { resourceName: options.resourceName } : {}),
async verify(token, context) {
const payload = await verifyJwt(token, audiencesOf(options.audience, context));
if (payload === null)
return null;
const principal = await principalOf(payload, options, context);
await bridgeAuthkitClaims(context.ctx, payload, {
mode: options.authkit,
globalRolesClaim: options.rolesClaim,
});
return principal;
},
};
}
/**
* Verify opaque access tokens with the authorization server's introspection endpoint (RFC 7662):
* one `POST` per request. `active: false` → `401`; an `aud` that does not name the hub, or none
* (unless `requireAudience: false`) → `401`. An unreachable endpoint → `503`.
*/
export function introspectionAuth(options) {
absoluteUrl(options.issuer, 'introspectionAuth `issuer`');
absoluteUrl(options.endpoint, 'introspectionAuth `endpoint`');
// RFC 6749 §2.3.1 (client_secret_basic): id and secret are form-urlencoded, then joined by `:`
// and base64-encoded — so a `:` in the id cannot split it.
const formEncode = (value) => new URLSearchParams({ v: value }).toString().slice(2);
const basic = Buffer.from(`${formEncode(options.clientId)}:${formEncode(options.clientSecret)}`).toString('base64');
return {
authorizationServers: [options.issuer],
...(options.scopes !== undefined ? { scopes: options.scopes } : {}),
...(options.resourceName !== undefined ? { resourceName: options.resourceName } : {}),
async verify(token, context) {
const response = await fetch(options.endpoint, {
method: 'POST',
headers: {
authorization: `Basic ${basic}`,
'content-type': 'application/x-www-form-urlencoded',
accept: 'application/json',
},
body: new URLSearchParams({ token, token_type_hint: 'access_token' }).toString(),
signal: AbortSignal.timeout(5000),
});
if (!response.ok) {
throw new Error(`[@adonis-agora/agent] token introspection at ${options.endpoint} answered ${response.status}`);
}
const claims = (await response.json());
if (claims.active !== true)
throw new McpAuthError('invalid_token: the token is not active');
if (typeof claims.iss === 'string' && !sameIssuer(claims.iss, options.issuer)) {
throw new McpAuthError('invalid_token: the token was issued by another server');
}
if (typeof claims.exp === 'number' && claims.exp * 1000 < Date.now()) {
throw new McpAuthError('invalid_token: the token expired');
}
const aud = claims.aud;
if (aud === undefined && options.requireAudience !== false) {
throw new McpAuthError('invalid_token: the token names no audience (resource)');
}
if (aud !== undefined) {
const given = Array.isArray(aud) ? aud : [aud];
const accepted = audiencesOf(options.audience, context);
if (!given.some((a) => typeof a === 'string' && accepted.includes(a))) {
throw new McpAuthError('invalid_token: the token was not issued for this resource');
}
}
return principalOf(claims, options, context);
},
};
}
// ── validation (provider + doctor) ──────────────────────────────────────────
/** What is wrong with a `devTools.auth` value, read structurally. Empty → usable. */
export function devToolsAuthProblems(auth) {
const errors = [];
const warnings = [];
if (typeof auth !== 'object' || auth === null) {
return {
errors: ['`devTools.auth` must be an object (e.g. `jwtAuth({ issuer })`).'],
warnings,
};
}
const value = auth;
if (typeof value.verify !== 'function') {
errors.push('`devTools.auth.verify` is missing: no token can be verified.');
}
const servers = value.authorizationServers;
if (!Array.isArray(servers) || servers.length === 0) {
warnings.push('`devTools.auth.authorizationServers` is empty: MCP clients cannot discover where to sign in.');
}
else {
for (const server of servers) {
try {
absoluteUrl(String(server), '');
}
catch {
errors.push(`\`devTools.auth.authorizationServers\` has ${JSON.stringify(server)}, not an absolute http(s) URL.`);
}
}
}
return { errors, warnings };
}
/** The issuers of a `devTools.auth`, for messages. */
export function devToolsAuthIssuers(auth) {
const servers = auth?.authorizationServers;
return Array.isArray(servers) ? servers.map(String) : [];
}
//# sourceMappingURL=auth.js.map