Skip to main content
Version: 0.4.2 (Previous)

🔐 Authentication Service

Testing Status

The Authentication Service provides a complete authentication system for identity registration, login, logout, and token management with JWT-based security and cookie support.


🚀 Quickstart

import express from 'express';
import { MongoClient } from 'mongodb';
import {
services,
middlewares,
types
} from '@nodeblocks/backend-sdk';

const client = new MongoClient('mongodb://localhost:27017').db('dev');

express()
.use(
services.authService(
{
identity: client.collection('identity'),
onetimetoken: client.collection('onetimetoken'),
invitations: client.collection('invitations'),
},
{
authSecrets: {
authEncSecret: 'your-encryption-secret',
authSignSecret: 'your-signing-secret',
},
maxFailedLoginAttempts: 5,
accessTokenExpireTime: '2h',
refreshTokenExpireTime: '2d',
verifyEmailConfig: {
enabled: true,
sender: 'noreply@example.com',
mailService: {
sendMail: async (mailData: types.MailData) => {
console.log(mailData);
return true;
},
},
emailConfig: {
bodyTemplate: 'Hello {{email}}',
subject: 'Welcome to our app',
urlTemplate: 'https://example.com/verify-email?token={{token}}',
},
},
invitation: {
enabled: true,
emailConfig: {
bodyTemplate: '<h1>You\'re invited!</h1><p>Click <a href="${url}">here</a> to accept the invitation.</p>',
subject: 'You\'re invited to join our organization',
urlTemplate: 'https://yourapp.com/invitations/accept?token=${token}&email=${email}',
sender: 'invites@yourapp.com'
},
target: 'invitation'
}
},
{
sendMail: async (mailData: types.MailData) => {
console.log(mailData);
return true;
},
}
)
)
.use(middlewares.nodeBlocksErrorMiddleware())
.listen(8089, () => console.log('Server running'));

📋 Endpoint Summary

MethodPathDescription
Authentication Endpoints
POST/auth/registerRegister a new identity account
POST/auth/loginAuthenticate identity and receive tokens
POST/auth/logoutLogout and invalidate tokens
Email Verification Endpoints
POST/auth/:identityId/send-verification-emailSend email verification to identity
POST/auth/confirm-emailConfirm email with verification token
Invitation Endpoints
POST/invitationsCreate a new invitation
GET/invitationsList invitations with optional filtering
GET/invitations/:invitationIdGet invitation by ID
DELETE/invitations/:invitationIdDelete invitation

🗄️ Entity Schema

The authentication service manages user identities with the following schema:

Identity Entity

{
"id": "string",
"email": "string",
"password": "string",
"attempts": "number",
"locked": "boolean",
"createdAt": "string",
"updatedAt": "string",
"typeId": "string"
}

Field Details

FieldTypeAuto-GeneratedRequiredDescription
idstringUnique identifier (UUID)
emailstringIdentity's email address
passwordstringHashed password
attemptsnumberFailed login attempts counter
lockedbooleanAccount lock status
createdAtstringCreation timestamp
updatedAtstringLast update timestamp
typeIdstringIdentity role identifier (e.g., "100" for admin, "001" for user)

Additional Field Details:

  • attempts: Tracks the number of consecutive failed login attempts for security purposes. After a certain threshold (configurable), the account will be automatically locked.

  • locked: Indicates whether the account is currently locked due to too many failed login attempts or administrative action. A locked account cannot be used for authentication until unlocked.

  • typeId: A string identifier that determines the identity's role and permissions in the system. Adjustable for each service. Common values might include:

    • "100": Administrator with full system access
    • "001": Standard user with basic permissions
    • "000": Guest user with lowest permissions
    • Additional custom roles can be defined as needed

Invitation Entity

The authentication service also manages invitations with the following schema:

{
"id": "string",
"email": "string",
"fromUserId": "string",
"orgId": "string",
"role": "string",
"status": "string",
"createdAt": "string",
"updatedAt": "string"
}

Invitation Field Details

