All files / src/apis/p2p p2p.middleware.ts

97.5% Statements 39/40
100% Branches 9/9
90% Functions 9/10
100% Lines 35/35

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139      6x                               6x     6x 6x 6x   5x   3x   1x                       6x           5x 5x   5x 5x 5x   5x 5x   5x                                                 6x 9x   8x   7x                       6x                 1x 1x   1x 5x 5x   5x   4x   4x 2x     2x         2x 2x   2x            
import type { Request, RequestHandler } from "express";
import type { AnyParameters } from "../shared";
import type { P2pBillsApi } from "./bills.api";
import { P2pBillNotificationError } from "./p2p.errors";
import type { BillStatusBody, BillStatusNotificationBody } from "./p2p.types";
 
type Promisify<T> = T extends Promise<any> ? T : Promise<T>;
type AnyCallableFunction = (...parameters: AnyParameters) => unknown;
type PromisifyReturnType<T extends AnyCallableFunction> = Promisify<ReturnType<T>>;
type PromiseWrappedFunction<T extends AnyCallableFunction> = (
  ...parameters: Parameters<T>
) => PromisifyReturnType<T>;
 
/**
 * @template {AnyCallableFunction} T
 *
 * @param {T} callable
 * @return {PromiseWrappedFunction<T>}
 */
export function promise<T extends AnyCallableFunction>(
  callable: T
): PromiseWrappedFunction<T> {
  return (...parameters: AnyParameters): any => {
    try {
      const result = callable(...parameters);
 
      if (result instanceof Promise) return result;
 
      return Promise.resolve(result);
    } catch (error) {
      return Promise.reject(error);
    }
  };
}
 
/**
 *
 *
 * @template T
 * @param {Request} request
 * @return {Promise<T>} Promise<T>
 */
export async function parseJsonRequestBody<T>(request: Request): Promise<T> {
  /* istanbul ignore next */
  if (typeof request.body === "object" && request.body) {
    return request.body;
  }
 
  return new Promise((resolve, reject) => {
    let body = "";
 
    request.on("error", (error) => reject(error));
    request.on("data", (chunk) => {
      body += chunk.toString();
    });
    request.on("end", () => {
      const data = JSON.parse(body.toString());
 
      resolve(data);
    });
  });
}
 
export type BillRequestHandler = RequestHandler<
  Record<string, string>,
  any,
  BillStatusNotificationBody
>;
 
export type MiddlewareOptions = {
  memo?: boolean;
  memoTime?: number;
};
 
/* istanbul ignore next */
const skipMiddleware: RequestHandler = (_request, _response, next) => next();
 
/**
 *
 *
 * @param {(string | string[] | undefined)} value
 * @return {string} string
 */
export function resolveHeaderValue(value?: string | string[] | undefined): string {
  if (!value) return "";
 
  if (Array.isArray(value)) return resolveHeaderValue(value[0]);
 
  return value;
}
 
/**
 *
 *
 * @export
 * @param {P2pBillsApi} bills
 * @param {MiddlewareOptions} [options={}]
 * @param {BillRequestHandler} [handler]
 * @return {BillRequestHandler} BillRequestHandler
 */
export function createP2pNotificationMiddleware(
  bills: P2pBillsApi,
 
  /* istanbul ignore next */
  options: MiddlewareOptions = {},
 
  /* istanbul ignore next */
  handler: BillRequestHandler = skipMiddleware
): BillRequestHandler {
  const calls = new Map<string, number>();
  const { memo = true, memoTime = 1000 * 60 * 15 } = options;
 
  return async function p2pNotificationMiddleware(request, response, next) {
    const notification = await parseJsonRequestBody<BillStatusBody>(request);
    const signature = resolveHeaderValue(request.headers["x-api-signature-sha256"]);
 
    if (memo && calls.has(signature)) return next();
 
    const { bill } = notification;
 
    if (!bills.checkNotificationSignature(signature, notification)) {
      return next(new P2pBillNotificationError(bill));
    }
 
    request.body = bill;
 
    /* istanbul ignore next */
    if (!memo) return handler(request, response, next);
 
    await promise(handler)(request, response, next);
    calls.set(signature, Date.now());
 
    for (const [signature, time] of calls) {
      /* istanbul ignore next */
      if (Date.now() - memoTime > time) calls.delete(signature);
    }
  };
}