main
HerrHase 3 months ago
parent 257a025490
commit bf1c7687c3

2
.gitignore vendored

@ -75,6 +75,7 @@ web_modules/
# dotenv environment variable files
.env
.env.test
.env.development.local
.env.test.local
.env.production.local
@ -129,4 +130,3 @@ dist
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*

@ -0,0 +1,9 @@
MIT License
Copyright (c) 2024 Björn Hase, me@herr-hase.wtf
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

@ -1,2 +1,3 @@
# nano-session
# Nano Session
Functions and Classes for handle session with [@nano/sqlite](https://git.node001.net/nano/sqlite) in [Bun](https://bun.sh/).

Binary file not shown.

@ -0,0 +1,2 @@
[install.scopes]
"@nano" = "https://git.node001.net/api/packages/nano/npm/"

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

@ -0,0 +1,22 @@
{
"name": "@nano/session",
"version": "0.1.0",
"description": "Handle User Session with Sqlite",
"repository": {
"type": "git",
"url": "git@git.node001.net:nano/session.git"
},
"author": "Björn Hase <me@herr-hase.wtf>",
"license": "MIT",
"type": "module",
"scripts": {
"test": "bun test ./test/*"
},
"dependencies": {
"@nano/sqlite": "^0.1.0",
"dayjs": "^1.11.12"
},
"devDependencies": {
"dotenv": "^16.4.5"
}
}

@ -0,0 +1,7 @@
CREATE TABLE IF NOT EXISTS sessions (
id INTEGER PRIMARY KEY,
user TEXT,
token TEXT,
expired_at TEXT,
created_at TEXT
)

@ -0,0 +1,152 @@
import { createHmac, randomBytes } from 'node:crypto'
import dayjs from 'dayjs'
import SessionStore from './sessionStore.ts'
/**
* Session
*
*
*/
class Session {
/**
*
*
*/
private db
/**
*
*
*/
constructor(db: object) {
this.db = db
this.sessionStore = new SessionStore(db)
}
/**
* create session
*
* @param number userId
* @param string agent
* @param string language
* @param string ip
* @return object
*
*/
public async create(userId: number, agent: string, language: string, ip: string): object {
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 > process.env.NANO_MAX_LOGINS) {
const session = await this.sessionStore.dropOldest(userHash)
}
const token = randomBytes(64).toString('hex')
const tokenHmac = this.createTokenHmac(token, agent, language, ip)
// create date
const date = dayjs()
await this.sessionStore.create({
'user' : userHmac,
'token' : tokenHmac,
'expired_at': date.add(process.env.NANO_SESSION_DURATION, 'minute').toISOString(),
'created_at': date.toISOString()
})
return {
'user': userHmac,
'token': token // raw token goes in cookie
}
}
/**
* delete single session for a user
*
* @param object userId
*
*/
public async destroy(user: object): void {
await this.sessionStore.remove(user.id)
}
/**
* delete all session for a user
*
* @param number userId
*
*/
public async destroyAll(userId: number): void {
const userHash = this.createUserHmac(userId)
const users = await this.sessionStore.findByUser(userHash)
for (const index in users) {
await this.destroy(users[index])
}
}
/**
* getting single session
*
* @param number userId
* @param string agent
* @param string language
* @param string ip
* @param string token
* @return string
*
*/
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 user = await this.sessionStore.findOneByUserAndToken(userHash, tokenHash)
// if user found, check expired_at, if expired, delete session
if (user && user.expired_at) {
if (dayjs().isAfter(dayjs(user.expired_at))) {
await this.destroy(user)
user = null
}
}
return user
}
/**
* creating hmac for userId
*
* @param number userId
* @return string
*
*/
private createUserHmac(userId: number): string {
const hmac = createHmac('sha512', process.env.NANO_SESSION_SECRET)
const buffer = new Buffer(userId)
return hmac.update(buffer).digest('base64')
}
/**
* creating hmac for token
*
* @param number userId
* @param string agent
* @param string language
* @param string ip
* @return 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)
return hmac.update(buffer).digest('base64')
}
}
export default Session

@ -0,0 +1,37 @@
import { Store } from '@nano/sqlite'
/**
* Session
*
*
*/
class SessionStore extends Store {
constructor(db) {
super(db, 'sessions')
}
public async findOneByUser(user) {
return this.db.query('SELECT * FROM ' + this.tableName + ' WHERE user = $user')
.get({
'$user': user
})
}
public async findByUser(user) {
return this.db.query('SELECT * FROM ' + this.tableName + ' WHERE user = $user')
.all({
'$user': user
})
}
public async findOneByUserAndToken(user, token) {
return this.db.query('SELECT * FROM ' + this.tableName + ' WHERE user = $user AND token = $token')
.get({
'$user' : user,
'$token' : token
})
}
}
export default SessionStore

@ -0,0 +1,15 @@
import { expect, test } from 'bun:test'
import path from 'path'
import { runMigrationSqlite, getOrCreateSqlite } from '@nano/sqlite'
import { Database } from 'bun:sqlite'
test('migration', async () => {
const db = getOrCreateSqlite({ 'name': ':memory:', 'create': true, 'readwrite': true })
await runMigrationSqlite(path.resolve(__dirname, './../src/migration'), db)
// check for boxes
const results = db.query("SELECT name FROM sqlite_master WHERE type='table' AND name='sessions'").get()
expect(results).toEqual({ name: 'sessions' })
})

@ -0,0 +1,73 @@
import { expect, test } from 'bun:test'
import { runMigrationSqlite, getOrCreateSqlite } from '@nano/sqlite'
import SessionStore from './../src/sessionStore.ts'
import dayjs from 'dayjs'
import path from 'path'
import dotenv from 'dotenv'
import Session from './../src/session.ts'
test('session / create', 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, '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('3qC9SK5Z8XC0DXQXs3Fs5CbK5ZS9YOVZziNT8Ulzc2dehXh9qJNMyoVl6jGJJnbbd77/qPdID2wRDFEzqtKshg==').toEqual(result.user)
})
test('session / find', 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, '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 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('3qC9SK5Z8XC0DXQXs3Fs5CbK5ZS9YOVZziNT8Ulzc2dehXh9qJNMyoVl6jGJJnbbd77/qPdID2wRDFEzqtKshg==').toEqual(user.user)
})
test('session / expired', 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, '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().toISOString() })
// getting user
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
})
test('session / destroy all', 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)
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()
expect([]).toEqual(result)
})
Loading…
Cancel
Save