@versini/auth-common
v4.6.2
Published
Shared low-level building blocks (constants, token helpers, PKCE utilities, session helpers) used by `@versini/auth-provider` and any backend or frontend integration that needs to validate / manipulate auth artifacts.
Readme
@versini/auth-common
Shared low-level building blocks (constants, token helpers, PKCE utilities, session helpers) used by @versini/auth-provider and any backend or frontend integration that needs to validate / manipulate auth artifacts.
Install
pnpm add @versini/auth-commonPeer dependency expectations: none (pure ESM, no React required).
Exports Overview
All exports are re-exported via the package root:
AUTH_TYPES– Enum-like constants describing supported authentication flows (code, passkey, etc.)verifyAndExtractToken(token: string)– Verifies a JWT (signature/structure) and returns a decoded payload or throws on failure.pkceChallengePair()– Generates a secure PKCE code_verifier and corresponding code_challenge (S256).getToken(...)/getSession(...)– Helpers to retrieve tokens / session data from storage or cookie contexts (implementation depends on consumer usage pattern).isGranted(roles: string[], required: string | string[])– Authorization helper performing role / permission checks (deny-by-default pattern recommended).constants– Centralized constants including JWT claim keys (JWT.USER_ID_KEY, etc.) andAPI_TYPEfor discriminating API operations.
Keep a deny-by-default stance: always guard privileged operations with
isGrantedor equivalent server-side enforcement.
Usage Example
import {
AUTH_TYPES,
pkceChallengePair,
verifyAndExtractToken,
isGranted
} from "@versini/auth-common";
async function beginAuth() {
const { code_verifier, code_challenge } = await pkceChallengePair();
// send code_challenge to authorization endpoint, persist code_verifier securely (in-memory)
}
async function validate(idToken: string) {
const jwt = await verifyAndExtractToken(idToken);
if (!isGranted(jwt.payload.roles || [], "admin")) {
throw new Error("Not authorized");
}
return jwt.payload[AUTH_TYPES.AUTH];
}Security Notes
- Never persist the PKCE
code_verifierbeyond the user session in plaintext storage. - Avoid logging raw tokens; if needed log only the first/last 6 chars.
- Perform server-side validation even if
verifyAndExtractTokenpasses client-side.
TypeScript
Distributed with full TypeScript declarations (dist/*.d.ts). All functions are strictly typed—avoid using any; prefer narrowing unknown data before passing to these helpers.
License
MIT © gizmette.com
