{"id":25321302,"url":"https://github.com/simon-fontaine/aegis-auth","last_synced_at":"2026-02-18T14:32:49.780Z","repository":{"id":276546573,"uuid":"928021461","full_name":"Simon-Fontaine/aegis-auth","owner":"Simon-Fontaine","description":"A credentials-based auth solution for Next.js (and other Node projects) with IP rate-limiting, account lockouts, and sessions in DB.","archived":false,"fork":false,"pushed_at":"2025-02-26T14:05:27.000Z","size":609,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-10-09T17:08:11.438Z","etag":null,"topics":["authentication","database-sessions","nextjs-auth","nodejs-auth","rate-limiting"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/aegis-auth","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/Simon-Fontaine.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":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2025-02-05T23:33:26.000Z","updated_at":"2025-02-14T09:34:18.000Z","dependencies_parsed_at":"2025-02-23T12:21:42.643Z","dependency_job_id":"1e4e9d13-da62-4846-a3c3-42f6a8e46b74","html_url":"https://github.com/Simon-Fontaine/aegis-auth","commit_stats":null,"previous_names":["simon-fontaine/aegis-auth","simon-fontaine/spectra-auth"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/Simon-Fontaine/aegis-auth","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Simon-Fontaine%2Faegis-auth","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Simon-Fontaine%2Faegis-auth/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Simon-Fontaine%2Faegis-auth/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Simon-Fontaine%2Faegis-auth/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Simon-Fontaine","download_url":"https://codeload.github.com/Simon-Fontaine/aegis-auth/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Simon-Fontaine%2Faegis-auth/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29582318,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-18T13:56:48.962Z","status":"ssl_error","status_checked_at":"2026-02-18T13:54:34.145Z","response_time":162,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: 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":["authentication","database-sessions","nextjs-auth","nodejs-auth","rate-limiting"],"created_at":"2025-02-13T22:36:21.527Z","updated_at":"2026-02-18T14:32:44.769Z","avatar_url":"https://github.com/Simon-Fontaine.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Aegis Auth\n\nAegis Auth is a secure, feature-rich authentication library for Next.js and Node.js applications. It provides everything you need to handle user authentication and session management—including user registration, login/logout, email verification, password resets, rate limiting, **role management**, and CSRF protection—all while following best security practices.\n\n\u003e **Note:** Aegis Auth uses [Prisma](https://www.prisma.io/) for database interactions, [Upstash Redis](https://upstash.com/) for rate limiting, and [Resend](https://resend.com/) for email delivery.\n\n## Features\n\n- **User Registration**: Secure sign-up with input validation and duplicate user prevention.\n- **User Login \u0026 Logout**: Create and revoke sessions with rate limiting and account lockout support.\n- **Session Management**: Create, validate, rotate, and revoke user sessions (with rolling sessions support).\n- **Password Reset**: Initiate and complete password resets using secure verification tokens.\n- **Email Verification**: Verify user emails during registration or upon request using customizable email templates.\n- **Rate Limiting**: Protect endpoints against abuse by limiting the number of requests per IP using Upstash Redis.\n- **CSRF Protection**: Generate and verify CSRF tokens to secure state-changing requests.\n- **Role Management**: Assign and update user roles (`updateUserRoles`) and ban/unban users for added security.\n- **Secure Password Hashing**: Utilizes the scrypt algorithm for password hashing.\n- **Flexible Configuration**: Customize every aspect of Aegis Auth via environment variables or by passing a configuration object.\n\n## Installation\n\nInstall the package via npm, Yarn, or pnpm:\n\n```bash\nnpm install aegis-auth\n# or\nyarn add aegis-auth\n# or\npnpm add aegis-auth\n```\n\n## Prerequisites\n\nBefore using Aegis Auth, ensure you have the following set up:\n\n- **Node.js** (v14 or higher)\n- **Database Connection**: Configure your database (PostgreSQL is supported) via the `DATABASE_URL` environment variable.\n- **Upstash Redis**: For rate limiting, provide `KV_REST_API_URL` and `KV_REST_API_TOKEN` in your environment.\n- **Resend API**: For email notifications, set the `RESEND_API_KEY` environment variable.\n- **Environment Variables**: See the [.env.example](.env.example) file for required and optional settings.\n\n## Configuration\n\nAegis Auth is highly configurable. You can override the default settings by providing a custom configuration object when you instantiate the library. For example:\n\n```typescript\nimport { PrismaClient } from \"@prisma/client\";\nimport { AegisAuth } from \"aegis-auth\";\n\nconst prisma = new PrismaClient();\n\n// Optionally override the default configuration\nconst customConfig = {\n  session: {\n    maxSessionsPerUser: 3, // Limit the number of concurrent sessions per user\n  },\n  accountSecurity: {\n    requireEmailVerification: true, // Force email verification on registration\n  },\n  // ...other custom settings\n};\n\nconst auth = new AegisAuth(prisma, customConfig);\n```\n\nYou can also configure most options via environment variables. See the provided `.env.example`:\n\n```dotenv\nSESSION_TOKEN_SECRET=\"change-me-in-prod\"\nCSRF_SECRET=\"change-me-in-prod\"\nKV_REST_API_URL=\"https://...\"\nKV_REST_API_TOKEN=\"...\"\nDATABASE_URL=\"your_database_connection_string\"\nNODE_ENV=\"development\"\nRESEND_API_KEY=\"your-resend-api-key\"\nEMAIL_FROM=\"no-reply@yourdomain.com\"\n```\n\nFor a full list of configuration options, refer to the [configuration schema](./src/config/schema.ts).\n\n## Usage\n\n### Initializing Aegis Auth\n\n```typescript\nimport { PrismaClient } from \"@prisma/client\";\nimport { AegisAuth } from \"aegis-auth\";\n\nconst prisma = new PrismaClient();\nconst auth = new AegisAuth(prisma);\n```\n\n### Registering a New User\n\n```typescript\n// Example: Register a new user\nconst registrationResult = await auth.registerUser(\n  { headers: request.headers },\n  {\n    username: \"john_doe\",\n    email: \"john@example.com\",\n    password: \"SecurePassword123!\",\n  }\n);\n\nif (registrationResult.success) {\n  console.log(\"User registered:\", registrationResult.data.user);\n} else {\n  console.error(\"Registration error:\", registrationResult.message);\n}\n```\n\n### Logging In\n\n```typescript\n// Example: Log in a user\nconst loginResult = await auth.loginUser(\n  { headers: request.headers },\n  {\n    usernameOrEmail: \"john@example.com\",\n    password: \"SecurePassword123!\",\n  }\n);\n\nif (loginResult.success) {\n  const { user, session } = loginResult.data;\n  console.log(\"Login successful for:\", user);\n  // Use session.sessionToken to set your session cookie\n} else {\n  console.error(\"Login failed:\", loginResult.message);\n}\n```\n\n### Managing Sessions\n\n- **Session Creation**: Performed during login.\n- **Session Validation \u0026 Rotation**: Use `validateAndRotateSession` to verify and refresh sessions.\n- **Logout**: Revoke the current session.\n\n```typescript\n// Example: Log out a user\nconst logoutResult = await auth.logoutUser({ sessionToken: \"user_session_token\" });\n\nif (logoutResult.success) {\n  console.log(\"User logged out successfully\");\n} else {\n  console.error(\"Logout error:\", logoutResult.message);\n}\n```\n\n### Password Reset\n\n#### Initiate Password Reset\n\n```typescript\n// Initiate the password reset process (sends an email with a verification token)\nconst initiateResult = await auth.initiatePasswordReset(\n  { headers: request.headers },\n  { email: \"john@example.com\" }\n);\nconsole.log(initiateResult.message);\n```\n\n#### Complete Password Reset\n\n```typescript\n// Complete the password reset using the token sent via email\nconst completeResult = await auth.completePasswordReset(\n  { headers: request.headers },\n  {\n    token: \"verification_token_from_email\",\n    newPassword: \"NewSecurePassword123!\",\n  }\n);\n\nif (completeResult.success) {\n  console.log(\"Password reset successful\");\n} else {\n  console.error(\"Password reset error:\", completeResult.message);\n}\n```\n\n### Email Verification\n\nWhen email verification is enabled, a verification email is sent upon registration. To verify the email:\n\n```typescript\nconst verificationResult = await auth.verifyEmail(\n  { headers: request.headers },\n  { token: \"verification_token_from_email\" }\n);\n\nif (verificationResult.success) {\n  console.log(\"Email verified successfully\");\n} else {\n  console.error(\"Email verification failed:\", verificationResult.message);\n}\n```\n\n### Role Management \u0026 Banning\n\n#### Update User Roles\n\n```typescript\n// Example: Assign or update user roles\nconst updateRolesResult = await auth.updateUserRoles({\n  userId: \"some_user_id\",\n  roles: [\"admin\", \"moderator\"],\n});\n\nif (updateRolesResult.success) {\n  console.log(\"Roles updated successfully\");\n} else {\n  console.error(\"Failed to update roles:\", updateRolesResult.message);\n}\n```\n\n#### Ban a User\n\n```typescript\n// Example: Ban a user\nconst banResult = await auth.banUser({ userId: \"some_user_id\" });\n\nif (banResult.success) {\n  console.log(\"User banned successfully\");\n} else {\n  console.error(\"Ban error:\", banResult.message);\n}\n```\n\n#### Unban a User\n\n```typescript\n// Example: Unban a user\nconst unbanResult = await auth.unbanUser({ userId: \"some_user_id\" });\n\nif (unbanResult.success) {\n  console.log(\"User unbanned successfully\");\n} else {\n  console.error(\"Unban error:\", unbanResult.message);\n}\n```\n\nThese actions are **not** automatically restricted to administrators. In your application, you should implement your own checks (e.g., only call `banUser` if the current user is an admin).\n\n## Testing\n\nAegis Auth includes a comprehensive suite of tests using Jest. To run the tests:\n\n```bash\nnpm test\n```\n\n## Development\n\nTo build the project, run:\n\n```bash\nnpm run build\n```\n\nLint your code with:\n\n```bash\nnpm run lint\n```\n\n## Security\n\nSecurity is a top priority. If you discover any vulnerabilities, please refer to our [SECURITY.md](SECURITY.md) for instructions on reporting issues.\n\n## License\n\nAegis Auth is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.\n\n## Contact\n\nFor questions, support, or contributions, please open an issue on [GitHub](https://github.com/Simon-Fontaine/aegis-auth) or email [github@simonfontaine.com](mailto:github@simonfontaine.com).\n\n---\n\nHappy coding!\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsimon-fontaine%2Faegis-auth","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsimon-fontaine%2Faegis-auth","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsimon-fontaine%2Faegis-auth/lists"}