@adonis-agora/agent
Version:
Governed, durable-backed AI agent (chat + tool-calling + governance) for AdonisJS — part of the Agora ecosystem.
209 lines • 8.74 kB
JavaScript
import { actorFromClaims } from '../mcp/jwt-verifier.js';
/**
* Build the account's {@link BridgedIdentity} from the authkit server in this process: its email,
* profile and global roles (through the app's `resolveTokenRoles` when set). No organization is
* bridged: a token carries no verified active org. `null` when the account no longer exists.
*/
export async function identityForToken(app, token) {
const service = (await app.container.make('authkit.server'));
const config = service?.config;
const now = Date.now();
const base = {
userId: token.accountId,
issuedAt: now,
expiresAt: token.expiresAt !== undefined ? token.expiresAt * 1000 : now + 60_000,
orgId: null,
orgSlug: null,
orgRole: null,
};
if (typeof config?.findAccount !== 'function') {
return { ...base, email: '', globalRoles: [], raw: { sub: token.accountId } };
}
const account = await config.findAccount(token.accountId);
if (!account)
return null;
const globalRoles = config.resolveTokenRoles
? await config.resolveTokenRoles(account, { clientId: token.clientId, activeOrg: null })
: (account.globalRoles ?? []);
const roles = Array.isArray(globalRoles) ? globalRoles.filter((r) => typeof r === 'string') : [];
return {
...base,
email: account.email ?? '',
globalRoles: roles,
profile: {
...(account.name ? { name: account.name } : {}),
...(account.avatarUrl ? { avatarUrl: account.avatarUrl } : {}),
},
raw: {
sub: token.accountId,
...(account.email ? { email: account.email } : {}),
[config.globalRolesClaim ?? 'roles']: roles,
client_id: token.clientId,
scope: token.scopes.join(' '),
},
};
}
/** An authenticator for an app without `@adonis-agora/authkit-client` (no `resolveUser`). */
function identityAuthenticator(identity) {
return {
identity,
resolvesUser: false,
getIdentity: async () => identity,
authenticate: async () => identity,
check: async () => true,
hasGlobalRole: (role) => identity.globalRoles.includes(role),
getUser: async () => null,
getUserOrFail: async () => {
throw new Error('Not authenticated: no user for the current session');
},
toSharedProps: async () => ({ user: null, globalRoles: identity.globalRoles }),
};
}
/**
* Put `identity` on the request the way a browser session would be:
*
* 1. `ctx.authkit` becomes an authkit `Authenticator` resolving to it — built by the app's own
* authkit client (so `resolveUser`, e.g. `lucidMirror`, gives `getUser()` the app's user), or a
* minimal one when the app has no authkit client.
* 2. `authkit.server`'s `bindBearerAccount(ctx, accountId)` (optional, newer authkit-server) records
* the account for `getAccountId(ctx)`, `realAccountId(ctx)` and `impersonationState(ctx)` (not
* impersonating).
* 3. When `ctx.auth`'s default guard is `authkitClientGuard`, it is (re)authenticated from that, so
* `ctx.auth.user` and `ctx.auth.check()` see the account too — even after a silent-auth middleware
* already found no browser session on this request.
*
* Best effort past step 1: a guard that fails leaves `ctx.auth` as it was.
*/
export async function bridgeIdentity(app, ctx, identity) {
await bindBearerAccount(app, ctx, identity.userId);
await bindIdentity(ctx, identity, app);
}
let authkitClient;
/** `@adonis-agora/authkit-client`, when the app has it (with the identity bridge); else `null`. */
export function loadAuthkitClient() {
authkitClient ??= import('@adonis-agora/authkit-client').then((mod) => {
const candidate = mod;
return typeof candidate.bindAuthkitIdentity === 'function' &&
typeof candidate.identityFromClaims === 'function' &&
typeof candidate.Authenticator === 'function'
? candidate
: null;
}, () => null);
return authkitClient;
}
/**
* `ctx.authkit` (and an `authkitClientGuard` `ctx.auth`) for `identity`: authkit-client's
* `bindAuthkitIdentity` when installed, else the structural fallback below.
*/
async function bindIdentity(ctx, identity, app) {
const client = await loadAuthkitClient();
if (client !== null) {
await client.bindAuthkitIdentity(ctx, identity);
return;
}
let authenticator;
if (app?.container.hasBinding('authkit.client')) {
try {
const manager = (await app.container.make('authkit.client'));
authenticator = await manager.createAuthenticator(ctx, {
resolver: { resolver: async () => ({ resolve: async () => identity }) },
});
}
catch {
authenticator = undefined;
}
}
ctx.authkit =
authenticator ?? identityAuthenticator(identity);
const auth = ctx.auth;
if (auth === undefined || typeof auth.use !== 'function')
return;
try {
const guard = auth.use();
if (guard?.driverName !== 'authkit_client' || guard.isAuthenticated === true)
return;
// A silent-auth middleware may already have tried (and found no browser session).
guard.authenticationAttempted = false;
await auth.check();
}
catch {
// leave ctx.auth alone
}
}
/**
* Put the claims of a JWT access token verified remotely (`jwtAuth`, `oidcAuth`) on the request as
* an authkit identity, the way authkit-client's `bridgeAuthkitToken` does, without verifying it a
* second time. A `client_credentials` token (`sub` = `client_id`) has no user and is not bridged.
*
* A token without an `email` claim (authkit's access tokens carry none today) is bound to
* `ctx.authkit` only: the app's `resolveUser` (e.g. `lucidMirror`, which syncs the email) is not run
* and `ctx.auth` is left alone, so a mirrored user is never overwritten with an empty email.
* Returns whether an identity was bound.
*/
export async function bridgeAuthkitClaims(ctx, claims, options = {}) {
if (ctx === undefined || options.mode === false)
return false;
const sub = claims.sub;
if (typeof sub !== 'string' || sub === '')
return false;
if (typeof claims.client_id === 'string' && claims.client_id === sub)
return false;
const client = await loadAuthkitClient();
if (client === null && options.mode !== true)
return false;
const rolesClaim = options.globalRolesClaim ?? 'roles';
const identity = client !== null
? client.identityFromClaims(claims, rolesClaim)
: localIdentity(claims, rolesClaim);
if (identity.email === '') {
ctx.authkit =
client !== null
? new client.Authenticator(ctx, { resolver: { resolve: async () => identity } })
: identityAuthenticator(identity);
return true;
}
await bindIdentity(ctx, identity);
return true;
}
/** `identityFromClaims` for an app without authkit-client (`authkit: true` forced). */
function localIdentity(claims, rolesClaim) {
const roles = claims[rolesClaim];
const text = (key) => (typeof claims[key] === 'string' ? claims[key] : null);
const actor = actorFromClaims(claims);
return {
userId: String(claims.sub),
email: text('email') ?? '',
globalRoles: Array.isArray(roles)
? roles.filter((r) => typeof r === 'string')
: [],
profile: {
...(text('name') !== null ? { name: text('name') } : {}),
...(text('picture') !== null ? { avatarUrl: text('picture') } : {}),
},
...(text('sid') !== null ? { sessionId: text('sid') } : {}),
orgId: text('org_id') ??
text('active_organization_id') ??
text('organization_id') ??
text('tenant_id') ??
text('tid'),
orgSlug: text('org_slug'),
orgRole: text('org_role'),
...(actor !== undefined ? { actor } : {}),
issuedAt: typeof claims.iat === 'number' ? claims.iat * 1000 : 0,
expiresAt: typeof claims.exp === 'number' ? claims.exp * 1000 : 0,
raw: claims,
};
}
async function bindBearerAccount(app, ctx, accountId) {
if (!app.container.hasBinding('authkit.server'))
return;
try {
const service = (await app.container.make('authkit.server'));
if (typeof service?.bindBearerAccount === 'function')
service.bindBearerAccount(ctx, accountId);
}
catch {
// an authkit server that cannot be built binds nothing
}
}
//# sourceMappingURL=authkit-bridge.js.map