Registry / auth-security / haaremy-auth

haaremy-auth

JSON →
library2.0.0jsnpmunverified

The official Haaremy SSO Authentication SDK provides a comprehensive solution for integrating Haaremy's Single Sign-On system into JavaScript applications. It encapsulates token handling, login/logout flows, BroadcastChannel-based tab synchronization, and offers specific integrations for React and Next.js. Currently at version 2.0.0, this SDK is actively maintained with a focus on security and developer experience. Key differentiators include its 'zero localStorage' approach (tokens are memory-only), proactive token refresh, server-side replay detection for token families, and efficient offline JWT validation using JWKS caching with Ed25519 signatures. It offers distinct entrypoints for vanilla JS/framework-agnostic core logic, React hooks and components, and Next.js middleware/server-side helpers, making it adaptable to various application architectures.

npm install haaremy-auth
INSTALL
IMPORT
SIG · HAAREMY-AUTH
H
haaremy-auth
auth-securityjavascriptv2.0.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

init
import { init } from '@haaremy/auth'
const { init } = require('@haaremy/auth')
The core library is primarily designed for ESM usage. CommonJS `require` is not officially supported and may lead to issues, especially in environments like Next.js Edge Runtime.
useAuth
import { useAuth } from '@haaremy/auth/react'
import { useAuth } from '@haaremy/auth'
`useAuth` is a React Hook and must be imported from the `/react` subpath. Importing from the main entrypoint will result in `undefined` or a module not found error.
HmyAuthProvider
import { HmyAuthProvider } from '@haaremy/auth/react'
The React context provider `HmyAuthProvider` is specific to React applications and must be imported from the `/react` subpath.
createHmyMiddleware
import { createHmyMiddleware } from '@haaremy/auth/next'
import createHmyMiddleware from '@haaremy/auth/next'
`createHmyMiddleware` is a named export from the `/next` subpath, intended for Next.js `middleware.ts` files. It is not a default export.
login
import { login } from '@haaremy/auth'
The `login` function is part of the core vanilla JS API. It's an async function and should be awaited.

This quickstart demonstrates how to set up the `HmyAuthProvider` at your application root and use the `useAuth` hook in a child component to manage authentication state, display user information, handle login via `HmyLoginForm`, and perform logout. It showcases both authenticated and unauthenticated states.

