Skip to content
abdulrdeveloperPublic

About

Clavis: a self-hosted OpenID Connect provider. Let other apps add "Continue with Clavis" using the authorization code flow with PKCE, RS256 ID tokens and a consent screen. Includes email verification, per-device sessions and connected apps. Express 5, TypeScript, MongoDB, Redis, React 18.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

2 stars

Watchers

0 watching

Forks

Repository files navigation

Clavis

Open-source identity for your apps: sign-up, sign-in, and OpenID Connect, self-hosted.

Clavis is an open-source identity platform, built in the same spirit as Clerk. Users sign up, verify their email and sign in once. Your other apps then receive standard OpenID Connect tokens. Use the hosted version, or run it on your own infrastructure with MongoDB, Redis and Resend.

Open Clavis · Register an app · Self-host · Report a bug

Live License: MIT Express 5 React 18 TypeScript PRs welcome


What is Clavis?

Almost every SaaS, dashboard or side project needs the same thing first: a safe way for people to sign up and sign in. Building it properly takes days, and small mistakes (tokens in localStorage, unlimited OTP guesses, leaking stack traces) turn into real security problems.

Clavis covers the parts that are easy to get wrong, already built and tested:

  • Backend: Express 5, TypeScript, MongoDB (Mongoose), Upstash Redis and Resend.
  • Frontend: React 18, Vite and Tailwind CSS v4.
  • Sessions: a short-lived access token and a rotating refresh token, both in HttpOnly cookies that JavaScript cannot read.

It is focused on a few things done well: email and password accounts, a hosted-style sign-in UI, and an OpenID Connect provider for your other apps. Social login and an admin dashboard are not included yet.

Try it

Clavis is live at clavis.abdulrdeveloper.me.

  1. Create an account and enter the 6-digit code sent to your email.
  2. Open the dashboard to see your signed-in devices and the apps you have connected.
  3. Open Developers and click New app to get a client ID and secret. The page also shows the issuer URL and discovery document to give your OpenID Connect library.
  4. Add "Sign in with Clavis" to your site using the OpenID Connect flow below.

The hosted version is run by the maintainer. If you want full control over accounts, signing keys and data, run your own copy.

Features

Sign up and verify

  • Register with name, email and password.
  • A 6-digit code is emailed through Resend and expires after 5 minutes.
  • Resend the code with a cooldown, and get signed in automatically after verifying.
  • Unverified accounts are deleted automatically after 24 hours.

Sign in and stay signed in

  • 15 minute access token and 7 day refresh token, both HttpOnly cookies.
  • The refresh token rotates on every use, and an old one is rejected.
  • The frontend refreshes the session silently. Five requests failing at once still trigger only one refresh.
  • Each device gets its own session. Signing in on a phone does not sign out the laptop.
  • Logout ends only this device's session, and the device loses access at once.

Recover an account

  • Forgot password sends a separate reset code.
  • Resetting the password signs out every device.

Protected by default

  • Wrong OTP guesses are limited to 5 per code, even when sent in parallel.
  • IP rate limiting on login, register, OTP and email routes.
  • Passwords hashed with bcrypt and never returned by the API.
  • Generic responses on forgot password and resend, so the API does not reveal which emails have accounts.
  • A central error handler returns clean JSON and never leaks stack traces.
  • The server refuses to start if a required environment variable is missing, or if the access and refresh secrets are the same.

Ready for your app

  • ProtectedRoute and PublicRoute wrappers, plus a useAuth() hook with the current user.
  • After login, users return to the page they were trying to open.
  • The dashboard lists every signed-in device (browser, system, IP, last active). One click and a confirmation sign a device out immediately.
  • Connected apps: users see every app they signed in to with Clavis and can remove one. Its access token stops working at once and it must ask again. Consent is asked once per app, not on every sign-in.
  • A Developers page (/developers) to register apps, copy the client ID, see the secret once, and delete apps.
  • Every timing and limit lives in one config file.
  • Responsive layout with labelled, keyboard-friendly forms.

How it works

  1. Register: the user signs up and receives a verification code by email.
  2. Verify: the code is checked against Redis, the account is marked verified, and the user is signed in.
  3. Use the app: every request carries the access cookie. When it expires, the frontend calls /api/auth/refresh once and retries the request.
  4. Sign out: the refresh token is deleted from Redis and both cookies are cleared.

Run it yourself

