Skip to content

Latest commit

 

History

History
133 lines (96 loc) · 5.03 KB

README.md

File metadata and controls

133 lines (96 loc) · 5.03 KB

signatur

Sign and unsign HTTP request with ease


MIT License

It is always a recommended best practice to sign every HTTP request that contains any payload to ensure that the payload that sends along has not been tampered with. This module provides some handy methods to sign and unsign the data payload.

Table of contents

Usage

import { sign, unsign } from 'nodemod/dist/signatur/index.js';

(async () => {
  const payload = {
    id: 'b4cd8c1',
    t: '1580581220222',
  };
  const signedRequest = await sign(payload, {
    secret: 'fixed-secret',
    separator: ':',
  });

  signedRequest === 'eyJpZCI6ImI0Y2Q4YzEiLCJ0IjoiMTU4MDU4MTIyMDIyMiJ9:vXRKs8XZlLq1iJrPaYDsBsrLegjedzUCd3pnQqMB2Qg'; /** true */

  /** This shows how to handle error when a signature is invalid */
  try {
    await unsign(
      'eyJpZCI6ImI0Y2Q4YzEiLCJ0IjoiMTU4MDU4MTIyMDIyMiJ9:vXRKs8XZlLq1iJrPaYDsBsrLegjedzUCd3pnQqMB2Qg',
      { secret: 'fixed-secret', /** separator: ':', error: new Error('Bad signature detected'), */ }
    );
  } catch (e) {
    /** Handle error here */
    e;
    /**
     * {
     *   error: {
     *     type: 'invalid-signature',
     *     message: 'Signature not match',
     *   }
     * }
     */
  }
})();

API Reference

SignaturError

  • error <Object> Error object for bad signature.
    • type <string> Error type. Defaults to invalid-signature.
    • message <string> Error message. Defauls to Signature not match.

SignaturOptions

  • separator <?string> Optional separator. Defaults to period (.).

sign(data, secret[, options])

  • data <T> Raw data payload in the type of T.
  • secret <string> Secret used to encrypt the data payload.
  • options <?SignaturOptions> Options for signing the payload.
  • returns: <Promise<string>> Promise which resolves with a URL-safe base64 encoded HMAC-SHA256 signature that encrypts the raw data payload with a required secret key.

unsign(signature, secret[, options])

  • signature <string> URL-safe signature.
  • secret <string> Secret used to encrypt the data payload.
  • options <?SignaturOptions> Options for signing the payload.
  • returns: <Promise<T>> Promise which resolves with decoded data payload in the type of T.

Throws a error object for bad signature in the type of SignaturError.

signSync(data, secret[, options])

This methods works the same as sign(data, secret[, options]) except that this is the synchronous version.

unsignSync(data, secret[, options])

This methods works the same as unsign(signature, secret[, options]) except that this is the synchronous version.

License

MIT License © Rong Sen Ng