FieldTypeAuto-GeneratedRequiredDescription
idstringUnique identifier (UUID)
emailstringEmail address of the invitee
fromUserIdstringID of the identity sending the invitation
orgIdstringID of the organization to invite to
rolestringRole for the invitee in the organization
statusstringInvitation status (e.g., "pending", "accepted")
createdAtstringCreation timestamp
updatedAtstringLast update timestamp

🔐 Authentication Headers

For protected endpoints, include the following headers:

Authorization: Bearer <access_token>
x-nb-fingerprint: <device_fingerprint>

⚠️ Important: The x-nb-fingerprint header is required for all authenticated requests if fingerprint was specified during authorization. Without it, requests will return 401 Unauthorized.


🔧 API Endpoints

1. Register Identity

Register a new identity account with email and password.

Request:

  • Method: POST
  • Path: /auth/register
  • Headers:
    • Content-Type: application/json
  • Authorization: None required

Request Body:

FieldTypeRequiredDescription
emailstring✅*Identity's email address
passwordstringIdentity's password
tokenstring✅*Invitation token

*Either email OR token is required, but not both.

Response Body:

FieldTypeDescription
No response body-Registration endpoint returns no response body on success

Validation:

  • Schema Validation: Enforced automatically (email and password or token and password required)
  • Route Validators: None

Example Request:

curl -X POST {{host}}/auth/register \
-H "Content-Type: application/json" \
-d '{
"email": "user@example.com",
"password": "securepassword123"
}'

Example Request with Token (for existing users):

curl -X POST {{host}}/auth/register \
-H "Content-Type: application/json" \
-d '{
"token": "invitation-token",
"password": "securepassword123"
}'

Success Response:

HTTP/1.1 201 Created
Content-Type: application/json

Error Responses:

When email already exists:

HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json

{
"error": {
"message": "unable to register \"user@example.com\""
}
}

When request body is missing required fields:

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
"error": {
"message": "Validation Error",
"data": [
"request body must have required property 'email'",
"request body must have required property 'token'",
"request body must match exactly one schema in oneOf"
]
}
}

2. Login Identity

Authenticate credentials and receive access and refresh tokens.

Request:

  • Method: POST
  • Path: /auth/login
  • Headers:
    • Content-Type: application/json
  • Authorization: None required

Request Body:

FieldTypeRequiredDescription
emailstringIdentity's email address
passwordstringIdentity's password
fingerprintstringDevice fingerprint for security

Response Body:

FieldTypeDescription
accessTokenstringJWT access token for API authentication
idstringIdentity's unique identifier
refreshTokenstringJWT refresh token for obtaining new access tokens

Validation:

  • Schema Validation: Enforced automatically (email, password required)
  • Route Validators: None

Example Request:

curl -X POST {{host}}/auth/login \
-H "Content-Type: application/json" \
-d '{
"email": "user@example.com",
"password": "securepassword123",
"fingerprint": "device-fingerprint"
}'

Success Response:

HTTP/1.1 200 OK
Content-Type: application/json
Access-Control-Allow-Credentials: true
Set-Cookie: accessToken=...; Path=/
Set-Cookie: refreshToken=...; Path=/

{
"accessToken": "c911c0dd107f8d7e92c0608aa149d041:dee2...",
"id": "0b3839a6-92b4-4044-a13b-ed834a105646",
"refreshToken": "9f0cad0da1ceec15c01de729a2359236:2acc8ee1b57fd971473..."
}

Error Responses:

When credentials are invalid:

HTTP/1.1 401 Unauthorized
Content-Type: application/json

{
"error": {
"message": "wrong credentials provided"
}
}

3. Logout Identity

Logout identity and invalidate refresh tokens.

Request:

  • Method: POST
  • Path: /auth/logout
  • Headers:
    • Authorization: Bearer <token>
    • x-nb-fingerprint: <device-fingerprint>
  • Authorization: Bearer token required

Request Body: No body required. Uses access token from Authorization header.

Response Body:

FieldTypeDescription
No response body-Logout endpoint returns no response body on success

Validation:

  • Schema Validation: None
  • Route Validators: verifyAuthentication(getBearerTokenInfo) - Validates bearer token authentication

Example Request:

curl -X POST {{host}}/auth/logout \
-H "Authorization: Bearer <access-token>"