import { HmyAuthProvider, useAuth, HmyLoginForm } from '@haaremy/auth/react'; const ssoUrl = process.env.NEXT_PUBLIC_SSO_URL ?? 'https://sso.haaremy.de'; // Ensure SSO URL is configured // This component would typically be in your _app.tsx or layout.tsx function AppWrapper({ children }) { return ( <HmyAuthProvider config={{ ssoUrl: ssoUrl }}> {children} </HmyAuthProvider> ); } // This component demonstrates how to use the auth state within your application function MyAuthenticatedPage() { const { state, user, login, logout, getAccessToken } = useAuth(); if (state === 'loading') { return <div>Authentifizierungsstatus wird geladen...</div>; } if (state === 'unauthenticated') { return ( <div> <p>Sie sind nicht angemeldet.</p> <HmyLoginForm onSuccess={(loggedInUser) => { console.log('Login erfolgreich:', loggedInUser.display_name); }} onError={(error) => { console.error('Login fehlgeschlagen:', error.message); }} /> </div> ); } // State is 'authenticated' return ( <div> <h1>Hallo, {user?.display_name}!</h1> <p>Ihre E-Mail: {user?.email}</p> <button onClick={logout}>Abmelden</button> <button onClick={async () => { const token = await getAccessToken(); console.log('Aktueller Access Token:', token ? token.substring(0, 20) + '...' : 'Kein Token'); }}>Token anzeigen</button> </div> ); } // Example usage within a React component tree: // function Root() { // return ( // <AppWrapper> // <MyAuthenticatedPage /> // </AppWrapper> // ) // } // export default Root;
Debug
Known issues
breakingVersion 2.0.0 introduces a refactor of the SDK's internal architecture, particularly how subpath imports are organized. Ensure all React-specific components (`HmyAuthProvider`, `useAuth`, `HmyLoginForm`) are imported from `@haaremy/auth/react` and Next.js-specific utilities (`createHmyMiddleware`) from `@haaremy/auth/next`.
fix
Review all import statements. For React components/hooks, change `import { X } from '@haaremy/auth'` to `import { X } from '@haaremy/auth/react'`. For Next.js middleware, ensure `import { createHmyMiddleware } from '@haaremy/auth/next'` is used.
affects: >=2.0.0
gotchaThe SDK strictly adheres to a 'zero localStorage' policy for Access Tokens, storing them only in JavaScript memory. This means that if a user closes all tabs or the browser, the Access Token is lost, requiring a re-login (which might be handled transparently by the refresh token in the cookie on next visit).
fix
Design your application's user experience with this in mind. Ensure your login flow can gracefully handle token expiry or loss on browser close. Leverage the refresh token mechanism for persistent sessions via SSO cookies.
affects: >=1.0.0
gotchaThe Next.js Middleware (`createHmyMiddleware`) relies on `publicPaths` to define routes that do not require authentication. Failing to correctly configure this array can lead to all routes being protected, including login/registration pages, resulting in redirect loops or inaccessible routes.
fix
Carefully define `publicPaths` in your `createHmyMiddleware` configuration. Include `/login`, `/register`, API routes that should be public (e.g., `/api/public*`), and any static assets or `_next` paths as needed. Ensure `loginPath` points to your actual login route.
affects: >=2.0.0
breakingThe `authFetch` utility, which automatically injects the Access Token into requests, expects an initialized SDK with a valid session. Using `authFetch` before `await init()` has completed or when the user is `unauthenticated` can lead to failed requests.
fix
Always call and `await init()` at your application's startup. When using `authFetch`, ensure the authentication state indicates `authenticated` to prevent unauthorized requests. Consider wrapping `authFetch` calls in conditional logic based on the `state` from `useAuth` or `subscribe`.
affects: >=2.0.0
gotchaThe SDK uses Ed25519 for JWT signing. While highly secure, ensure your backend SSO system correctly issues Ed25519-signed JWTs and exposes a compatible JWKS endpoint (`/.well-known/jwks.json`). Incompatibilities can lead to token validation failures.
fix
Verify that your SSO provider is configured to use Ed25519 for JWT signatures. Ensure the `jwks.json` endpoint is publicly accessible and contains the correct public keys matching the SSO's private key.
affects: >=1.0.0
Errors
Common errors & fixes
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
Attempting to use a React component like `HmyAuthProvider` or `HmyLoginForm` imported from the main `@haaremy/auth` entrypoint instead of the `@haaremy/auth/react` subpath.
fix
Change `import { HmyAuthProvider } from '@haaremy/auth'` to `import { HmyAuthProvider } from '@haaremy/auth/react'` (and similarly for other React components/hooks).
TypeError: Cannot destructure property 'createHmyMiddleware' of 'undefined' as it is undefined.
This error typically occurs if `createHmyMiddleware` is imported incorrectly from the main package or if the Next.js subpath is not correctly resolved.
fix
Ensure you are importing `createHmyMiddleware` from the correct subpath: `import { createHmyMiddleware } from '@haaremy/auth/next'`.
ReferenceError: init is not defined
The `init` function was called without being imported, or imported incorrectly from a CommonJS `require` statement that doesn't align with the ESM-first design.
fix
Add `import { init } from '@haaremy/auth'` to the top of your file. If using CommonJS, consider migrating to ESM or ensuring your build process correctly transpiles.
ERR_INVALID_AUTH_STATE: Cannot perform authenticated request. User is not authenticated.
An `authFetch` request was attempted when the SDK's internal state indicated the user was 'unauthenticated' or 'loading', meaning no valid access token was available.
fix
Before making requests with `authFetch`, ensure your application has completed initialization (`await init()`) and the user state is `authenticated`. You can use `subscribe` or `useAuth` to monitor the authentication state.
Upgrade
Version history
2.0.0latest on npm
Audit
Dependencies
nextoptionalRequired for the `@haaremy/auth/next` entrypoint for middleware and server-side helpers.
reactoptionalRequired for the `@haaremy/auth/react` entrypoint for React hooks and components.
Agent activity
15 hits · last 30 days
node
14
OpenAI (training)
1
Resources