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

cotter-token-js

v0.1.11

Published

Cotter Tokens and JWT Handler for validating Cotter's responses and validating JWT tokens

Downloads

130

Readme

cotter-token-js

npm version

Cotter Helper to Validate Responses and JWT Tokens for JavaScript

Validate Cotter's Identity and Event responses, read and decode jwt tokens generated by Cotter using the classes defined here. To read more about Cotter, get started with our 📚 integration guides and example projects.

Install

npm install cotter-token-js --save

or

yarn add cotter-token-js

Usage

To decode a jwt token:

import { CotterJwtToken } from "cotter-token-js";

const decodedToken = new CotterJwtToken(token);

console.log(decodedToken.payload); // decoded jwt token object

console.log(decodedToken.token); // original token string

Expiry, IssuedAt, and Audience

// getting payload.exp
const expiredAt = decodedToken.getExpiration();

// getting payload.iat
const issuedAt = decodedToken.getIssuedAt();

// getting payload.aud
const audience = decodedToken.getAudience();

Usage with Cotter

Cotter returns 2 types of jwt token, CotterAccessToken and CotterIDToken.

CotterAccessToken

This access token should be passed to your backend server, and used to authorize users to access your API. Validate the access token passed to your backend server using this example.

To decode a the access token:

import { CotterAccessToken } from "cotter-token-js";

const decodedToken = new CotterAccessToken(accessToken);

console.log(decodedToken.payload); // decoded jwt token object

console.log(decodedToken.token); // original token string

CotterAccessToken have the following attributes

class CotterAccessToken {
  token: string; // This is the original token string
  payload: {
    client_user_id: string;
    authentication_method: string;
    type: string;
    scope: string;
    identifier: string;

    // standard claims
    aud: string;
    exp: number;
    jti: string;
    iat: number;
    iss: string;
    nbf: number;
    sub: string; // Cotter User ID
  }
  
  getAuthMethod(): string   // Get Authentication method (OTP/MAGIC_LINK/TRUSTED_DEVICE/WEBAUTHN)
  getScope(): string        // Get Scope
  getID(): string           // Get Cotter User ID
  getIdentifier(): string   // Get user's identifier (email/phone/username)
  getClientUserID(): string // DEPRECATED: Get client_user_id
}

CotterAccessToken also extends all the methods available for CotterJWTToken.

CotterIDToken

The ID token is following OpenID specifications, and is provided to get more information about the user.

To decode a the id token:

import { CotterIDToken } from "cotter-token-js";

const decodedToken = new CotterIDToken(accessToken);

console.log(decodedToken.payload); // decoded jwt token object

console.log(decodedToken.token); // original token string

CotterIDToken have the following attributes

class CotterIDToken {
  token: string; // This is the original token string
  payload: {
    client_user_id: string;
    auth_time: string;      // authentication time
    identifier: string;     // User's email/phone/username
    type: string;           
    
    // standard claims
    aud: string;
    exp: number;
    jti: string;
    iat: number;
    iss: string;
    nbf: number;
    sub: string; // Cotter User ID
  }
  
  getAuthTime(): string     // Get authentication time
  getIdentifier(): string   // Get user's identifier (email/phone/username)
  getID(): string           // Get Cotter User ID
  getClientUserID(): string // DEPRECATED: Get client_user_id
}

CotterIDToken also extends all the methods available for CotterJWTToken.

Getting Access Token from Cotter

When you want to request access tokens from cotter, add a query paramater ?oauth_token=true at the end of your request.

For reference, current base url for Cotter:


https://www.cotter.app/api/v0

There are several endpoints where you can request access tokens from:

1. Create User Endpoint

POST /user/create?oauth_token=true

2. Update Methods Endpoint

PUT /user/:client_user_id?oauth_token=true

3. Create Approved Event Request Endpoint

POST /event/create?oauth_token=true

4. Get Event Request Endpoint

GET /event/get/:event_id?oauth_token=true

5. Get Identity Endpoint (using PKCE flow)

GET /verify/get_identity?oauth_token=true

When using these endpoints, you'll get an additional field called oauth_token:

Response

{
  ...
  "oauth_token": {
    "access_token": "eyJhbGciOiJFUzI1sInR5cC...",
    "auth_method": "TRUSTED_DEVICE",
    "expires_in": 3600,
    "id_token": "eyJhbGciOiJFUz...",
    "refresh_token": "60:79hbLxl3aTjWWgCcIRnn...",
    "token_type": "Bearer"
  }
}

Get Token using Refresh Token

When your access token expires, you can get a new one using the refresh token that was given.

POST /token
Content-Type: application/json
API_KEY_ID: <API-KEY-ID>


{
  "grant_type": "refresh_token",
  "refresh_token": "3:8xhGfVzGa91WOZ1eDk..."
}

Response

Note that you don't get a refresh token back.

{
  "access_token": "eyJhbGciOsInR5cCI6...",
  "auth_method": "OTP",
  "expires_in": 3600,
  "id_token": "eyJhbGciOiJFUzI1NiI...",
  "token_type": "Bearer"
}

Validating JWT Token

To validate the access or identity token, you can use Cotter's package cotter-node

import { CotterValidateJWT } from "cotter-node";

try {
  var valid = await CotterValidateJWT(token);
} catch (e) {
  console.log(e);
}

If you can't use the package above

To validate the jwt token, you need Cotter's JWT Public Key. The Public Key is specified in this endpoint:

GET /token/jwks

There's only one key for now, so use that key.

To Validate jwt token using this key, check the example

A simple example to validate the jwt token:

var jwt = require("jsonwebtoken");
var jwkToPem = require("jwk-to-pem");
var axios = require("axios");

const validateToken = async (token) => {
  const publicKeys = await axios.default.get(
    "https://www.cotter.app/api/v0/token/jwks"
  );
  const jwk = publicKeys.data.keys[0];
  const pem = jwkToPem(jwk);
  jwt.verify(token, pem, { algorithms: ["ES256"] }, function (err, decodedToken) {
    console.log(err);
    console.log(decodedToken);
  });
}

validateToken(accessToken); // 👈 pass in access token here