Success Response:

HTTP/1.1 204 No Content
Content-Type: application/json

Error Responses:

When refresh token invalidation operation fails:

HTTP/1.1 500 Internal Server Error
Content-Type: application/json

{
"error": {
"message": "failed to delete refresh token"
}
}

4. Send Verification Email

Send an email verification link to a identity's email address.

Request:

  • Method: POST
  • Path: /auth/:identityId/send-verification-email
  • Headers:
    • Authorization: Bearer <token>
    • x-nb-fingerprint: <device-fingerprint>
  • Authorization: Bearer token required (admin or self access)

Path Parameters:

FieldTypeRequiredDescription
identityIdstringIdentity's unique identifier

Request Body:

FieldTypeRequiredDescription
fingerprintstringDevice fingerprint for security

Response Body:

FieldTypeDescription
No response body-Send verification email endpoint returns no response body on success

Validation:

  • Schema Validation: Enforced automatically
  • Route Validators:
    • verifyAuthentication(getBearerTokenInfo) - Validates bearer token authentication
    • validateResourceAccess(['admin', 'self'], getBearerTokenInfo) - Ensures identity has admin role or is self

Example Request:

curl -X POST {{host}}/auth/identity-12345/send-verification-email \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <access-token>" \
-d '{
"fingerprint": "device-fingerprint"
}'

Success Response:

HTTP/1.1 204 No Content
Content-Type: application/json

Error Responses:

When email verification is not enabled:

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
"error": {
"message": "verification email feature not enabled"
}
}

When mail service is missing:

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
"error": {
"message": "verification email feature requires a mail service to be provided"
}
}

When email configuration is missing:

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
"error": {
"message": "verifyEmailConfig requires emailConfig with fields bodyTemplate, subject, urlTemplate"
}
}

When email sending fails:

HTTP/1.1 500 Internal Server Error
Content-Type: application/json

{
"error": {
"message": "Failed to send verification email"
}
}

5. Confirm Email

Confirm a identity's email address using a verification token.

Request:

  • Method: POST
  • Path: /auth/confirm-email
  • Headers:
    • Content-Type: application/json
  • Authorization: None required

Request Body:

FieldTypeRequiredDescription
tokenstringVerification token from email

Response Body:

FieldTypeDescription
No response body-Confirm email endpoint returns no response body on success

Validation:

  • Schema Validation: Enforced automatically (token required)
  • Route Validators: None

Example Request:

curl -X POST {{host}}/auth/confirm-email \
-H "Content-Type: application/json" \
-d '{
"token": "jwt-verification-token"
}'

Success Response:

HTTP/1.1 204 No Content
Content-Type: application/json

Error Responses:

When token is invalid:

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
"error": {
"message": "Unable to verify token"
}
}

6. Create Invitation

Create a new invitation for an entity to join a service.

Request:

  • Method: POST
  • Path: /invitations
  • Headers:
    • Content-Type: application/json
    • Authorization: Bearer <token>
    • x-nb-fingerprint: <device-fingerprint>
  • Authorization: Bearer token required (admin access)

Request Body:

FieldTypeRequiredDescription
emailstringEmail address of the invitee
fromUserIdstringID of the identity sending the invitation
orgIdstringID of the organization to invite to
rolestringRole for the invitee in the organization

Response Body:

FieldTypeDescription
invitationIdstringUnique identifier of the created invitation

Validation:

  • Schema Validation: Enforced automatically (email, fromUserId required)
  • Route Validators:
    • verifyAuthentication(getBearerTokenInfo) - Validates bearer token authentication
    • validateResourceAccess(['admin'], getBearerTokenInfo) - Ensures identity has admin role

Example Request:

curl -X POST {{host}}/invitations \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <access-token>" \
-d '{
"email": "newuser@example.com",
"fromUserId": "392157b1-dc7a-4935-a6f9-a2d333b910ea",
"orgId": "org123",
"role": "member"
}'

Success Response:

HTTP/1.1 201 Created
Content-Type: application/json

{
"invitationId": "62564a60-e720-4907-bb85-3afaa2729e0d"
}

