{"id":46880526,"url":"https://github.com/amankrsahu/authkit","last_synced_at":"2026-07-26T20:00:16.691Z","repository":{"id":325749662,"uuid":"1102241744","full_name":"AmanKrSahu/authkit","owner":"AmanKrSahu","description":"AuthKit is a production-ready Identity Provider (IdP) and Identity \u0026 Access Management (IAM) microservice designed for secure, scalable authentication and authorization.","archived":false,"fork":false,"pushed_at":"2026-07-20T11:40:41.000Z","size":286,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-07-20T13:21:30.214Z","etag":null,"topics":["commitlint","docker","eslint","express","husky","identity-provider","jwt-authentication","magic-link","mfa-authentication","nodejs","oauth2","oidc-provider","postresql","prettier","prisma","redis","resend","typescript","zod"],"latest_commit_sha":null,"homepage":"","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/AmanKrSahu.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"docs/security_architecture.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-11-23T04:38:05.000Z","updated_at":"2026-07-20T11:39:53.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/AmanKrSahu/authkit","commit_stats":null,"previous_names":["amankrsahu/auth-backend","amankrsahu/authkit"],"tags_count":3,"template":true,"template_full_name":null,"purl":"pkg:github/AmanKrSahu/authkit","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AmanKrSahu%2Fauthkit","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AmanKrSahu%2Fauthkit/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AmanKrSahu%2Fauthkit/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AmanKrSahu%2Fauthkit/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/AmanKrSahu","download_url":"https://codeload.github.com/AmanKrSahu/authkit/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AmanKrSahu%2Fauthkit/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":35926497,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-07-20T02:08:10.276Z","status":"online","status_checked_at":"2026-07-26T02:00:06.503Z","response_time":89,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"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":["commitlint","docker","eslint","express","husky","identity-provider","jwt-authentication","magic-link","mfa-authentication","nodejs","oauth2","oidc-provider","postresql","prettier","prisma","redis","resend","typescript","zod"],"created_at":"2026-03-10T21:08:51.553Z","updated_at":"2026-07-26T20:00:16.671Z","avatar_url":"https://github.com/AmanKrSahu.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# AuthKit: Identity Provider (IdP) \u0026 IAM Infrastructure\n\n\u003cimg src=\"https://img.shields.io/badge/TypeScript-3178C6?style=for-the-badge\u0026logo=typescript\u0026logoColor=white\" /\u003e \u003cimg src=\"https://img.shields.io/badge/Node.js-339933?style=for-the-badge\u0026logo=node.js\u0026logoColor=white\" /\u003e \u003cimg src=\"https://img.shields.io/badge/Express.js-000000?style=for-the-badge\u0026logo=express\u0026logoColor=white\" /\u003e\n\u003cimg src=\"https://img.shields.io/badge/Prisma-2D3748?style=for-the-badge\u0026logo=prisma\u0026logoColor=white\" /\u003e \u003cimg src=\"https://img.shields.io/badge/PostgreSQL-4169E1?style=for-the-badge\u0026logo=postgresql\u0026logoColor=white\" /\u003e \u003cimg src=\"https://img.shields.io/badge/Nginx-009639?style=for-the-badge\u0026logo=nginx\u0026logoColor=white\" /\u003e \u003cimg src=\"https://img.shields.io/badge/Redis-DC382D?style=for-the-badge\u0026logo=redis\u0026logoColor=white\" /\u003e \u003cimg src=\"https://img.shields.io/badge/Swagger-85EA2D?style=for-the-badge\u0026logo=swagger\u0026logoColor=black\" /\u003e \u003cimg src=\"https://img.shields.io/badge/Docker-2496ED?style=for-the-badge\u0026logo=docker\u0026logoColor=white\" /\u003e\n\n## 1. Project Abstract\n\nAuthKit is a production-grade **Identity Provider (IdP)** and **Identity \u0026 Access Management (IAM)** microservice. Engineered with a focus on cryptographic integrity and protocol compliance, it facilitates centralized authentication via **OpenID Connect (OIDC) 1.0** and **OAuth 2.0**. The platform abstracts complex security handshakes—including PKCE-enforced authorization flows, multi-factor verification (MFA), and stateless session orchestration—enabling rapid deployment of secure, scalable service ecosystems.\n\n---\n\n## Table of Contents\n\n- [1. Project Abstract](#1-project-abstract)\n- [2. Technology Stack](#2-technology-stack)\n- [3. Developer Setup](#3-developer-setup)\n- [4. Core Architecture \u0026 Security Infrastructure](#4-core-architecture--security-infrastructure)\n- [5. OIDC Identity Provider (IdP) Implementation](#5-oidc-identity-provider-idp-implementation)\n- [6. API Inventory \u0026 Endpoint Specifications](#6-api-inventory--endpoint-specifications)\n- [7. Comprehensive Security, Performance \u0026 Feature Audit (July 2026)](#7-comprehensive-security-performance--feature-audit-july-2026)\n\n---\n\n## 2. Technology Stack\n\n- **Language**: TypeScript (Node.js LTS)\n- **Framework**: Express.js\n- **Persistence**: PostgreSQL orchestrated via Prisma ORM\n- **State Store**: High-concurrency Redis instances (OIDC State \u0026 Session Caching)\n- **Validation**: Zod (Runtime Type Verification)\n- **Documentation**: Swagger / OpenAPI 3.0\n- **Orchestration**: Docker \u0026 Docker Compose\n- **Email Delivery**: Resend\n- **Cryptography**: Bcrypt (Hashing), Speakeasy (MFA/TOTP), RSA-256 (JWT/JWKS)\n\n---\n\n## 3. Developer Setup\n\n### 3.1 Containerized Orchestration (Docker)\n\n**Prerequisites**: Docker \u0026 Docker Compose\n\n1.  **Clone Repository**:\n\n    ```bash\n    git clone https://github.com/AmanKrSahu/authkit.git\n    ```\n\n2.  **Initialize the Environment Variables**:\n\n    ```bash\n    cp .env.example .env\n    ```\n\n3.  **Generate secure tokens and JWKs**:\n\n    ```bash\n    # Populate .env with cryptographic primitives from generated-secrets.json\n    pnpm generate:secrets\n    ```\n\n4.  **Build and Run the Containers**:\n\n    ```bash\n    docker-compose -f docker-compose.dev.yml up --build -d\n    ```\n\n### 3.2 Native Runtime Environment (Local)\n\n**Prerequisites**: Node.js (LTS), pnpm, PostgreSQL, Redis\n\n1.  **Dependency Resolution**:\n\n    ```bash\n    pnpm install\n    ```\n\n2.  **Initialize the Environment Variables**:\n\n    ```bash\n    cp .env.example .env\n    ```\n\n3.  **Generate secure tokens and JWKs**:\n\n    ```bash\n    # Populate .env with cryptographic primitives from generated-secrets.json\n    pnpm generate:secrets\n    ```\n\n4.  **Schema Migration \u0026 Seeding**:\n\n    ```bash\n    pnpm db:generate\n    pnpm db:push\n    # Optional: pnpm db:seed\n    ```\n\n5.  **Run the Server**:\n\n    ```bash\n    pnpm dev\n    ```\n\n### 3.3 Access Vectors\n\nDepending on your configured environment (direct execution vs. behind Nginx):\n\n- **Local Dev API**: `http://localhost:8000/api/v1/`\n- **Local Dev Swagger Portal**: `http://localhost:8000/docs`\n- **Production API (behind Nginx)**: `http://localhost/api/v1/`\n- **Production Swagger Portal (behind Nginx)**: `http://localhost/docs`\n\n👉 Full testing guide: [**Testing \u0026 Deployment Workflows**](./docs/testing-workflows.md)\n\n---\n\n## 4. Core Architecture \u0026 Security Infrastructure\n\n**Systemic Architecture**:\nThe infrastructure adheres to a **Modular Layered Architecture (MLA)** utilizing the Controller-Service-Repository pattern. This ensures deterministic separation of concerns, facilitating high maintainability and vertical scalability. Core business logic is encapsulated within feature-isolated modules (Auth, Identity, Session Management).\n\n**Cryptographic \u0026 Protocol Security**:\n\n- **Bearer Tokenization**: Short-lived JWTs (Access Tokens) issued via RSA-256 signing.\n- **Refresh Token Rotation (RTR)**: Cryptographically linked rotation cycles to mitigate replay attacks.\n- **MFA (Multi-Factor Authentication)**: TOTP implementation via speakeasy for secondary verification.\n- **Atomic Session Management**: Redis-backed session lifecycle with real-time revocation capabilities.\n- **Data Integrity**: Bcrypt-hashed credentials and deterministic redirection whitelisting.\n- **Defensive Middleware**: Global rate-limiting, Helmet-enforced security headers, and CORS strictness.\n- **Account Enumeration Prevention**: Enforces uniform, indistinguishable success responses across forgot-password, resend-verification, and magic-link login routes, preventing user registration probing.\n- **Per-Account Lockout**: Redis-backed account lockout (5 failed attempts within 15 minutes locks the account for 15 minutes) preventing distributed brute-force guess attempts.\n- **Ingress Gateway Isolation**: Routing production traffic through an Nginx proxy container to isolate backend sockets.\n- **Dynamic Proxy Trust**: Custom, environment-validated `TRUST_PROXY` Express configuration.\n- **Enhanced Ingress Rate-Limiting**: Enforces strict route-level rate limiting across login, register, magic-link, and MFA endpoints, plus user-bound attempt budgets to prevent distributed bypasses.\n- **Hardened Caching Layer**: Implements full Redis password authentication, production TLS transport options, loopback port containment, and AES-256-GCM encryption of cached TOTP setup secrets.\n\n👉 Full Documentation: [**Detailed Security Architecture**](./docs/security_architecture.md)\n\n### 4.1 Architectural Design Decisions Registry\n\nTo track and audit architectural decisions, we maintain a registry of design logs detailing critical security solutions:\n\n| Design Decision Record                                                                                         | Technical \u0026 Functional Description                                                                        | Context / Origin                                                              |\n| :------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------- |\n| [**Unified Origin Validator**](./docs/design-decisions/audit-2026-07-20/unified-origin-validator.md)           | Unifies CORS, CSRF, and redirect whitelisting logic to block subdomain suffix spoofing and enforce HTTPS. | **July 2026 Security Audit** (Task [SEC-H1](./docs/audit/2026-07-20/task.md)) |\n| [**Client IP \u0026 Lockout Security**](./docs/design-decisions/audit-2026-07-20/client-ip-and-lockout-security.md) | Formulates the Nginx reverse-proxy ingress, proxy header filtering, and Redis-backed login lockouts.      | **July 2026 Security Audit** (Task [SEC-H3](./docs/audit/2026-07-20/task.md)) |\n\n---\n\n## 5. OIDC Identity Provider (IdP) Implementation\n\nAuthKit functions as a centralized IdP, supporting dynamic client registration and multi-phase authorization handshakes. The implementation conforms to strict **OpenID Connect 1.0** specifications.\n\n\u003e [!IMPORTANT]\n\u003e For an exhaustive technical breakdown of the OIDC handshake, token introspection, and dynamic client provisioning, refer to the [OIDC Implementation Guide](./docs/oidc_implementation.md). This documentation details the **PKCE verification**, **7-stage interaction handshake**, and **Discovery protocol (RFC 8414)**.\n\n---\n\n## 6. API Inventory \u0026 Endpoint Specifications\n\n| Domain             | Functional Scope            | Protocol / Logic       | Details                                           |\n| :----------------- | :-------------------------- | :--------------------- | :------------------------------------------------ |\n| **Identity (IdP)** | Auth, Token, JWKS, UserInfo | OIDC 1.0 / OAuth 2.0   | Centralized SSO \u0026 Third-party provisioning        |\n| **Auth**           | Registration, Login, Logout | Password-based Auth    | Secure credential handling \u0026 session initiation   |\n| **MFA**            | TOTP Setup \u0026 Verification   | RFC 6238 (speakeasy)   | Multi-factor secondary verification layer         |\n| **OAuth**          | Google Social Integration   | OAuth 2.0 Protocol     | Third-party identity federation                   |\n| **Magic Link**     | Passwordless Auth           | Token-based / SMTP     | Email-verified session provisioning               |\n| **User/Session**   | Profile \u0026 Active State Mgmt | REST / Redis-backed    | Real-time session tracking \u0026 profile modification |\n| **Admin**          | Moderation \u0026 Client Ops     | Restricted REST / RBAC | User lifecycle moderation \u0026 Client Registration   |\n| **System**         | Health \u0026 Dependency Checks  | Heartbeat Logic        | Multi-component dependency status monitoring      |\n| **Metadata**       | Discovery, Key Exposition   | RFC 8414               | Automated client configuration (Well-known)       |\n\nComprehensive specifications including request/response schemas are accessible via the Swagger portal.\n\n👉 Full Documentation: [**API Endpoints Documentation**](./docs/api_endpoints.md)\n\n---\n\n## 7. Comprehensive Security, Performance \u0026 Feature Audit (July 2026)\n\nTo elevate **AuthKit** from a robust side-project showcase to a **production-ready, enterprise-grade Identity Provider (IdP)** meeting global standards, a thorough engineering audit was performed. This audit systematically analyzed the codebase for cryptographic rigor, protocol compliance, bottleneck optimization, and enterprise scalability.\n\nAll findings, remediations, and strategic feature additions have been structured into a master roadmap designed to prevent regressions and secure the platform's core trust base.\n\n### 7.1 Audit Artifacts \u0026 Findings\n\nThe audit is broken down into specialized focus areas. You can review the exhaustive reports here:\n\n- [**Master Task Plan \u0026 Execution Roadmap (`task.md`)**](./docs/audit/2026-07-20/task.md) — The central steering document outlining sequencing, complexity, and priority.\n- [**Security Audit Report (`security-audit.md`)**](./docs/audit/2026-07-20/security-audit.md) — Exhaustive analysis of threat vectors, session caching vulnerabilities, and sanitization leaks.\n- [**Performance \u0026 Scalability Audit (`performance.md`)**](./docs/audit/2026-07-20/performance.md) — Profiling query paths, database connection pooling, and latency-heavy transactions.\n- [**Enterprise Feature Recommendations (`feature-recommendations.md`)**](./docs/audit/2026-07-20/feature-recommendations.md) — Functional specifications for B2B multi-tenancy, passkeys, webhooks, and audit trails.\n- [**Supplementary Findings (`supplementary-findings.md`)**](./docs/audit/2026-07-20/supplementary-findings.md) — Additional architectural findings and recommendations discovered during the planning phase of the July 2026 security audit (specifically addressing proxy trust dynamics, header verification, and reverse-proxy deployments).\n\n---\n\n### 7.2 Why This Audit?\n\nModern IAM (Identity \u0026 Access Management) systems require zero-compromise security posture. The audit was conducted to:\n\n1.  **Harden Cryptographic Primitives**: Eliminate weak entropy, secure TOTP/MFA secrets, and enforce strict, cryptographically bound token states.\n2.  **Ensure Zero-Trust Defaults**: Upgrade session invalidation, CORS handling, and OAuth state verification.\n3.  **Optimize High-Concurrency Paths**: Remove expensive bottlenecks (e.g., Bcrypt execution blocking DB transactions) and introduce proper indices.\n4.  **Establish B2B/Enterprise Readiness**: Define clear milestones for Multi-Tenancy (Organizations), SAML/OIDC SSO, and Webhook dispatchers.\n\n---\n\n### 7.3 Master Execution Roadmap\n\nThe master tasks are sequenced into three distinct phases to manage risks and safeguard production stability:\n\n#### **Phase 1: Critical Fixes (Security-First \u0026 Immediate Deployment)**\n\n- **Token Binding**: Explicitly bind password-reset tokens to the payload email (resolving SEC-C1).\n- **SSO Hardening**: Address OIDC MFA bypasses during social SSO redirection.\n- **Secret Rotation \u0026 Vaulting**: Coordination of automated secret rotation policies (JWT keys, RSA keypairs) and moving credentials to a secrets manager.\n- **Strict CORS Policy**: Transition from loose substring matching to strict exact-origin allowlists.\n- **Session Revocation**: Real-time validation checks for JWT session cache revocation in Redis.\n\n#### **Phase 2: Stability \u0026 Performance**\n\n- **Testing Harness**: Setup automated integration testing with Vitest, Supertest, and Testcontainers.\n- **High-ROI DB Optimizations**: Add composite indexes on session tables and decouple slow hashing operations from atomic database transactions.\n- **Observability**: Integrate Prometheus metrics (`/metrics`), tracing headers, and standard audit logs.\n\n#### **Phase 3: Modernization \u0026 Enterprise Features**\n\n- **Passwordless (Passkeys)**: Deploy WebAuthn-based biometrics.\n- **Multi-Tenancy**: Introduce logical Organization partitioning.\n- **Enterprise Integration**: Enable SAML 2.0 / OIDC RP federation and transactional Webhooks.\n\nFor details on individual ticket tracking, metrics, and exit criteria, refer directly to the [**Master Execution Roadmap (`task.md`)**](./docs/audit/2026-07-20/task.md).\n\n---\n\n## 📬 Contact\n\nFound a bug, have a feature request, or want to contribute? Feel free to open an issue, start a discussion, or connect with me.\n\n[![LinkedIn](https://img.shields.io/badge/LinkedIn-0A66C2?style=for-the-badge\u0026logo=linkedin\u0026logoColor=white)](https://www.linkedin.com/in/amankrsahu)\n[![Discord](https://img.shields.io/badge/Discord-5865F2?style=for-the-badge\u0026logo=discord\u0026logoColor=white)](https://discordapp.com/users/539751578866024479)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Famankrsahu%2Fauthkit","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Famankrsahu%2Fauthkit","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Famankrsahu%2Fauthkit/lists"}