unkey icon indicating copy to clipboard operation
unkey copied to clipboard

feat: a developer can run auth locally without third party

Open mcstepp opened this issue 7 months ago • 14 comments

What does this PR do?

This feature allows developers, mostly contributors, to run Unkey locally without needing to sign-up for a third party, such as WorkOS, in order to create a user.

With local auth, a default user and default organization will be created, and the default local user may create a single workspace. Due to the single organization functionality, additional features are unavailable to local auth developers, including switching organizations, sign-in, inviting users to the workspace (also requires Stripe credentials), and creating additional local workspaces.

Developers who need to access to these features are recommended to use the WorkOS provider and provide their own WorkOS credentials to continue. Invitations and multi-member workspaces require the workspace to be locally upgraded to Pro plan or higher, which requires Stripe credentials.

Type of change

  • [ ] Bug fix (non-breaking change which fixes an issue)
  • [ ] Chore (refactoring code, technical debt, workflow improvements)
  • [ ] Enhancement (small improvements)
  • [x] New feature (non-breaking change which adds functionality)
  • [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • [x] This change requires a documentation update

How should this be tested?

  1. Checkout the branch.
  2. Ensure AUTH_PROVIDER = "local"
  3. Run pnpm dev
  4. Ensure local user stays signed in. Ensure local user can create only 1 workspace. Ensure local user is the only user in the system.

Checklist

Required

  • [x] Filled out the "How to test" section in this PR
  • [x] Read Contributing Guide
  • [x] Self-reviewed my own code
  • [x] Commented on my code in hard-to-understand areas
  • [x] Ran pnpm build
  • [x] Ran pnpm fmt
  • [x] Checked for warnings, there are none
  • [x] Removed all console.logs
  • [x] Merged the latest changes from main onto my branch with git pull origin main
  • [x] My changes don't cause any responsiveness issues

Appreciated

  • [ ] If a UI change was made: Added a screen recording or screenshots to this PR
  • [x] Updated the Unkey Docs if changes were necessary

Summary by CodeRabbit

  • New Features

    • Introduced a local authentication mode for development with a fixed user, organization, and membership.
    • Added support for switching between authentication providers, including the new local mode.
  • Bug Fixes

    • Improved error handling and notification when session data is missing during organization switching.
  • Documentation

    • Updated setup instructions to clarify the local authentication mode and removed references to obsolete external authentication requirements.
  • Chores

    • Disabled authentication middleware when using local authentication.
    • Restricted workspace creation to a single workspace in local authentication mode.

mcstepp avatar May 02 '25 16:05 mcstepp

⚠️ No Changeset found

Latest commit: 064245eb4fa7167238ac5c5e5c0a628abc3b3eaa

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

changeset-bot[bot] avatar May 02 '25 16:05 changeset-bot[bot]

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
dashboard ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 6, 2025 8:46pm
engineering ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 6, 2025 8:46pm

vercel[bot] avatar May 02 '25 16:05 vercel[bot]

[!IMPORTANT]

Review skipped

Review was skipped due to path filters

:no_entry: Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml

CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including **/dist/** will override the default block on the dist directory, by removing the pattern from both the lists.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

📝 Walkthrough

Walkthrough

This update introduces a local authentication provider for the dashboard application. It implements a LocalAuthProvider class that simulates a single-user, single-organization environment for local development. The authentication server logic is updated to support this new provider. Session management is adapted to recognize and handle local sessions, bypassing normal validation and refresh flows. Workspace creation logic is restricted under local auth to prevent multiple workspaces. Documentation is updated to clarify the new local auth mode, its limitations, and the distinction between required and optional external services. Middleware logic is also adjusted to disable authentication checks when in local mode.

Changes

File(s) Change Summary
apps/dashboard/lib/auth/local.ts Implements the LocalAuthProvider class, providing a fixed single-user, single-organization, and single-membership environment for local development. All authentication and organization methods return fixed or mock data, with no real multi-user or multi-org functionality.
apps/dashboard/lib/auth/base-provider.ts Expands and documents the BaseAuthProvider abstract class with comprehensive method signatures and JSDoc comments. Removes middleware-related logic and imports, focusing the class on authentication provider interfaces. Adds utility methods for error handling and response formatting.
apps/dashboard/lib/auth/server.ts Adds support for the "local" authentication provider in the AuthProvider class, including a private method to initialize the LocalAuthProvider.
apps/dashboard/lib/auth/sessions.ts Updates the updateSession function to handle the "local" authentication provider, issuing a persistent local session token and bypassing normal validation and refresh logic.
apps/dashboard/lib/auth/types.ts Adds exported constants: LOCAL_USER_ID, LOCAL_ORG_ID, and LOCAL_ORG_ROLE for use with the local authentication provider.
apps/dashboard/app/new/create-workspace.tsx Refactors the onSuccess callback in the workspace creation flow to use async/await, adds error handling for missing session expiration, and adjusts cookie options for stricter security. Enhances the onError callback to handle a specific "METHOD_NOT_SUPPORTED" error code with a custom toast and navigation action.
apps/dashboard/lib/trpc/routers/workspace/create.ts Adds a check to prevent multiple workspace creation when the authentication provider is "local", throwing an error if an additional workspace is attempted.
apps/dashboard/middleware.ts Changes the middleware to disable authentication checks when AUTH_PROVIDER is set to "local", enabling them for all other providers.
apps/engineering/content/contributing/index.mdx Updates documentation to clarify the local authentication mode, its limitations, and the distinction between required and optional external services. Removes references to Clerk as a required service and adds instructions for enabling local auth.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Dashboard
    participant LocalAuthProvider
    participant SessionManager

    User->>Dashboard: Access dashboard (local dev)
    Dashboard->>SessionManager: updateSession(request)
    SessionManager->>SessionManager: Check AUTH_PROVIDER == "local"
    alt Local Auth
        SessionManager->>SessionManager: Set local session token/cookie
        SessionManager-->>Dashboard: Return local session object
    else Other Auth
        SessionManager->>AuthProvider: Validate/refresh session
        AuthProvider-->>SessionManager: Session result
        SessionManager-->>Dashboard: Return session object
    end
    Dashboard-->>User: Render dashboard as local user
sequenceDiagram
    participant User
    participant Dashboard
    participant WorkspaceRouter
    participant DB

    User->>Dashboard: Create workspace (local auth)
    Dashboard->>WorkspaceRouter: createWorkspace mutation
    WorkspaceRouter->>DB: Query workspaces for tenant
    DB-->>WorkspaceRouter: Return workspace list
    WorkspaceRouter->>WorkspaceRouter: Check AUTH_PROVIDER == "local" and workspace exists
    alt Workspace exists and local auth
        WorkspaceRouter-->>Dashboard: Throw METHOD_NOT_SUPPORTED error
        Dashboard-->>User: Show error (only one workspace allowed)
    else No workspace or not local auth
        WorkspaceRouter->>DB: Create workspace
        DB-->>WorkspaceRouter: Workspace created
        WorkspaceRouter-->>Dashboard: Success
        Dashboard-->>User: Workspace created
    end

Suggested reviewers

  • perkinsjr
  • chronark
  • ogzhanolguncu

Suggested labels

Feature, Dashboard


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

coderabbitai[bot] avatar May 02 '25 16:05 coderabbitai[bot]

Thank you for following the naming conventions for pull request titles! 🙏

github-actions[bot] avatar May 02 '25 16:05 github-actions[bot]

@mcstepp can you review the Code Rabbit suggestions.

Can you also resolve the pnpm lock.

I checked everything out and everything works as expected as far as I can tell.

perkinsjr avatar May 05 '25 15:05 perkinsjr

CleanShot 2025-05-06 at 09 07 32@2x the names don't match, not sure if we want that or not

chronark avatar May 06 '25 07:05 chronark

Local workspaces should probably be created with the team quota enabled. It's a bit frustrating right now.

  1. I click "invite member".
  2. I get denied and asked if I want to start a trial.
  3. Then I get told stripe is not set up.

chronark avatar May 06 '25 07:05 chronark

When trying to create a new workspace, I get the toast error about the limit. That's great, but let's add a button to it to navigate back. Right now there's no way to escape the /new screen

The toast component has an action prop for it. Though I'm not sure how nice it will be to conditionally display it. checking error.shape?.code is probably pretty easy

toast.error(`Failed to create workspace: ${error.message}`,{action: <ButtonIGuess/>});

CleanShot 2025-05-06 at 09 10 21@2x

chronark avatar May 06 '25 07:05 chronark

Why would you change the core functionality of the product?

The /new I get.

The setting for teams is “annoying” I don’t. This is how the real flow in Unkey dashboard works, enabling Stripe is a requirement for teams.

Then if you want to actually do anything with teams, like invite a user, you’ll have to swap from local auth to WorkOS anyway.

What’s the benefit of not giving the correct flow in local auth? Zero.

perkinsjr avatar May 06 '25 11:05 perkinsjr

the benefit is that it just works out of the box

chronark avatar May 06 '25 11:05 chronark

ah wait maybe I’m thinking the wrong thing here

chronark avatar May 06 '25 11:05 chronark

yeah fair point ignore me

good first day..

chronark avatar May 06 '25 11:05 chronark

The /new I’ll fix in a couple mins

perkinsjr avatar May 06 '25 11:05 perkinsjr

I added some padding to the button so its not so crowded and dismissed the button on button click

mcstepp avatar May 06 '25 15:05 mcstepp