Error Responses:

When request body is missing required fields:

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
"error": {
"message": "Validation Error",
"data": [
"request body must have required property 'email'"
]
}
}

When request body is missing fromUserId:

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
"error": {
"message": "Validation Error",
"data": [
"request body must have required property 'fromUserId'"
]
}
}

When email format is invalid:

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
"error": {
"message": "Validation Error",
"data": [
"request body must match format \"email\""
]
}
}

When request contains extra properties:

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
"error": {
"message": "Validation Error",
"data": [
"request body must NOT have additional properties"
]
}
}

When invitation creation fails:

HTTP/1.1 500 Internal Server Error
Content-Type: application/json

{
"error": {
"message": "Failed to create invitation"
}
}

7. List Invitations

Retrieve all invitations with optional filtering and pagination.

Request:

  • Method: GET
  • Path: /invitations
  • Headers:
    • Authorization: Bearer <token>
    • x-nb-fingerprint: <device-fingerprint>
  • Authorization: Bearer token required (admin access)

Query Parameters:

FieldTypeRequiredDescription
emailstringFilter by invitee email address
fromUserIdstringFilter by inviter identity ID
orgIdstringFilter by organization ID
rolestringFilter by role
pagenumberPage number for pagination
limitnumberNumber of items per page

Response Body:

FieldTypeDescription
emailstringEmail address of the invitee
fromUserIdstringID of the identity sending the invitation
orgIdstringID of the organization to invite to
rolestringRole for the invitee in the organization
statusstringInvitation status (e.g., "pending", "accepted")
createdAtstringCreation timestamp
idstringUnique invitation identifier
updatedAtstringLast update timestamp

Validation:

  • Schema Validation: Enforced automatically
  • Route Validators:
    • verifyAuthentication(getBearerTokenInfo) - Validates bearer token authentication
    • validateResourceAccess(['admin'], getBearerTokenInfo) - Ensures identity has admin role

Example Request:

curl -X GET "{{host}}/invitations" \
-H "Authorization: Bearer <access-token>"

Success Response:

HTTP/1.1 200 OK
Content-Type: application/json

[
{
"email": "newuser@example.com",
"fromUserId": "392157b1-dc7a-4935-a6f9-a2d333b910ea",
"orgId": "org123",
"role": "member",
"status": "pending",
"createdAt": "2025-07-04T06:29:32.905Z",
"id": "62564a60-e720-4907-bb85-3afaa2729e0d",
"updatedAt": "2025-07-04T06:29:32.905Z"
}
]

Empty Response:

HTTP/1.1 200 OK
Content-Type: application/json

[]

8. Get Invitation by ID

Retrieve a specific invitation by its unique identifier.

Request:

  • Method: GET
  • Path: /invitations/:invitationId
  • Headers:
    • Authorization: Bearer <token>
    • x-nb-fingerprint: <device-fingerprint>
  • Authorization: Bearer token required (admin access)

Path Parameters:

FieldTypeRequiredDescription
invitationIdstringUnique invitation identifier

Validation:

  • Schema Validation: Enforced automatically
  • Route Validators:
    • verifyAuthentication(getBearerTokenInfo) - Validates bearer token authentication
    • validateResourceAccess(['admin'], getBearerTokenInfo) - Ensures identity has admin role

Example Request:

curl -X GET {{host}}/invitations/62564a60-e720-4907-bb85-3afaa2729e0d \
-H "Authorization: Bearer <access-token>"

Success Response:

HTTP/1.1 200 OK
Content-Type: application/json

{
"email": "newuser@example.com",
"fromUserId": "392157b1-dc7a-4935-a6f9-a2d333b910ea",
"orgId": "org123",
"role": "member",
"status": "pending",
"createdAt": "2025-07-04T06:29:32.905Z",
"id": "62564a60-e720-4907-bb85-3afaa2729e0d",
"updatedAt": "2025-07-04T06:29:32.905Z"
}

Error Responses:

When invitation is not found:

HTTP/1.1 404 Not Found
Content-Type: application/json

{
"error": {
"message": "Invitation not found"
}
}

9. Delete Invitation

