@ricardoqmd/auth-core
v1.3.0
Published
Framework-agnostic XState machine and types for authentication flows
Maintainers
Readme
@ricardoqmd/auth-core
Framework-agnostic authentication primitives — the brain of
@ricardoqmd/auth-*.
This package contains the XState state machine and TypeScript contracts that drive authentication flows. It has zero runtime dependencies on React, Next.js, or any specific identity provider.
Pair it with an adapter (e.g. @ricardoqmd/auth-keycloak) and a framework binding (e.g. @ricardoqmd/auth-nextjs).
Install
npm install @ricardoqmd/auth-coreMost consumers will not install auth-core directly — it comes as a transitive dependency through bindings like @ricardoqmd/auth-nextjs. Install it explicitly only if you are building your own adapter or framework binding.
What's in the box
- State machine (
createAuthMachine) that owns the lifecycle:idle → initializing → authenticated | unauthenticated → loggingOut → ... AuthProvider<TIdpClaims>contract — the interface every IDP adapter implements.- Public types —
AuthTokens,AuthUserClaims,AuthInitResult,LogoutOptions, and the structuredAuthError.
IDP-agnostic by design
The core exposes a user.roles: string[] field that is the universal contract across all identity providers (Keycloak, Entra ID, Cognito, Auth0, …). Each adapter is responsible for mapping its IDP-specific claims into this universal shape.
For IDP-specific data (Keycloak's resource_access, for example), the core exposes a generic idpClaims<TIdpClaims> that adapters populate. Consumers opt in to typed access by passing their IDP claims interface to bindings like useAuth<KeycloakIdpClaims>().
Error contract
Auth failures surface as a structured AuthError, not a plain Error, so
consumers branch on a stable code instead of parsing messages:
import type { AuthError } from "@ricardoqmd/auth-core";
interface AuthError {
code: "INIT_FAILED" | "REFRESH_FAILED" | "TOKEN_EXPIRED" | "NETWORK_ERROR";
message: string;
}Bindings expose it directly — e.g. useAuth().error and errorComponent in
@ricardoqmd/auth-nextjs. New codes may be added over time, so always handle a
default branch. (TOKEN_EXPIRED is reserved and not currently emitted by
auth-keycloak; see ADR-009.)
Getting a token for API requests
There are two ways to read a token, and only one of them is correct for a request.
| | What it is | Use it for |
|---|---|---|
| AuthHandle.getToken() | A call-time snapshot — a plain string, read once | Display, debugging, UI gates |
| AuthHandle.acquireToken(minValidity?) | A promise that resolves a token valid for at least minValidity seconds (default 30) when the IdP can grant it, refreshing first if needed. Near the session's maximum lifetime the remaining session time caps the token, in which case the freshest obtainable token is returned | Every API request |
Always use acquireToken() to attach a token to a request. Two things make the
synchronous snapshot unsafe. First, a snapshot captured inside a long-lived closure
(a TanStack Query queryFn, an axios interceptor, an event handler) pins a string
that goes stale, producing 401s that depend on how long the closure has been alive.
Second, the machine's proactive refresh is a setTimeout, and browsers throttle
timers in hidden tabs and pause them entirely during system sleep — so on tab return
the machine can still be holding an expired token. The proactive refresh is a latency
optimization; acquireToken() is the correctness guarantee.
const token = await auth.acquireToken();
if (token === null) return redirectToLogin(); // session over — re-authenticate
await fetch("/api/things", { headers: { Authorization: `Bearer ${token}` } });null means the session is over (unauthenticated, refresh failed, or error). Treat
it as "re-authenticate" — never retry the request with a previously held token.
Concurrent callers share a single refresh: the refresh runs through the machine, which
only accepts a REFRESH in authenticated.active, so overlapping calls hang off the
same in-flight transition instead of stacking network requests.
Bindings re-expose this: useAuth().acquireToken in @ricardoqmd/auth-nextjs and
@ricardoqmd/auth-vue.
Typical consumer code
You will almost never call auth-core APIs directly. The typical pattern is:
// Through @ricardoqmd/auth-nextjs
import { useAuth } from "@ricardoqmd/auth-nextjs";
import type { KeycloakIdpClaims } from "@ricardoqmd/auth-keycloak";
const { user, hasRole, idpClaims } = useAuth<KeycloakIdpClaims>();auth-core is the layer that sits underneath, owning state transitions and contracts.
Building your own adapter
If you need to support an identity provider that does not yet have an official adapter, implement the AuthProvider<TIdpClaims> contract:
import type { AuthProvider, AuthInitResult } from "@ricardoqmd/auth-core";
interface MyIdpClaims {
// your IDP-specific token claims
}
export function createMyIdpProvider(config: MyConfig): AuthProvider<MyIdpClaims> {
return {
async init(): Promise<AuthInitResult<MyIdpClaims>> {
// initialize your IDP SDK, return tokens + user + idpClaims
},
login() { /* ... */ },
logout(options) { /* ... */ },
async refreshToken() { /* ... */ },
};
}Status
Stable. The public API is frozen and follows SemVer from 1.0 onward (see
ADR-009):
additive changes are non-breaking; removing or renaming an export, or adding a
method to the AuthProvider port, is a major bump.
License
MIT © ricardoqmd
