diff --git a/.gitignore b/.gitignore index ceaea36..43960c5 100644 --- a/.gitignore +++ b/.gitignore @@ -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.* - diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..ddb280e --- /dev/null +++ b/LICENSE @@ -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. diff --git a/README.md b/README.md index 0b16cd6..f2a73a2 100644 --- a/README.md +++ b/README.md @@ -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/). diff --git a/bun.lockb b/bun.lockb new file mode 100755 index 0000000..edcef50 Binary files /dev/null and b/bun.lockb differ diff --git a/bunfig.toml b/bunfig.toml new file mode 100644 index 0000000..f6b3dcd --- /dev/null +++ b/bunfig.toml @@ -0,0 +1,2 @@ +[install.scopes] +"@nano" = "https://git.node001.net/api/packages/nano/npm/" diff --git a/index.ts b/index.ts new file mode 100644 index 0000000..c4d9452 --- /dev/null +++ b/index.ts @@ -0,0 +1,7 @@ +import Session from './src/session.ts' +import SessionStore from './src/sessionStore.ts' + +export default { + 'Session': Session, + 'SessionStore': SessionStore +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..e16addb --- /dev/null +++ b/package.json @@ -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 ", + "license": "MIT", + "type": "module", + "scripts": { + "test": "bun test ./test/*" + }, + "dependencies": { + "@nano/sqlite": "^0.1.0", + "dayjs": "^1.11.12" + }, + "devDependencies": { + "dotenv": "^16.4.5" + } +} diff --git a/src/migration/sessions.sql b/src/migration/sessions.sql new file mode 100644 index 0000000..5cd2e35 --- /dev/null +++ b/src/migration/sessions.sql @@ -0,0 +1,7 @@ +CREATE TABLE IF NOT EXISTS sessions ( + id INTEGER PRIMARY KEY, + user TEXT, + token TEXT, + expired_at TEXT, + created_at TEXT +) diff --git a/src/session.ts b/src/session.ts new file mode 100644 index 0000000..2624a25 --- /dev/null +++ b/src/session.ts @@ -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 diff --git a/src/sessionStore.ts b/src/sessionStore.ts new file mode 100644 index 0000000..0bcda40 --- /dev/null +++ b/src/sessionStore.ts @@ -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 diff --git a/test/migration.test.ts b/test/migration.test.ts new file mode 100644 index 0000000..bda13fa --- /dev/null +++ b/test/migration.test.ts @@ -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' }) +}) diff --git a/test/session.test.ts b/test/session.test.ts new file mode 100644 index 0000000..aee5701 --- /dev/null +++ b/test/session.test.ts @@ -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) +})