Delete a specific invitation by its unique identifier.

Request:

  • Method: DELETE
  • Path: /invitations/:invitationId
  • Headers:
    • Authorization: Bearer <token>
    • x-nb-fingerprint: <device-fingerprint>
  • Authorization: Bearer token required (admin access)

Path Parameters:

FieldTypeRequiredDescription
invitationIdstringUnique invitation identifier

Validation:

  • Schema Validation: Enforced automatically
  • Route Validators:
    • verifyAuthentication(getBearerTokenInfo) - Validates bearer token authentication
    • validateResourceAccess(['admin'], getBearerTokenInfo) - Ensures identity has admin role

Example Request:

curl -X DELETE {{host}}/invitations/62564a60-e720-4907-bb85-3afaa2729e0d \
-H "Authorization: Bearer <access-token>"

Success Response:

HTTP/1.1 204 OK
Content-Type: application/json

Error Responses:

When invitation is not found:

HTTP/1.1 404 Not Found
Content-Type: application/json

{
"error": {
"message": "Invitation not found"
}
}

🔒 Security Features

Account Protection

  • Failed Login Attempts: Tracks failed login attempts
  • Account Locking: Automatically locks accounts after 5 failed attempts (configurable)
  • Password Hashing: Passwords are securely hashed
  • Token Security: JWT tokens include device fingerprinting and IP validation

Token Management

  • Access Tokens: Short-lived tokens for API access
  • Refresh Tokens: Long-lived tokens for token renewal
  • Token Verification: Validates domain, fingerprint, IP, and user agent
  • Secure Cookies: HTTP-only, secure cookies for token storage

Authentication Methods

Bearer Token Authentication

// Use in Authorization header
Authorization: Bearer <access-token>
// Tokens automatically sent with requests

⚙️ Configuration Options

Service Configuration

interface AuthServiceConfig {
authSecrets?: {
authEncSecret: string; // JWT encryption secret
authSignSecret: string; // JWT signing secret
};
maxFailedLoginAttempts?: number; // Default: 5
cookieOpts?: {
domain?: string;
maxAge?: number;
path?: string;
sameSite?: 'strict' | 'lax' | 'none';
};
jwtOpts?: {
jwtSignOptions?: SignOptions;
stateful?: boolean;
};
accessTokenExpireTime?: string; // Default: '2h'
onetimeTokenExpireTime?: string; // Default: '2h'
refreshTokenExpireTime?: string; // Default: '2d'
verifyEmailConfig?: {
enabled: boolean; // Enable email verification feature
emailConfig?: {
bodyTemplate: string; // Email body template with {{email}} and {{token}} placeholders
subject: string; // Email subject line
urlTemplate: string; // URL template with {{token}} placeholder
};
mailService?: MailService; // Mail service implementation
sender: string; // Sender email address
};
invitation?: {
enabled: boolean; // Enable invitation feature
emailConfig?: {
bodyTemplate: string; // Email body template with {{email}} and {{token}} placeholders
subject: string; // Email subject line
urlTemplate: string; // URL template with {{token}} placeholder
sender: string; // Sender email address
};
target: string; // Token target for invitation validation
};
}

Configuration Details

The authentication service configuration is organized into logical groups for security, cookies, JWT settings, invitations and email verificartion

🔐 Security Settings

authSecrets - JWT token security secrets

  • Type: { authEncSecret: string; authSignSecret: string }
  • Description: Secret keys for JWT encryption and signing
  • Default: { authEncSecret: '', authSignSecret: '' }
  • Required: Yes (for production)
  • Child Properties:
    • authEncSecret: Secret key for JWT payload encryption
    • authSignSecret: Secret key for JWT signature verification

maxFailedLoginAttempts - Account lockout threshold

  • Type: number
  • Description: Maximum failed login attempts before account lockout
  • Default: 5
  • Behavior: Locks account after threshold is exceeded, requires manual unlock

