npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@goa/session

v3.1.1

Published

Session Middleware For Goa.

Downloads

22

Readme

@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.

| Name | Type | Description | | ------------------- | ----------------------------------- | ---------------------------------------------------------------------------------------- | | isNew* | boolean | Returns true if the session is new. | | populated* | boolean | Populated flag, which is just a boolean alias of .length. | | maxAge* | (number | string) | Get/set cookie's maxAge. | | save* | () => void | Save 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.