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

cookie-signature-subtle

v1.0.0

Published

Sign and unsign cookies using web standard SubtleCrypto (browser-compatible)

Downloads

192

Readme

cookie-signature-subtle

Sign and unsign cookies using web standard SubtleCrypto (browser-compatible)

CI Status JavaScript Style Guide Conventional Commits

This library makes it easy to sign response cookie values and authenticate request cookie values using a shared secret. Although the intent is to handle cookie values for your application, this library doesn't work directly with a request or response headers, and it can be used for signing/authenticating any simple strings.

This is a rewrite of the original cookie-signature package that uses the SubtleCrypto standard of the modern Web Crypto API instead of the Node.js-specific crypto module, for better compatibility with runtimes like Vercel's Edge Runtime. It shares the same API contract as cookie-signature except that the methods are asynchronous (returning a Promise) instead of synchronous, due to the nature of the SubtleCrypto API.

This library is meant to be compatible with web standards and modern runtimes. Although it should be compatible with a browser environment/runtime, it is generally not a good idea to expose secrets used for generating digital signatures to code running on a client's browser.

See below for usage and examples.

Install

$ npm i cookie-signature-subtle
// default export for standard use
import signature from 'cookie-signature-subtle'

const secret = 'not a good secret'

const signedValue = await signature.sign('cookievalue', secret)
// => 'cookievalue.XAn8/gvhqwlDLy7ibUMVNWlXpQetHJJFQ9cz6u9Oeeg'

const originalValue = await signature.unsign(signedValue, secret)
// => 'cookievalue'

const bogusValue = await signature.unsign('not valid', secret)
// => false

const bogusSecret = await signature.unsign(signedValue, 'another bad secret')
// => false
// named export for customization
import { CookieSignature } from 'cookie-signature-subtle'

const signature = CookieSignature.get({ separator: '_', hash: 'SHA-512' })
const secret = 'not a good secret'

const signedValue = await signature.sign('cookievalue', secret)
// => 'cookievalue_/8OaZNevtP9If8FmWIbA6AWo9Tuowu/GXnYQ90VvzztyQzNCsLCBnRbVXIuqE3bUCahmlXhHN33zNAdWm55azw'

const originalValue = await signature.unsign(signedValue, secret)
// => 'cookievalue'

const bogusValue = await signature.unsign('not valid', secret)
// => false

const bogusSecret = await signature.unsign(signedValue, 'another bad secret')
// => false

API

The default export is an instance of the CookieSignature class configured with default options that are compatible with the original cookie-signature package except that the methods of this library are async (return a Promise). Otherwise the API contract is the same as cookie-signature.

The main API methods are:

  • signature.sign(valueToSign, secret)

    Sign the given string with a signature derived from the given secret.

    valueToSign must be a string; otherwise this method rejects (throws) with a TypeError.

    secret may be a string, Buffer, TypedArray, CryptoKey, or anything accepted by importKey. It cannot be null or undefined; otherwise this method rejects (throws) with a TypeError.

    Returns a Promise that resolves to a string containing the given value concatenated with a separator ('.' by default) and the HMAC signature (a sha256 hash by default) encoded as base64 without any padding. The returned value can be provided to the unsign method with the same secret to validate its authenticity and be converted back to the original unsigned value.

    Example:

    import signature from 'cookie-signature-subtle'
    
    const signedValue = await signature.sign('hello', 'not a good secret')
    // => 'hello.6J710tYHo2C2ka+uG9bw9xol/u3K+Is1FVaOyNlAiBE'
  • signature.unsign(signedCookieValue, secret)

    Convert an authenticated/signed string value back into its original unsigned string value.

    signedCookieValue must be a string; otherwise this method rejects (throws) with a TypeError.

    secret may be a string, Buffer, TypedArray, CryptoKey, or anything accepted by importKey. It cannot be null or undefined; otherwise this method rejects (throws) with a TypeError.

    Returns a Promise that resolves to either the unsigned string value (if authenticated) or the boolean value false (if not authenticated).

    Example:

    import signature from 'cookie-signature-subtle'
    
    const originalValue = await signature.unsign('hello.6J710tYHo2C2ka+uG9bw9xol/u3K+Is1FVaOyNlAiBE', 'not a good secret')
    // => 'hello'
    
    const bogusValue = await signature.unsign('not valid', 'not a good secret')
    // => false

This module also exports the CookieSignature class as a named export if you'd like to customize the separator or hash algorithm used. You can construct your own signature instance using the constructor (i.e. new CookieSignature(opts)) or a static get convenience method (i.e. CookieSignature.get(opts)).

The options accepted when constructing a new instance are:

  • opts.separator (string, default '.'): the string used to separate the unsigned value from the signature in the signed value

    Must be a string; otherwise the given option will be ignored and '.' will be used.

    Since the signature is always a base64-encoded string, make sure you use a separator that will never be part of the encoded signature (i.e. don't use a-z, A-Z, 0-9, '+', or '/').

    Example:

    import { CookieSignature } from 'cookie-signature-subtle'
    const signature = CookieSignature.get({ separator: '_' })
    
    const signedValue = await signature.sign('hello', 'not a good secret')
    // => 'hello_6J710tYHo2C2ka+uG9bw9xol/u3K+Is1FVaOyNlAiBE'
    
    const originalValue = await signature.unsign(signedValue, 'not a good secret')
    // => 'hello'
  • opts.hash (string, default 'SHA-256'): the hashing algorithm to use when generating the signature

    Per the SubtleCrypto API, accepts values 'SHA-1', 'SHA-256', 'SHA-384', or 'SHA-512'. If an unknown value is given, it will be ignored and 'SHA-256' will be used.

    Example:

    import { CookieSignature } from 'cookie-signature-subtle'
    const signature = CookieSignature.get({ hash: 'SHA-384' })
    
    const signedValue = await signature.sign('hello', 'not a good secret')
    // => 'hello.6J0vmMamuPKikY6ufK/uE6oqE75/7GwjtixxVss8MBGtLv07L9UuiAFjHhU7wPyA'
    
    const originalValue = await signature.unsign(signedValue, 'not a good secret')
    // => 'hello'

License

ISC © Andrew Goode