cookieOpts - HTTP cookie configuration

  • Type: { domain?: string; maxAge?: string | number; path?: string; sameSite?: 'strict' | 'lax' | 'none' }
  • Description: Controls how authentication tokens are stored in browser cookies
  • Default: undefined (uses token expiration)
  • Child Properties:
    • domain: Cookie domain scope
      • Type: string
      • Description: Controls cookie scope across subdomains
      • Example: '.example.com' for all subdomains
    • maxAge: Cookie expiration time
      • Type: string | number
      • Description: Sets cookie expiration time in ms
    • path: Cookie path scope
      • Type: string
      • Description: Restricts cookie to specific URL paths
      • Default: '/' (entire domain)
      • Example: '/api' for API-only cookies
    • sameSite: CSRF protection level
      • Type: 'strict' | 'lax' | 'none'
      • Description: Controls when cookies are sent in cross-site requests
      • Values:
        • 'strict': Cookies only sent in same-site requests (most secure)
        • 'lax': Cookies sent in cross-site navigation (balanced)
        • 'none': Cookies sent in all cross-site requests (requires secure: true)

🔑 JWT Settings

jwtOpts - JWT token generation and validation options

  • Type: { jwtSignOptions?: SignOptions; stateful?: boolean }
  • Description: Customize JWT signing and validation behavior
  • Default: undefined (uses standard JWT settings)
  • Child Properties:
    • jwtSignOptions: JWT signing configuration
      • Type: SignOptions (from jsonwebtoken package)
      • Description: Customize JWT signing algorithm and parameters
      • Default: Standard JWT signing
    • stateful: Server-side token validation (this property requires confirmation)
      • Type: boolean
      • Description: Enable server-side token validation for enhanced security
      • Default: false (stateless)
      • Use Case: Token revocation and enhanced security

⏰ Token Expiration Times

accessTokenExpireTime - Access token lifetime

  • Type: string (ms package format)
  • Description: Short-lived token for API access
  • Default: undefined
  • Format: ms package format ('30m', '1h', '2h')
  • Security: Minimizes exposure window

refreshTokenExpireTime - Refresh token lifetime

  • Type: string (ms package format)
  • Description: Long-lived token for obtaining new access tokens
  • Default: undefined
  • Format: ms package format ('1d', '7d', '30d')
  • Security: Stored in secure HTTP-only cookies

onetimeTokenExpireTime - One-time token lifetime

  • Type: string (ms package format)
  • Description: Temporary token for password reset, email verification
  • Default: undefined
  • Format: ms package format ('15m', '1h', '2h')
  • Security: Single-use tokens with short lifespan

📧 Email Verification Settings

verifyEmailConfig - Email verification configuration

  • Type: { enabled: boolean; emailConfig?: EmailConfig; mailService?: MailService; sender: string }
  • Description: Controls email verification feature and email templates
  • Default: undefined (email verification disabled)
  • Child Properties:
    • enabled: Enable email verification feature
      • Type: boolean
      • Description: Master switch for email verification functionality
      • Default: false
      • Required: Yes (when using email verification)
    • emailConfig: Email template configuration
      • Type: { bodyTemplate: string; subject: string; urlTemplate: string }
      • Description: Templates for verification emails
      • Required: Yes (when enabled)
      • Child Properties:
        • bodyTemplate: HTML email body template
          • Type: string
          • Description: HTML template for email body with {{url}}, {{email}} and {{token}} placeholders. Will use urlTemplate value for url
          • Example: "Hello {{email}}, click <a href="{{url}}">here</a> to verify your email."
        • subject: Email subject line
          • Type: string
          • Description: Subject line for verification emails
          • Example: "Verify your email address"
        • urlTemplate: URL template for verification link
          • Type: string
          • Description: URL template with {{email}} and {{token}} placeholders
          • Example: "https://yourapp.com/verify?token={{token}}"
    • mailService: Mail service implementation
      • Type: MailService
      • Description: Mail service for sending verification emails
      • Required: No (can be provided as third parameter to service)
      • Example: Custom mail service implementation
    • sender: Sender email address
      • Type: string
      • Description: Email address that verification emails will be sent from
      • Required: Yes (when enabled)
      • Example: "noreply@yourapp.com"

📨 Invitation Settings

