🧩 Authentication Blocks
Authentication blocks provide pure business logic functions for secure user authentication and authorization operations. These blocks handle token management, email verification, identity validation, and comprehensive error handling.
🎯 Overview
Authentication blocks are designed to:
- Validate user identities and manage authentication tokens
- Handle email verification with secure one-time tokens
- Support password reset functionality with token validation
- Provide comprehensive error handling for authentication failures
- Manage token lifecycle including generation, validation, and invalidation
- Ensure security with fingerprint tracking and request validation
📋 Available Authentication Blocks
Identity Management Blocks
assertIdentityExists
Verifies that an identity exists in the authentication database.
Purpose: Validates that a user identity exists in the database
Parameters:
db: AuthenticationServiceDataStore['identities']- Authentication service database connectionidentityId: string- Unique identifier for the identity to verify
Returns: Promise<Result<boolean, AuthenticationNotFoundError | AuthenticationUnexpectedDbError>>
Handler Process:
- Input: Identities collection and
identityId - Process: Queries the identities collection for the given ID and determines existence
- Output:
ok(true)if identity exists, otherwise an appropriate error - Errors:
AuthenticationNotFoundErrorwhen not found;AuthenticationUnexpectedDbErroron DB failure
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
const result = await blocks.assertIdentityExists(database, "identity123");
if (result.isOk()) {
// Identity exists, proceed with authentication
}
checkEmailIsUniqueInIdentities
Verifies that an email address is not already registered in the identities collection.
Purpose: Validates email uniqueness for registration and email change operations
Parameters:
db: AuthenticationServiceDataStore['identities']- Authentication service database connectionemail: string- Email address to check for uniqueness
Returns: Promise<Result<boolean, AuthenticationConflictError | AuthenticationUnexpectedDbError>>
Handler Process:
- Input: Identities collection and
email - Process: Checks for existing identity with the same email
- Output:
ok(true)if email is unique; conflict error if already taken - Errors:
AuthenticationConflictErrorwhen email exists;AuthenticationUnexpectedDbErroron DB failure
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
const result = await blocks.checkEmailIsUniqueInIdentities(database, "identity@example.com");
if (result.isOk()) {
// Email is available, proceed with registration
}
getIdentityIdByEmail
Retrieves an identity ID by searching for the associated email address.
Purpose: Looks up identity ID using email address
Parameters:
db: AuthenticationServiceDataStore['identities']- Authentication service database connectionemail: string- Email address to search for
Returns: Promise<Result<string, AuthenticationNotFoundError | AuthenticationUnexpectedError | AuthenticationUnexpectedDbError>>
Handler Process:
- Input: Identities collection and
email - Process: Finds identity by email and extracts its ID
- Output:
ok(identityId)on success; error on not found or failure - Errors:
AuthenticationNotFoundErrorif not found;AuthenticationUnexpectedErrororAuthenticationUnexpectedDbErroron failure
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
const result = await blocks.getIdentityIdByEmail(database.identities, "identity@example.com");
if (result.isOk()) {
const identityId = result.value;
// Use identity ID for further processing
}
isEmail
Validates that a string conforms to a basic email address format.
Purpose: Validates email format using regex pattern
Parameters:
maybeEmail: string- Email address string to validate
Returns: Result<boolean, AuthenticationInvalidInputError>
Handler Process:
- Input: String to validate as email
- Process: Validates string against email regex pattern
- Output:
ok(true)when valid; error result when invalid - Errors:
AuthenticationInvalidInputErrorwhen format does not match
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
const result = blocks.isEmail("identity@example.com");
if (result.isOk()) {
// Email format is valid, proceed with processing
}
buildUpdateIdentityPasswordPayload
Builds the payload for updating an identity password with type safety.
Purpose: Creates a type-safe payload object for password update operations
Parameters:
password: string- The new password string to be set for the identity
Returns: Result<{ password: string }, never>
Handler Process:
- Input: password as a string
- Process: Wraps the password in an object and returns it as a Result
- Output: Result containing an object with the password string
- Errors: Never returns an error (Result is always ok)
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
const result = blocks.buildUpdateIdentityPasswordPayload('newSecret123');
if (result.isOk()) {
// result.value = { password: 'newSecret123' }
// Use the payload for database update operations
}
hash
Hashes a string using bcrypt with salt rounds for secure password storage.
Purpose: Securely hashes passwords and sensitive strings using bcrypt
Parameters:
s: string- String to hash (typically a password)
Returns: Promise<Result<string, AuthenticationUnexpectedError>>
Handler Process:
- Input: String to hash (typically a password)
- Process: Applies bcrypt hashing with 10 salt rounds
- Output: Returns hashed string or error if hashing fails
- Errors: AuthenticationUnexpectedError if bcrypt hashing operation fails
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
// Used in password hashing flows:
const hashResult = await blocks.hash("password123");
if (hashResult.isOk()) {
const hashedPassword = hashResult.value;
// Store hashed password in database
}
normalizeIdentity
Normalizes identity object by removing password and _id fields for secure API responses.
Purpose: Sanitizes identity objects by removing sensitive fields before API responses
Parameters:
identity: { password?: string; _id?: string; [key: string]: unknown }- Identity object containing password, _id, and other user data
Returns: Result<Record<string, unknown>, never> - Result with normalized identity data (never fails)
Handler Process:
- Input: Identity object with optional password, _id, and other properties
- Process: Destructures password and _id fields, returns remaining properties
- Output: Clean identity object without sensitive fields
- Security: Prevents password exposure in API responses
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
const identity = { _id: 'abc', password: 'secret', email: 'a@b.com', name: 'Alice' };
const result = blocks.normalizeIdentity(identity);
if (result.isOk()) {
const safeIdentity = result.value;
// safeIdentity = { email: 'a@b.com', name: 'Alice' }
}
const partialIdentity = { email: 'a@b.com', name: 'Alice' };
const safePartial = blocks.normalizeIdentity(partialIdentity);
// Returns: Ok({ email: 'a@b.com', name: 'Alice' })
normalizeIdentitiesWithoutPassword
Normalizes multiple identities by removing password fields for secure API responses.
Purpose: Sanitizes an array of identity objects by removing password and _id fields
Parameters:
identities: Record<string, unknown>[]- Array of identity objects to normalize
Returns: Result<Record<string, unknown>[], never> - Result with sanitized identities (never fails)
Handler Process:
- Input: Array of identity objects with potential password fields
- Process: Maps each identity through normalizeIdentity and combines results
- Output: Array of sanitized identity objects without password fields
- Errors: Never fails (Result type indicates no error cases)
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
// Used in route handlers for secure identity responses:
const identities = [
{ id: '1', email: 'user@example.com', password: 'secret' },
{ id: '2', name: 'John', password: 'hidden' }
];
const result = blocks.normalizeIdentitiesWithoutPassword(identities);
if (result.isOk()) {
const safeIdentities = result.value;
// safeIdentities = [
// { id: '1', email: 'user@example.com' },
// { id: '2', name: 'John' }
// ]
}
buildUpdateIdentityDeactivatedPayload
Builds the payload for deactivating an identity with deactivation timestamp and lock status.
Purpose: Creates a type-safe payload object for identity deactivation operations
Parameters: None
Returns: Result<{ deactivatedAt: Date; locked: boolean }, never> - Result with deactivation payload
Handler Process:
- Input: None (no parameters required)
- Process: Generates a payload with the current date as
deactivatedAtand setslockedto true - Output: Result object containing
{ deactivatedAt: Date; locked: boolean } - Errors: Never returns an error (Result is always ok)
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
// Use to generate a deactivation payload for identity update:
const result = blocks.buildUpdateIdentityDeactivatedPayload();
if (result.isOk()) {
// result.value: { deactivatedAt: Date; locked: true }
// Use the payload for database update operations
}
buildUpdateIdentityActivatedPayload
Builds the payload for activating an identity by clearing deactivation and unlocking status.
Purpose: Creates a type-safe payload object for identity activation operations
Parameters: None
Returns: Result<{ deactivatedAt: null; locked: boolean }, never> - Result with activation payload
Handler Process:
- Input: None (no parameters required)
- Process: Generates a payload with
deactivatedAtset tonulland setslockedtofalse - Output: Result object containing
{ deactivatedAt: null; locked: boolean } - Errors: Never returns an error (Result is always ok)
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
// Use to generate an activation payload for identity update:
const result = blocks.buildUpdateIdentityActivatedPayload();
if (result.isOk()) {
// result.value: { deactivatedAt: null; locked: false }
// Use the payload for database update operations
}
isEmailVerified
Checks if a user's email is verified for authentication purposes.
Purpose: Validates email verification status for authentication flows
Parameters:
emailVerified: boolean- Boolean flag indicating if the user's email is verified
Returns: Result<boolean, AuthenticationForbiddenError> - Result containing true if verified, or AuthenticationForbiddenError if not
Handler Process:
- Input:
emailVerifiedboolean indicating if the user's email is verified - Process: Returns
ok(true)if verified, otherwise returns anAuthenticationForbiddenError - Output:
Result<boolean, AuthenticationForbiddenError>indicating verification status or error - Errors: Returns
AuthenticationForbiddenErrorif the email is not verified
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
const result = blocks.isEmailVerified(user.emailVerified);
if (result.isOk()) {
// Proceed with authenticated action
} else {
// Handle forbidden error (email not verified)
}
compareStringAgainstHash
Compares a plaintext string against a hashed string for authentication validation.
Purpose: Validates passwords and other sensitive data using bcrypt comparison
Parameters:
hashedString: string- The bcrypt hash to compare againststringToCompare: string- The plaintext string to validate
Returns: Promise<Result<boolean, AuthenticationInvalidInputError | AuthenticationUnexpectedError>>
Handler Process:
- Input:
hashedString(bcrypt hash),stringToCompare(plaintext string) - Process: Uses bcrypt to compare the plaintext string with the hash
- Output: Returns
ok(true)if the strings match,err(AuthenticationInvalidInputError)if not, orerr(AuthenticationUnexpectedError)on failure - Errors:
AuthenticationInvalidInputErrorif the input does not match,AuthenticationUnexpectedErrorif comparison fails
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
// Usage in authentication flow:
const result = await blocks.compareStringAgainstHash(identity.hashedPassword, inputPassword);
if (result.isOk()) {
// Password matches
} else {
// Handle error or invalid input
}
Token Management Blocks
generateOneTimeToken
Generates a one-time token for email verification with security context.
Purpose: Creates encrypted one-time tokens for email verification
Parameters:
authSecrets: { authEncSecret: string; authSignSecret: string }- Authentication secrets for encryption and signingjwtSignOptions: SignOptions- JWT signing configuration optionstokenVerification: TokenVerification- Security context for token validationidentityId: string- Unique identifier for the user identityemail?: string- Optional email address to include in token data
Returns: Promise<Result<string, AuthenticationUnexpectedError>>
Handler Process:
- Input: Auth secrets, JWT sign options, token verification context,
identityId, optionalemail - Process: Builds payload, signs and encrypts a one-time token using provided secrets
- Output: Encrypted token string on success
- Errors:
AuthenticationUnexpectedErrorif token build/sign/encrypt fails
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
const result = await blocks.generateOneTimeToken(
authSecrets,
jwtOptions,
verification,
"identity123",
"identity@example.com"
);
if (result.isOk()) {
const token = result.value;
// Store and send token for email verification
}
checkOneTimeToken
Validates and decrypts a one-time token for email verification or change operations.
Purpose: Validates and decrypts one-time tokens for verification
Parameters:
authSecrets: { authEncSecret: string; authSignSecret: string }- Authentication secrets containing encryption and signing keystarget: TargetType- Expected token target type (confirm-email, change-email, or reset_password)token: string- Encrypted one-time token string to validate
Returns: Promise<Result<JwtPayload, AuthenticationInvalidInputError | AuthenticationUnauthorizedError>>
Handler Process:
- Input: Authentication secrets, target type, and encrypted token string
- Process: Validates auth secrets, decrypts token, verifies JWT signature, and validates token structure
- Output: Returns decoded JWT payload with token information or error
- Errors: AuthenticationInvalidInputError if auth secrets invalid or token structure incorrect, AuthenticationUnauthorizedError if token verification fails
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
// Used in email verification flows:
const tokenResult = await blocks.checkOneTimeToken(
authSecrets,
'confirm-email',
encryptedToken
);
if (tokenResult.isOk()) {
const tokenInfo = tokenResult.value;
// Process verified token information
}
storeOneTimeToken
Stores a one-time token in the database for later verification.
Purpose: Stores encrypted tokens in database for verification
Parameters:
db: Collection- Database connection with onetimetokens collection accessoneTimeToken: string- Encrypted token string to store
Returns: Promise<Result<boolean, AuthenticationInvalidInputError | AuthenticationUnexpectedDbError>>
Handler Process:
- Input: Tokens collection and encrypted token string
- Process: Persists the token with metadata for later validation
- Output:
ok(true)on successful storage - Errors:
AuthenticationUnexpectedDbErroron DB failure;AuthenticationInvalidInputErroron invalid input
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
const result = await blocks.storeOneTimeToken(database, encryptedToken);
if (result.isOk()) {
// Token stored successfully, proceed with email sending
}
assertValidOneTimeTokenExists
Verifies that a one-time token exists in the database and is still valid.
Purpose: Validates token existence and validity in database
Parameters:
db: Collection- Database collection containing one-time tokenstoken: string- Token string to validate in the database
Returns: Promise<Result<boolean, AuthenticationForbiddenError | AuthenticationUnexpectedDbError>>
Handler Process:
- Input: Tokens collection and token string
- Process: Checks that a matching token exists and is not invalidated/expired
- Output:
ok(true)if valid token exists - Errors:
AuthenticationForbiddenErrorwhen missing/invalid;AuthenticationUnexpectedDbErroron DB failure
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
const result = await blocks.assertValidOneTimeTokenExists(
database.onetimetokens,
"encrypted-token-string"
);
if (result.isOk()) {
// Token is valid and exists, proceed with verification
}
invalidateOneTimeToken
Marks a one-time token as invalid in the database to prevent reuse.
Purpose: Invalidates tokens to prevent reuse after consumption
Parameters:
db: Collection- Database collection containing one-time tokenstoken: string- Token string to mark as invalid in the database
Returns: Promise<Result<boolean, AuthenticationInvalidInputError | AuthenticationUnexpectedDbError>>
Handler Process:
- Input: Tokens collection and token string
- Process: Marks token as invalid/used in the datastore to prevent reuse
- Output:
ok(true)on successful invalidation - Errors:
AuthenticationUnexpectedDbErroron DB failure;AuthenticationInvalidInputErroron invalid input
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
const result = await blocks.invalidateOneTimeToken(
database.onetimetokens,
"encrypted-token-string"
);
if (result.isOk()) {
// Token successfully invalidated, prevent reuse
}
softDeleteRefreshTokens
Soft-deletes refresh tokens for a given identity in the database.
Purpose: Invalidates all refresh tokens for an identity by setting deletion flag
Parameters:
db: Collection- MongoDB collection containing refresh tokens (currently identities collection)identityId: string- The ID of the identity whose refresh tokens should be soft-deleted
Returns: Promise<Result<boolean, AuthenticationInvalidInputError | AuthenticationUnexpectedDbError>> - Result indicating success or error
Handler Process:
- Input: MongoDB collection and identity ID
- Process: Sets
delFlgto 1 for all refresh tokens matching the identity that are not already deleted - Output: Result object indicating success (true) or error
- Errors: Returns
AuthenticationUnexpectedDbErroron database failure
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
// Used in the deactivation flow to invalidate all refresh tokens for an identity:
const result = await blocks.softDeleteRefreshTokens(db, identityId);
if (result.isOk()) {
// Refresh tokens were soft-deleted
}
checkToken
Validates and processes authentication tokens with security checks and database verification.
Purpose: Comprehensive token validation with security checks
Parameters:
db: Collection- MongoDB collection for token storage and verificationauthSecrets: AuthSecrets- Authentication secrets for JWT verificationrequest: Request- HTTP request object containing headers and metadatatoken: string- JWT token string to validatetarget?: string- Optional target context for token validation
Returns: Promise<Result<string | object, AuthenticationBlockError>>
Handler Process:
- Input: Logger, database collection, auth secrets, request object, token string, and optional target
- Process: Extracts request info, verifies JWT token, performs security checks, handles different token types
- Output: identityId for access tokens, token data for onetime tokens, or error with appropriate status
- Errors: InvalidToken (verification failed), UnexpectedDBError (database issues)
Steps:
- Extract request info (host, ip, fingerprint, userAgent)
- Build tokenVerification object with security context
- Decrypt and verify JWT token using authSecrets
- Check if token is user access token:
- If yes, perform security checks against tokenVerification
- If checks pass, return identityId
- If checks fail, return AuthenticationInvalidTokenError
- Check if token is one-time token:
- If yes, verify target matches expected target
- Query database for token validity (exists and not invalid)
- If valid, invalidate token in database and return token data
- If invalid or not found, return AuthenticationInvalidTokenError
- If token is neither access nor one-time, return AuthenticationUnauthorizedError
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
// Used in authentication handlers:
const result = await blocks.checkToken(
db.tokens,
authSecrets,
request,
'jwt-token-string',
'user-session'
);
if (result.isOk()) {
const tokenData = result.value;
// Process validated token data
}
Email Authentication Blocks
sendEmail
Sends an email using the provided mail service with optional one-time token for verification flows.
Purpose: Sends authentication emails with embedded tokens for verification and invitation flows
Parameters:
mailService: MailService- Mail service instance for sending emailssender: string- Sender email address (from)emailConfig: { bodyTemplate: string; subject: string; urlTemplate: string }- Email configuration object with body template, subject, and URL templateemail: string- Recipient email addressoneTimeToken?: string- Optional one-time token to include in the email body
Returns: Promise<Result<boolean, AuthenticationUnexpectedError>>
Handler Process:
- Input: Mail service instance, sender email, email configuration (body template, subject, URL template), recipient email, and optional one-time token
- Process: Generates the email body using the provided template and token, then sends the email via the mail service
- Output: Returns
ok(true)if the email was sent successfully, or an error if sending failed - Errors:
AuthenticationUnexpectedErrorif sending fails or the mail service returns a failure
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
// Used in verification or invitation flows:
const result = await blocks.sendEmail(
mailService,
'no-reply@example.com',
{
bodyTemplate: 'Please verify your email: {{url}}',
subject: 'Verify your email',
urlTemplate: 'https://example.com/verify?token={{token}}',
},
'identity@example.com',
'onetime-token-string'
);
if (result.isOk()) {
// Email sent successfully
}
getConfirmEmailTokenTarget
Retrieves the confirmation email token target constant for email verification.
Purpose: Returns confirmation email target constant
Parameters: None
Returns: Result<TARGET_CONFIRM_EMAIL, never>
Handler Process:
- Input: None
- Process: Returns a constant token target used for confirm-email flows
- Output:
TARGET_CONFIRM_EMAILwrapped in Result - Errors: Never (returns ok)
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
const result = blocks.getConfirmEmailTokenTarget();
if (result.isOk()) {
const target = result.value;
// Use target for token verification
}
getChangeEmailTokenTarget
Retrieves the change email token target constant for email change verification.
Purpose: Returns change email target constant
Parameters: None
Returns: Result<TARGET_CHANGE_EMAIL, never>
Handler Process:
- Input: None
- Process: Returns a constant token target used for change-email flows
- Output:
TARGET_CHANGE_EMAILwrapped in Result - Errors: Never (returns ok)
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
const result = blocks.getChangeEmailTokenTarget();
if (result.isOk()) {
const target = result.value;
// Use target for token verification in email change flow
}
getResetPasswordTokenTarget
Retrieves the reset password token target constant for password reset verification.
Purpose: Returns reset password target constant
Parameters: None
Returns: Result<TARGET_RESET_PASSWORD, never>
Handler Process:
- Input: None
- Process: Returns a constant token target used for reset-password flows
- Output:
TARGET_RESET_PASSWORDwrapped in Result - Errors: Never (returns ok)
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
const result = blocks.getResetPasswordTokenTarget();
if (result.isOk()) {
const target = result.value;
// Use target for token verification in password reset flow
}
getLoginTokenTarget
Retrieves the login token target constant for OAuth callback verification.
Purpose: Returns login target constant for OAuth authentication flows
Parameters: None
Returns: Result<typeof TARGET_LOGIN, never>
Handler Process:
- Input: None
- Process: Returns a constant token target used for OAuth login flows
- Output:
TARGET_LOGINwrapped in Result - Errors: Never (returns ok)
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
const result = blocks.getLoginTokenTarget();
if (result.isOk()) {
const target = result.value;
// Use target for token verification in login flow
}
Security Validation Blocks
getFingerprint
Extracts and validates the fingerprint header from request headers for security tracking.
Purpose: Extracts and validates security fingerprint from request headers
Parameters:
headers: Request['headers']- Express request headers containing fingerprint information
Returns: Result<string | undefined, AuthenticationUnprocessableEntityError>
Handler Process:
- Input: HTTP headers object
- Process: Reads and validates fingerprint header, returning string or undefined
- Output: Extracted fingerprint or error on malformed value
- Errors:
AuthenticationUnprocessableEntityErrorfor invalid/missing header format
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
const result = blocks.getFingerprint(request.headers);
if (result.isOk()) {
const fingerprint = result.value;
// Use fingerprint for token verification
}
extractTokenFromAuthorizationHeader
Extracts the Bearer token from the Authorization header for authentication.
Purpose: Parses and validates Authorization header to extract Bearer token
Parameters:
authorization: string- Authorization header string (e.g.,'Bearer <token>')
Returns: Result<string, AuthenticationBadRequestError | AuthenticationUnauthorizedError> - Result with extracted token or error details
Handler Process:
- Input: Authorization header string from HTTP request
- Process: Splits the header, checks for 'Bearer' scheme, and extracts the token
- Output: Returns the token string if valid, or error if missing
- Errors: AuthenticationBadRequestError if header is missing or format is incorrect, AuthenticationUnauthorizedError if token is not present
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
// Used in authentication middleware:
const tokenResult = blocks.extractTokenFromAuthorizationHeader(request.headers.authorization || '');
if (tokenResult.isOk()) {
const token = tokenResult.value;
// Use token for further authentication
}
buildTokenVerification
Constructs a token verification object from request data for security validation.
Purpose: Builds security context for token validation
Parameters:
request: Request- Express request object containing headers and IP informationtarget: TargetType- Token target type (confirm-email, change-email, or reset_password)fingerprint: string- Security fingerprint string for tracking
Returns: Result<TokenVerification, never>
Handler Process:
- Input: HTTP request object, target token type, and fingerprint
- Process: Extracts request metadata (host, ip, userAgent) and builds verification object
- Output: TokenVerification object for signing/verification flows
- Errors: Never (returns ok)
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
const result = blocks.buildTokenVerification(request, target, fingerprint);
if (result.isOk()) {
const verification = result.value;
// Use verification object for token generation
}
buildJwtOptions
Builds JWT options object with expiration configuration for token generation.
Purpose: Creates JWT signing options with configurable expiration time
Parameters:
expiresIn: StringValue- Token expiration time as string value (e.g., "1h", "7d", "30m")
Returns: Result<Record<string, unknown>, never>
Handler Process:
- Input: Expiration time string value
- Process: Creates options object with expiresIn field, filtering out falsy values
- Output: JWT options object for token signing
- Errors: Never (returns ok)
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
// Build JWT options for 1 hour expiration
const options = blocks.buildJwtOptions("1h");
if (options.isOk()) {
// Result: { expiresIn: "1h" }
console.log(options.value);
}
// Use in JWT signing
const token = jwt.sign(payload, secret, options.value);
buildUpdateIdentityEmailAndEmailVerifiedPayload
Builds the payload to update identity email and set emailVerified to true.
Purpose: Creates update payload for email verification
Parameters:
email: string- New email address to assign to the identity
Returns: Result<{ email: string; emailVerified: boolean }, never>
Handler Process:
- Input: Email string
- Process: Produces update payload setting
emailandemailVerified: true - Output: Payload object wrapped in Result
- Errors: Never (returns ok)
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
const result = blocks.buildUpdateIdentityEmailAndEmailVerifiedPayload("user@example.com");
if (result.isOk()) {
const updatePayload = result.value;
// Use updatePayload to update the identity in the database
}
normalizeEmptyBody
Normalizes empty response body for API handlers.
Purpose: Standardizes empty API responses
Parameters: None
Returns: object
Handler Process:
- Input: None
- Process: Returns an empty object for consistent empty responses
- Output:
{} - Errors: None
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
const emptyBody = blocks.normalizeEmptyBody();
// Returns {} for consistent empty responses
Multi-Factor Authentication (MFA) Blocks
createMfaCode
Generates a secure MFA code with specified length for authentication.
Purpose: Creates cryptographically secure numeric codes for multi-factor authentication
Parameters:
length: number- Number of digits for the MFA code
Returns: Promise<Result<string, MfaUnexpectedError>>
Handler Process:
- Input: Numeric length parameter for code generation
- Process: Generates random integer, converts to string, and pads with leading zeros
- Output: Zero-padded numeric string of specified length
- Errors:
MfaUnexpectedErrorif random number generation fails
Key Features:
- Cryptographically secure random number generation
- Zero-padded for consistent length
- Configurable code length
- Suitable for email/SMS verification codes
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
// Generate 6-digit MFA code:
const result = await blocks.createMfaCode(6);
if (result.isOk()) {
console.log(result.value); // "012345" (example with leading zero)
}
// Generate 4-digit MFA code:
const shortCode = await blocks.createMfaCode(4);
// Output: "0123", "9876", etc.
createMfaToken
Creates MFA challenge token with expiration and stores in database.
Purpose: Generates and stores secure one-time tokens for MFA challenge verification
Parameters:
onetimetokenCollection: Collection- MongoDB collection for storing MFA challenge tokensauthSecrets: AuthSecrets- Authentication secrets for token generationexpireTime: StringValue- Token expiration duration as string value (e.g., '15m', '10m')fingerprint: string- Device/browser fingerprint for security trackingidentityId: string- Unique identifier of the user requesting MFA challengedestinationEmail: string- Email address where MFA code will be sentcode: string- Generated MFA verification code
Returns: Promise<Result<string, MfaUnexpectedError>>
Handler Process:
- Input: Database collection, auth secrets, expiration time, user context, and MFA code
- Process: Generates secure onetime token with MFA challenge data and stores in database
- Output: Encrypted token string for the created MFA challenge
- Errors:
MfaUnexpectedErrorif token generation or database storage fails
Key Features:
- Secure token generation with JWT encryption
- Configurable expiration time
- Fingerprint tracking for device verification
- Target set to
'mfa-challenge'for identification - Automatic base entity field generation (id, createdAt, updatedAt)
- Stores MFA code, destination email, and identity ID in token payload
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
// Create MFA challenge for user authentication:
const result = await blocks.createMfaToken(
db.collection('onetimetokens'),
authSecrets,
'15m', // 15 minute expiration
'device-fingerprint-123',
'user-identity-456',
'user@example.com',
'123456'
);
if (result.isOk()) {
const encryptedToken = result.value;
// Token can be used to verify MFA code submission
console.log('MFA token created:', encryptedToken);
}
sendMfaCode
Sends MFA code to recipient via email using mail service.
Purpose: Delivers MFA verification codes to users via email for authentication
Parameters:
mailService: MailService- Email service for sending MFA codessubject: string- Email subject line for the MFA code messagesender: string- Email address of the senderbodyTemplate: string- HTML template for email body generationdestinationEmail: string- Email address of the MFA code recipientcode: string- MFA code to include in the email
Returns: Promise<Result<true, MfaUnexpectedError>>
Handler Process:
- Input: Mail service, email subject, sender, body template, destination email, and MFA code
- Process: Generates HTML email body with code, sends via mail service
- Output: Result with
trueindicating email send success or error - Errors:
MfaSendMailFailedErrorif email sending fails;MfaUnexpectedErrorfor unexpected failures
Key Features:
- Template-based email generation with
${code}placeholder - Automatic HTML body generation
- Mail service integration
- Success/failure tracking
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
// Send MFA code email:
const sendResult = await blocks.sendMfaCode(
mailService,
'Your MFA Code',
'noreply@company.com',
'Your verification code is: ${code}',
'user@example.com',
'123456'
);
if (sendResult.isOk() && sendResult.value) {
console.log('MFA code sent successfully');
}
getMfaChallengeTokenTarget
Retrieves MFA challenge token target constant for authentication flow.
Purpose: Returns the predefined MFA challenge target constant for token identification
Parameters: None
Returns: Result<typeof TARGET_MFA_CHALLENGE, never>
Handler Process:
- Input: No parameters required
- Process: Returns the predefined MFA challenge target constant
- Output: Success result containing
TARGET_MFA_CHALLENGEvalue - Errors: Never fails (never error type)
Key Features:
- Returns constant value
'mfa-challenge' - Used for token target identification
- Never fails (always returns success)
- Useful for token verification flows
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
// Get MFA challenge target for token generation:
const targetResult = blocks.getMfaChallengeTokenTarget();
if (targetResult.isOk()) {
const target = targetResult.value; // 'mfa-challenge'
// Use target for token verification
}
verifyMfaCode
Verifies MFA code by comparing two provided codes for authentication.
Purpose: Validates MFA code submission by comparing user input against stored code
Parameters:
code1: string- First MFA code to verify (typically user input)code2: string- Second MFA code to compare against (typically stored code)
Returns: Promise<Result<true, MfaInvalidCodeError | MfaUnexpectedError>>
Handler Process:
- Input: Two MFA code strings to compare
- Process: Compares code1 and code2 for exact match
- Output: Success result with
trueif codes match, error if they don't - Errors:
MfaInvalidCodeErrorfor mismatched codes,MfaUnexpectedErrorfor system failures
Key Features:
- Exact string comparison for security
- Validates both codes have values
- Returns descriptive error for invalid codes
- Simple synchronous verification
- Case-sensitive comparison
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
// Verify MFA codes match:
const result = blocks.verifyMfaCode(userInputCode, storedCode);
if (result.isOk()) {
// MFA verification successful
console.log('Code verified successfully');
} else {
// Handle verification error
console.error(result.error.message);
}
// Typical usage in route handler:
const storedCode = tokenInfo.data.code;
const userCode = requestBody.code;
const verification = blocks.verifyMfaCode(userCode, storedCode);
MFA Error Classes
MfaInvalidCodeError
MFA invalid code error for incorrect MFA code submissions.
Purpose: Specific error for MFA code verification failures when codes don't match
Error hierarchy:
- Base:
AuthenticationBlockError - Usage: Thrown when user-provided MFA code doesn't match the stored code
Example Usage:
// Thrown when codes don't match:
throw new MfaInvalidCodeError('Invalid MFA code provided.');
// Return as Result error:
return err(new MfaInvalidCodeError('Invalid MFA code provided.'));
MfaUnexpectedError
MFA unexpected error for handling general MFA operation failures.
Purpose: Represents unexpected errors during MFA code generation, token creation, or email sending
Error hierarchy:
- Base:
AuthenticationBlockError - Usage: Thrown when MFA operations fail unexpectedly
Example Usage:
// Thrown during MFA operations:
throw new MfaUnexpectedError('Failed to create MFA code.');
// Return as Result error:
return err(new MfaUnexpectedError('Failed to send MFA code.'));
MfaSendMailFailedError
MFA send mail failed error for email delivery failures.
Purpose: Specific error for MFA email sending failures
Error hierarchy:
- Base:
AuthenticationBlockError - Usage: Thrown when mail service fails to send MFA code email
Example Usage:
// Thrown when email fails:
throw new MfaSendMailFailedError('Failed to send MFA code.');
MFA Constants
TARGET_MFA_CHALLENGE
Target type constant for MFA challenge tokens.
Value: 'mfa-challenge'
Purpose: Identifies tokens as MFA challenge tokens in the token management system
Usage:
import { TARGET_MFA_CHALLENGE } from '@nodeblocks/backend-sdk';
// Used in token verification:
if (token.target === TARGET_MFA_CHALLENGE) {
// Handle MFA challenge verification
}
🔗 Related Documentation
- Authentication Overview - Authentication domain overview