You need

  • Node.js 24 and pnpm 11 (corepack enable sets up pnpm)
  • A MongoDB database (Atlas free tier or a local mongodb://127.0.0.1:27017/clavis)
  • An Upstash Redis database (free tier), using the REST URL and token
  • A Resend API key (free tier) and a sender address on a domain verified in Resend

Quick start

git clone https://github.com/abdulrdeveloper/clavis.git
cd clavis

cd backend
pnpm install
cp .env.example .env
pnpm dev

In a second terminal:

cd frontend
pnpm install
cp .env.example .env
pnpm dev

Open http://localhost:5173. The API runs on http://localhost:3000.

Generate the two token secrets with this command, once for each. They must be different:

node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"

Configuration

Backend (backend/.env):

Variable Required What it is
PORT No API port, default 3000
NODE_ENV Yes in production Set to production to enable Secure cookies
FRONTEND_URL Yes Allowed frontend origin for CORS, comma-separated for several
COOKIE_SAMESITE Yes lax when frontend and API share a site, none when they are on different sites
MONGO_URI Yes MongoDB connection string
ACCESS_TOKEN_SECRET Yes Secret for access tokens
REFRESH_TOKEN_SECRET Yes Secret for refresh tokens, different from the access secret
RESEND_API_KEY Yes Resend API key
EMAIL_FROM Yes Sender address on your verified Resend domain
APP_NAME No Sender name shown in emails
UPSTASH_REDIS_REST_URL Yes Upstash Redis REST URL
UPSTASH_REDIS_REST_TOKEN Yes Upstash Redis REST token
ISSUER_URL Yes in production Public URL of the backend, used as the OpenID Connect issuer
OIDC_PRIVATE_KEY Yes in production RSA private key that signs ID tokens. Generate it with pnpm generate:keys
OIDC_KEY_ID No Key id in the token header, default clavis-key-v1

Frontend (frontend/.env):

Variable Required What it is
VITE_API_URL Yes in production Backend URL, default http://localhost:3000

Never commit .env files. Both folders include a .env.example.

Make it yours

What Where
Token lifetimes, OTP timings, password length, rate limits backend/src/config/auth.config.ts
Brand name, tagline and repository links frontend/src/config/site.ts
Email design and wording backend/src/services/mail.service.ts
Page title and favicon frontend/index.html, frontend/public/logo-mark.png
New protected pages Add a <Route> inside <ProtectedRoute> in frontend/src/App.tsx

Deploy

The hosted version runs the frontend on Vercel and the backend on Heroku. Clavis works on any Node.js host, but these two need no extra setup.

Backend on Heroku

  • Create an app in the Heroku dashboard. In its Deploy tab, connect this GitHub repository and deploy the main branch. No CLI is needed, and you can turn on automatic deploys for main.
  • Heroku builds from the repository root. The root package.json installs the backend with pnpm and compiles it with tsc, and the root Procfile runs node backend/dist/server.js.
  • In Settings, add every backend variable as a Config Var, with NODE_ENV=production, FRONTEND_URL set to your frontend URL (for the hosted version, https://clavis.abdulrdeveloper.me) and ISSUER_URL set to the app's own URL, shown under Domains.

Frontend on Vercel

  • Set the Root Directory to frontend and set VITE_API_URL to the backend URL.
  • frontend/vercel.json rewrites all routes to index.html.

After both are live, open /health on the backend to check it is running, then sign up on the frontend.

Cookies across domains

Some browsers, Safari in particular, block cookies sent between different sites. Put the API on a subdomain of the frontend's domain, for example app.example.com and api.example.com, and set COOKIE_SAMESITE=lax. Use none only when that is not possible. The hosted version uses none for now, because its API runs on a herokuapp.com address.

API

Account routes are under /api/auth.

Method Route What it does
POST /register Create an account and send a verification code
POST /verify-email Verify the code and sign in
POST /resend-otp Send a new verification code
POST /login Sign in with email and password
POST /refresh Rotate the refresh token and issue a new access token
GET /me Return the signed-in user
POST /logout End this device's session and clear cookies
GET /sessions List the signed-in devices, this one first
DELETE /sessions/:id Sign a device out immediately
POST /forgot-password Send a password reset code
POST /verify-reset-otp Check a reset code
POST /reset-password Set a new password and sign out every device

App and consent routes are under /api/oauth.

Method Route What it does
GET /client-info Return an app's name for the consent screen
POST /consent Allow an app and continue the sign-in
GET /clients List the apps this user registered
POST /clients Register an app and return its secret once
DELETE /clients/:clientId Delete an app
GET /grants List the apps this user has allowed
DELETE /grants/:clientId Remove an app's access

The OpenID Connect endpoints (/.well-known/* and /oauth/*) are listed in the OpenID Connect section.

GET /health returns { "status": "Welcome to Clavis!" } for uptime checks.

Tech stack

Area Tools
API Express 5, TypeScript, Zod
Data MongoDB with Mongoose, Upstash Redis
Auth JSON Web Tokens, bcrypt, HttpOnly cookies
Email Resend
UI React 18, React Router 7, Vite, Tailwind CSS 4, Lucide icons
Tooling pnpm

Useful commands

Folder Command What it does
backend pnpm dev Compile in watch mode and run the API
backend pnpm build / pnpm start Production build and server
backend pnpm type-check TypeScript check
frontend pnpm dev Start the Vite dev server
frontend pnpm build / pnpm preview Production build and local preview

Project layout

package.json             Heroku build from the repository root (installs and builds backend/)
Procfile                 Heroku start command
backend/
  server.ts              Startup, env checks, database connection
  src/config/            Auth and OIDC settings, cookies, validation schemas, database
  src/routes/            Account, OAuth and OpenID Connect routes
  src/controllers/       Request handlers, one file per feature
  src/middlewares/       Auth, validation, rate limit and error handling
  src/services/          Sessions, tokens, signing keys, OTP, email, Redis and OAuth clients
  src/utils/             Tokens, user agents and the public user object
  src/models/            Mongoose models for users, OAuth clients and grants
  src/scripts/           generate:keys and new-client commands
frontend/
  src/pages/             Landing page, auth pages, dashboard and Developers
  src/components/        Layout, form fields and route guards
  src/context/           AuthProvider and useAuth
  src/lib/               API client with silent refresh
  src/config/            Site branding
  public/                Favicon, app icons and social preview image

Project status

The full flow, from registration to logout, is tested end to end against real MongoDB and Upstash, in the API and in a headless browser.

One limitation is intentional, to keep Clavis simple:

  • Unverified email squatting. If someone registers another person's email and never verifies it, the real owner can still register, or recover the account with forgot password.

There are no automated tests in the repository yet.

Use it as a login provider for other sites (OpenID Connect)

The backend is an OpenID Connect provider. Any site can use it for login with a standard OIDC library (for example openid-client, Auth.js / NextAuth, or Passport).

Environment variables

Set ISSUER_URL, OIDC_PRIVATE_KEY and OIDC_KEY_ID as described in Configuration. Without OIDC_PRIVATE_KEY, development uses a temporary key that changes on every restart, and production refuses to start.

Endpoints

Endpoint Purpose
GET /.well-known/openid-configuration Discovery document. Most libraries only need this URL.
GET /.well-known/jwks.json Public key for verifying tokens.
GET /oauth/authorize Starts login. Signs the user in and asks for consent if needed.
POST /oauth/token Exchanges the code for id_token and access_token.
GET /oauth/userinfo Returns the user's profile for a Bearer access token.

Register a site (client)

  • Your own sites (no consent screen), from backend/:
    pnpm run new-client "My Site" https://mysite.com/auth/callback
    Add --untrusted to show the consent screen instead.
  • Other people's sites: a signed-in user opens Developers (/developers) and clicks New app, or calls POST /api/oauth/clients with name and redirectUris. Users see a consent screen the first time they sign in to these apps.

The client secret is shown only once, when the client is created.

Connected apps (signed-in user, under /api/oauth)

Method Route What it does
GET /grants Apps this user has allowed, with scopes and last use
DELETE /grants/:clientId Remove an app. Its access token stops working at once

Flow

  1. Send the user to /oauth/authorize?response_type=code&client_id=...&redirect_uri=...&scope=openid%20profile%20email&state=...&nonce=...&code_challenge=...&code_challenge_method=S256.
  2. The user comes back to redirect_uri?code=...&state=....
  3. Your server posts grant_type=authorization_code, code, redirect_uri and code_verifier to /oauth/token as a form, with the client id and secret in a Basic auth header.
  4. Verify the id_token with the JWKS, or call /oauth/userinfo with the access token.

Contributing

Contributions are welcome, from typo fixes to new features. Please read CONTRIBUTING.md and follow our Code of Conduct. Every change goes through a pull request.

Need help? See SUPPORT.md.

Security

Found a vulnerability? Please report it privately as described in SECURITY.md instead of opening a public issue.

Policies

License

Released under the MIT License. Copyright (c) 2026 Abdul Rahman.

About

Clavis: a self-hosted OpenID Connect provider. Let other apps add "Continue with Clavis" using the authorization code flow with PKCE, RS256 ID tokens and a consent screen. Includes email verification, per-device sessions and connected apps. Express 5, TypeScript, MongoDB, Redis, React 18.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages