npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@ricardoqmd/auth-core

v1.3.0

Published

Framework-agnostic XState machine and types for authentication flows

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-core

Most 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 structured AuthError.

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