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

@sagi.io/workers-jwt

v0.0.26

Published

Generate JWTs on Cloudflare Workers using the WebCrypto API

Downloads

7,328

Readme

workers-jwt

@sagi.io/workers-jwt helps you generate a JWT on Cloudflare Workers with the WebCrypto API. Helper function for GCP Service Accounts included.

⭐ We use it at OpenSay to efficiently access Google's REST APIs with 1 round trip.

CircleCI Coverage Status MIT License version

Installation

$ npm i @sagi.io/workers-jwt

API

We currently expose two methods: getToken for general purpose JWT generation and getTokenFromGCPServiceAccount for JWT generation using a GCP service account.

getToken({ ... })

Function definition:

const getToken = async ({
  privateKeyPEM,
  payload,
  alg = 'RS256',
  cryptoImpl = null,
  headerAdditions = {},
}) => { ... }

Where:

  • privateKeyPEM is the private key string in PEM format.
  • payload is the JSON payload to be signed, i.e. the { aud, iat, exp, iss, sub, scope, ... }.
  • alg is the signing algorithm as defined in RFC7518, currently only RS256 and ES256 are supported.
  • cryptoImpl is a WebCrypto API implementation. Cloudflare Workers support WebCrypto out of the box. For Node.js you can use require('crypto').webcrypto - see examples below and in the tests.
  • headerAdditions is an object with keys and string values to be added to the header of the JWT.

getTokenFromGCPServiceAccount({ ... })

Function definition:

const getTokenFromGCPServiceAccount = async ({
  serviceAccountJSON,
  aud,
  alg = 'RS256',
  cryptoImpl = null,
  expiredAfter = 3600,
  headerAdditions = {},
  payloadAdditions = {}
}) => { ... }

Where:

  • serviceAccountJSON is the service account JSON object .
  • aud is the audience field in the JWT's payload. e.g. https://www.googleapis.com/oauth2/v4/token'.
  • expiredAfter - the duration of the token's validity. Defaults to 1 hour - 3600 seconds.
  • payloadAdditions is an object with keys and string values to be added to the payload of the JWT. Example - { scope: 'https://www.googleapis.com/auth/chat.bot' }.
  • alg, cryptoImpl, headerAdditions are defined as above.

Example

Suppose you'd like to use Firestore's REST API. The first step is to generate a service account with the "Cloud Datastore User" role. Please download the service account and store its contents in the SERVICE_ACCOUNT_JSON_STR environment variable.

The aud is defined by GCP's service definitions and is simply the following concatenated string: 'https://' + SERVICE_NAME + '/' + API__NAME. More info here.

For Firestore the aud is https://firestore.googleapis.com/google.firestore.v1.Firestore.

Cloudflare Workers Usage

Cloudflare Workers expose the crypto global for the Web Crypto API.

const { getTokenFromGCPServiceAccount } = require('@sagi.io/workers-jwt')

const serviceAccountJSON = await ENVIRONMENT.get('SERVICE_ACCOUNT_JSON','json')
const aud = `https://firestore.googleapis.com/google.firestore.v1.Firestore`

const token = await getTokenFromGCPServiceAccount({ serviceAccountJSON, aud} )

const headers = { Authorization: `Bearer ${token}` }

const projectId = 'example-project'
const collection = 'exampleCol'
const document = 'exampleDoc'

const docUrl =
  `https://firestore.googleapis.com/v1/projects/${projectId}/databases/(default)/documents`
  + `/${collection}/${document}`

const response = await fetch(docUrl, { headers })

const documentObj =  await response.json()

Node Usage (version <=14)

We use the node-webcrypto-ossl package to imitate the Web Crypto API in Node.

const { Crytpo }= require('node-webcrypto-ossl');
const cryptoImpl  = new Crypto();
const { getTokenFromGCPServiceAccount } = require('@sagi.io/workers-jwt')

const serviceAccountJSON = { ... }
const aud = `https://firestore.googleapis.com/google.firestore.v1.Firestore`

const token = await getTokenFromGCPServiceAccount({ serviceAccountJSON, aud, cryptoImpl } )

<... SAME AS CLOUDFLARE WORKERS ...>

Node Usage (version 15+)

Node 15 introduces the Web Crypto API. When using NextJS, you may need to pass in the native Node webcrypto lib to get both SSR and webpack to work during dev mode.

const { getTokenFromGCPServiceAccount } = require('@sagi.io/workers-jwt')

const serviceAccountJSON = { ... }
const aud = 'https://firestore.googleapis.com/google.firestore.v1.Firestore';

const token = await getTokenFromGCPServiceAccount({
  serviceAccountJSON,
  aud,
  cryptoImpl: globalThis.crypto || require('crypto').webcrypto,
});

<... SAME AS CLOUDFLARE WORKERS ...>