Skip to content

Repository files navigation

auth logo

@prsm/auth

testnpm

PostgreSQL-backed authentication for Express. It owns its own auth tables and links to your user records through user_id, so it stays out of the way of however you model application users. One middleware attaches everything to req.auth: registration, login, sessions, remember-me, email confirmation, password reset, OAuth, role bitmasks, two-factor authentication, and audited impersonation.

Install

npm install @prsm/auth express express-session pg

For remember-me cookies, also mount cookie-parser:

npm install cookie-parser

Requires Node 24+.

Quick start

importexpressfrom"express"importsessionfrom"express-session"importcookieParserfrom"cookie-parser"importpgfrom"pg"import{createAuthMiddleware,createAuthTables,AuthRole}from"@prsm/auth"constpool=newpg.Pool({connectionString: process.env.DATABASE_URL})constauthConfig={db: pool,tablePrefix: "auth_",}awaitcreateAuthTables(authConfig)constapp=express()app.use(express.json())app.use(cookieParser())app.use(session({secret: process.env.SESSION_SECRET,resave: false,saveUninitialized: false}))app.use(createAuthMiddleware(authConfig))app.post("/register",async(req,res)=>{constaccount=awaitreq.auth.register(req.body.email,req.body.password)res.json({id: account.id})})app.post("/login",async(req,res)=>{awaitreq.auth.login(req.body.email,req.body.password,req.body.remember)res.json({ok: true})})app.get("/me",(req,res)=>{if(!req.auth.isLoggedIn())returnres.status(401).json({error: "not logged in"})res.json({id: req.auth.getId(),email: req.auth.getEmail(),roles: req.auth.getRoleNames()})})

Everything else hangs off req.auth. Mount createAuthMiddleware after express-session and cookie-parser, and call createAuthTables(config) once before the first request.

Role-based access

Roles are integer bitmasks. Use the built-in AuthRole set or define your own:

import{defineRoles}from"@prsm/auth"exportconstRoles=defineRoles("owner","editor","viewer")functionrequireRole(role){returnasync(req,res,next)=>{if(!req.auth.isLoggedIn())returnres.status(401).json({error: "not logged in"})if(!(awaitreq.auth.hasRole(role)))returnres.status(403).json({error: "forbidden"})next()}}app.get("/admin",requireRole(Roles.owner),(req,res)=>res.json({ok: true}))

Pass your role set as config.roles so req.auth.getRoleNames() and the devtools panel render the right names.

Two-factor authentication

TOTP (authenticator apps), email OTP, SMS OTP, and backup codes are built in. Enable it in config, then drive enrollment and the second-factor login step through req.auth.twoFactor:

constauthConfig={db: pool,twoFactor: {enabled: true,issuer: "MyApp"}}// enrollmentconstsetup=awaitreq.auth.twoFactor.setup.totp(true)// render setup.qrCode, then confirm with a code from the app:constbackupCodes=awaitreq.auth.twoFactor.complete.totp(req.body.code)// login: req.auth.login throws SecondFactorRequiredError when 2FA is requiredapp.post("/login/2fa",async(req,res)=>{awaitreq.auth.twoFactor.verify.totp(req.body.code)awaitreq.auth.completeTwoFactorLogin()res.json({ok: true})})

The TOTP implementation (RFC 6238) is built in, so there is no separate dependency to install or keep in sync.

OAuth

GitHub, Google, and Azure are supported. Configure providers and the flow is route-driven through req.auth.providers:

constauthConfig={db: pool,createUser: async(userData)=>(awaitappDb.users.create(userData)).id,providers: {github: { clientId, clientSecret,redirectUri: "https://app.example.com/auth/github/callback"},},}app.get("/auth/github",(req,res)=>res.redirect(req.auth.providers.github.getAuthUrl()))app.get("/auth/github/callback",async(req,res)=>{awaitreq.auth.providers.github.handleCallback(req)res.redirect("/dashboard")})

Impersonation

Audited impersonation preserves the original actor so support sessions stay traceable:

constauthConfig={db: pool,impersonation: {enabled: true,maxTtl: "1h",canImpersonate: (actor,target)=>(actor.rolemask&AuthRole.Admin)!==0,},}awaitreq.auth.startImpersonation({email: "customer@example.com"},{reason: "ticket #123",ttl: "30m"})// activity rows record actor_account_id throughoutawaitreq.auth.stopImpersonation()

Cross-instance invalidation

By default a session re-reads account state from the database on an interval (resyncInterval, default 30s), so a ban or role change can take up to that long to reach instances that already cached the session. Turn on LISTEN/NOTIFY and those changes propagate immediately:

constauthConfig={db: pool,invalidation: {listen: true},}

When enabled, security-relevant writes (force-logout, status, role, password) emit a notification and every instance drops the affected session on its next request. It uses the PostgreSQL connection you already have. If the listener connection is unavailable (for example, a pooler in transaction mode), it falls back to interval-based resync automatically.

Observability and rate limiting

Both are optional and duck-typed, so the package never depends on them:

import{createTracer}from"@prsm/trace"import{tokenBucket}from"@prsm/limit"constauthConfig={db: pool,tracer: createTracer({service: "api"}),// login is wrapped in a spanlimiter: tokenBucket({ redis,capacity: 5,refillRate: 5,refillInterval: "1m"}),// throttles login}

When a limiter is configured, login attempts are throttled per email and a RateLimitedError is thrown once the limit is hit. Without these options, behavior is unchanged.

Requestless context and admin tooling

createAuthContext(config) gives you the same user-management operations without a request, for scripts, workers, and cron jobs. The same object is the binding surface for the @prsm/devtools admin panel: it exposes listAccounts, getAccount, getStats, getRecentActivity, getRoles, and the role/status/force-logout/impersonation actions.

import{createAuthContext,AuthStatus}from"@prsm/auth"constauth=createAuthContext(authConfig)awaitauth.setStatusForUserBy({email: "abusive@example.com"},AuthStatus.Banned)awaitauth.forceLogoutForUserBy({email: "abusive@example.com"})const{ accounts, total }=awaitauth.listAccounts({search: "@example.com",limit: 50})

Maintenance

import{cleanupExpiredTokens,getAuthTableStats}from"@prsm/auth"awaitcleanupExpiredTokens(authConfig)// run on a scheduleconststats=awaitgetAuthTableStats(authConfig)

Documentation

Deeper guides live in docs/:

License

MIT

About

PostgreSQL-backed Express authentication: sessions, OAuth, roles, two-factor, and audited impersonation

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages