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.
npm install @versini/auth-commonShared 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.
``bash`
pnpm add @versini/auth-common
Peer dependency expectations: none (pure ESM, no React required).
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.) and API_TYPE for discriminating API operations.
> Keep a deny-by-default stance: always guard privileged operations with isGranted or equivalent server-side enforcement.
`ts
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];
}
`
- Never persist the PKCE code_verifier beyond the user session in plaintext storage.verifyAndExtractToken
- Avoid logging raw tokens; if needed log only the first/last 6 chars.
- Perform server-side validation even if passes client-side.
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.
MIT © gizmette.com