@nan0web/auth-core
v1.2.0
Published
Core auth primitives: User, Role, Membership, AccessControl, Password, Session
Readme
@nan0web/auth-core
🇬🇧 English | 🇺🇦 Українська
Minimal authentication core providing:
User– user model with role handling and token managementRole– enumeration of user rolesMembership– group based permission setsAccessControl– data-driven authorization resolver (parser + matcher)Password– secure password hashing (scrypt)Session– filesystem user persistenceTokenExpiryService– simple token lifetime utilitiesToken– sovereign JWT-compatible token (Ed25519 signed)Crypto– Ed25519 key generation, signing, verificationAuth– facade exporting the above
Installation
How to install with npm?
npm install @nan0web/auth-coreHow to install with pnpm?
pnpm add @nan0web/auth-coreHow to install with yarn?
yarn add @nan0web/auth-coreBasic usage – User
Create a user, assign roles and check role existence.
How to create a User and check roles?
import { User, Role } from "@nan0web/auth-core"
const user = new User({
name: 'Alice',
email: '[email protected]',
roles: ['admin', 'user'],
})
console.info(user.toString({ detailed: true, hideDate: true }))
// Alice <[email protected]> admin, user
console.info(user.is('admin')) // ← true
console.info(user.is('guest')) // ← falseToken handling
Manage tokens with TokenExpiryService.
How to create a token and validate its expiry?
import { TokenExpiryService } from "@nan0web/auth-core"
const service = new TokenExpiryService(2000) // 2 seconds
const tokenTime = new Date()
console.info(service.isValid(tokenTime)) // ← true
// fast‑forward simulation
const past = new Date(Date.now() - 3000)
console.info(service.isValid(past)) // ← false
console.info(service.getExpiryDate(tokenTime).toISOString())
// the date in ISO formatMembership – group permissions
Join a group, check permissions, mint daily coins and see admin bypass.
How to use Membership to manage group permissions?
import { Membership, Role } from "@nan0web/auth-core"
const mem = new Membership()
// regular group with explicit permissions
mem.join('lawyers', 'moderator', new Set(['r', 'w']), { dailyCoins: 10 })
console.info(mem.can('lawyers', 'r')) // ← true
console.info(mem.can('lawyers', 'd')) // ← false
mem.mintDailyCoins('lawyers')
const inner = mem.memberships.get('lawyers')
console.info(inner?.config.wallet === 10n) // ← true
// admin role bypasses all permission checks
mem.join('admins', 'admin', new Set(), {})
console.info(mem.can('admins', '*')) // ← trueAccessControl
Universal parser and matcher for access rules (.access and .group files). Three-level resolution: User → Group → Global (*).
How to check access using AccessControl?
import { AccessControl } from "@nan0web/auth-core"
const ac = new AccessControl()
// Load raw content (usually from files)
ac.load(
'* r /public\nadmin rwd /admin', // .access
'admin sovr', // .group
)
console.info(ac.check('sovr', '/admin', 'w')) // ← true (via admin group)
console.info(ac.check('guest', '/public', 'r')) // ← true (via *)
console.info(ac.check('guest', '/admin', 'r')) // ← falsePassword
Scrypt-based hashing with timing-safe verification.
How to hash and verify passwords?
import { Password } from "@nan0web/auth-core"
const hash = Password.hash('sovereign')
console.info(hash) // salt:hash string
console.info(Password.verify('sovereign', hash)) // ← true
console.info(Password.verify('wrong', hash)) // ← falseSession
Save/load user identity (email) to a JSON file.
How to persist user session?
import { Session } from "@nan0web/auth-core"
const session = new Session('./session.json')
session.save('[email protected]')
console.info(session.load()) // ← [email protected]
session.clear()Auth facade
Exported object provides easy access to core classes.
How to use the Auth facade?
import { Auth } from "@nan0web/auth-core"
const user = new Auth.User({ name: 'Bob' })
// Showing user name with createdAt date-time
console.info(user.toString())
// Bob
// YYYY-MM-DD HH:mm:SSToken – Sovereign JWT
Create, verify, and refresh Ed25519-signed tokens.
How to create and verify a Token?
import { Token, Crypto } from "@nan0web/auth-core"
const { publicKey, privateKey } = Crypto.generateKeyPair()
const token = Token.create({ sub: '[email protected]' }, privateKey, { expiresIn: 3600 })
console.info(typeof token) // ← 'string'
const result = Token.verify(token, publicKey)
console.info(result.valid) // ← true
console.info(result.payload.sub) // ← '[email protected]'API reference
User
Properties
name– stringemail– stringroles–Role[]createdAt–DateupdatedAt–Date
Methods
is(role)– checks if the user has the specified roletoObject()– plain representation without private tokens
Role
Static ROLES
admin–"a"author–"r"moderator–"m"user–"u"
Methods
toString()– returns role value
Membership
Properties
memberships–Map<string, { role: Role, perms: Set<string>, config: object }>
Methods
join(key, roleValue, perms, config)– add a groupcan(key, perm)– permission check (admin role bypasses)mintDailyCoins(key)– add daily coin amount from config (updateswalletin config)
AccessControl
- Methods
load(accessContent, groupContent)– parse rules from stringscheck(username, path, level)– true/falsefilterNav(items, username)– filter menu itemsinfo(username)– get effective rules and groups
Password
- Static Methods
hash(plain, projectSalt?)– returns "salt:hash"verify(input, stored, projectSalt?)– timing-safe check
Session
- Methods
save(email)load()clear()
TokenExpiryService
Constructor
new TokenExpiryService(lifetimeMs)
Methods
isValid(creationDate, lifetime?)getExpiryDate(issuedAt?, lifetime?)extendLifetime(creationDate, extensionMs?, maxLifetime?)
Auth
Facade exporting User, Role, TokenExpiryService, Membership, Token, Crypto.
Token
- Static Methods
Token.create(payload, privateKey, options?)– create signed tokenToken.verify(token, publicKey)– verify and decode{ valid, payload, error? }Token.decode(token)– decode without verificationToken.refresh(token, privateKey, options?)– re-sign with new iat/exp
Crypto
Static Properties
isNode– boolean, true in Node.js environment
Static Methods
generateKeyPair()– Ed25519 key pair (Base64 DER)sign(privateKey, data, options?)– sign data (Base64 or hex with{ compact: true })verify(publicKey, data, signature, options?)– verify signature
All exported classes should be available
JavaScript
Types are described via JSDoc and the generated .d.ts files.
Uses d.ts for autocomplete
Contributing
How to contribute? - check here
License
How to license ISC? - check here
