liquid-api-client
TypeScript icon, indicating that this package has built-in type declarations

2.0.0 • Public • Published

liquid-api-client

Client library and token-based authentication helper for the Liquid API.

This library exposes two classes:

  • LiquidClient is the API client used to make HTTP requests, and
  • JWTService is the authentication helper used to queue requests and issue tokens.

Quick Start

TODO.

JWTService

The JWTService is responsible for queueing and orchestrating API requests, ensuring that tokens are issued and used with strictly sequential nonces.

withToken

The withToken function takes two arguments, a payload which will be merged into the body of the JWT and an async callback which receives the one-time-use token as its only argument. The callback must return a promise and the token must not be used after that promise resolves or rejects.

Calling withToken enqueues the callback and returns a promise that resolves once the callback has been resolved. Callers are responsible for handling any errors, so please ensure that you use a try/catch block or a .catch statement with your withToken call.

Do not try to acquire a token with withToken and use it later. Doing so will result in a failed request due to non-sequential nonce values.

const tokenId = 1234;
const tokenSecret = "1fhfhieoanieoncvnia";
const tokenAlg = "RS256";
const bodySecureToken = "1fhfhieoanieoncvnia";

const tokenService = new JWTService(
  tokenId,
  tokenSecret,
  tokenAlg,
  bodySecureToken
);

const getUser = () => {
  try {
    // This function will block here until all queued withToken callbacks in
    // the tokenService have been processed.
    const response = await tokenService.withToken({ path: "/user" }, token =>
      fetch("/user", {
        headers: {
          "X-Quoine-Auth": token,
        },
      })
    );

    return response.json();
  } catch (err) {
    console.log(err);
  }
};

LiquidClient

The client constructor requires the API hostname as a string and accepts an optional configuration object:

  • defaultVendorId is the numeric vendor ID sent in the vendor header with every request,
  • headers is an object containing optional custom headers to send with every request,
  • publicEndpoints is an array of regular expressions which whitelist known-public API endpoints,
  • semiPublicEndpoints is an array of regular expressions which identify API endpoints which can be called both with and without authentication, and
  • tokenService is an optional instance of the JWTService which is used to authenticate requests.

The configuration object is optional, however it is highly recommended to specify the default vendor ID as some endpoints have undefined behavior if the vendor is not set.

import { LiquidClient } from "liquid-api-client";

const client = new LiquidClient("https://api.liquid.com", {
  defaultVendorId: 3, // global (non-jp) vendor
  publicEndpoints: [/^\/products$/],
});

const products = await client.get("/products");

LiquidClient exposes functions for get, post, put, patch and delete operations which are fetch-like with some syntactic sugar for handling request bodies.

Public Endpoints

As a performance optimization LiquidClient will not send an auth token with any requests to paths that match at least one of the RegExes in the publicEndpoints array.

This permits non-authenticated requests to be sent immediately and in parallel, rather than being queued.

Some endpoints behave differently depending on whether the user is logged in or not. These should be checked by supplying a regex to the semiPublicEndpoints array. If a request path matches one of these endpoints and the user is logged in, an authenticated request will be made. If the user is logged out, a non-authenticated request will be made.

Requests made to a private endpoint (i.e. a path that does not match a publicEndpoints or semiPublicEndpoints regex) while there is no registered token service will immediately throw a synthetic 401 error.

Authentication

Users can authenticate with LiquidClient by passing in a token service. This project ships with the JWTService class that signs and issues tokens and sequences requests to prevent nonce conflicts.

Instantiate an instance of JWTService with a token ID and secret (from the Liquid authentication endpoint) and pass it into LiquidClient with your vendor ID via the authenticateWith function.

client.authenticateWith(tokenService, vendorId);

// client will now make authenticated requests

Calling deauthenticate will de-authenticate the user and reset vendor ID to the default value.

client.deauthenticate();

// client will now make unauthenticated requests and throw if a private endpoint is requested

Readme

Keywords

none

Package Sidebar

Install

npm i liquid-api-client

Weekly Downloads

20

Version

2.0.0

License

MIT

Unpacked Size

214 kB

Total Files

17

Last publish

Collaborators

  • jeredmasters
  • quoine-front-end