@adonis-agora/agent
Version:
Governed, durable-backed AI agent (chat + tool-calling + governance) for AdonisJS — part of the Agora ecosystem.
101 lines • 4.82 kB
JavaScript
import { scopeRole } from '../a2a/gate.js';
import { PERSONAL_AGENT_ROLE } from '../a2a/permission-tool.js';
import { bridgeAuthkitClaims } from '../dev-tools/authkit-bridge.js';
import { McpAuthError, POPPY_GRANT_TYPE } from './auth.js';
import { absoluteUrl, actorFromClaims, createJwtVerifier, rolesFrom, scopesFrom, } from './jwt-verifier.js';
/**
* Authenticate MCP clients with JWT access tokens of a remote OAuth / OIDC authorization server
* (authkit-server on another host, or any issuer with a JWKS). Nothing of the authorization server
* runs in this process: the token's signature is checked against the issuer's JWKS (found by
* discovery, keys cached), then `iss`, `aud` (the endpoint's URL by default) and `exp`.
*
* The endpoint advertises the issuer in its RFC 9728 metadata and answers a refused request with
* `WWW-Authenticate: Bearer resource_metadata=…`, so an MCP client opens the login. With authkit, list
* the endpoint's URL in authkit-server's `mcpClients.resources` so it issues tokens for it.
*
* A token that is not a JWT of this issuer is "not mine" (a plain `Error`): inside {@link anyOf} the
* next strategy gets it. A token it recognizes and refuses throws {@link McpAuthError}.
*/
export function oidcAuth(options) {
absoluteUrl(options.issuer, 'oidcAuth `issuer`');
if (options.jwksUri !== undefined)
absoluteUrl(options.jwksUri, 'oidcAuth `jwksUri`');
const scopes = options.scopes ?? ['openid', 'profile', 'email', 'offline_access', 'roles'];
const rolesClaim = options.rolesClaim ?? 'roles';
const toActor = options.toActor ??
(({ subject, roles }) => ({ id: subject, ...(roles !== undefined ? { roles } : {}) }));
const verifyJwt = createJwtVerifier(options);
return async () => ({
oauth: {
issuer: options.issuer,
scopesSupported: scopes,
resourceName: options.resourceName ?? 'Agent MCP Server',
},
async verify(token, context) {
const audiences = options.resource !== undefined
? Array.isArray(options.resource)
? options.resource
: [options.resource]
: context !== undefined
? [context.resource]
: [];
if (audiences.length === 0) {
throw new McpAuthError('invalid_token: no resource to check the token audience against');
}
const claims = await verifyJwt(token, audiences);
if (claims === null) {
// Not a JWT of this issuer: plain `Error`, so `anyOf` tries the next strategy.
throw new Error(`not an access token of ${options.issuer}`);
}
const subject = claims.sub;
const tokenScopes = scopesFrom(claims);
const missing = (options.requiredScopes ?? []).filter((s) => !tokenScopes.includes(s));
if (missing.length > 0) {
throw new McpAuthError(`insufficient_scope: this endpoint needs "${missing.join(' ')}"`, {
status: 403,
});
}
const clientId = typeof claims.client_id === 'string'
? claims.client_id
: typeof claims.azp === 'string'
? claims.azp
: undefined;
const actor = actorFromClaims(claims);
const personalAgent = claims.gty === POPPY_GRANT_TYPE;
const resolved = await toActor({
subject,
claims,
scopes: tokenScopes,
roles: rolesFrom(claims[rolesClaim]),
clientId,
actor,
personalAgent,
});
// As `authKitAuth`: a personal agent reaches only the tools of the scopes its user granted.
const acting = personalAgent
? {
...resolved,
roles: [
...new Set([
...(resolved.roles ?? []),
PERSONAL_AGENT_ROLE,
...tokenScopes.map(scopeRole),
]),
],
}
: resolved;
await bridgeAuthkitClaims(context?.ctx, claims, {
mode: options.authkit,
globalRolesClaim: rolesClaim,
});
return {
token,
clientId: clientId ?? '',
scopes: tokenScopes,
...(typeof claims.exp === 'number' ? { expiresAt: claims.exp } : {}),
extra: { actor: acting, claims, ...(actor !== undefined ? { act: actor } : {}) },
};
},
});
}
//# sourceMappingURL=oidc-auth.js.map