{"id":27863142,"url":"https://github.com/ahs12/nestjs-xsecurity","last_synced_at":"2026-04-11T21:37:09.164Z","repository":{"id":260462335,"uuid":"881079857","full_name":"AHS12/nestjs-xsecurity","owner":"AHS12","description":"🔐 Robust security middleware for NestJS applications with token validation, rate limiting, and path exclusion.","archived":false,"fork":false,"pushed_at":"2024-11-04T06:55:09.000Z","size":377,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-09-11T10:02:03.858Z","etag":null,"topics":["nestjs","path-exclusion","rate-limiting","security","token-validation"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/nestjs-xsecurity","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/AHS12.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2024-10-30T21:56:58.000Z","updated_at":"2024-11-04T06:54:03.000Z","dependencies_parsed_at":"2025-05-04T20:44:54.330Z","dependency_job_id":"1dfea480-fafb-4962-ab69-ee7ebe752a9b","html_url":"https://github.com/AHS12/nestjs-xsecurity","commit_stats":null,"previous_names":["ahs12/nestjs-xsecurity"],"tags_count":3,"template":false,"template_full_name":null,"purl":"pkg:github/AHS12/nestjs-xsecurity","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AHS12%2Fnestjs-xsecurity","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AHS12%2Fnestjs-xsecurity/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AHS12%2Fnestjs-xsecurity/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AHS12%2Fnestjs-xsecurity/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/AHS12","download_url":"https://codeload.github.com/AHS12/nestjs-xsecurity/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AHS12%2Fnestjs-xsecurity/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31696743,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-11T21:17:31.016Z","status":"ssl_error","status_checked_at":"2026-04-11T21:17:24.556Z","response_time":54,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["nestjs","path-exclusion","rate-limiting","security","token-validation"],"created_at":"2025-05-04T20:44:36.697Z","updated_at":"2026-04-11T21:37:09.142Z","avatar_url":"https://github.com/AHS12.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# nestjs-xsecurity\n\n\u003cdiv align=\"center\"\u003e\n\n🔐 Robust security middleware for NestJS applications with token validation, rate limiting, and path exclusion.\n\n[![npm version](https://badge.fury.io/js/nestjs-xsecurity.svg)](https://badge.fury.io/js/nestjs-xsecurity)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n[![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/)\n[![NestJS](https://img.shields.io/badge/NestJS-Compatible-green.svg)](https://nestjs.com/)\n\n\u003c/div\u003e\n\n## 📦 Installation\n\n```bash\n# Using npm\nnpm install nestjs-xsecurity\n\n# Using yarn\nyarn add nestjs-xsecurity\n\n# Using pnpm\npnpm add nestjs-xsecurity\n```\n\n## 📖 Documentation\n\n- [Quick Start Guide](https://github.com/ahs12/nestjs-xsecurity?tab=readme-ov-file#-quick-start) (below)\n- [Complete Documentation](https://github.com/ahs12/nestjs-xsecurity/wiki) - Visit the [Wiki](https://github.com/ahs12/nestjs-xsecurity/wiki) for:\n  - Advanced Configuration Examples\n  - Security Best Practices\n  - Troubleshooting\n  - And More!\n\n## 🌟 Features\n\n- **Token-based Security**\n  - HMAC-SHA256 signature validation\n  - Configurable token expiration\n  - Custom header support\n\n- **Rate Limiting**\n  - IP-based request throttling\n  - Configurable attempt limits\n  - Automatic cleanup of expired records\n\n- **Path Control**\n  - Exclude specific routes\n  - Support for wildcards and patterns\n  - RegExp compatibility\n\n- **Developer Experience**\n  - Full TypeScript support\n  - Comprehensive configuration options\n  - CLI setup tool\n  - Cross-platform token generators\n  - Wiki documentation. [Wiki](https://github.com/ahs12/nestjs-xsecurity/wiki)\n\n\n## 🚀 Quick Start\n\n### 1. Initialize with CLI\n\n```bash\nnpx nestjs-xsecurity install\n```\n\nThis command will:\n- Generate a secure random secret\n- Set up environment variables\n- Create initial configuration\n\n### 2. Module Registration\n\nChoose one of these approaches:\n\n#### ⭐ Recommended: Async Configuration\n\n```typescript\nimport { Module } from '@nestjs/common';\nimport { ConfigModule, ConfigService } from '@nestjs/config';\nimport { XSecurityModule } from 'nestjs-xsecurity';\n\n@Module({\n  imports: [\n    ConfigModule.forRoot(),\n    XSecurityModule.registerAsync({\n      imports: [ConfigModule],\n      inject: [ConfigService],\n      useFactory: (config: ConfigService) =\u003e ({\n        enabled: config.get('XSECURITY_ENABLED', true),\n        secret: config.get('XSECURITY_SECRET'),\n        rateLimit: {\n          enabled: config.get('XSECURITY_RATE_LIMIT_ENABLED', true),\n          maxAttempts: config.get('XSECURITY_MAX_ATTEMPTS', 5),\n          decayMinutes: config.get('XSECURITY_DECAY_MINUTES', 1),\n          storeLimit: config.get('XSECURITY_RATE_LIMIT_STORE_LIMIT', 10000),\n        },\n        exclude: ['/health', '/metrics', '/api/docs/*'],\n      }),\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\n#### Alternative: Static Configuration\n\n```typescript\nimport { Module } from '@nestjs/common';\nimport { XSecurityModule } from 'nestjs-xsecurity';\n\n@Module({\n  imports: [\n    XSecurityModule.register({\n      enabled: true,\n      secret: process.env.XSECURITY_SECRET,\n      rateLimit: {\n        enabled: true,\n        maxAttempts: 5,\n        decayMinutes: 1,\n      },\n      exclude: ['/health'],\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\n## 🔧 Configuration\n\n### Environment Variables\n\nDetails configuration options can be found in this [Wiki Page](https://github.com/AHS12/nestjs-xsecurity/wiki/Configuration-Options#configuration-sections).\n\n```env\n# Required\nXSECURITY_SECRET=your-secure-secret-key\n\n# Optional\nXSECURITY_ENABLED=true\nXSECURITY_MAX_ATTEMPTS=5\nXSECURITY_DECAY_MINUTES=1\n```\n\n### Configuration Options\n\n```typescript\ninterface XSecurityConfig {\n  // Enable/disable middleware\n  enabled?: boolean;\n\n  // Your secret key for token validation\n  secret?: string;\n\n  // Rate limiting settings\n  rateLimit?: {\n    enabled?: boolean;      // Default: true\n    maxAttempts?: number;    // Default: 5\n    decayMinutes?: number;   // Default: 1\n    cleanupInterval?: number; // Default: 5\n    storeLimit?: number;      // Default: 10000\n  };\n\n  // Token configuration\n  token?: {\n    headerName?: string;     // Default: 'X-SECURITY-TOKEN'\n    expirySeconds?: number;  // Default: 10 (10 seconds)\n  };\n\n  // Paths to exclude from security checks\n  exclude?: Array\u003cstring | RegExp\u003e;\n\n  // Custom error messages\n  errorMessages?: {\n    rateLimitExceeded?: string;\n    invalidToken?: string;\n  };\n}\n```\n\n## 🔑 Token Implementation\n\n### Node.js / TypeScript\n\n```typescript\nimport crypto from 'crypto';\n\nfunction generateXsecurityToken(secretKey: string, expirySeconds = 300): string {\n  const expiryTimestamp = Math.floor(Date.now() / 1000) + expirySeconds;\n  const randomBytes = crypto.randomBytes(16).toString('hex'); // Add randomness\n  const payload = {\n    expiry: expiryTimestamp,\n    nonce: randomBytes,\n    iat: Date.now()\n  };\n\n  const token = Buffer.from(JSON.stringify(payload)).toString('base64');\n  const signature = crypto\n    .createHmac('sha256', secretKey)\n    .update(token)\n    .digest('hex');\n\n  return `${token}.${signature}`;\n}\n\n// Usage\nconst token = generateXsecurityToken('your-secret-key');\n```\n\n### Python\n\n```python\nimport time\nimport json\nimport hmac\nimport base64\nimport secrets\nimport hashlib\nfrom typing import Optional\n\ndef generate_xsecurity_token(secret_key: str, expiry_seconds: int = 300) -\u003e str:\n    \"\"\"\n    Generate a secure token with expiry and nonce.\n\n    Args:\n        secret_key (str): Secret key for signing\n        expiry_seconds (int): Token validity duration in seconds\n\n    Returns:\n        str: Generated security token\n    \"\"\"\n    expiry_timestamp = int(time.time()) + expiry_seconds\n    random_bytes = secrets.token_hex(16)  # 16 bytes = 32 hex chars\n\n    payload = {\n        \"expiry\": expiry_timestamp,\n        \"nonce\": random_bytes,\n        \"iat\": int(time.time() * 1000)  # milliseconds\n    }\n\n    # Convert payload to base64\n    token = base64.b64encode(\n        json.dumps(payload).encode('utf-8')\n    ).decode('utf-8')\n\n    # Generate signature\n    signature = hmac.new(\n        secret_key.encode('utf-8'),\n        token.encode('utf-8'),\n        hashlib.sha256\n    ).hexdigest()\n\n    return f\"{token}.{signature}\"\n```\n\n### Flutter / Dart\n\n```dart\nimport 'dart:convert';\nimport 'dart:math';\nimport 'package:crypto/crypto.dart';\n\nclass XSecurityToken {\n  static String generate(String secretKey, {int expirySeconds = 300}) {\n    final expiryTimestamp = (DateTime.now().millisecondsSinceEpoch ~/ 1000) + expirySeconds;\n\n    // Generate random bytes for nonce\n    final random = Random.secure();\n    final randomBytes = List\u003cint\u003e.generate(16, (i) =\u003e random.nextInt(256));\n    final nonce = randomBytes.map((byte) =\u003e byte.toRadixString(16).padLeft(2, '0')).join();\n\n    final payload = {\n      'expiry': expiryTimestamp,\n      'nonce': nonce,\n      'iat': DateTime.now().millisecondsSinceEpoch\n    };\n\n    // Convert payload to base64\n    final token = base64Encode(utf8.encode(jsonEncode(payload)));\n\n    // Generate signature\n    final hmacSha256 = Hmac(sha256, utf8.encode(secretKey));\n    final signature = hmacSha256.convert(utf8.encode(token)).toString();\n\n    return '$token.$signature';\n  }\n}\n```\n\n## 📝 Examples\n\n### Making a Secured Request\n\n```typescript\n// Client-side\nconst token = generateXsecurityToken(secretKey);\n\nawait fetch('https://api.example.com/data', {\n  headers: {\n    'X-SECURITY-TOKEN': token\n  }\n});\n```\n\n### Path Exclusion Patterns\n\n```typescript\nXSecurityModule.register({\n  exclude: [\n    '/health',           // Exact match\n    '/api/*',           // Wildcard match\n    '/v1/:param/data',  // Parameter match\n    /^\\/public\\/.*/     // RegExp match\n  ]\n});\n```\n\n### Error Responses\n\n```typescript\n// Rate limit exceeded\n{\n  \"statusCode\": 429,\n  \"message\": \"Too many requests. Please try again later.\",\n  \"error\": \"Too Many Requests\"\n}\n\n// Invalid token\n{\n  \"statusCode\": 403,\n  \"message\": \"Invalid XSECURITY token\",\n  \"error\": \"Forbidden\"\n}\n```\n\n## 🛠️ CLI Reference\n\n```bash\nnpx nestjs-xsecurity \u003ccommand\u003e\n\nCommands:\n  install     Initialize security configuration\n  init        Alias for install\n  help        Show help information\n```\n\n## 🔒 Security Best Practices\n\n1. **Secret Management**\n   - Use environment variables for secrets\n   - Never expose secrets in client code\n\n\n2. **Rate Limiting**\n   - Adjust limits based on your API's capacity\n   - Monitor rate limit hits\n   - Implement progressive delays\n\n## 🤝 Contributing\n\nContributions are welcome! Please read our [contributing guidelines](CONTRIBUTING.md) before submitting changes.\n\n\n## 📄 License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## ✨ Creator\n\n[Azizul Hakim](https://github.com/ahs12)\n\n---\n\n\u003cdiv align=\"center\"\u003e\n\nMade with ❤️ for the NestJS community\n\n\u003c/div\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fahs12%2Fnestjs-xsecurity","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fahs12%2Fnestjs-xsecurity","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fahs12%2Fnestjs-xsecurity/lists"}