SDK guide¶
@rossbsol/kiban-sdk is the TypeScript package a web application or a module frontend uses to
talk to a Kiban deployment: the login flow, the tokens, typed calls to the platform API and the
error envelope. It has no runtime dependencies (native fetch and crypto only) and talks to
the gateway origin alone, never to Keycloak or to a module's service directly. The sample shell
in web/shell/ is one consumer of it; you do not need the shell to use the SDK.
Every sample on this page compiles against the package as shipped: the same code lives in
web/sdk/docs-snippets/guide.ts and server.ts, which the SDK's type check and unit tests
cover.
Install¶
npm i @rossbsol/kiban-sdk
Every release is published to the public npm registry, so no .npmrc and no token are needed.
The package ships ESM only (dist/index.js and dist/server/index.js, each with its .d.ts). Node 20 or a modern browser
gives you the fetch and crypto.subtle it relies on.
Create a session¶
The session runs the OpenID Connect authorization-code flow with PKCE (S256) against the
gateway's Keycloak proxy, validates state and nonce, and refreshes tokens one flight at a
time.
import { createSession } from "@rossbsol/kiban-sdk";
const gatewayOrigin = "https://127.0.0.1:8443"; // your gateway; self-signed TLS in `make dev`
const session = createSession({
authOrigin: gatewayOrigin,
realm: "kiban",
clientId: "kiban-frontend",
redirectUri: "http://localhost:5173/callback.html",
persistTokens: true
});
- A "Log in" button calls
await session.login(); the browser goes to Keycloak and comes back toredirectUriwithcodeandstate. - The callback route calls
await session.handleCallback(window.location.href)once on load. The call is idempotent for the samecode, so a React StrictMode double effect does not exchange the code twice. session.isAuthenticated()andsession.getAccessToken()are synchronous and never trigger a refresh.session.refresh()does; concurrent callers share one network call.session.logout()clears the tokens and sends the browser to Keycloak's logout endpoint, then back topostLogoutRedirectUri(default: the origin root ofredirectUri, not the callback route).
redirectUri must be registered on the kiban-frontend client. Bootstrap writes that list on
every start: https://<KIBAN_DOMAIN>/* when KIBAN_DOMAIN is set, otherwise the fixed
localhost set, plus every entry of KIBAN_EXTRA_ORIGINS. An edit in the Keycloak admin console
lasts until the next start; KIBAN_EXTRA_ORIGINS is the place to add an origin. Integrate your app
has the list and the steps.
Where tokens live¶
The token set (access, refresh and ID token plus expiry) is held in memory. With
persistTokens: true it is also written to sessionStorage under kiban.oidc.tokens, so a page
reload or a direct link keeps the session; the entry goes away when the tab closes. The SDK never
writes tokens to localStorage. On reload a persisted set is only trusted if it is still usable:
not expired, or expired but carrying a refresh token (the next 401 refreshes it). Anything else
is dropped and the user logs in again.
Keep the default storage for a browser login. The login is a redirect, and the only thing
written to sessionStorage for it is the PKCE transaction: a one-time random verifier,
state and nonce, useless without the authorization code and deleted on the callback. It is
not a credential. createMemoryStorage() is for tests and for hosts without browser storage;
a browser login cannot use it, because the page unloads for the redirect and the transaction
goes with it. Any script on your origin can read the tokens, so serve your application with a
Content-Security-Policy as the gateway does for the sample shell.
decodeIdTokenClaims(idToken) reads the ID token's claims for display (name, email) without
verifying the signature. Use it for the header, never for an authorization decision.
The API client¶
createApiClient is the one fetch wrapper every typed client is built on. It attaches the bearer
and an x-correlation-id, JSON-encodes the body, unwraps the { data } envelope and turns an
{ error } envelope into a KibanApiError.
import { createApiClient } from "@rossbsol/kiban-sdk";
const api = createApiClient({
baseUrl: gatewayOrigin,
getAccessToken: () => session.getAccessToken(),
getAccessTokenExpiresAt: () => session.getTokens()?.expiresAt,
refreshAccessToken: () => session.refresh()
});
A token that expires within the next 30 seconds is refreshed before the request is sent, when
getAccessTokenExpiresAt is wired. On a 401 the client calls refreshAccessToken once and retries
the request once if it returned a token. A second 401 is thrown as a KibanApiError, so a persistently rejected endpoint never
loops. A 204 resolves to undefined. api.request<T>(path, options) is available for a module's
own endpoints: options takes method, body, headers, query and an AbortSignal.
The clients¶
Each client is a function of the API client and returns an object of typed methods.
| Client | Methods | Endpoint |
|---|---|---|
createCapabilitiesClient(api) |
list(), get(moduleKey) |
GET /api/platform/capabilities[/{module}] |
createEffectiveAccessClient(api) |
can(request), batchCan(request), summary(companyId?) |
POST /api/auth/effective-access/can, /batch-can, GET .../summary |
createOrgClient(api) |
meCompanies(), memberDirectory(companyId, q?, page?, pageSize?), positionDirectory(companyId, page?, pageSize?), groupDirectory(companyId, page?, pageSize?), and the admin methods (a superadmin, or an administrator of that company) adminListPositions, adminCreatePosition, adminAssignPosition, adminHandoverPosition, adminEndAssignment, adminListGroups, adminCreateGroup, adminListGroupMembers, adminAddGroupMember, adminRemoveGroupMember |
/api/org/... |
createSuperadminClient(api) |
catalog(), enableModule(key), disableModule(key), grantPlatformRole(subjectId, role), revokePlatformRole(subjectId, role) |
/api/platform/catalog, /api/platform/admin/... |
createDemoModeClient(api) |
get() |
GET /api/platform/demo-mode |
Effective access is self-scoped: the gateway answers for the bearer only, and a request body
naming another subject is rejected. summary() returns the feature keys, role bindings and
direct object grants the caller holds, globally or in one company; it is a display composition
for navigation, while can and batchCan are the gate a component asks before acting.
import { createEffectiveAccessClient, createOrgClient } from "@rossbsol/kiban-sdk";
const effectiveAccess = createEffectiveAccessClient(api);
const org = createOrgClient(api);
const companies = await org.meCompanies();
const summary = await effectiveAccess.summary(companies[0]?.id);
const decisions = await effectiveAccess.batchCan({
featureKey: "docs.create",
moduleKey: "docs",
scope: "company",
companyId: summary.companyId,
items: [
{ object: { type: "docs_document", id: "doc-1" }, relation: "viewer" },
{ object: { type: "docs_document", id: "doc-2" }, relation: "viewer" }
]
});
const visible = decisions.filter((d) => d.decision.allowed).map((d) => d.object.id);
The sample modules (notification, docs, helpdesk, timesheet) have no clients in the SDK; call
their endpoints with api.request and the types from their OpenAPI files in the
reference.
queryKeys is a key factory for TanStack Query users, one entry per client above, so cache
invalidation uses the same keys everywhere. createSessionContext() keeps the active company
selection and user preferences in localStorage; it is a convenience for the UI, not an
authorization source.
Recipes¶
Two use-case functions answer common product questions in one call. Each has a pattern page and a live end-to-end test in the repository.
canI: "can I use this feature, here?"¶
import { createCanI } from "@rossbsol/kiban-sdk";
const canI = createCanI(effectiveAccess);
const admin = await canI({
featureKey: "auth.platform_administration.access",
requiredPlatformRole: "kiban-superadmin"
});
const view = await canI({ featureKey: "notification.inbox.view", moduleKey: "notification", companyId: summary.companyId });
if (!view.allowed) {
console.log(view.reason); // e.g. "COMPANY_MEMBERSHIP_REQUIRED"
}
Omit companyId for a global check, set it for a company-scoped one. A global check must set
requiredPlatformRole; without it the server answers 400 VALIDATION_ERROR. A denial is a
normal { allowed: false, reason } result and does not throw; KibanApiError is thrown for a
non-2xx answer (a 400 for an invalid request, a 422 for a feature key a registered app does
not declare, 401, 5xx).
grantObjectAccess: "share this object with that subject"¶
import { createGrantObjectAccess } from "@rossbsol/kiban-sdk";
const { grantObjectAccess, revokeObjectAccess } = createGrantObjectAccess(api);
await grantObjectAccess({
companyId: summary.companyId, // the company whose docs module owns the document
objectType: "docs_document",
objectId: "doc-1",
relation: "viewer",
subjectType: "group",
subjectId: "group-12",
subjectRelation: "member" // every current member of the group; omit for a single user
});
await revokeObjectAccess({
companyId: summary.companyId,
objectType: "docs_document",
objectId: "doc-1",
relation: "viewer",
subjectType: "group",
subjectId: "group-12",
subjectRelation: "member"
});
Both write one tuple through POST /api/auth/grants. The gateway admits a superadmin
or a registered app's backend (a service token whose client id is the app's service client);
anyone else, which includes every other browser login, receives 403 FORBIDDEN. The authz service then binds the request to the
company named by companyId and to the one enabled module whose fragment declares the object
type: docs_document belongs to the docs module, a base type such as company is refused (the one exception: a superadmin may grant or revoke
company:<companyId>#admin for a user, which appoints a company administrator), and
the object must already be anchored to that company's module (the module does this when it
creates the object). A request without a UUID companyId is answered 400; an object type no
enabled module declares, or an unanchored object, 422. A position's holder is
subjectType: "position" with subjectRelation: "holder".
Error handling¶
Every non-2xx response throws KibanApiError with status, code, message, optional details
and the correlationId the client sent, which also appears in the gateway's logs and audit
rows. ApiErrorCode holds the canonical codes as constants; the ones a frontend usually
branches on:
import { ApiErrorCode, KibanApiError } from "@rossbsol/kiban-sdk";
try {
await org.adminCreateGroup(summary.companyId, { code: "sales", name: "Sales" });
} catch (err) {
if (!(err instanceof KibanApiError)) throw err;
switch (err.code) {
case ApiErrorCode.AuthTokenMissing:
case ApiErrorCode.AuthTokenInvalid:
session.login(); // refresh already failed; start over
break;
case ApiErrorCode.Forbidden:
case ApiErrorCode.AuthorizationDenied:
// the caller may not do this; hide the control
break;
case ApiErrorCode.ModuleDisabled:
case ApiErrorCode.ModuleNotInstalled:
// the module is off for this deployment
break;
case ApiErrorCode.ValidationFailed:
case ApiErrorCode.Conflict:
// show err.message and err.details to the user
break;
case ApiErrorCode.AuthorizationUnavailable:
// authz could not answer (503); retry later, never fail open
break;
default:
throw err;
}
}
code is "UNKNOWN_ERROR" when a non-2xx response carried no JSON envelope (a proxy error
page). A request that never got a response (network failure, abort) rejects with the error
fetch threw, not a KibanApiError. Do not parse message; it is for people.
The backend entry: @rossbsol/kiban-sdk/server¶
The same package has a second entry for a Node backend that runs beside Kiban. It needs no
browser: fetch and crypto.subtle from Node 20 or later.
import { createAppClient, createServiceCredentials, createTokenVerifier } from "@rossbsol/kiban-sdk/server";
const gatewayOrigin = "https://127.0.0.1:8443";
const credentials = createServiceCredentials({ gatewayOrigin, clientId: "tokidesk-backend", clientSecret });
const kiban = createAppClient({ gatewayOrigin, appKey: "tokidesk", credentials });
const verifier = createTokenVerifier({ gatewayOrigin });
createServiceCredentialsobtains the app's own access token by the client-credentials grant and caches it until shortly before expiry (concurrent callers share one request).createTokenVerifier(...).verify(token)checks a user's token against the realm's signing keys (RS256, WebCrypto), the issuer, the audience and the time claims, and returns the subject, the client id (azp) and every claim. It refetches the keys once for an unknown key id. It rejects with an error whose message starts withkiban: invalid token; when the key set cannot be loaded, withkiban: JWKS fetch failed.createAppClientgivescan(userBearer, request),canService(request),batchCanandbatchCanService,grant(companyId, tuples),revoke(companyId, tuples),anchorTuple(objectType, objectId, companyId),memberBySubject(companyId, subject), the org readsmeCompanies(userBearer),memberDirectory,positionDirectory,groupDirectory,positionHolderandgroupMembers, andregisterApp(superadminBearer, manifest), plusapi, a plain client on the gateway origin for any other route. It attaches no token: passheaders: { Authorization: "Bearer " + (await credentials.getAccessToken()) }yourself. Errors areKibanApiErrorlike the browser client's.
Integrate your app walks the ten steps with these calls; its Node samples are compiled and run by this package's test suite.
Python and Go¶
kiban-sdk (Python, sdk/python) and github.com/rosschiu/kiban/sdk (Go) are the backend entry
for those languages, with the same surface as the Node server entry: the service token, user
token verification, can and batch_can (for the user, or for the service account), tuple
grant and revoke with the anchor helper, member lookup by subject, the org reads (companies the
user may see, member, position and group directories, position holder on a date, group members)
and app registration.
The Integrate page shows every call in all three languages.
Wire types¶
The package exports the request and response shapes as TypeScript types, hand-typed from the Go
handlers and pinned by tests: Capability, CatalogEntry, EffectiveAccessRequest,
EffectiveAccessDecision, EffectiveAccessSummary, AuthzTuple, OrgMeCompany,
OrgPositionWithHolder, OrgGroupWithMemberCount, Page<T> (items, total, page,
pageSize, totalPages) and Cursor<T>. Capability and CatalogEntry do not yet declare
three fields the server sends: external, serviceClientId and features. ApiErrorCode and EffectiveAccessReason are string
constants checked against the same golden file as the Go side, so a code you compare against
exists on the wire.
Versioning¶
The SDK follows semantic versioning and ships with each platform release; before 1.0 a minor
version may rename an export, and the rename is listed under "Changed (breaking — pre-1.0)" in
web/sdk/CHANGELOG.md. Pin
the version and read that file when you bump it.
Reference¶
- SDK API reference, generated from the source's doc comments at the same commit.
- Recipes catalog, with the pattern page and test for each recipe.
- Platform API for the endpoints the clients call.