@zollikon/auth
v1.0.1
Published
Authentication service with JWT, 2FA TOTP, CSRF, Google OAuth, bcrypt
Maintainers
Readme
@zollikon/auth
Authentication service with JWT access/refresh tokens, TOTP 2FA with backup codes, CSRF signing, bcrypt password utilities, Google OAuth, session management, and security audit logging.
Installation
npm install @zollikon/auth
# or
yarn add @zollikon/auth
# or
pnpm add @zollikon/authThe package is fully standalone: it has no dependency on Prisma or any ORM, and does not read your app's configuration. Database-backed functions (session, trusted-device and audit services) receive a client you supply, typed by the exported AuthDbClient interface.
Database client (bring your own)
Any client exposing refreshToken, revokedToken, trustedDevice, securityEvent and user delegates with create / findUnique / findFirst / findMany / update / updateMany / delete / deleteMany, plus $transaction, satisfies AuthDbClient. A Prisma client generated from your own schema works as-is:
// in your app (e.g. backend/src/db.ts) — Prisma lives here, not in this package
import { PrismaClient } from '@prisma/client';
import { createRefreshToken } from '@zollikon/auth';
const prisma = new PrismaClient();
await createRefreshToken(prisma, userId, 1, device, epoch, '7d');Your schema must define the models/fields these services use (RefreshToken, RevokedToken, TrustedDevice, SecurityEvent, User with tokenVersion, role, deletedAt). The reference schema lives in the host app's prisma/schema.prisma. If you only use the pure utilities (passwords, JWT, TOTP, CSRF, Google OAuth, PQ encryption), no database is needed.
Quick Start
import {
// types
JwtAccessPayload,
TokenPair,
DeviceInfo,
GoogleUserInfo,
TotpSetupResult,
BackupCodeResult,
PasswordStrengthResult,
// constants
BCRYPT_ROUNDS,
MAX_FAILED_LOGIN_ATTEMPTS,
BACKUP_CODE_COUNT,
TRUSTED_DEVICE_EXPIRY_DAYS,
// password
hashPassword,
verifyPassword,
validatePasswordStrength,
generateSecureToken,
generateNumericCode,
// tokens
signAccessToken,
signPendingToken,
verifyAccessToken,
verifyPendingToken,
// 2FA / TOTP
generateTotpSecret,
verifyTotpCode,
generateBackupCodes,
verifyBackupCode,
generateEmailFallbackCode,
// CSRF
generateCsrfToken,
validateCsrfToken,
// Google OAuth
verifyGoogleIdToken,
// sessions
createRefreshToken,
rotateRefreshToken,
revokeRefreshToken,
revokeAllUserTokens,
cleanupExpiredTokens,
// audit
logSecurityEvent,
SecurityEventType,
SecurityEventSeverity,
} from '@zollikon/auth';Security Constants
| Constant | Default | Description |
| ---------------------------- | ------------------ | --------------------------------------- |
| BCRYPT_ROUNDS | 12 | bcrypt work factor |
| MAX_FAILED_LOGIN_ATTEMPTS | 5 | Failed attempts before account lock |
| ACCOUNT_LOCK_DURATION_MS | 900 000 (15 min) | Lock duration |
| BACKUP_CODE_COUNT | 10 | Backup codes generated per 2FA setup |
| BACKUP_CODE_LENGTH | 8 | Characters per backup code |
| TRUSTED_DEVICE_EXPIRY_DAYS | 30 | Days a device stays trusted |
| REFRESH_ROTATION_GRACE_MS | 30 000 | Grace window for refresh-token rotation |
| COMMON_PASSWORDS | Set<string> | Blocked weak passwords (83 entries) |
Password Utilities
validatePasswordStrength(password: string): PasswordStrengthResult
Validates that a password meets security requirements. Returns { valid: boolean, errors: string[] }.
const result = validatePasswordStrength('MyStr0ng!Pass');
// { valid: true, errors: [] }
validatePasswordStrength('weak');
// { valid: false, errors: [
// 'Minimum 12 characters required',
// 'At least one uppercase letter required',
// ...
// ]}Requirements enforced:
- Minimum 12 characters
- At least one uppercase letter
- At least one lowercase letter
- At least one digit
- At least one special character
- No more than 3 consecutive identical characters
- Must not be a common password (83-entry blocklist)
hashPassword(password: string): Promise<string>
Hashes a plaintext password using bcrypt (12 rounds).
const hash = await hashPassword('MySecretPass!');
// => $2b$12$...verifyPassword(password: string, hash: string): Promise<boolean>
Verifies a plaintext password against a bcrypt hash.
const ok = await verifyPassword('MySecretPass!', hash);
// => truegenerateSecureToken(bytes = 32): string
Generates a cryptographically-secure hex token (default 32 bytes / 64 hex chars).
const token = generateSecureToken();
// => 'a3f1c2...' (64 hex characters)
const shortToken = generateSecureToken(16);
// => 'a3f1c2...' (32 hex characters)generateNumericCode(digits = 6): string
Generates a cryptographically-secure numeric code padded to the given number of digits.
const code = generateNumericCode();
// => '042917'
const code4 = generateNumericCode(4);
// => '7391'JWT Tokens
Token Secrets Interface
All token-signing and signing functions accept a TokenSecrets object:
interface TokenSecrets {
accessSecret: string; // HMAC / RS256 secret for access tokens
refreshSecret: string; // Separate secret for refresh tokens
pendingSecret?: string; // Separate secret for pending-2FA tokens
accessExpiresIn: string; // e.g. '15m', '1h'
refreshExpiresIn: string; // e.g. '7d', '30d'
issuer?: string; // default: 'ev-engine'
audience?: string; // default: 'ev-engine-client'
}Best practice: Use separate secrets for access and refresh tokens. Rotate them independently using token versioning.
signAccessToken(payload, secrets): string
Signs an access JWT.
const token = signAccessToken(
{ sub: userId, role: 'USER', version: 1 },
{ accessSecret: process.env.JWT_ACCESS_SECRET!, accessExpiresIn: '15m', ... }
);
// => 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'| Claim | Value |
| --------- | ---------------------------------------- |
| sub | User / subject ID |
| role | ADMIN, USER, etc. |
| version | Token version (used for bulk revocation) |
| type | 'access' |
| iss | 'ev-engine' |
| aud | 'ev-engine-client' |
signPendingToken(userId: string, pendingSecret: string): string
Signs a short-lived pending-2FA token (expires in PENDING_2FA_EXPIRY, default 5 minutes). Uses a
dedicated secret (JWT_PENDING_SECRET), separate from the access-token secret, so a leaked access
secret can't be used to forge pending-2FA tokens.
const pendingToken = signPendingToken(userId, process.env.JWT_PENDING_SECRET!);
// => 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...' type: 'pending_2fa'verifyAccessToken(token: string, secret: string): JwtAccessPayload
Verifies and decodes an access token. Throws on invalid / expired / wrong-type token.
const payload = verifyAccessToken(token, process.env.JWT_ACCESS_SECRET!);
// { sub: '...', role: 'USER', version: 1, type: 'access', iat: ..., exp: ... }verifyPendingToken(token: string, secret: string): JwtPendingPayload
Verifies and decodes a pending-2FA token against the dedicated JWT_PENDING_SECRET.
const payload = verifyPendingToken(pendingToken, process.env.JWT_PENDING_SECRET!);
// { sub: '...', type: 'pending_2fa', iat: ..., exp: ... }Two-Factor Authentication (TOTP)
generateTotpSecret(accountName, issuer?): Promise<TotpSetupResult>
Generates a TOTP secret, the otpauth URL, and a QR code as a base64 data URL.
const { secret, otpauthUrl, qrCodeDataUrl } = await generateTotpSecret('[email protected]');
// secret => 'JBSWY3DPEHPK3PXP...'
// qrCodeDataUrl => 'data:image/png;base64,iVBORw0KGgoAAA...'Render the QR code in the browser:
<img :src="qrCodeDataUrl" alt="Scan with Authenticator" />verifyTotpCode(secret: string, token: string): boolean
Verifies a 6-digit TOTP code from Google Authenticator, Authy, etc.
const ok = verifyTotpCode(secret, '123456');
// => true / falsegenerateBackupCodes(): Promise<BackupCodeResult>
Generates 10 one-time backup codes (8 base64-url characters each).
const { rawCodes, hashedCodes } = await generateBackupCodes();
// Show `rawCodes` to the user ONCE — store only `hashedCodes` in the database
console.log(rawCodes);
// ['PZ3GHT9A', 'KJ7MWR2F', ...]
user.hashedBackupCodes = hashedCodes; // persist theseverifyBackupCode(inputCode: string, hashedCodes: string[]): Promise<BackupCodeVerifyResult>
Checks a backup code against the stored hashes. On success the matched code is removed so it cannot be used again.
const { valid, remainingHashedCodes } = await verifyBackupCode('PZ3GHT9A', user.hashedBackupCodes);
if (valid) {
user.hashedBackupCodes = remainingHashedCodes;
await user.save();
}generateEmailFallbackCode(): string
Generates a 6-digit numeric fallback code for email-based passwordless / 2FA bypass flows.
const code = generateEmailFallbackCode();
// => '042917'CSRF Protection
generateCsrfToken(secret: string): { token: string; nonce: string }
Generates a CSRF token / nonce pair using HMAC-SHA256.
const { token, nonce } = generateCsrfToken(process.env.CSRF_SECRET!);
// token => 'f1a2b3c4...' (64 hex chars)
// nonce => 'a1b2c3d4...' (32 hex chars)Set nonce as a csrf_nonce cookie, return token in the response body.
validateCsrfToken(token: string, nonce: string, secret: string): boolean
Validates a CSRF token / nonce pair using constant-time comparison (timing-safe).
const ok = validateCsrfToken(token, nonce, process.env.CSRF_SECRET!);
// => true / falseFlow for clients:
1. GET /auth/csrf-token → { csrfToken } + Set-Cookie: csrf_nonce=<nonce>
2. Client stores the token, browser sends csrf_nonce cookie automatically
3. Client includes header: x-csrf-token: <csrfToken>
4. Server calls validateCsrfToken(req.body.token, req.cookies.csrf_nonce, secret)Google OAuth
Requires
google-auth-library(peer dependency, bundled with this package).
verifyGoogleIdToken(idToken: string, clientId: string): Promise<GoogleUserInfo>
Verifies a Google ID token and returns user info.
const userInfo = await verifyGoogleIdToken(googleIdToken, process.env.GOOGLE_CLIENT_ID!);
// {
// googleId: '1234567890',
// email: '[email protected]',
// firstName: 'John',
// lastName: 'Doe',
// emailVerified: true,
// }GraphQL input example:
mutation GoogleLogin {
loginWithGoogle(input: { idToken: "google-id-token", deviceName: "Chrome on Mac" }) {
accessToken
user {
id
email
username
firstName
lastName
role
twoFactorEnabled
}
}
}Session Management
All session functions require an AuthDbClient instance (e.g. your Prisma client) and an optional DeviceInfo object:
const device: DeviceInfo = { ipAddress, userAgent, deviceName };createRefreshToken(prisma, userId, tokenVersion, device): Promise<{ rawToken, tokenId }>
Creates a new refresh token, stores its SHA-256 hash in the database, and returns the raw token (unhashed).
const { rawToken, tokenId } = await createRefreshToken(prisma, userId, 1, device);
// Set rawToken as an HTTP-only cookie (__ev_refresh)rotateRefreshToken(prisma, rawToken, device, secrets): Promise<{ tokenPair, userId }>
Atomically invalidates the old refresh token, creates a new one, and issues a new access token.
Detects refresh-token reuse — if the same token is rotated twice, it throws 'REUSE_DETECTED'.
const {
tokenPair: { accessToken, refreshToken },
userId,
} = await rotateRefreshToken(prisma, rawCookieToken, device, tokenSecrets);revokeRefreshToken(prisma, tokenId: string): Promise<void>
Revokes (deletes) a single refresh token from the database.
await revokeRefreshToken(prisma, tokenId);revokeAllUserTokens(prisma, userId: string): Promise<void>
Atomically revokes every session for a user by bumping tokenVersion and deleting all stored refresh tokens.
await revokeAllUserTokens(prisma, userId);cleanupExpiredTokens(prisma: AuthDbClient): Promise<void>
Deletes all expired records from refreshToken, revokedToken, and trustedDevice tables. Suitable for running as a periodic cron job.
await cleanupExpiredTokens(prisma);Security Audit Logging
logSecurityEvent(prisma, params, chainSecret): Promise<void>
Writes a tamper-evident security event to the securityEvent table. Each entry is chained to the
previous entry using an HMAC-SHA256 hash (keyed with chainSecret, e.g. AUDIT_CHAIN_SECRET),
forming an append-only audit trail that can't be recomputed/forged without the secret — including
by someone with direct database write access.
import { logSecurityEvent, SecurityEventType } from '@zollikon/auth';
await logSecurityEvent(
prisma,
{
eventType: SecurityEventType.LOGIN_SUCCESS,
userId: user.id,
ipAddress: req.ip,
userAgent: req.headers['user-agent'],
details: {
deviceName: 'MacBook Pro',
twoFactorUsed: false,
},
},
process.env.AUDIT_CHAIN_SECRET!
);verifyAuditChain(prisma, chainSecret): Promise<{ valid: boolean; brokenAtId?: string }>
Walks the entire chain from oldest to newest and recomputes each chainHash, returning
{ valid: false, brokenAtId } at the first row whose hash doesn't match — signalling tampering.
const result = await verifyAuditChain(prisma, process.env.AUDIT_CHAIN_SECRET!);
if (!result.valid) {
console.error(`Audit chain broken at event ${result.brokenAtId}`);
}Security event types:
| Type | Severity | Description |
| -------------------------- | -------- | ------------------------------------------- |
| LOGIN_SUCCESS | INFO | Successful authentication |
| LOGIN_FAILED | WARN | Invalid credentials |
| LOGIN_BLOCKED | WARN | Account temporarily locked |
| LOGOUT | INFO | User logged out |
| LOGOUT_ALL | INFO | All sessions revoked |
| REGISTER | INFO | New account created |
| EMAIL_VERIFIED | INFO | Email address confirmed |
| PASSWORD_CHANGED | INFO | Password updated |
| PASSWORD_RESET_REQUESTED | INFO | Reset link sent |
| PASSWORD_RESET_COMPLETED | INFO | Password reset finished |
| 2FA_ENABLED | INFO | 2FA activated |
| 2FA_DISABLED | WARN | 2FA deactivated |
| 2FA_VERIFIED | INFO | Successful TOTP verification |
| 2FA_BACKUP_USED | WARN | Recovery code consumed |
| GOOGLE_LOGIN | INFO | OAuth login via Google |
| TOKEN_REUSE_DETECTED | CRITICAL | Potential session hijack |
| ACCOUNT_LOCKED | WARN | Account locked after repeated failed logins |
| ACCOUNT_UNLOCKED | INFO | Account unlocked |
GraphQL API Reference
The following GraphQL schema is provided for reference. To use it in your server, add @zollikon/auth as a dependency and integrate the resolvers into your GraphQL module.
Mutations
Register
Creates a new user account. Returns the access token and user profile on success.
mutation Register {
register(
input: {
email: "[email protected]"
username: "johndoe"
password: "SecurePassword123!"
firstName: "John"
lastName: "Doe"
referralCode: "optional-referral-code"
}
) {
accessToken
user {
id
email
username
firstName
lastName
role
isEmailVerified
twoFactorEnabled
}
}
}Password rules: minimum 12 characters, one uppercase, one lowercase, one digit, one special character.
Login
Authenticates a user with email and password. Returns TwoFactorRequiredError (with pendingToken) when 2FA is enabled and no twoFactorCode is supplied.
mutation Login {
login(
input: {
email: "[email protected]"
password: "SecurePassword123!"
deviceName: "MacBook Pro"
twoFactorCode: "123456"
}
) {
accessToken
user {
id
email
username
firstName
lastName
role
isEmailVerified
twoFactorEnabled
}
}
}Response: accessToken (JWT for the Authorization: Bearer header) + refreshToken (HTTP-only __ev_refresh cookie).
AuthPayload
Refreshes the access token using the __ev_refresh HTTP-only cookie. Call this when the access token expires.
mutation AuthPayload {
authPayload {
accessToken
refreshToken
user {
id
email
username
firstName
lastName
role
twoFactorEnabled
}
}
}Logout
Revokes the current session's refresh token.
mutation Logout {
logout {
success
message
}
}LogoutAll
Revokes ALL active sessions / refresh tokens for the currently authenticated user (atomically bumps tokenVersion).
mutation LogoutAll {
logoutAll {
success
message
}
}ChangePassword
Changes the authenticated user's password. Requires the current password for verification.
mutation ChangePassword {
changePassword(currentPassword: "OldPassword123!", newPassword: "NewSecurePass456!") {
success
message
}
}VerifyEmail
Confirms the user's email address using the verification token sent via email.
mutation VerifyEmail {
verifyEmail(token: "verification-token-from-email") {
success
message
}
}RequestPasswordReset
Sends a password-reset link to the user's email address.
mutation RequestPasswordReset {
requestPasswordReset(email: "[email protected]") {
success
message
}
}ResetPassword
Completes a password reset using the token from the reset email.
mutation ResetPassword {
resetPassword(token: "reset-token-from-email", newPassword: "NewSecureP@ss456!") {
success
message
}
}EnableTwoFactor
Generates and returns a TOTP secret key with a QR code. Scan the QR code with Google Authenticator, Authy, or a similar app, then confirm with confirmTwoFactor.
mutation EnableTwoFactor {
enableTwoFactor {
qrCodeDataUrl
backupCodes
}
}ConfirmTwoFactor
Enables 2FA after the user has scanned the QR code and entered the 6-digit TOTP code.
mutation ConfirmTwoFactor {
confirmTwoFactor(code: "123456") {
success
message
}
}Returns backup codes — the user must save these securely for account recovery.
DisableTwoFactor
Disables 2FA for the authenticated user. Requires the current TOTP code for verification.
mutation DisableTwoFactor {
disableTwoFactor(code: "123456") {
success
message
}
}VerifyTwoFactor
Completes a two-step 2FA login. Use this after receiving TWO_FACTOR_REQUIRED from the login mutation.
mutation VerifyTwoFactor {
verifyTwoFactor(
input: { pendingToken: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", code: "123456" }
) {
accessToken
user {
id
email
}
}
}Backup code variant:
mutation VerifyTwoFactor {
verifyTwoFactor(
input: {
pendingToken: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
code: "BACKUP_CODE"
isBackupCode: true
}
) {
accessToken
user {
id
email
}
}
}DeleteAccount
Permanently deletes the authenticated user's account. Requires the current password.
mutation DeleteAccount {
deleteAccount(password: "YourPassword123!") {
success
message
}
}LoginWithGoogle
Authenticates or creates a user via Google OAuth.
mutation GoogleLogin {
loginWithGoogle(input: { idToken: "google-id-token", deviceName: "Chrome on Mac" }) {
accessToken
user {
id
email
username
firstName
lastName
role
twoFactorEnabled
}
}
}Queries
Me
Returns the profile of the currently authenticated user.
query Me {
me {
id
email
username
firstName
lastName
role
isEmailVerified
twoFactorEnabled
}
}Error Handling
All mutations that can fail return MessagePayload:
type MessagePayload {
success: Boolean!
message: String!
}Common extended errors:
| code | HTTP | Description |
| --------------------- | ---- | -------------------------------------------------------- |
| UNAUTHENTICATED | 401 | Missing or invalid access token |
| TWO_FACTOR_REQUIRED | 403 | 2FA step pending; carry pendingToken from extensions |
| FORBIDDEN | 403 | Authenticated but not authorised |
| VALIDATION_ERROR | 400 | Invalid input — check message |
| TOKEN_INVALIDATED | 401 | Refresh token been revoked; re-authenticate |
CSRF Token Request
Fetch a CSRF token before making mutations from an external consumer:
GET /auth/csrf-token{ "csrfToken": "f1a2b3c4...3849" }The response also sets a csrf_nonce cookie. Include the token in mutation requests via the x-csrf-token header.
License
MIT
