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

@samespace/token-service-koa

v1.0.9

Published

Implements Samespace Token Service with koa Middleware

Downloads

6

Readme

🔌Token Service (Koa Middleware)

npm version code cov CircleCI Dependencies Known Vulnerabilities

Table of Contents

Getting started

Install @samespace/token-service-koa using npm.

# NPM
npm install @samespace/token-service-koa --save

# YARN
yarn add @samespace/token-service-koa

Obtaining Service Account

Service accounts can be obtained by raising a request at Selfcare

Documentation

Token Service API documentation can be found here.

Usage

TokenService middleware should be the first middleware after any bod-parser

const Koa = require('koa');
const app = new Koa();

const TokenService = require('@samespace/token-service-koa');
const TokenServiceMiddleware = new TokenService({
  path: '/TokenService',
  audience: 'https://exmaple.com/TokenService',
  keyFile: './serviceAccount.json'
});

app.use(TokenServiceMiddleware);

app.use(async ctx => {
  ctx.body = 'Hello World';
});

app.listen(3000);

Arguments

| Argument | Type | Description | Required | | ------------- | ------------- | ------------- | ------------- | | path | String | Path at which the middleware will listen for Token Server requests. | ✔️ | | audience | String | Audience against which tokens will be verified. | ✔️ | | keyFile | String | Object | Path from root of service account file or Object containing service account configuration. | ✔️ | | ignorePaths | Array | Array of paths or regular expression to ignore AuthenticationE.g: ignorePaths: ['/login', /\/(about-us\|contact)/]This will skip authentication on path /login and any path containing the keywords about-us or contact | ❌ | | tokenTtl | Integer | TTL of the token to be validated locally, after expiry a verifyToken call will be made. | ❌ | | onRedirect | Function | Function to trigger when token is not provided by the client and redirection to redirect_uri needs to be overridden. | ❌ | | onExpiry | Function | Function to trigger when an expired token is provided by the client. | ❌ | | onDeauthorize | Function | Function to trigger when a token is forcefully deauthorized by an audience scope. | ❌ | | onError | Function | Function to trigger when an unhandled error has occured. | ❌ |

Reference

onRedirect

Default:

// Deafult will redirect user to redirect_uri

Usage:

new TokenService({
  onRedirect: (ctx) => {
    ctx.redirect('/login')
  }
})

onExpiry

Default:

new TokenService({
  onExpiry: (err, ctx) => {
    ctx.status = 401
    ctx.body = {
      code: 401,
      msg: 'TOKEN_EXPIRY',
      service: 'TokenService'
    }
  }
})

Usage:

new TokenService({
  onExpiry: (err, ctx) => {
    // Log err to console
    ctx.logger.error(err)
        
    // Set status for client
    ctx.status = 401
  }
})

onDeauthorize

Default:

new TokenService({
  onDeauthorize: () => {}
})

Usage:

new TokenService({
  onDeauthorize: (ctx, deauthorizeToken) => {
    // Log err to console
    ctx.logger.info(`Deauthorized token: ${deauthorizeToken}`)
  }
})

onError

Default:

new TokenService({
  onError: (err, ctx) => {
    console.error(err)
    ctx.status = 500
    ctx.body = {
      code: 500,
      msg: 'INTERNAL_SERVICE_ERROR',
      service: 'TokenService'
    }
  }
})

Usage:

new TokenService({
  onError: (err, ctx) => {
    // Log err to console
    ctx.logger.error(err)
        
    // Set status for client
    ctx.status = 500
  }
})

Helper Functions

These functions can be used to provide additional functionalities. For ease, they are binded to ctx.tokenService.

ctx.tokenService.generateToken(String, String)

/*
 * @async
 * @param {string} subject - Subject for the JWT Token
 * @param {string} claims - JWT Token private claim
 * @return {Promise<string>}
**/
ctx.tokenService.generateToken(subject, claims).then(({ subject, token }) => {
  // ...do something with token
}).catch(err => {
  // ...error handling
})

Rejections:

{
  name: 'TokenServiceError',
  message: 'INVALID_SUBJECT'
}
{
  name: 'TokenServiceError',
  message: 'INVALID_PAYLOAD'
}
{
  name: 'TokenServiceError',
  message: 'INVALID_ACCOUNT_CREDENTIALS'
}
{
  name: 'TokenServiceError',
  message: 'SERVER_ERROR'
}

ctx.tokenService.verifyToken(String)

/*
 * @async
 * @param {string} token - JWT Token to verify
 * @return {Promise<string>}
**/
ctx.tokenService.verifyToken(token).then(() => {
  // Token Verified
}).catch(err => {
  // ...error handling
})

Rejections:

{
  name: 'TokenServiceError',
  message: 'INVALID_KEY_ID'
}
{
  name: 'TokenServiceError',
  message: 'INVALID_TOKEN'
}
// Thrown when the token is malformed and the client is 
// unable to verify with the provider.
{
  name: 'JsonWebTokenError',
  message: 'jwt malformed'
}

ctx.tokenService.refreshToken(String)

/*
 * @async
 * @param {string} token - JWT Token to refresh
 * @return {Promise<string>}
**/
ctx.tokenService.refreshToken(token).then(freshSignedToken => {
  // provide { freshSignedToken } to the client
}).catch(err => {
  // ...error handling
})

ctx.tokenService.revokeToken(String)

/*
 * @async
 * @param {string} subject - subject of JWT Token to deauthorize
 * @return {Promise<string>}
**/
ctx.tokenService.revokeToken(keyId).then(() => {
  // successfully deauthorized the token 
  // across all the clients in audience
}).catch(err => {
  // ...error handling
})

Rejections:

{
  name: 'TokenServiceError',
  message: 'INVALID_KEY_ID'
}

ctx.tokenService.deauthorizeToken(String)

/*
 * @async
 * @param {string} subject - subject of JWT Token to deauthorize
 * @return {Promise<string>}
**/
ctx.tokenService.deauthorizeToken(subject).then(() => {
  // successfully deauthorized the token 
  // across all the clients in audience
}).catch(err => {
  // ...error handling
})

Rejections:

{
  name: 'TokenServiceError',
  message: 'INVALID_SUBJECT'
}

License

Released under the MIT license.