Compare commits

..

No commits in common. '4c870a46e16ece6f45fc476ad9416238dacb749b' and 'bf1c7687c3b31d5e7bf8a9f8bc98b30293bcd8cc' have entirely different histories.

@ -1 +0,0 @@
NANO_SESSION_SECRET="your-secret"

1
.gitignore vendored

@ -75,6 +75,7 @@ web_modules/
# dotenv environment variable files
.env
.env.test
.env.development.local
.env.test.local
.env.production.local

@ -1,31 +1,3 @@
# Nano Session
Functions and Classes for handle session with [@nano/sqlite](https://git.node001.net/nano/sqlite) in [Bun](https://bun.sh/).
## API
### Session
```
import { getOrCreateSqlite } from '@nano/sqlite'
const db = getOrCreateSqlite({ 'name': ':memory:', 'create': true, 'readwrite': true })
const session = new Session(db)
```
#### create(userId: number, agent: string, language: string, ip = '')
Create a new Session for User. Agent and Language from User will be used to create a Hmac value in the DB. The IP is optional. If
one of these values are changed, the session is invalid. After Creating the session you get a Random Token, and the userId as
hash.
### get(userHash: string, token: string, agent: string, language: string, ip = '')
Get Session for User. If session has expired, the entry will be removed from Database.
### destroy(sessionId: number)
Remove single Session for User with id of Session.
### destroyAll(userId: number)
Remove all session for a User with UserId.

Binary file not shown.

@ -1,7 +1,7 @@
import Session from './src/session.ts'
import SessionStore from './src/sessionStore.ts'
export {
Session,
SessionStore
export default {
'Session': Session,
'SessionStore': SessionStore
}

@ -13,7 +13,7 @@
"test": "bun test ./test/*"
},
"dependencies": {
"@nano/sqlite": "0.2.0",
"@nano/sqlite": "^0.1.0",
"dayjs": "^1.11.12"
},
"devDependencies": {

@ -1,6 +1,5 @@
CREATE TABLE IF NOT EXISTS sessions (
id INTEGER PRIMARY KEY,
user_id INTEGER,
user TEXT,
token TEXT,
expired_at TEXT,

@ -1,4 +1,4 @@
import { createHmac, createHash, randomBytes } from 'node:crypto'
import { createHmac, randomBytes } from 'node:crypto'
import dayjs from 'dayjs'
import SessionStore from './sessionStore.ts'
@ -6,47 +6,23 @@ import SessionStore from './sessionStore.ts'
/**
* Session
*
* @author Björn Hase <me@herr-hase.wtf>
* @license http://opensource.org/licenses/MIT The MIT License
* @link https://git.node001.net/nano/session.git
*
*/
class Session {
// database object
/**
*
*
*/
private db
// store for sessions
private sessionStore
// max logins for one user
private maxLogins = 5;
// duration for expired_at
private duration = 60;
/**
*
* @param object db
*
*/
constructor(db: object) {
this.db = db
this.sessionStore = new SessionStore(db)
if (!process.env.NANO_SESSION_SECRET) {
throw new Error('NANO_SESSION_SECRET is undefined, please check .env-file')
}
// if NANO_MAX_LOGINS is set in .env
if (process.env.NANO_SESSION_MAX_LOGINS) {
this.maxLogins = process.env.NANO_SESSION_MAX_LOGINS
}
// if NANO_SESSION_DURATION is set in .env
if (process.env.NANO_SESSION_DURATION) {
this.duration = process.env.NANO_SESSION_DURATION
}
}
/**
@ -59,14 +35,13 @@ class Session {
* @return object
*
*/
public async create(userId: number, agent: string, language: string, ip = ''): object {
public async create(userId: number, agent: string, language: string, ip: string): object {
const userHash = this.createUserHash(userId)
const userHmac = this.createUserHmac(userHash)
const userHmac = this.createUserHmac(userId)
const users = await this.sessionStore.findOneByUser(userHmac)
// if users are not longer can login, drop oldest
if (users && users.length > this.maxLogins) {
if (users && users.length > process.env.NANO_MAX_LOGINS) {
const session = await this.sessionStore.dropOldest(userHash)
}
@ -77,16 +52,15 @@ class Session {
const date = dayjs()
await this.sessionStore.create({
'user_id': userId,
'user' : userHmac,
'token' : tokenHmac,
'expired_at': date.add(this.duration, 'minute').toISOString(),
'expired_at': date.add(process.env.NANO_SESSION_DURATION, 'minute').toISOString(),
'created_at': date.toISOString()
})
return {
'user': userHash,
'token': token // raw token goes in the cookie
'user': userHmac,
'token': token // raw token goes in cookie
}
}
@ -96,8 +70,8 @@ class Session {
* @param object userId
*
*/
public async destroy(sessionId: number): void {
await this.sessionStore.remove(sessionId)
public async destroy(user: object): void {
await this.sessionStore.remove(user.id)
}
/**
@ -107,11 +81,11 @@ class Session {
*
*/
public async destroyAll(userId: number): void {
const userHmac = this.createUserHmac(this.createUserHash(userId))
const sessions = await this.sessionStore.findByUser(userHmac)
const userHash = this.createUserHmac(userId)
const users = await this.sessionStore.findByUser(userHash)
for (const index in sessions) {
await this.destroy(sessions[index].id)
for (const index in users) {
await this.destroy(users[index])
}
}
@ -126,21 +100,21 @@ class Session {
* @return string
*
*/
public async get(userHash: string, token: string, agent: string, language: string, ip = ''): string {
const userHmac = this.createUserHmac(userHash)
const tokenHmac = this.createTokenHmac(token, agent, language, ip)
public async get(userId: number, agent: string, language: string, ip: string, token: string): string {
const userHash = this.createUserHmac(userId)
const tokenHash = this.createTokenHmac(token, agent, language, ip)
let session = await this.sessionStore.findOneByUserAndToken(userHmac, tokenHmac)
let user = await this.sessionStore.findOneByUserAndToken(userHash, tokenHash)
// if user found, check expired_at, if expired, delete session
if (session && session.expired_at) {
if (dayjs().isAfter(dayjs(session.expired_at))) {
await this.destroy(session.id)
session = null
if (user && user.expired_at) {
if (dayjs().isAfter(dayjs(user.expired_at))) {
await this.destroy(user)
user = null
}
}
return session
return user
}
/**
@ -150,23 +124,9 @@ class Session {
* @return string
*
*/
private createUserHash(userId: number): string {
const hash = createHash('sha256')
const buffer = new Buffer(userId)
return hash.update(buffer).digest('hex')
}
/**
* creating hmac for userId
*
* @param number userId
* @return string
*
*/
private createUserHmac(userHash: string): string {
private createUserHmac(userId: number): string {
const hmac = createHmac('sha512', process.env.NANO_SESSION_SECRET)
const buffer = new Buffer(userHash)
const buffer = new Buffer(userId)
return hmac.update(buffer).digest('base64')
}
@ -181,7 +141,7 @@ class Session {
* @return string
*
*/
private createTokenHmac(token: string, agent: string, language: string, ip = ''): string {
private createTokenHmac(token: string, agent: string, language: string, ip: string): string {
const hmac = createHmac('sha512', process.env.NANO_SESSION_SECRET)
const buffer = new Buffer(token + agent + language + ip)

@ -1,11 +1,8 @@
import { Store } from '@nano/sqlite'
/**
* SessionStore
* Session
*
* @author Björn Hase <me@herr-hase.wtf>
* @license http://opensource.org/licenses/MIT The MIT License
* @link https://git.node001.net/nano/session.git
*
*/
class SessionStore extends Store {
@ -14,25 +11,25 @@ class SessionStore extends Store {
super(db, 'sessions')
}
public async findOneByUser(userHmac) {
public async findOneByUser(user) {
return this.db.query('SELECT * FROM ' + this.tableName + ' WHERE user = $user')
.get({
'$user': userHmac
'$user': user
})
}
public async findByUser(userHmac) {
public async findByUser(user) {
return this.db.query('SELECT * FROM ' + this.tableName + ' WHERE user = $user')
.all({
'$user': userHmac
'$user': user
})
}
public async findOneByUserAndToken(userHmac, tokenHmac) {
public async findOneByUserAndToken(user, token) {
return this.db.query('SELECT * FROM ' + this.tableName + ' WHERE user = $user AND token = $token')
.get({
'$user' : userHmac,
'$token' : tokenHmac
'$user' : user,
'$token' : token
})
}
}

@ -7,15 +7,6 @@ import path from 'path'
import dotenv from 'dotenv'
import Session from './../src/session.ts'
const userHashResult = '6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d'
const userHmacResult = 'qMMo5J3Kq0q3+IPadNretbmitllWakjUTD/6HnTRdSNoifrjkLEf5p6sc0qx2q0bSGTeqXI4OaP5VuUQk0EzuQ=='
const request = {
agent: 'Mozilla/2.0 (X11; Windows x86;) Gecko/20100101 Firefox/120.0',
agentChrome: 'Mozilla/2.0 (X11; Windows x86;) Gecko/20100101 Chrome/121.0',
language: 'de,en-US;q=0.8,en;q=0.10',
ip: '1.1.1.1'
}
test('session / create', async () => {
const db = getOrCreateSqlite({ 'name': ':memory:', 'create': true, 'readwrite': true })
await runMigrationSqlite(path.resolve(__dirname, './../src/migration'), db)
@ -23,9 +14,9 @@ test('session / create', async () => {
dotenv.config('./../.env.test')
const session = new Session(db)
const result = await session.create(1, request.agent, request.language, request.ip)
const result = await session.create(1, 'Mozilla/2.0 (X11; Windows x86;) Gecko/20100101 Firefox/120.0', 'de,en-US;q=0.7,en;q=0.3', '1.1.1.1')
expect(result.user).toEqual(userHashResult)
expect('3qC9SK5Z8XC0DXQXs3Fs5CbK5ZS9YOVZziNT8Ulzc2dehXh9qJNMyoVl6jGJJnbbd77/qPdID2wRDFEzqtKshg==').toEqual(result.user)
})
test('session / find', async () => {
@ -35,25 +26,11 @@ test('session / find', async () => {
dotenv.config('./../.env.test')
const session = new Session(db)
const result = await session.create(1, request.agent, request.language, request.ip)
const userSession = await session.get(result.user, result.token, request.agent, request.language, request.ip)
expect(userHmacResult).toEqual(userSession.user)
})
test('session / find / change browser', async () => {
const db = getOrCreateSqlite({ 'name': ':memory:', 'create': true, 'readwrite': true })
await runMigrationSqlite(path.resolve(__dirname, './../src/migration'), db)
dotenv.config('./../.env.test')
const session = new Session(db)
const result = await session.create(1, request.agent, request.language, request.ip)
const result = await session.create(1, 'Mozilla/2.0 (X11; Windows x86;) Gecko/20100101 Firefox/120.0', 'de,en-US;q=0.7,en;q=0.3', '1.1.1.1')
const userSession = await session.get(result.user, result.token, request.agentChrome, request.language, request.ip)
const user = await session.get(1, 'Mozilla/2.0 (X11; Windows x86;) Gecko/20100101 Firefox/120.0', 'de,en-US;q=0.7,en;q=0.3', '1.1.1.1', result.token)
expect(null).toEqual(userSession)
expect('3qC9SK5Z8XC0DXQXs3Fs5CbK5ZS9YOVZziNT8Ulzc2dehXh9qJNMyoVl6jGJJnbbd77/qPdID2wRDFEzqtKshg==').toEqual(user.user)
})
test('session / expired', async () => {
@ -63,14 +40,14 @@ test('session / expired', async () => {
dotenv.config('./../.env.test')
const session = new Session(db)
const result = await session.create(1, request.agent, request.language, request.ip)
const result = await session.create(1, 'Mozilla/2.0 (X11; Windows x86;) Gecko/20100101 Firefox/120.0', 'de,en-US;q=0.7,en;q=0.3', '1.1.1.1')
// change manually session, and set expired_at to
const sessionStore = new SessionStore(db)
await sessionStore.update(1, { 'expired_at': dayjs().subtract(60, 'minute').toISOString() })
await sessionStore.update(1, { 'expired_at': dayjs().toISOString() })
// getting user
const user = await session.get(result.user, result.token, request.agent, request.language, request.ip)
const user = await session.get(1, 'Mozilla/2.0 (X11; Windows x86;) Gecko/20100101 Firefox/120.0', 'de,en-US;q=0.7,en;q=0.3', '1.1.1.1', result.token)
expect(null).toEqual(user) // user not found, because expired user is deleted
})
@ -83,11 +60,11 @@ test('session / destroy all', async () => {
const session = new Session(db)
await session.create(1, request.agent, request.language, request.ip)
await session.create(1, request.agent, request.language, request.ip)
await session.create(1, request.agent, request.language, request.ip)
await session.create(1, request.agent, request.language, request.ip)
await session.create(1, request.agent, request.language, request.ip)
await session.create(1, 'Mozilla/2.0 (X11; Windows x86;) Gecko/20100101 Firefox/120.0', 'de,en-US;q=0.7,en;q=0.3', '1.1.1.1')
await session.create(1, 'Mozilla/2.0 (X11; Windows x86;) Gecko/20100101 Firefox/120.0', 'de,en-US;q=0.7,en;q=0.3', '1.1.1.2')
await session.create(1, 'Mozilla/2.0 (X11; Windows x86;) Gecko/20100101 Firefox/120.0', 'de,en-US;q=0.7,en;q=0.3', '1.1.1.3')
await session.create(1, 'Mozilla/2.0 (X11; Windows x86;) Gecko/20100101 Firefox/120.0', 'de,en-US;q=0.7,en;q=0.3', '1.1.1.4')
await session.create(1, 'Mozilla/2.0 (X11; Windows x86;) Gecko/20100101 Firefox/120.0', 'de,en-US;q=0.7,en;q=0.3', '1.1.1.5')
await session.destroyAll(1)
const result = db.query("SELECT * FROM sessions").all()

Loading…
Cancel
Save