invitation - Invitation management configuration

  • Type: { enabled: boolean; emailConfig?: InvitationEmailConfig; target: string }
  • Description: Controls invitation feature and email templates
  • Default: undefined (invitation feature disabled)
  • Child Properties:
    • enabled: Enable invitation feature
      • Type: boolean
      • Description: Master switch for invitation functionality
      • Default: false
      • Required: Yes (when using invitation feature)
    • emailConfig: Invitation email template configuration
      • Type: { bodyTemplate: string; subject: string; urlTemplate: string; sender: string }
      • Description: Templates for invitation emails
      • Required: Yes (when enabled)
      • Child Properties:
        • bodyTemplate: HTML email body template
          • Type: string
          • Description: HTML template for email body with {{url}}, {{token}} and {{email}} placeholders. Will use urlTemplate value for url
          • Example: "<h1>You're invited!</h1><p>Click <a href='{{url}}'>here</a> to accept the invitation.</p>"
        • subject: Email subject line
          • Type: string
          • Description: Subject line for invitation emails
          • Example: "You're invited to join our organization"
        • urlTemplate: URL template for invitation link
          • Type: string
          • Description: URL template with {{token}} and {{email}} placeholders
          • Example: "https://yourapp.com/invitations/accept?token={{token}}&email={{email}}"
        • sender: Sender email address
          • Type: string
          • Description: Email address that invitation emails will be sent from
          • Required: Yes (when enabled)
          • Example: "invites@yourapp.com"
    • target: Token target for invitation validation
      • Type: string
      • Description: Target identifier for invitation token validation
      • Default: "invitation"
      • Required: No
      • Example: "invitation"

Example Configuration

const authConfig = {
authSecrets: {
authEncSecret: process.env.AUTH_ENC_SECRET || 'your-enc-secret',
authSignSecret: process.env.AUTH_SIGN_SECRET || 'your-sign-secret'
},
maxFailedLoginAttempts: 3,
cookieOpts: {
secure: true,
sameSite: 'strict',
maxAge: 2 * 24 * 60 * 60 * 1000 // 2 days
},
accessTokenExpireTime: '1h',
refreshTokenExpireTime: '7d',
onetimeTokenExpireTime: '30m',
verifyEmailConfig: {
enabled: true,
emailConfig: {
bodyTemplate: 'Hello {{email}}, click <a href="{{url}}">here</a> to verify your email address.',
subject: 'Verify your email address',
urlTemplate: 'https://yourapp.com/verify?token={{token}}'
},
sender: 'noreply@yourapp.com'
},
invitation: {
enabled: true,
emailConfig: {
bodyTemplate: '<h1>You\'re invited!</h1><p>Click <a href="{{url}}">here</a> to accept the invitation.</p>',
subject: 'You\'re invited to join our organization',
urlTemplate: 'https://yourapp.com/invitations/accept?token={{token}}&email={{email}}',
sender: 'invites@yourapp.com'
},
target: 'invitation'
}
};

🚨 Error Handling

All authentication errors return JSON format with appropriate HTTP status codes:

Common Error Codes

StatusError MessageDescription
400Validation ErrorInvalid request body format
400verification email feature not enabledEmail verification not configured
400verification email feature requires a mail service to be providedMail service not configured
400verifyEmailConfig requires emailConfig with fields bodyTemplate, subject, urlTemplateMissing email configuration
400Unable to verify tokenInvalid verification token
401wrong credentials providedInvalid email/password
401This account is lockedAccount locked due to failed attempts
401Token is not valid access tokenInvalid or expired token
401Token fails security checkToken security validation failed
401token could not be verifiedMissing or invalid authorization token
403token does not contain expected dataToken validation failed
403User is not authorized to access this resourceUser lacks required permissions (admin access)
404User not foundUser does not exist
404Invitation not foundInvitation does not exist
409Email already verified or no changes madeEmail already verified
422unable to register "email"Email already exists
500unable to generate access tokenToken generation failed
500unable to generate refresh tokenRefresh token generation failed
500Failed to send verification emailEmail sending process failed
400/500Failed to create invitationInvitation creation failed

Error Response Format

{
"error": {
"message": "Error message description",
"data": ["Additional error details"]
}
}