3.1.1 • Published 4 years ago

@goa/session v3.1.1

Weekly downloads
21
License
AGPL-3.0
Repository
github
Last release
4 years ago

@goa/session

npm version

@goa/session is Session Middleware for Goa apps written in ES6 and optimised with JavaScript Compiler. It is used in the Idio web server.

yarn add @goa/session

Fork Diff

This package is a fork of koa-session with a number of improvements:

  1. The session middleware constructor does not require the app, and will not extend the context with .session property, if middleware wasn't explicitly used. Fixes 177 to avoid confusion when .session is not expected to be present, but is read from cookies anyway.
  2. Remove crc32 hash checking which was unnecessary. Fixes 161 as JSON comparison is enough.
  3. Fix the bug when initial maxAge is not set on the initial session cookie, resulting in a session-only sessions.

Table Of Contents

API

The package is available by importing its default function:

import session from '@goa/session'

session(  opts=: !SessionConfig,): !_goa.Middleware

Initialize the session middleware with opts.

  • opts !SessionConfig (optional): The configuration passed to koa-session.

The interface is changed from the original package, so that the app is always passed as the first argument.

SessionConfig: Configuration for the session middleware.

Example

import aqt from '@rqt/aqt'
import Goa from '@goa/koa'
import session from '@goa/session'

const app = new Goa()
app.keys = ['g', 'o', 'a']
app.use(session({ signed: false })) // normally, signed should be true

app.use((ctx) => {
  if (ctx.path == '/set') {
    ctx.session.message = 'hello'
    ctx.body = 'You have cookies now:'
  } else if (ctx.path == '/exit') {
    ctx.session = null
    ctx.body = 'Bye'
  }
  else ctx.body = `Welcome back: ${ctx.session.message}`
})

app.listen(async function() {
  const { port } = this.address()
  const url = `http://localhost:${port}`

  // 1. Acquire cookies
  let { body, headers } = await aqt(`${url}/set`)
  console.log(body, headers, '\n')
  const cookie = headers['set-cookie']

  // 2. Exploit cookies
  ;({ body, headers } = await aqt(url, {
    headers: {
      cookie,
    },
  }))
  console.log(body, headers, '\n')

  // 3. Destroy cookies
  ;({ body, headers } = await aqt(`${url}/exit`, {
    headers: {
      cookie,
    },
  }))
  console.log(body, headers)

  this.close()
})
You have cookies now: { 'content-type': 'text/plain; charset=utf-8',
  'content-length': '21',
  'set-cookie': 
   [ 'koa:sess=eyJtZXNzYWdlIjoiaGVsbG8iLCJfZXhwaXJlIjoxNTc4NjY2NDgzNjc4LCJfbWF4QWdlIjo4NjQwMDAwMH0=; path=/; expires=Fri, 10 Jan 2020 14:28:03 GMT; httponly' ],
  date: 'Thu, 09 Jan 2020 14:28:03 GMT',
  connection: 'close' } 

Welcome back: hello { 'content-type': 'text/plain; charset=utf-8',
  'content-length': '19',
  date: 'Thu, 09 Jan 2020 14:28:03 GMT',
  connection: 'close' } 

Bye { 'content-type': 'text/plain; charset=utf-8',
  'content-length': '3',
  'set-cookie': 
   [ 'koa:sess=; path=/; expires=Fri, 10 Jan 2020 14:28:03 GMT; httponly' ],
  date: 'Thu, 09 Jan 2020 14:28:03 GMT',
  connection: 'close' }

If your session store requires data or utilities from context, opts.ContextStore is also supported. ContextStore must be a class which implements three instance methods demonstrated below. new ContextStore(ctx) will be executed on every request.

ExternalStore: By implementing this class, the session can be recorded and retrieved from an external store (e.g., a database), instead of cookies.

const sessions = {}

export default {
  async get(key) {
    return sessions[key]
  },

  async set(key, value) {
    sessions[key] = value
  },

  async destroy(key) {
    sessions[key] = undefined
  },
}

The session object itself (ctx.session) has the following methods.

Session: The session instance accessible via Goa's context.

NameTypeDescription
isNew*booleanReturns true if the session is new.
populated*booleanPopulated flag, which is just a boolean alias of .length.
maxAge*(number | string)Get/set cookie's maxAge.
save*() => voidSave this session no matter whether it is populated.
manuallyCommit*() => !Promise<void>Session headers are auto committed by default. Use this if autoCommit is set to false.

Typedefs

This package is meant to be used as part of the Idio web server. But it also can be used on its own with Koa. To enable auto-completions when configuring the middleware, please install typedefs, and import them in your application entry:

npm version

const sess = session({
  // you can access ctx as context now
  valid(ctx, obj) {
    // force presence of a key in headers too
    const s = ctx.get('secret-key')
    return obj['secret-key'] == s
  }
})
// at the bottom of the file
/**
 * @typedef {import('@typedefs/goa').Context} _goa.Context
 */

Usage Events

This middleware integrates with Idio that collects middleware usage statistics to reward package maintainers. It will emit certain events to bill its usage:

  1. save: When the session is saved via cookies.
  2. save-external: When the session is saved via external storage.

The usage is recorded via the ctx.neoluddite context property set by a server such as Idio. In future, more fine-grained usage events might appear.

Copyright & License

GNU Affero General Public License v3.0

Affero GPL means that you're not allowed to use this middleware on the web unless you release the source code for your application. This is a restrictive license which has the purpose of defending Open Source work and its creators.

Please refer to the Idio license agreement for more info on dual-licensing. You're allowed to use this middleware without disclosing the source code if you sign up on neoluddite.dev package reward scheme.

Original Work by dead-horse and contributors under MIT license.

3.1.1

4 years ago

3.1.0

4 years ago

3.0.0

4 years ago

2.1.0

4 years ago

2.0.0

4 years ago

1.0.3

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago