# @hsuite/auth-types - Authentication Type Definitions

A comprehensive TypeScript library providing type-safe authentication, authorization, and user management type definitions for Web2 and Web3 applications within the HSuite ecosystem.

## Table of Contents

* [Quick Start](#quick-start)
* [Key Features](#key-features)
* [Installation & Setup](#installation--setup)
* [Usage Examples](#usage-examples)
* [API Reference](#api-reference)
* [Guides](#guides)
* [Examples](#examples)
* [Integration](#integration)

***

## Quick Start

```bash
npm install @hsuite/auth-types
```

```typescript
import { IAuth, Auth } from '@hsuite/auth-types';

// Use interfaces for type checking
const loginData: IAuth.ICredentials.IWeb2.IDto.ILogin = {
  username: "john_doe",
  email: "john@example.com", 
  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
* **`IUser`** - User entity and 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

#### 👥 **User (Models)**

* **`User.Safe`** - Safe user entity model with public properties
* User management type definitions
* User entity interfaces and implementations

#### 🎯 **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.

```typescript
@Roles(['admin', 'moderator'])
@Get('admin-only')
adminRoute() {
  return 'Access granted to admin or moderator';
}
```

#### @Public()

Marks route as publicly accessible without authentication.

```typescript
@Public()
@Get('health')
healthCheck() {
  return 'OK';
}
```

#### @isTwoFactorAuth()

Enforces two-factor authentication requirement.

```typescript
@isTwoFactorAuth()
@Post('sensitive-data')
sensitiveOperation() {
  return 'Access granted after 2FA verification';
}
```

#### @bypassTokenGate()

Bypasses token gate verification checks.

```typescript
@bypassTokenGate()
@Get('unrestricted')
unrestrictedAccess() {
  return 'Token gate check bypassed';
}
```

### Core Interfaces

#### IAuth.IConfiguration.IAuthentication

```typescript
interface IAuthentication {
  enabled: boolean;
  commonOptions: IOptions;
  web2Options?: IWeb2.IOptions;
  web3Options?: IWeb3.IOptions;
}
```

#### IAuth.ICredentials.IWeb2.IDto.ILogin

```typescript
interface ILogin {
  username: string;
  email: string;
  password: string;
}
```

#### IAuth.ICredentials.IWeb2.IDto.ISignup

```typescript
interface ISignup {
  username: string;
  email: string;
  password: string;
  tags: Array<ITags>;
}
```

#### IAuth.ICredentials.IUser.IEntity

```typescript
interface IEntity {
  username: string;
  email: string;
  created_at: number;
  updated_at: number;
  tags: Array<ITags>;
}
```

### Model Classes

#### Auth.Configuration.Authentication

```typescript
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

```typescript
class Login implements IAuth.ICredentials.IWeb2.IDto.ILogin {
  public username: string;
  public email: string;
  public password: string;
}
```

#### Auth.Credentials.Web3.Entity

```typescript
class Entity implements IAuth.ICredentials.IWeb3.IEntity {
  public walletId: string;
  public publicKey: string;
  public balance: Array<IAuth.IConfiguration.IWeb3.ITokenGate.IEntity>;
}
```

#### Auth.TwoFactor.Auth

```typescript
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

```typescript
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

```typescript
import { Auth, IAuth } from '@hsuite/auth-types';

// Login credentials
const loginDto = new Auth.Credentials.Web2.Dto.Login({
  username: "john_doe",
  email: "john@example.com",
  password: "securePassword123"
});

// Signup credentials
const signupDto = new Auth.Credentials.Web2.Dto.Signup({
  username: "jane_doe", 
  email: "jane@example.com",
  password: "strongPassword456",
  tags: [{ key: "role", value: "user" }]
});

// User entity
const userEntity = new Auth.Credentials.User.Entity({
  username: "john_doe",
  email: "john@example.com",
  created_at: Date.now(),
  updated_at: Date.now(),
  tags: [{ key: "status", value: "active" }]
});
```

### Web3 Authentication Models

```typescript
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

```typescript
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: "user@example.com",
  qr_code: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA..."
});
```

### User Types

```typescript
import { User, IAuth } from '@hsuite/auth-types';

// Safe user model without sensitive data
const safeUser = new User.Safe({
  email: "user@example.com",
  username: "johndoe",
  created_at: Date.now(),
  updated_at: Date.now(),
  confirmed: true,
  type: IAuth.ICredentials.IUser.IType.STANDARD,
  role: 'user',
  tags: [
    { key: 'api-key', value: 'your-api-key' },
    { key: 'plan', value: 'premium' }
  ],
  banned: false,
  twoFactorAuth: {
    status: IAuth.ITwoFactor.IStatus.ENABLED,
    factorSid: "YF123...",
    identity: "user@example.com"
  }
});
```

### Configuration Models

```typescript
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: "your-email@example.com",
          pass: "your-password"
        }
      }
    }
  },
  web3Options: {
    tokenGateOptions: {
      enabled: true,
      requiredTokens: ["0x123..."],
      minBalance: 1
    }
  }
});
```

***

## 🔗 Integration

### Required Dependencies

```json
{
  "@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

```json
{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "strict": true,
    "strictPropertyInitialization": false
  }
}
```

### Metadata Keys

```typescript
// 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.

<p align="center">Built with ❤️ by the HSuite Team<br>Copyright © 2025 HSuite. All rights reserved.</p>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.hsuite.network/developers/libs/auth-types.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
