@haneinfo/iam-keycloak
v0.3.5
Published
Keycloak backend IAM profile implementing @haneinfo/plugin-api IamProfilePort.
Readme
@haneinfo/iam-keycloak
Keycloak 26.8.2 backend IamProfilePort implementation for @haneinfo/plugin-api.
Usage
import { createKeycloakIamProfile } from '@haneinfo/iam-keycloak';
import { validateTokenTimestamps } from '@haneinfo/plugin-api';
const profile = createKeycloakIamProfile({
deployment,
// Optional: custom fetch or discovery timeout (default: globalThis.fetch, 5000ms)
});
const metadata = await profile.getTrustedMetadata();
const claims = profile.normalizeClaims('web', rawPayload, rawHeader);
// Time window checks (iat / exp bounds and clock tolerance) are NOT performed by
// normalizeClaims; consumers must run validateTokenTimestamps from @haneinfo/plugin-api.
const timeResult = validateTokenTimestamps({
iat: claims.issuedAt,
exp: claims.expiresAt,
nowSeconds: Math.floor(Date.now() / 1000),
});Error Handling
normalizeClaims throws when a token header or payload violates the Keycloak IAM contract. Consumers must not depend on KeycloakClaimsRejectedError or inspect its reason field for control flow; treat any thrown error from normalizeClaims as invalid_token.
Runtime Constraints
- Pure Node.js (
>=22.0.0), CommonJS. - Runtime dependencies are restricted to
@haneinfo/plugin-apiand Node built-ins (globalThis.fetch,AbortSignal.timeout). - Never reads or forwards IAM role/group claims (
realm_access,resource_access,groups).
Token Exchange (KeycloakTokenExchangeProvider)
@haneinfo/iam-keycloak also exports KeycloakTokenExchangeProvider and KeycloakTokenExchangeProviderConfig from the root entry point, implementing @haneinfo/plugin-api's TokenExchangeProvider (IAM_TOKEN_EXCHANGE).
- No plugin registration yet:
@haneinfo/iam-keycloak/pluginintentionally does not providehaneinfo.iam-token-exchange. Cross-app delegation (O3) is disabled by default and will only be integrated in a pilot app after O3 conformance is accepted.
Web Profile (@haneinfo/iam-keycloak/web)
@haneinfo/iam-keycloak/web is a server-only entry point exporting createKeycloakWebProfile(options?), which implements @haneinfo/plugin-api's IamWebProfile for @haneinfo/frontend-auth:
import { createFrontendAuth } from '@haneinfo/frontend-auth/server';
import { createKeycloakWebProfile } from '@haneinfo/iam-keycloak/web';
export const auth = createFrontendAuth({
webProfile: createKeycloakWebProfile(),
iam: {
issuer: process.env.IAM_ISSUER!,
clientId: process.env.IAM_WEB_CLIENT_ID!,
clientSecret: process.env.IAM_WEB_CLIENT_SECRET!,
},
});- Uses
profileId: 'keycloak'and fixedcallbackId: 'iam'(/api/auth/callback/iam). - Defaults
scopesto'openid profile email'and enables['pkce', 'state']checks. - Resolves
token_endpointandend_session_endpointfrom${issuer}/.well-known/openid-configurationwith verbatimissuerverification and without caching failed discovery responses. - Does not import NestJS or
zodat runtime.
Provisioner (@haneinfo/iam-keycloak/provisioner)
createKeycloakIamProvisioner(options?) implements @haneinfo/plugin-api's IamProvisioner (plan, apply with dryRun, drift) for an existing Keycloak 26.8.2 realm, using a service-account client with the realm-management roles manage-clients, manage-realm, view-clients and view-realm plus the kc-admin-api client scope. The full rules are in the haneinfo-packages specs, iam-contract section 8.1.
It manages:
Per app: one client scope per manifest scope (with a single-resource audience mapper, plus
auth_time,amrandacrmappers on admin scopes), realm default optional client scopes, and the confidential Web client (never its secret).MCP connector objects (tagged
haneinfo.managed-by=haneinfo-mcp):- the
haneinfo-mcp-employeeandhaneinfo-mcp-adminbrowser flows (the admin flow requires OTP) - the
haneinfo-cimdclient profile and policy: CIMD metadata executor with the resource allow list, plus PKCE S256 - the employee and admin flow-selection policies
- the trusted CIMD clients derived from the HTTPS entries in the manifests'
allowedClientIds
Each trusted CIMD client is pre-registered with a real authorization request, using the first
redirect_urisentry of its metadata document. The provisioner then setsminimum.acr.value=1, reduces the default scopes tobasicandacr, attaches the resource scopes plusoffline_access, and createscimd-resource-indicator-*mappers with token claims disabled.- the
Rules:
- Shared lists change only for the apps in the input. An app is removed only when listed in
removedAppIds. - Same-name objects without the managed marker are conflicts:
plan()reports them, andapply()fails before any write. plan()andapply({ dryRun: true })send only Admin RESTGETrequests. They never send the registration request.- The machine running the provisioner must reach the trusted clients' metadata hosts (for Claude,
claude.ai). - It never changes the realm
browserFlow, existing Web client flow overrides, the built-inoffline_accessscope, accounts or realm session settings. - Run
apply()serially per realm: Keycloak replaces/client-policies/profilesand/client-policies/policiesas whole documents. Althoughapply()re-reads and re-merges against the latest realm document up to 3 attempts before each whole-documentPUT, callers/CI jobs targeting the same realm must serializeapply()runs.
pnpm test:keycloak runs the disposable-Keycloak acceptance (Docker, outbound HTTPS to claude.ai; set HANEINFO_DEV_REALM_JSON when the dev-infra realm JSON is not at ../dev-infra/keycloak/haneinfo-dev-realm.json).
