Git Product home page Git Product logo

koa-session-minimal's Introduction

koa-session-minimal

NPM version Downloads Build Status codecov

Native Koa 2 session middleware, inspired by and compatible with koa-generic-session. This can be used as a drop-in replacement for koa-generic-session in Koa 2.

This rewrite implements koa-generic-session's essential interfaces, with around 100 lines of code in ES6. It supports existing session stores for koa-generic-session.

Version 4+ requires node 8+. Please use v3.0.4 for node versions older than 8.

Minimum features and storage usage

This middleware guarantees the following:

  • Minimum data generation and storage. No session data modification / pollution.
    • Neither a cookie nor a session store record is created unless session data gets populated by other middlewares.
    • Cookie options are not saved in the ctx.session object or session store (try to address this concern).
  • Minimum updates on cookie and session store. Cookie and session store only get updated when session data has been changed.
    • When ctx.session gets updated (is a non-empty object), cookie and store data will be updated with new values and new expiration time (maxAge).
    • When ctx.session gets cleared ( = {} or null ), cookie and store data will be deleted.
    • If a session has not been updated within maxAge, its data will be expired.
  • Minimum public interfaces and configuration options.
    • Cookie options: maxAge, path, domain, secure, httpOnly
    • Session interfaces: session, sessionHandler { regenerateId() }
    • Store interfaces: get(), set(), destroy()

Installation

$ npm install koa-session-minimal

Usage

const Koa = require('koa')
const session = require('koa-session-minimal')
const redisStore = require('koa-redis')

const app = new Koa()

app.use(session({
  store: redisStore()
}))

// count middleware, increment when url = /add
app.use(async (ctx, next) => {
  ctx.session.count = ctx.session.count || 0
  if (ctx.path === '/add') ctx.session.count++

  await next()

  ctx.body = ctx.session.count
})

app.listen(3000)

Interfaces

  • session data via ctx.session (the same way as koa-generic-session)
  • session methods via ctx.sessionHandler
    • regenerateId(): regenerate session id

Options

  • key: session cookie name and store key prefix
  • store: session store
  • cookie: cookie options, can be an object (static cookie options) or a function that returns an object (dynamic cookie options). Only maxAge, path, domain, secure, httpOnly are supported as option keys (see option details in cookies module).

Session expiration

Default session has settings cookie.maxAge = 0 for cookie and ttl = ONE_DAY for session store, means that a session will be expired in one of the following circumstances:

  • A user close the browser window (transient cookie ends)
  • Session data hasn't been updated within ONE_DAY (storage expires)

With settings that cookie.maxAge > 0, the ttl for store data will be always the same as maxAge.

Dynamic session expiration (cookie options)

When setting cookie option to a plain object, all sessions will use the same cookie options. If a function is assigned to cookie, cookie options will be dynamically calculated at each (non-empty) session's saving stage. For example, you can use an arrow function to set different maxAge for user and guest sessions, as below:

session({
  cookie: ctx => ({
    maxAge: ctx.session.user ? ONE_MONTH : 0
  })
})

Session security

Middlewares are recommended to call sessionHandler.regenerateId() during authentication state change (login). This middleware provides the essential interface, It will be other middleware's decision on when and how often they want to roll the session id.

NOTE: Below is mostly copied from koa-generic-session's README, because the two middlewares share the same store interfaces. Any store that implements koa-generic-session's store interfaces should also work with koa-session-minimal. koa-redis is tested as an example in test/store_redis.test.js

Session store

You can use any other store to replace the default MemoryStore, it just needs to follow this api:

  • get(sid): get session object by sid
  • set(sid, sess, ttl): set session object for sid, with a ttl (in ms)
  • destroy(sid): destroy session for sid

the api needs to return a Promise, Thunk, generator, or an async function.

Stores presented

License

MIT

koa-session-minimal's People

Contributors

dependabot[bot] avatar lzztt avatar natesilva avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

koa-session-minimal's Issues

Additional validation support

Hi, I'm trying to figure out if it'll be possible to implement some additional session validation mechanisms (to help guard against session hijacking). Currently, I don't see anywhere where ctx can be obtained by the session store from koa-session-minimal; this is something that'd be necessary for my purposes.

Is there any way that this could be implemented or hooked in? Possibly an optional Promise call for stores? A new option that takes a fn that returns a promise and gets passed the ctx and session?

Consider migrating to `fast-deep-equal`

deep-equal is not only 2 orders of magnitude slower than fast-deep-equal, but it's by far the biggest dependency tree limbs in the project containing polyfills that haven't been needed for browsers or Node since 2015 (and your package.json denotes "node": ">= 14"). At 38M weekly downloads, it is not a small project either. Swapping dependencies to fast-deep-equal could save consumers kilobytes and reap a performance benefit. Transitive dependencies would go from 53 to 4.

Typescript typings

Hey thanks for lib as koa-generic is a bit outdated, btw using this with Postgres is same with this lib + koa-pg-session? Or anything else recommended?

Also main question any possibilites for typescript 2 typings? Would be really awesome to use this with typescript

'secure' cookie option

any reason you provided a default for the 'secure' option? the cookies module dynamic default seems more intuitive than your hardcoding of false

Session lost on node restart

First of all: great session middleware - it works really well as a drop-in replacement for koa-generic-session. Thanks!

I am using this in conjunction with the redisStore and, whenever node restarts, the session is lost.

The secret option is a fixed string - so I'm not so sure why this is happening.

Just putting it out there in case it's not just me. ๐Ÿ˜„

cant delete session

image

although i set session to null in a setTimeout, and terminal also show it is null, but when i call getPin int the second, the ctx.session.pin has a value

image

my enviroment: macos, node 7.2.0, koa-session-minimal-3.0.2, koa-generic-session-mongo-0.3.0

cicyle dependecies

when i use koa-generic-session-mongo with koa-session-minimal in koa2, it tell me cicyle dependecies
image
this is my app.js:
image
and i just get a user from mongodb , and set it to session.user:
image
my node version is 7.2.1,and i use it with --harmony to handle async function.

occur a waring

i use it with koa-generic-session-mongo like this:
app.use(session({
cookie: {maxAge: 1000 * 60 * 60 * 24 * 30},//30 days
store: new MongoStore()
}))

when i set: ctx.session.user = user , the shell tell me:
(node:12780) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'maxAge' of undefined

node version: 7.2.0

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.