{"id":26070231,"url":"https://github.com/rintoj/hypergraph-auth","last_synced_at":"2025-08-17T10:40:38.640Z","repository":{"id":274015973,"uuid":"921636934","full_name":"rintoj/hypergraph-auth","owner":"rintoj","description":"NestJS based modules for authentication. Supports local (email, username \u0026 password) and Supabase authentication.","archived":false,"fork":false,"pushed_at":"2025-07-17T02:08:30.000Z","size":192,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-07-24T08:36:06.784Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"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/rintoj.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":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-01-24T10:23:04.000Z","updated_at":"2025-07-17T02:06:25.000Z","dependencies_parsed_at":"2025-06-06T00:33:44.946Z","dependency_job_id":"bb08f103-60ff-49d2-beec-b7982114a140","html_url":"https://github.com/rintoj/hypergraph-auth","commit_stats":null,"previous_names":["rintoj/hypergraph-auth"],"tags_count":15,"template":false,"template_full_name":null,"purl":"pkg:github/rintoj/hypergraph-auth","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rintoj%2Fhypergraph-auth","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rintoj%2Fhypergraph-auth/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rintoj%2Fhypergraph-auth/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rintoj%2Fhypergraph-auth/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rintoj","download_url":"https://codeload.github.com/rintoj/hypergraph-auth/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rintoj%2Fhypergraph-auth/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":269457806,"owners_count":24420300,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-08-08T02:00:09.200Z","response_time":72,"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":[],"created_at":"2025-03-08T23:07:40.228Z","updated_at":"2025-08-17T10:40:38.609Z","avatar_url":"https://github.com/rintoj.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Hypergraph Auth: Seamless Authentication for Your NestJS Applications (`@hgraph/auth`)\n\n**Embark on a journey to effortless user management with Hypergraph Auth, your trusted companion for\nimplementing robust authentication in NestJS.** This module empowers you to swiftly integrate a wide\narray of authentication providers, from social giants like Google and GitHub to a bespoke local\nstrategy, all within a unified and elegant framework.\n\n## The Story of Secure Access\n\nImagine building a vibrant online community. Your users arrive, eager to join, but a cumbersome\nregistration process stands in their way. Frustration mounts, and potential members are lost. This\nis where Hypergraph Auth steps in. Like a skilled concierge, it streamlines the entry process,\noffering a welcoming hand to each user, regardless of their preferred sign-in method.\n\nWith Hypergraph Auth, you craft a seamless experience. Users can authenticate with their existing\nsocial accounts, or register directly, all while you maintain control and security behind the\nscenes. This library acts as your silent guardian, handling the complexities of authentication so\nyou can focus on building the heart of your application.\n\n## Installation\n\nBegin your integration journey by installing the Hypergraph Auth module using npm or yarn:\n\n```bash\nnpm install @hgraph/auth\n```\n\nor\n\n```bash\nyarn add @hgraph/auth\n```\n\n## Usage\n\nIntegrating Hypergraph Auth into your NestJS application is a straightforward process. The following\nexample illustrates how to configure the module with both a local strategy for traditional\nusername/password authentication and a Supabase strategy for leveraging social logins and other\nadvanced features.\n\n### Example Configuration\n\n```typescript\nimport { Module } from '@nestjs/common'\nimport { UserModule } from './user/user.module'\nimport { UserService } from './user/user.service'\nimport { AuthModule } from '@hgraph/auth'\nimport { createLocalStrategy } from '@hgraph/auth/local'\nimport { createSupabaseAuthStrategy } from '@hgraph/auth/supabase'\nimport { createGoogleAuthStrategy } from '@hgraph/auth/google'\n\n@Module({\n  imports: [\n    UserModule, // Your custom module to manage user data\n    AuthModule.forRoot({\n      userService: UserService, // Your implementation of the user service (explained below)\n      strategies: [\n        createLocalStrategy({\n          enableGraphQLAPI: true, // Expose local auth via GraphQL\n          enableRestAPI: true, // Expose local auth via REST\n        }),\n        createSupabaseAuthStrategy({\n          supabaseUrl: config.SUPABASE_URL, // Your Supabase project URL\n          supabaseAnonKey: config.SUPABASE_ANON_KEY, // Your Supabase anon key\n          redirectUrl: config.AUTH_REDIRECT_URL, // URL to redirect after OAuth login\n          providers: ['google', 'github', 'facebook'], // Enabled OAuth providers\n        }),\n        createGoogleAuthStrategy({\n          clientId: config.GOOGLE_CLIENT_ID,\n          clientSecret: config.GOOGLE_CLIENT_SECRET,\n          redirectUrl: config.GOOGLE_REDIRECT_URL,\n        }),\n      ],\n      jwtConfig: {\n        secret: config.JWT_SECRET, // Secret key for signing JWTs\n        expiry: config.JWT_EXPIRY, // Expiration time for access tokens\n        refreshSecret: config.JWT_REFRESH_SECRET, // Secret for refresh tokens\n        refreshExpiry: config.JWT_REFRESH_EXPIRY, // Expiration for refresh tokens\n      },\n    }),\n  ],\n  controllers: [AppController], // Your application's main controller\n})\nexport class AppModule {}\n```\n\n**Important Note:** To effectively use the Supabase strategy, you need to configure authentication\nproviders within your Supabase project. Please refer to the\n[Supabase Auth documentation](https://supabase.com/docs/guides/auth) for detailed instructions on\nsetting up providers like Google, GitHub, and Facebook.\n\n## API Endpoints: Your Gateway to User Authentication\n\nHypergraph Auth provides a comprehensive suite of RESTful endpoints and a GraphQL API to manage user\nauthentication effectively.\n\n### RESTful Endpoints\n\n| Endpoint                    | Method | Description                                                                                            | Request Body                             | Response Body                                 |\n| :-------------------------- | :----- | :----------------------------------------------------------------------------------------------------- | :--------------------------------------- | :-------------------------------------------- |\n| `/auth/signup`              | `POST` | Registers a new user with a username and password.                                                     | `{ username: string, password: string }` | `{ userId: string }`                          |\n| `/auth/signin`              | `POST` | Authenticates an existing user with a username and password.                                           | `{ username: string, password: string }` | `{ accessToken: string, userId: string }`     |\n| `/auth/signout`             | `POST` | Logs out the currently authenticated user.                                                             | _None_                                   | _None_                                        |\n| `/auth/supabase/{provider}` | `GET`  | Initiates the Supabase authentication flow for the specified provider (e.g., `/auth/supabase/google`). | _None_                                   | _Redirects to provider's authentication page_ |\n| `/auth/supabase/callback`   | `GET`  | Handles the Supabase authentication callback.                                                          | `{ code: string, state: string }`        | `{ code: string, provider: string }`          |\n| `/auth/google`              | `GET`  | Initiates the Google authentication flow.                                                              | _None_                                   | _Redirects to Google's authentication page_   |\n| `/auth/google/callback`     | `GET`  | Handles the Google authentication callback.                                                            | `{ code: string, state: string }`        | `{ code: string, provider: string }`          |\n| `/auth/google/token`        | `POST` | Exchanges the Google authentication code for an access token.                                          | `{ code: string, provider: string }`     | `{ accessToken: string, userId: string }`     |\n| `/auth/token`               | `POST` | Get token using OAuth Code and provider                                                                | `{ code: string, provider: string }`     | `{ accessToken: string, userId: string }`     |\n\n### GraphQL API: Flexibility and Power\n\nFor those who prefer the expressiveness of GraphQL, Hypergraph Auth offers a complete schema to\ninteract with the authentication system.\n\n#### Schema Definition\n\n```graphql\nscalar DateTime\n\ntype Mutation {\n  signupWithUsername(password: String!, username: String!): SignupResponse!\n  signinWithUsername(password: String!, username: String!): SigninResponse!\n  signinWithCode(code: String!, provider: String!): SigninResponse!\n  signout: Boolean!\n}\n\ntype Query {\n  me: User\n}\n\ntype SigninResponse {\n  accessToken: String!\n  userId: String!\n}\n\ntype SignupResponse {\n  userId: String!\n}\n\ntype User {\n  createdAt: DateTime\n  email: String!\n  id: ID!\n  name: String!\n  phoneNumber: String\n  pictureUrl: String\n  roles: [UserRole!]!\n  updatedAt: DateTime\n}\n\nenum UserRole {\n  Admin\n  User\n}\n```\n\n#### Schema Breakdown\n\n- **Mutations:**\n  - `signupWithUsername`: Registers a new user.\n  - `signinWithUsername`: Logs in an existing user.\n  - `signinWithCode`: Logs in a user using OAuth code and provider.\n  - `signout`: Logs out the current user.\n- **Queries:**\n  - `me`: Retrieves information about the currently authenticated user.\n- **Types:**\n  - `SigninResponse`: Represents a successful sign-in, returning an access token and user ID.\n  - `SignupResponse`: Represents a successful sign-up, returning the newly created user's ID.\n  - `User`: Defines the structure of a user object.\n  - `UserRole`: An enumeration of possible user roles (e.g., `Admin`, `User`).\n\n## The User Service: Bridging Authentication and Your Application\n\nTo seamlessly integrate Hypergraph Auth, you need to implement a `UserService` that conforms to the\n`UserServiceSpec` interface provided by the library. This service acts as a bridge between the\nauthentication system and your application's user data.\n\n### `UserServiceSpec` Interface\n\n```typescript\nimport { AuthInfo, UserMetadata } from '@hgraph/auth'\n\ninterface UserServiceSpec {\n  findById(id: string): Promise\u003cAuthInfo | undefined\u003e\n  findByIdentifier(identifier: string): Promise\u003cAuthInfo | undefined\u003e\n  createUser(user: UserMetadata): Promise\u003cAuthInfo\u003e\n}\n```\n\n### `AuthInfo` and `UserMetadata` Types\n\n```typescript\nexport type AuthInfo = {\n  userId: string\n  identifier: string\n  roles: string[]\n}\n\nexport type UserMetadata = {\n  identifier: string\n  name: string\n  phoneNumber?: string\n  pictureUrl?: string\n}\n```\n\n### Sample `UserService` Implementation\n\nBelow is an example of how you might implement the `UserService` using NestJS and a hypothetical\n`User` entity from a data access layer (e.g., `@hgraph/storage/nestjs`).\n\n```typescript\nimport { generateIdOf } from '@hgraph/storage'\nimport { InjectRepo, Repository } from '@hgraph/storage/nestjs'\nimport { Injectable } from '@nestjs/common'\nimport { UserServiceSpec, AuthInfo, UserMetadata } from '@hgraph/auth'\nimport { User, UserStatus } from './user.model' // Your user entity\n\n@Injectable()\nexport class UserService implements UserServiceSpec {\n  constructor(@InjectRepo(User) protected readonly userRepository: Repository\u003cUser\u003e) {}\n\n  protected toAuthInfo(user: User | undefined): AuthInfo | undefined {\n    if (!user) return\n    return {\n      userId: user.id,\n      identifier: user.email, // Assuming email is the unique identifier\n      roles: user.roles,\n    }\n  }\n\n  protected generateId(identifier: string) {\n    return generateIdOf('email:' + identifier?.toLocaleLowerCase().trim())\n  }\n\n  async findById(id: string): Promise\u003cAuthInfo | undefined\u003e {\n    return this.toAuthInfo(await this.userRepository.findById(id))\n  }\n\n  async findByIdentifier(identifier: string): Promise\u003cAuthInfo | undefined\u003e {\n    const user = await this.userRepository.findOne(q =\u003e q.whereEqualTo('email', identifier))\n    return this.toAuthInfo(user)\n  }\n\n  async createUser(input: UserMetadata): Promise\u003cAuthInfo\u003e {\n    const id = this.generateId(input.identifier)\n    const user = await this.userRepository.insert({\n      id,\n      name: input.name,\n      email: input.identifier,\n      phoneNumber: input.phoneNumber,\n      pictureUrl: input.pictureUrl,\n      status: UserStatus.Active, // Assuming you have a UserStatus enum\n      roles: ['User'], // Default role for new users\n    })\n    return this.toAuthInfo(user)\n  }\n}\n```\n\n**Explanation:**\n\n1.  **`toAuthInfo`:** A utility method to convert your `User` entity to the `AuthInfo` type expected\n    by Hypergraph Auth.\n2.  **`generateId`:** A utility method to create unique IDs.\n3.  **`findById`:** Retrieves a user by their ID and returns their `AuthInfo`.\n4.  **`findByIdentifier`:** Retrieves a user by their unique identifier (e.g., email) and returns\n    their `AuthInfo`.\n5.  **`createUser`:** Creates a new user in your database and returns their `AuthInfo`.\n\n## Conclusion\n\nHypergraph Auth provides a robust and flexible solution for implementing authentication in your\nNestJS applications. By following the guidelines and examples in this documentation, you can quickly\nintegrate various authentication strategies, manage user data effectively, and focus on building the\ncore features of your application. Welcome to a world of seamless and secure user access!\n\n---\n\n**Copyright 2025 Rinto Jose**\n\n**Released under the MIT License**\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frintoj%2Fhypergraph-auth","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frintoj%2Fhypergraph-auth","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frintoj%2Fhypergraph-auth/lists"}