verifayda-auth-client
v1.0.0
Published
Node.js/TypeScript SDK for VeriFayda eSignet authentication flow
Maintainers
Readme
VeriFayda Auth Client
Node.js/TypeScript SDK for VeriFayda eSignet authentication flow implementing OAuth2/OIDC with OTP authentication.
Installation
npm install verifayda-auth-clientConfiguration
All configuration must be provided via environment variables:
Required Configuration
VERIFAYDA_CLIENT_ID- OAuth2 client identifierVERIFAYDA_REDIRECT_URI- OAuth2 redirect URIVERIFAYDA_PRIVATE_KEY- RSA private key (format depends onVERIFAYDA_PRIVATE_KEY_TYPE)VERIFAYDA_PRIVATE_KEY_TYPE- Private key type:JWKS_BASE64orPEM_RAWVERIFAYDA_BASE_URL- Base URL for VeriFayda services
Optional Configuration
VERIFAYDA_SCOPE- OAuth2 scope (defaults to "openid profile email")VERIFAYDA_CLAIMS- OAuth claims as JSON string (defaults to id_token with email and name)VERIFAYDA_NONCE- OAuth nonce (auto-generated if not provided)VERIFAYDA_STATE- OAuth state (auto-generated if not provided)VERIFAYDA_CLAIMS_LOCALES- Claims locales (defaults to "en")VERIFAYDA_CODE_CHALLENGE- PKCE code challenge (auto-generated if not provided)VERIFAYDA_CODE_CHALLENGE_METHOD- PKCE code challenge method (defaults to "S256")
Private Key Types
JWKS_BASE64
Base64-encoded JSON Web Key Set (JWK) format. The private key should be provided as a base64-encoded string containing the JWK JSON.
PEM_RAW
Standard PEM format RSA private key. The private key should be provided as a raw PEM string.
Quick Start
Using the TypeScript/JavaScript SDK
import { VeriFaydaClient } from 'verifayda-auth-client';
// Initialize client with configuration from environment variables
const client = new VeriFaydaClient({
clientId: process.env.VERIFAYDA_CLIENT_ID!,
redirectUri: process.env.VERIFAYDA_REDIRECT_URI!,
privateKey: process.env.VERIFAYDA_PRIVATE_KEY!,
privateKeyType: process.env.VERIFAYDA_PRIVATE_KEY_TYPE as 'JWKS_BASE64' | 'PEM_RAW',
baseUrl: process.env.VERIFAYDA_BASE_URL!,
scope: process.env.VERIFAYDA_SCOPE
});
// Complete the full authentication flow with configurable OAuth parameters
const result = await client.completeAuthenticationFlow({
individualId: 'user_individual_id',
otpValue: '123456', // OTP received by user
otpChannels: ['phone', 'email'],
claims: { id_token: { email: null, name: null, phone_number: null } }, // Optional
nonce: process.env.VERIFAYDA_NONCE, // Optional, auto-generated if not provided
state: process.env.VERIFAYDA_STATE, // Optional, auto-generated if not provided
claimsLocales: process.env.VERIFAYDA_CLAIMS_LOCALES || 'en', // Optional
codeChallenge: process.env.VERIFAYDA_CODE_CHALLENGE, // Optional
codeChallengeMethod: process.env.VERIFAYDA_CODE_CHALLENGE_METHOD || 'S256', // Optional
});
console.log(`Access Token: ${result.accessToken}`);
console.log(`User Info:`, result.userInfo);Step-by-Step Authentication Flow
For more control, execute each step individually:
import { VeriFaydaClient } from 'verifayda-auth-client';
const client = new VeriFaydaClient({
clientId: process.env.VERIFAYDA_CLIENT_ID!,
redirectUri: process.env.VERIFAYDA_REDIRECT_URI!,
privateKey: process.env.VERIFAYDA_PRIVATE_KEY!,
privateKeyType: process.env.VERIFAYDA_PRIVATE_KEY_TYPE as 'JWKS_BASE64' | 'PEM_RAW',
baseUrl: process.env.VERIFAYDA_BASE_URL!
});
// Step 1: Get CSRF token
await client.getCsrfToken();
// Step 2: Post OAuth details with configurable parameters
const oauthRequest = client.buildOAuthRequest({
claims: { id_token: { email: null, name: null, phone_number: null } },
nonce: process.env.VERIFAYDA_NONCE, // Optional, auto-generated if not provided
state: process.env.VERIFAYDA_STATE, // Optional, auto-generated if not provided
claimsLocales: process.env.VERIFAYDA_CLAIMS_LOCALES || 'en',
codeChallenge: process.env.VERIFAYDA_CODE_CHALLENGE, // Optional, uses instance value
codeChallengeMethod: process.env.VERIFAYDA_CODE_CHALLENGE_METHOD || 'S256'
});
await client.postOAuthDetails(oauthRequest);
// Step 3: Send OTP
await client.sendOtp('user_individual_id', ['phone']);
// Step 4: Authenticate with OTP (user provides OTP)
const challengeList = [
{ authFactorType: 'OTP', challenge: '123456', format: 'alpha-numeric' }
];
await client.authenticateUser('user_individual_id', challengeList);
// Step 5: Request authorization code
await client.requestAuthCode();
// Step 6: Exchange code for tokens
const tokenResponse = await client.exchangeCodeForTokens();
// Step 7: Get user info
const userInfo = await client.getUserInfo();JWT Decoding and Language-Coded Fields
The SDK provides utilities for decoding JWT tokens and handling language-coded fields.
Decoding JWT Tokens
import { VeriFaydaClient, JWTUtils } from 'verifayda-auth-client';
// Decode ID token
const idTokenPayload = client.getIdTokenPayload();
// Or decode any JWT manually
const decoded = JWTUtils.decodeJwt(idToken, false);Handling Language-Coded Fields
Some fields in the JWT payload may have language variants (e.g., name#en, name#am), while others do not (e.g., email, phone_number).
import { VeriFaydaClient } from 'verifayda-auth-client';
const userInfo = await client.getUserInfo();
// Get a field with language support (defaults to 'en')
const name = VeriFaydaClient.getFieldWithLanguage(userInfo, 'name', 'en');
// Get all language variants of a field
const nameVariants = VeriFaydaClient.getAllLanguageVariants(userInfo, 'name');
// Returns: { base: 'John Doe', en: 'John Doe', am: 'ጆን ዶይ' }
// Fields without language variants (email, phone_number, etc.)
const email = VeriFaydaClient.getFieldWithLanguage(userInfo, 'email');Fields with Language Variants
namenationalityaddressgenderbirthdate
Fields without Language Variants
emailphone_numbersubindividual_idpicture
API Reference
VeriFaydaClient
Main client class for VeriFayda authentication.
Constructor
new VeriFaydaClient(config: VeriFaydaClientConfig)Methods
getCsrfToken(): Get CSRF token from serverpostOAuthDetails(oauthRequestBody): Post OAuth details to initiate authentication flowsendOtp(individualId, otpChannels?, captchaToken?): Send OTP to userauthenticateUser(individualId, challengeList): Authenticate user with OTPrequestAuthCode(acceptedClaims?, permittedScopes?): Request authorization codeexchangeCodeForTokens(code?): Exchange authorization code for access and ID tokensgetUserInfo(): Get user information using access tokengetIdTokenPayload(): Decode and return the ID token payloadbuildOAuthRequest(options?): Build OAuth request body with configurable parameterscompleteAuthenticationFlow(options): Complete the full authentication flow
Static Methods
getFieldWithLanguage(decodedData, fieldName, languageCode?): Get a field value with language code supportgetAllLanguageVariants(decodedData, fieldName): Get all language variants of a field
Error Handling
The SDK provides custom error classes:
import { VeriFaydaError, AuthenticationError, ConfigurationError } from 'verifayda-auth-client';
try {
await client.completeAuthenticationFlow(options);
} catch (error) {
if (error instanceof ConfigurationError) {
console.error('Configuration error:', error.message);
} else if (error instanceof AuthenticationError) {
console.error('Authentication error:', error.message);
} else if (error instanceof VeriFaydaError) {
console.error('VeriFayda error:', error.message);
}
}License
MIT
Author
Fayda Team - [email protected]
