Coder Social home page Coder Social logo

ms-token's Introduction

Token Orchestrator

Build Status codecov

There is a common task that requires one to request challenges to be performed for a specific action. Imagine user, who wants to register for you service and you need to validate an email, or you want to issue an invitation and remove the burden of activation from a user, as well as supply extra meta information with that token. Furthermore, you often need to throttle specific requests and make sure they are not performed more than once in a certain time span. All of these tasks are easily handled by this module

Install me

npm i ms-token -S

API

Module API is pretty simple and contains only 4 functions alongside initialization. When reading docs, keep in mind that anything in [] is an optional prop.

new TokenManager(args)

  • args.backend:
    • name: supported backends include: redis
    • connection: appropriate connector, ioredis instance for redis
    • prefix: optional, used in redis backend as key prefix
  • args.encrypt, used in crypto.createCipher(algorithm, password) when encoding long tokens:
    • algorithm: one of openssl list-cipher-algorithms, example: aes192
    • sharedSecret: The password is used to derive the cipher key and initialization vector (IV). The value must be either a 'binary' encoded string or a Buffer.
const TokenManager = require('ms-token');
const Redis = require('ioredis');
const tokenManager = new TokenManager({
  backend: {
    name: 'redis',
    connection: new Redis(),
    prefix: 'ms-token:',
  },
  encrypt: {
    algorithm: 'aes256',
    sharedSecret: Buffer.from('incredibly-long-secret-ooooohooo'),
  },
});

tokenManager.create(args)

Use this to create challenge token, which should be sent to user for verification purposes.

Accepts:

  • args.action: unique action name, non-empty string
  • args.id: unique request identification. For instance, if you are going to send this to an email, use email as id. If this is going to be a token sent to the phone - use normalized phone number. Combination of action & id grants access to secret, while secret grants access to all associated metadata
  • [args.ttl]: token expiration, in seconds
  • [args.throttle]:
    • true: would be equal to args.ttl, in that case ttl must be defined
    • Number: do not allow creating token for args.{action,id} combo for Number amount of seconds. Sometimes you want throttle to be small (60 seconds), and ttl to be 15 mins (text messages), or 2 hours and 24 hours (emails)
  • [args.metadata]: Mixed content, must be able to JSON.stringify it
  • [args.secret]:
    • true, default. in that case secret would be automatically generated and would include encrypted public data + generated secret
    • false, do not generate secret. In that case it would simply use action + id for verification/unlocking
    • Object:
      • type: enumerable, acceptable values are: alphabet, number, uuid (default uuid)
      • [alphabet]: string containing characters that are allowed to be used in the secret. Only used in alphabet mode
      • [length]: length of generated secret, only used in alphabet and number mode
      • [encrypt]: defaults to true for uuid. If true - then returned token includes action, id & generated secret encrypted in it. That token alone is enough for verification function. If false - it returns plain text generated secret, you must pass action, id and secret to verification function in order for it to succeed
  • [args.regenerate]: defauls to false. If set to true would allow usage of .regenerate() API by returning uid of this challenge

Returns Object:

  • id: id from args
  • action: action from args
  • [uid]: token unique identificator, when regenerate is true
  • [secret]: send secret to user for completing challenge (for instance via SMS). Secret is not present if was set to false

tokenManager.info(args)

Returns associated data for an already created token. It doesn't perform any verifications. This action should be considered a system action, which could be used for debugging purposes.

Input:

  • args, must have one of uid, args.action and args.id combo or args.secret + args.encrypt combo
  • args.uid: String
  • args.action: String
  • args.id: String
  • args.secret: String
  • args.encrypt: Boolean - true is secret must be encrypted, false otherwise. If false then id and action must be supplied alongside secret

Response:

  • Object: associated metadata with a given input

tokenManager.regenerate(uid)

Works with both uid OR action& id combo. Sometimes challenge token might not reach the user and the user would want to ask for another challenge token. Idea of this is to accept public challenge uid, which would use previous data passed in .create(args) and generate new secret based on this. Can only be used when regenerate was set to true on the .create(args) action

Input:

  • uid - uid from .create(args), when regenerate was set to true

Response:

  • String: newly generated secret, either plain-text or encrypted based on what was passed earlier in .create(args)

tokenManager.verify(args, [opts])

Used for completing challenge by verifying user input.

Accepts:

  • args as String, we would attempt to decode & verify in according with encryption settings
  • args as Object:
    • args.action - action from .create()
    • args.id - id from .create()
    • args.token - secret from .crete() return value
  • [opts] as Object:
    • opts.erase: Defaults to true. if true, when verification succeeds - associated throttle is removed, as well as any notion of this token
    • opts.log: if true, logs attempt time.
    • opts.control: verifies that decrypted args contains same values
      • opts.id -> checks id
      • opts.action -> checks action

Response, always Object in case of successful verification:

  • id
  • action
  • uid
  • secret
  • created
  • settings
  • metadata
  • isFirstVerification - whether this was a first successful verification
  • verified - timestamp when it was verified

Otherwise rejects promise with an error

tokenManager.remove(args)

  • args as String, we would attempt to decode & verify in according with encryption settings
  • args as Object:
    • args.uid - either uid OR action & id combination
    • args.action - action from .create()
    • args.id - id from .create()

ms-token's People

Contributors

avvs avatar aleksxor avatar annahassel avatar sentiens avatar

Stargazers

David Teather avatar  avatar

Watchers

 avatar  avatar James Cloos avatar  avatar  avatar bludzhd avatar  avatar  avatar

Forkers

sentiens

ms-token's Issues

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


The push permission to the Git repository is required.

semantic-release cannot push the version tag to the branch master on remote Git repository with URL http://[secure]@github.com/makeomatic/ms-token.git.

Please refer to the authentication configuration documentation to configure the Git credentials on your CI environment and make sure the repositoryUrl is configured with a valid Git URL.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

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.