authtrust
v0.1.0
Published
Zero-config authentication built on Better Auth. Email/password, social login, admin user CRUD, sessions, roles & middleware — all preconfigured.
Maintainers
Readme
authtrust
Zero-config authentication built on Better Auth. Email/password, social login, admin user CRUD, sessions, roles & Express middleware — all preconfigured.
Install
npm install authtrust
# or
pnpm add authtrustQuick Start
1. Create Auth Instance
import { createAuth } from 'authtrust';
export const auth = createAuth({
secret: process.env.BETTER_AUTH_SECRET,
baseURL: 'http://localhost:3000',
database: new Database('./sqlite.db'), // any Better Auth database
appName: 'My App',
// Email & password (enabled by default)
emailAndPassword: true,
// Social providers
socialProviders: {
github: {
clientId: process.env.GITHUB_CLIENT_ID!,
clientSecret: process.env.GITHUB_CLIENT_SECRET!,
},
google: {
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
},
},
// Session config
session: {
expiresIn: 60 * 60 * 24 * 7, // 7 days
cookieCache: true,
},
// Admin plugin (enabled by default)
admin: {
defaultRole: 'user',
adminRoles: ['admin'],
},
// Rate limiting
rateLimit: { enabled: true, window: 10, max: 100 },
// Extend user schema
user: {
additionalFields: {
phone: { type: 'string', required: false },
plan: { type: ['free', 'pro', 'enterprise'], defaultValue: 'free' },
},
},
});2. Mount on Express
import express from 'express';
import { createAuth } from 'authtrust';
import { authHandler, authMiddleware, adminMiddleware } from 'authtrust/express';
const app = express();
const auth = createAuth({ /* config */ });
// Mount Better Auth routes
app.all('/api/auth/*', authHandler(auth));
// Protected route
app.get('/api/me', authMiddleware(auth), (req, res) => {
res.json(req.auth);
});
// Admin-only route
app.get('/api/admin/dashboard',
authMiddleware(auth),
adminMiddleware(),
(req, res) => {
res.json({ message: 'Welcome, admin!' });
}
);3. User CRUD (Server-Side)
import {
createUser,
getUser,
listUsers,
updateUser,
removeUser,
setRole,
banUser,
unbanUser,
setUserPassword,
} from 'authtrust';
// Create a user (requires admin headers)
const user = await createUser(auth, {
email: '[email protected]',
password: 'secure-password',
name: 'John Doe',
role: 'user',
}, headers);
// List users with search & pagination
const { users, total } = await listUsers(auth, {
searchValue: 'john',
searchField: 'name',
limit: 20,
offset: 0,
sortBy: 'createdAt',
sortDirection: 'desc',
}, headers);
// Update a user
await updateUser(auth, {
userId: user.id,
data: { name: 'John Smith' },
}, headers);
// Set role
await setRole(auth, user.id, 'admin', headers);
// Ban / unban
await banUser(auth, { userId: user.id, banReason: 'Spam' }, headers);
await unbanUser(auth, user.id, headers);
// Remove user
await removeUser(auth, user.id, headers);4. Session Management
import {
getSession,
listUserSessions,
revokeSession,
revokeAllSessions,
impersonateUser,
stopImpersonating,
} from 'authtrust';
// Get current session
const session = await getSession(auth, headers);
// List all sessions for a user
const sessions = await listUserSessions(auth, userId, headers);
// Revoke a specific session
await revokeSession(auth, sessionToken, headers);
// Revoke all sessions for a user
await revokeAllSessions(auth, userId, headers);
// Impersonate a user (admin)
const impersonated = await impersonateUser(auth, userId, headers);
await stopImpersonating(auth, headers);5. Client-Side
import { createAuthClient } from 'authtrust/client';
const authClient = createAuthClient({
baseURL: 'http://localhost:3000',
});
// Sign up
await authClient.signUp.email({
email: '[email protected]',
password: 'password',
name: 'User',
});
// Sign in
await authClient.signIn.email({ email, password });
// Get session
const { data: session } = await authClient.getSession();
// Admin operations
const { data: users } = await authClient.admin.listUsers();
await authClient.admin.banUser({ userId: 'user-id' });
// Sign out
await authClient.signOut();Config Reference
| Option | Type | Default | Description |
|---|---|---|---|
| secret | string | BETTER_AUTH_SECRET env | Signing/encryption secret (min 32 chars) |
| baseURL | string | BETTER_AUTH_URL env | Base URL of your app |
| basePath | string | "/api/auth" | Base path for auth routes |
| appName | string | "Better Auth" | App display name |
| database | various | — | Database connection (SQLite, PG, MySQL, ORM adapter) |
| emailAndPassword | boolean \| object | true | Email/password auth config |
| socialProviders | object | — | OAuth provider configs |
| session | object | 7-day expiry | Session management options |
| admin | boolean \| object | true | Admin plugin options |
| user | object | — | User schema extensions |
| rateLimit | boolean \| object | — | Rate limiting config |
| plugins | array | — | Additional Better Auth plugins |
| advanced | object | — | Advanced Better Auth options |
What's Included
- Email/Password Auth — sign up, sign in, password reset
- Social Login — Google, GitHub, Apple, Discord, Twitter, Facebook, Microsoft & more
- Admin Plugin — full user CRUD, role management, ban/unban, impersonation
- Session Management — cookie-based sessions, listing, revocation
- Express Middleware —
authMiddleware,adminMiddleware,authHandler - Client SDK — preconfigured client with admin operations
- Rate Limiting — built-in rate limiter
- TypeScript — fully typed config, user, session, and CRUD types
License
MIT
