@egose/keycloak-fluent
v0.14.0
Published
Fluent TypeScript wrapper for the Keycloak Admin API with idempotent provisioning for realms, users, clients, flows, organizations, and admin operations.
Maintainers
Readme
Keycloak Fluent
What It Is
@egose/keycloak-fluent builds on top of @keycloak/keycloak-admin-client and turns low-level admin calls into a fluent, chainable API for Keycloak provisioning and operations.
Instead of stitching together ids, searches, and update payloads everywhere, you work through handles such as:
kc.realm('demo')realm.user('alice')realm.client('app')realm.authenticationFlow('browser-copy')realm.organization('acme')realm.cache()kc.serverInfo()
The library stays close to Keycloak rather than inventing a separate abstraction model. You keep the official admin client underneath, but get a much better working surface for repeatable automation.
Why Use It
- Write provisioning code that reads like intent instead of request plumbing.
- Use
ensure(...)anddiscard()for idempotent setup and cleanup flows. - Traverse Keycloak resources from a realm through dedicated resource handles.
- Cover more than CRUD: authentication flows, organizations, workflows, cache, attack detection, user storage sync, client policies,
serverInfo, andwhoAmIare supported too. - Keep access to the official admin client through
kc.core.
Why Not Just Use @keycloak/keycloak-admin-client?
You still can, and this package intentionally keeps that option open.
Use the raw admin client when you want direct access to every endpoint with no extra abstraction.
Use @egose/keycloak-fluent when you want:
- idempotent provisioning with
ensure(...)anddiscard() - resource-scoped handles instead of passing ids and lookup results around manually
- readable scripts for realms, users, clients, flows, and organizations
- a cleaner working surface for operational tasks like cache clearing, attack detection, and server inspection
In practice, this library is best seen as a better orchestration layer on top of the official Keycloak client, not a replacement for it.
Supported Keycloak Versions
This package currently depends on @keycloak/keycloak-admin-client@^26.5.7.
Tested matrix in this repository:
- Node.js
>=20is required - package dependency range:
@keycloak/keycloak-admin-client@^26.5.7 - packed consumer minimum-upstream check:
@keycloak/[email protected] - lockfile-resolved admin client used by local/CI checks:
@keycloak/[email protected] - local integration sandbox server: Keycloak
26.6.1
The supported policy is Keycloak Admin Client 26.x from 26.5.7 upward, verified at the declared minimum and at the current lockfile-resolved version. If you target an older or significantly newer Keycloak release, verify the specific endpoints you depend on, especially for newer areas such as organizations, workflows, and authentication-flow administration.
Public API Shape
The supported package shape is root-only. Import runtime helpers, catchable errors, and public TypeScript types from @egose/keycloak-fluent; implementation subpaths are not supported public entry points.
import KeycloakAdminClientFluent, {
AuthenticationFlowNotFoundError,
DuplicateWorkflowNameError,
UserPasswordProvisioningError,
WorkflowNotFoundError,
createManagedKeycloakClient,
} from '@egose/keycloak-fluent';
import type { RealmHandle, UserHandle, UserInputData } from '@egose/keycloak-fluent';Installation
Requirements:
- Node.js
>=20 - A reachable Keycloak server
- Credentials for the Keycloak Admin API
npm install @egose/keycloak-fluentQuick Start
import KeycloakAdminClientFluent from '@egose/keycloak-fluent';
const kc = new KeycloakAdminClientFluent({
baseUrl: 'http://localhost:8080',
realmName: 'master',
});
await kc.simpleAuth({
username: 'admin',
password: 'admin', // pragma: allowlist secret
clientId: 'admin-cli',
});
const realm = await kc.realm('demo').ensure({
displayName: 'Demo Realm',
});
const user = await realm.user('alice').ensure({
email: '[email protected]',
enabled: true,
});
const group = await realm.group('developers').ensure({
description: 'Application developers',
});
await user.assignGroup(group);Authentication
simpleAuth(...)
simpleAuth(...) picks the grant type for you:
passwordgrant whenpasswordis providedrefresh_tokengrant whenrefreshTokenis providedclient_credentialsgrant otherwiseusernameandpasswordmust be provided togetherpasswordandrefreshTokenare mutually exclusive- Supplied
username,password,refreshToken,clientId, andclientSecretvalues must be non-empty strings - Authentication failures expose only bounded OAuth error fields plus safe status/code diagnostics; passwords, refresh tokens, client secrets, and arbitrary response bodies are not included in the public error graph
await kc.simpleAuth({
username: 'admin',
password: 'admin', // pragma: allowlist secret
clientId: 'admin-cli',
});
await kc.simpleAuth({
clientId: 'my-service-account',
clientSecret: 'my-secret', // pragma: allowlist secret
});
await kc.simpleAuth({
clientId: 'admin-cli',
refreshToken: process.env.KEYCLOAK_REFRESH_TOKEN,
});auth(...)
If you need full control over the grant configuration, call the underlying auth method directly:
await kc.auth({
grantType: 'password',
clientId: 'admin-cli',
username: 'admin',
password: 'admin', // pragma: allowlist secret
});Managed clients
createManagedKeycloakClient(...) authenticates on demand, refreshes expired tokens without timers, and shares one authentication attempt across concurrent requests. Credential resolver functions are called again whenever authentication is required, allowing secret rotation.
Service-account authentication uses client_credentials and is the default mode:
import { createManagedKeycloakClient } from '@egose/keycloak-fluent';
const kc = createManagedKeycloakClient({
baseUrl: 'http://localhost:8080',
authRealm: 'master',
clientId: 'provisioning-service',
clientSecret: () => secretStore.get('keycloak-client-secret'),
});Direct user authentication uses the OAuth password grant. The client must have Direct Access Grants enabled:
const kc = createManagedKeycloakClient({
baseUrl: 'http://localhost:8080',
authRealm: 'master',
authMode: 'user_credentials',
clientId: 'admin-cli',
username: () => secretStore.get('keycloak-admin-username'),
password: () => secretStore.get('keycloak-admin-password'),
});Service accounts are recommended for background automation because their permissions and lifecycle are independent of a human administrator.
Example Flows
Realm and User Provisioning
const realm = await kc.realm('my-realm').ensure({
displayName: 'My Realm',
});
await realm.user('john.doe').ensure({
firstName: 'John',
lastName: 'Doe',
email: '[email protected]',
});Users can also be targeted by immutable Keycloak ID. User handles expose temporary password reset, verification email, managed realm-role reconciliation, and managed attribute reconciliation:
const user = kc.realm('my-realm').userById(userId);
await user.resetPassword(generatedPassword, { temporary: true });
await user.sendVerifyEmail();
await user.reconcileRealmRoles(['application-user'], {
managedRoleNames: ['application-user', 'application-admin'],
ensureMissing: true,
});
await user.reconcileAttributes({ tenantId: ['tenant-42'] }, { managedKeys: ['tenantId'] });Supplying passwordTemporary during creation or ensure uses the same disabled-create and cleanup guarantees as ordinary password provisioning:
await kc.realm('my-realm').user('new-user').create({
enabled: true,
password: generatedPassword,
passwordTemporary: true,
});Authentication Flows
const flow = await kc.realm('demo').authenticationFlow('browser-copy').ensure({
description: 'Custom browser flow',
providerId: 'basic-flow',
topLevel: true,
builtIn: false,
});
await flow.copy('browser-copy-v2');
await flow.addExecution('auth-cookie');Organizations
const realm = kc.realm('demo');
const organization = await realm.organization('acme').ensure({
name: 'Acme Corp',
});
await organization.addMember(realm.user('alice'));
const google = realm.identityProvider('google');
await organization.linkIdentityProvider(google);Operational Helpers
const realm = kc.realm('demo');
await realm.cache().clearUserCache();
await realm.attackDetection('user-id').clear();
const info = await kc.serverInfo().get();
const me = await kc.whoAmI('master').get();Main Entry Points
Root Client
KeycloakAdminClientFluent exposes:
auth(credentials)simpleAuth({...})realm(name)searchRealms(keyword)serverInfo()whoAmI(currentRealm, realmName?)
Realm Handle
RealmHandle is the main entry point for resource-scoped work. From a realm you can access handles for:
- clients
- authentication flows
- components
- client scopes
- roles
- groups
- users
- identity providers
- organizations
- user storage providers
- workflows
- browser login client helpers
- service accounts
- realm admin service accounts
- cache
- attack detection
- client policies
It also includes realm-level search and operational methods such as:
searchClients(...)searchClientScopes(...)searchRoles(...)searchGroups(...)searchUsers(...)searchIdentityProviders(...)searchOrganizations(...)searchAuthenticationFlows(...)searchWorkflows(...)- realm import/export helpers
- event queries
- localization helpers
- session helpers
Main Handles At A Glance
| Handle | Purpose |
| ------------------------------ | ------------------------------------------------------------------------------------ |
| KeycloakAdminClientFluent | Root entry point for auth, realm access, server info, and who-am-i |
| RealmHandle | Realm-scoped entry point for users, groups, roles, clients, flows, and operations |
| UserHandle | Manage users, credentials, role mappings, groups, sessions, and federated identities |
| GroupHandle | Manage groups, hierarchy, membership, and role mappings |
| RoleHandle | Manage realm roles and related mappings |
| ClientHandle | Manage clients, client roles, and protocol mappers |
| ClientScopeHandle | Manage client scopes and scope mappers |
| IdentityProviderHandle | Manage identity providers and provider-level mapper access |
| IdentityProviderMapperHandle | Manage mappers attached to an identity provider |
| AuthenticationFlowHandle | Manage flows, executions, authenticator config, and required actions |
| OrganizationHandle | Manage organizations, members, invitations, and linked identity providers |
| WorkflowHandle | Manage realm workflows and workflow listing |
| ComponentHandle | Manage realm components such as user storage-related components |
| UserStorageProviderHandle | Trigger sync, unlink, naming, and mapper sync operations for user storage providers |
| CacheHandle | Clear realm caches |
| AttackDetectionHandle | Inspect or clear user and realm attack-detection state |
| ClientPoliciesHandle | Read and update client profiles and client policies |
| ServerInfoHandle | Read root server info and effective message bundles |
| WhoAmIHandle | Inspect the currently authenticated admin user |
Supported Areas
The currently documented and tested surface includes:
- realms
- users
- groups
- roles
- clients
- client scopes
- protocol mappers
- identity providers
- identity provider mappers
- authentication flows
- organizations
- workflows
- components
- user storage providers
- cache operations
- attack detection
- client policies
- server info
- who-am-i
Notes
- For resource-style handles,
update(...)and the update path ofensure(...)now merge the supplied fields into the existing representation before sending the admin update call. This keeps unspecified nested fields such as attributes, config blocks, redirect URIs, and other existing settings intact. WorkflowHandlenow follows the same contract as the other mutable handles: it exposescreate(...),update(...),ensure(...),delete(), anddiscard().- Some higher-level helpers resolve resources lazily by alias or name, so code stays concise while still failing explicitly when a resource cannot be resolved.
- You can always access the underlying official admin client through
kc.core.
Documentation
- Site:
https://keycloak-fluent.pages.dev - Quick Start:
https://keycloak-fluent.pages.dev/about/quick-start/ - API Reference:
https://keycloak-fluent.pages.dev/api/keycloak-admin-client-fluent/ - Examples:
https://keycloak-fluent.pages.dev/example/general/
Development
Sandbox-free local checks can run without Docker or a Keycloak server:
pnpm install
pnpm lint:check
pnpm typecheck
pnpm typecheck:tests
pnpm test:unit
pnpm build
pnpm docs:checkLive integration tests need the Docker/Keycloak sandbox described below. Do not run pnpm test or pnpm test:integration until the sandbox is reachable.
Build, Type-check, And Release Verification
npm run buildProduces the publishabledist/from current source viatsup(ESM + CJS +.d.ts/.d.cts). The packageexports/main/module/typesentry points all point atdist/index.{cjs,js,d.ts}, so the bundle is the source of truth for the installed tarball.npm run typecheckRunstsc --noEmitfor project-wide type validation. This is the non-emitting type gate used by CI and pre-publish checks; it does not writebuild/.npm run pack:inspectRebuildsdist/, runsnpm pack --dry-run --json, and asserts the tarball contains only the intended files (dist/index.*,README.md,LICENSE,CHANGELOG.md,package.json) and no source maps. Useful as a guard against stale or accidental package-file drift.npm run pack:consumersBuilds and packs the tarball, then installs it into isolated ESM, CJS, and TypeScript consumer projects under.packed-consumers/and exercises the real root export surface,simpleAuth()validation/default flow, and representative handle creation in each. TypeScript consumers also runtsc --noEmitwithskipLibCheck: falseagainst the packed.d.ts, including a fixture pinned to the minimum supported@keycloak/[email protected].npm run publish:checkRuns the sandbox-free pre-publish chain:lint:check->typecheck->typecheck:tests->test:unit->build->pack:inspect->pack:consumers. The tag publish workflow adds livetest:integrationin the sandbox before publishing the exact tagged commit.npm run docs:checkVerifies documentation version strings and critical public snippets against checked-in package metadata and source declarations.
Test Layers
The repo intentionally has two different kinds of tests:
npm run test:unitRuns the mocked implementation/contract tests intests/implementation-*.spec.ts. These verify the fluent wrapper behavior itself: lazy resolution, correct admin-client method selection, payload shaping, pagination wiring, and resource-handle contracts.npm run test:integrationRuns the live Keycloak integration tests in the rest oftests/*.spec.ts. These create real realms and resources against a running Keycloak instance throughtests/test-utils.ts.npm testRuns the full suite and therefore requires the integration sandbox to be running.
The mocked tests are not meant to replace the live integration suite. They exist because some wrapper guarantees are easier and safer to assert at the admin-client call boundary than through a live server alone.
Integration Sandbox
The live integration tests (npm run test:integration) target a Keycloak instance provisioned by the sandbox/ Docker Compose stack:
make DAEMON=true up # start Keycloak + Postgres in the background
make logs # tail sandbox service logs
make down # stop and remove sandbox containers
make destroy # down + remove volumes and imagesThe stack pins every image by immutable digest (postgres:18.4-alpine3.22@sha256:..., quay.io/keycloak/keycloak:26.6.1@sha256:..., and the golang mkcert build stage) and builds the local mkcert cert from the pinned mkcert release tag (v1.4.4, commit-pinned inside the Dockerfile), so a forced re-pull cannot silently advance the runtime to a different image than the one the tests were authored against.
The integration tests read their target endpoint and credentials from environment variables so a non-default Keycloak instance can be targeted without editing the test sources. Defaults match the local sandbox:
| Environment variable | Default | Purpose |
| ----------------------- | ----------------------- | ------------------------------------------ |
| KEYCLOAK_BASE_URL | http://localhost:8080 | Keycloak admin API base URL. |
| KEYCLOAK_MASTER_REALM | master | Master realm name to authenticate against. |
| KEYCLOAK_USERNAME | admin | Admin username for simpleAuth(). |
| KEYCLOAK_PASSWORD | password | Admin password for simpleAuth(). |
For example, to run the integration suite against Keycloak on https://kc.example:8443 with custom credentials:
KEYCLOAK_BASE_URL=https://kc.example:8443 \
KEYCLOAK_USERNAME=ci-admin \
KEYCLOAK_PASSWORD="$CI_ADMIN_PASSWORD" \
npm run test:integrationIn CI, .github/actions/setup-tools delegates tool installation to the pinned egose/actions/asdf-tools action commit and the versions in .tool-versions (nodejs, pnpm, picotools, and docker-compose). The repository does not currently enforce a checksum for the installed Docker Compose binary. The .github/actions/setup-sandbox composite action then brings the sandbox up, waits for the master realm openid-configuration to be reachable, runs the provided script, and tears the services down via an EXIT trap that fires on success, failure, and job cancellation, so cleanup and diagnostic logs run even if the script is interrupted.
License
Apache-2.0
