@hsuite/auth-types
A comprehensive TypeScript library providing type-safe authentication and authorization solutions for Web2 and Web3 applications with HSuite ecosystem.
Table of Contents
Quick Start
npm install @hsuite/auth-types
import { IAuth, Auth } from '@hsuite/auth-types';
// Use interfaces for type checking
const loginData: IAuth.ICredentials.IWeb2.IDto.ILogin = {
username: "john_doe",
email: "[email protected]",
password: "securePassword123"
};
// Use models for runtime logic
const loginDto = new Auth.Credentials.Web2.Dto.Login(loginData);
Key Features
Comprehensive TypeScript library for authentication and authorization type definitions
Complete set of TypeScript interfaces, models, and decorators for implementing secure, type-safe authentication across applications within the HSuite ecosystem.
🏗️ Architecture
Core Namespaces
🔒 IAuth (Interfaces)
ITwilio
- Twilio service integration interfacesITwoFactor
- Two-factor authentication interfacesIConfiguration
- System configuration interfacesIWeb3
- Blockchain authentication interfacesIWeb2
- Traditional authentication interfacesICredentials
- Credential management interfaces
🏛️ Auth (Models)
Twilio
- SMS and voice verification modelsTwoFactor
- TOTP and verification modelsConfiguration
- Authentication system settingsWeb3
- Blockchain wallet authentication modelsWeb2
- Traditional credential modelsCredentials
- Secure credential storage models
🎯 Decorators
@Roles()
- Role-based access control@Public()
- Public route marker@isTwoFactorAuth()
- Two-factor authentication requirement@bypassTokenGate()
- Token gate bypass
Module Structure
src/
├── interfaces/ # IAuth namespace interfaces
│ ├── namespaces/
│ │ ├── twilio/ # Twilio integration interfaces
│ │ ├── two-factor/ # 2FA interfaces
│ │ ├── configuration/ # Config interfaces
│ │ ├── credentials/ # Credential interfaces
│ │ └── auth.namespace.ts # Main IAuth namespace
├── models/ # Auth namespace models
│ ├── namespaces/
│ │ ├── configuration/ # Config model implementations
│ │ ├── credentials/ # Credential model implementations
│ │ └── two-factor/ # 2FA model implementations
├── decorators/ # NestJS decorators
└── index.ts # Public API exports
🔧 API Reference
Decorators
@Roles(roles: string[])
Role-based access control decorator using Reflector pattern.
@Roles(['admin', 'moderator'])
@Get('admin-only')
adminRoute() {
return 'Access granted to admin or moderator';
}
@Public()
Marks route as publicly accessible without authentication.
@Public()
@Get('health')
healthCheck() {
return 'OK';
}
@isTwoFactorAuth()
Enforces two-factor authentication requirement.
@isTwoFactorAuth()
@Post('sensitive-data')
sensitiveOperation() {
return 'Access granted after 2FA verification';
}
@bypassTokenGate()
Bypasses token gate verification checks.
@bypassTokenGate()
@Get('unrestricted')
unrestrictedAccess() {
return 'Token gate check bypassed';
}
Core Interfaces
IAuth.IConfiguration.IAuthentication
interface IAuthentication {
enabled: boolean;
commonOptions: IOptions;
web2Options?: IWeb2.IOptions;
web3Options?: IWeb3.IOptions;
}
IAuth.ICredentials.IWeb2.IDto.ILogin
interface ILogin {
username: string;
email: string;
password: string;
}
IAuth.ICredentials.IWeb2.IDto.ISignup
interface ISignup {
username: string;
email: string;
password: string;
tags: Array<ITags>;
}
IAuth.ICredentials.IUser.IEntity
interface IEntity {
username: string;
email: string;
created_at: number;
updated_at: number;
tags: Array<ITags>;
}
Model Classes
Auth.Configuration.Authentication
class Authentication implements IAuth.IConfiguration.IAuthentication {
public enabled: boolean;
public commonOptions: IAuth.IConfiguration.IOptions;
public web2Options: IAuth.IConfiguration.IWeb2.IOptions;
public web3Options: IAuth.IConfiguration.IWeb3.IOptions;
}
Auth.Credentials.Web2.Dto.Login
class Login implements IAuth.ICredentials.IWeb2.IDto.ILogin {
public username: string;
public email: string;
public password: string;
}
Auth.Credentials.Web3.Entity
class Entity implements IAuth.ICredentials.IWeb3.IEntity {
public walletId: string;
public publicKey: string;
public balance: Array<IAuth.IConfiguration.IWeb3.ITokenGate.IEntity>;
}
Auth.TwoFactor.Auth
class Auth implements IAuth.ITwoFactor.IAuth {
status: IAuth.ITwoFactor.IStatus;
factorSid: string;
identity: string;
qr_code: string;
}
📖 Guides
Decorator Usage Guide
Learn how to use authentication decorators for route protection and access control. Implement role-based permissions, public endpoints, and advanced authentication patterns.
Interface Reference Guide
Complete reference for all authentication interfaces and type definitions. Understand the authentication system architecture and type contracts.
Model Implementation Guide
How to use model classes for type-safe authentication data handling. Learn about concrete implementations and runtime logic patterns.
🎯 Examples
Role-Based Access Control
import { Controller, Get, Post, UseGuards } from '@nestjs/common';
import { Roles, Public, isTwoFactorAuth, bypassTokenGate } from '@hsuite/auth-types';
@Controller('api')
export class SecureController {
// Admin and moderator access
@Roles(['admin', 'moderator'])
@Get('admin-panel')
getAdminPanel() {
return { message: 'Welcome to admin panel' };
}
// Admin only access
@Roles(['admin'])
@Post('delete-user')
deleteUser() {
return { message: 'User deleted by admin' };
}
// Public endpoint (no auth required)
@Public()
@Get('public-info')
getPublicInfo() {
return { message: 'Public information' };
}
// Requires 2FA verification
@isTwoFactorAuth()
@Roles(['admin'])
@Post('critical-operation')
criticalOperation() {
return { message: 'Critical operation completed' };
}
// Bypasses token gate
@bypassTokenGate()
@Get('no-token-gate')
noTokenGate() {
return { message: 'Token gate bypassed' };
}
}
Web2 Authentication Models
import { Auth, IAuth } from '@hsuite/auth-types';
// Login credentials
const loginDto = new Auth.Credentials.Web2.Dto.Login({
username: "john_doe",
email: "[email protected]",
password: "securePassword123"
});
// Signup credentials
const signupDto = new Auth.Credentials.Web2.Dto.Signup({
username: "jane_doe",
email: "[email protected]",
password: "strongPassword456",
tags: [{ key: "role", value: "user" }]
});
// User entity
const userEntity = new Auth.Credentials.User.Entity({
username: "john_doe",
email: "[email protected]",
created_at: Date.now(),
updated_at: Date.now(),
tags: [{ key: "status", value: "active" }]
});
Web3 Authentication Models
import { Auth, IAuth } from '@hsuite/auth-types';
// Web3 entity with wallet information
const web3Entity = new Auth.Credentials.Web3.Entity({
walletId: "0.0.1234567",
publicKey: "dhiueri7r4bxhbxwb",
balance: [
{ tokenId: "0.0.123", amount: "100" },
{ tokenId: "0.0.456", amount: "200" }
]
});
// Authentication request data
const authData = new Auth.Credentials.Web3.Request.Authentication.Data({
token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
});
// Signed data for authentication
const signedData = new Auth.Credentials.Web3.Request.Authentication.SignedData({
signature: new Uint8Array([1, 2, 3, 4, 5]),
serverSigningAccount: "0x1234567890abcdef"
});
// Complete authentication request
const authRequest = new Auth.Credentials.Web3.Request.Authentication.Authenticate({
signedData: signedData,
payload: {
url: "https://example.com/auth",
node: "node-1",
data: authData
}
});
Two-Factor Authentication
import { Auth, IAuth } from '@hsuite/auth-types';
// Two-factor authentication setup
const twoFactorAuth = new Auth.TwoFactor.Auth({
status: IAuth.ITwoFactor.IStatus.PENDING,
factorSid: "YF1234567890abcdef1234567890abcdef",
identity: "[email protected]",
qr_code: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA..."
});
Configuration Models
import { Auth, IAuth } from '@hsuite/auth-types';
// Complete authentication configuration
const authConfig = new Auth.Configuration.Authentication({
enabled: true,
commonOptions: {
jwt: {
secret: "your-secret-key",
signOptions: { expiresIn: "24h" }
},
passport: IAuth.IConfiguration.IPassportStrategy.JWT
},
web2Options: {
confirmation_required: true,
admin_only: false,
sendMailOptions: {
confirm: {
subject: "Confirm your account",
template: "confirmation"
}
},
mailerOptions: {
transport: {
host: "smtp.example.com",
port: 587,
auth: {
user: "[email protected]",
pass: "your-password"
}
}
}
},
web3Options: {
tokenGateOptions: {
enabled: true,
requiredTokens: ["0x123..."],
minBalance: 1
}
}
});
🔗 Integration
Required Dependencies
{
"@nestjs/common": "^10.4.2",
"@nestjs/core": "^10.4.2",
"@hsuite/shared-types": "^2.0.0",
"@hsuite/smart-network-types": "^2.0.0",
"@hsuite/nestjs-swagger": "latest"
}
TypeScript Configuration
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"strict": true,
"strictPropertyInitialization": false
}
}
Metadata Keys
// Decorator metadata keys
export const IS_PUBLIC = 'isPublic';
export const IS_TWO_FACTOR_AUTH = 'isTwoFactorAuth';
export const BYPASS_TOKEN_GATE = 'bypassTokenGate';
🔧 Type Safety: All interfaces and models provide full TypeScript support with strict type checking and validation.
📐 Architecture: Clean separation between interfaces (IAuth namespace) and implementations (Auth namespace) following SOLID principles.
🎯 Best Practice: Use interfaces for type definitions and model classes for runtime validation and data transformation.
Built with ❤️ by the HbarSuite Team Copyright © 2024 HbarSuite. All rights reserved.
Last updated