HbarSuite Docs
  • Welcome to HbarSuite
  • HbarSuite Developer Documentation
    • HbarSuite Smart Engine Applications
      • @hsuite/cross-chain-exchange
      • @hsuite/dao
        • DAO Application Testing
      • @hsuite/exchange
      • @hsuite/launchpad
      • @hsuite/multisig
      • @hsuite/nft-exchange
      • HSuite Smart App - Enterprise Hedera Application Framework
    • HSuite Libraries
      • @hsuite/api-key - Enterprise API Key Authentication System
      • @hsuite/auth-types
      • @hsuite/auth - Authentication Module
      • @hsuite/client-types
      • @hsuite/client - Client Service Module
      • @hsuite/dkg-types - Distributed Key Generation Type Definitions
      • @hsuite/hashgraph-types - Hedera Hashgraph Type Definitions
      • @hsuite/health - Comprehensive System Health Monitoring
      • @hsuite/helpers - Utility Library
      • @hsuite/ipfs - InterPlanetary File System Integration
      • @hsuite/shared-types - Shared Type Definitions
      • @hsuite/smart-config - Configuration Management
      • @hsuite/smart-ledgers - Multi-Ledger Management
      • @hsuite/smart-network-types - Smart Network Type Definitions
      • @hsuite/smart-transaction-types - Smart Transaction Type Definitions
      • @hsuite/smartnode-sdk - SmartNode Software Development Kit
      • @hsuite/snapshots - Multi-Ledger Token Snapshot Management
      • @hsuite/subscriptions-types - Subscription Management Type Definitions
      • @hsuite/subscriptions - Enterprise Subscription Management System
      • @hsuite/throttler-types - Rate Limiting Type Definitions
      • @hsuite/throttler - Advanced Rate Limiting for NestJS
      • @hsuite/users-types - User Type Definitions
      • @hsuite/users - User Management Module
      • @hsuite/validators-types
  • General Documentation
    • Smart Apps and Interaction
      • Subscription-Based Model
      • Token-Gate Model
    • The Smart Node Network
      • security-layer
      • Type of Validators Explained
      • Understanding Validators in Our System
      • Automating Responses to Network Changes & Key Rotation
      • Ensuring Continuous Operation and Recovery
      • Generating and Sharing Keys Collaboratively
      • Handling Node Expulsion and Replacement
      • Managing Cluster Membership
      • Protecting Secrets with Shamir's Method
      • Security Layer Integration
      • Setting Up Secure Clusters
    • Tokenomics
      • Tokenomics v1
      • Tokenomics V2
    • What is a Smart Node?
  • Restful APIs Documentation
Powered by GitBook
On this page
  • Table of Contents
  • Quick Start
  • Key Features
  • Comprehensive TypeScript library for authentication and authorization type definitions
  • 🏗️ Architecture
  • Core Namespaces
  • Module Structure
  • 🔧 API Reference
  • Decorators
  • Core Interfaces
  • Model Classes
  • 📖 Guides
  • Decorator Usage Guide
  • Interface Reference Guide
  • Model Implementation Guide
  • 🎯 Examples
  • Role-Based Access Control
  • Web2 Authentication Models
  • Web3 Authentication Models
  • Two-Factor Authentication
  • Configuration Models
  • 🔗 Integration
  • Required Dependencies
  • TypeScript Configuration
  • Metadata Keys
  • 🎯 Best Practice: Use interfaces for type definitions and model classes for runtime validation and data transformation.
  1. HbarSuite Developer Documentation
  2. HSuite Libraries

@hsuite/auth-types

Previous@hsuite/api-key - Enterprise API Key Authentication SystemNext@hsuite/auth - Authentication Module

Last updated 2 days ago

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 interfaces

  • ITwoFactor - Two-factor authentication interfaces

  • IConfiguration - System configuration interfaces

  • IWeb3 - Blockchain authentication interfaces

  • IWeb2 - Traditional authentication interfaces

  • ICredentials - Credential management interfaces

🏛️ Auth (Models)

  • Twilio - SMS and voice verification models

  • TwoFactor - TOTP and verification models

  • Configuration - Authentication system settings

  • Web3 - Blockchain wallet authentication models

  • Web2 - Traditional credential models

  • Credentials - 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.

Quick Start
Key Features
Installation & Setup
Usage Examples
API Reference
Guides
Examples
Integration