All files / platform/packages/url-signer/src UrlSigner.js

100% Statements 40/40
90.24% Branches 37/41
100% Functions 6/6
100% Lines 40/40

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            1x 1x                         2x 2x                                           21x     21x     14x 14x 1x     13x             13x 13x 13x                   9x 9x 9x 1x     8x 8x 3x   5x 5x                   21x 21x 21x 21x 21x 21x 21x 21x 21x               21x 4x   17x 3x                     26x 26x 26x   26x       1x  
'use strict';
 
/** @typedef {import('@adonisjs/framework/src/Request')} Request */
/** @typedef {import('@adonisjs/framework/src/Route')} Route */
/** @typedef {import('./MessageVerifier')} MessageVerifier */
 
const encodeUrl = require('encodeurl');
const qs = require('qs');
 
/**
 * Adonis Signed URLs
 * This is copy version from Adonis 5 [@adonisjs/http-server@5.5.4]
 */
class UrlSigner {
  /**
   *
   * @param {Route} router
   * @param {MessageVerifier} messageVerifier
   */
  constructor(router, messageVerifier) {
    this.router = router;
    this.messageVerifier = messageVerifier;
  }
 
  /**
   * Makes a signed url, which can be confirmed for it's integrity without
   * relying on any sort of backend storage.
   * @method sign
   * @param {string} routeIdentifier - Route name or controller action
   * @param {Object} params
   * @param {Object} options
   * @throws {Error}
   * @return {String}
   */
  makeSignedUrl(routeIdentifier, params = {}, options = {}) {
    const {
      params: normalizedParams,
      expiresAt,
      purpose,
      query,
      domain,
      protocol,
      prefixUrl,
    } = this.normalizeMakeSignedUrlOptions(params, options);
 
    // Validate options values
    this.validateOptions({ expiresAt, purpose });
 
    // Generate url with params and domain, protocol
    let url = this.router.url(routeIdentifier, normalizedParams, { domain, protocol });
    if (!url) {
      return null;
    }
    // Making the signature from the qualified url.
    const signature = this.messageVerifier.sign(
      this.suffixQueryString(url, query),
      expiresAt,
      purpose,
    );
 
    // Adding signature to the query string and re-making the url again
    Object.assign(query, { signature });
    url = this.suffixQueryString(url, query);
    return url && /^http(s)?/.test(url) ? url : `${prefixUrl}${url}`;
  }
 
  /**
   * Returns a boolean telling if a signed url as a valid signature or not.
   * @param {Request} request
   * @param {string} purpose
   * @returns
   */
  hasValidSignature(request, purpose) {
    const { signature, ...rest } = request.qs;
    const url = request.url();
    if (!signature) {
      return false;
    }
    // Return false when signature fails
    const signedUrl = this.messageVerifier.unsign(signature, purpose);
    if (!signedUrl) {
      return false;
    }
    const queryString = qs.stringify(rest);
    return queryString ? `${url}?${queryString}` === signedUrl : url === signedUrl;
  }
 
  /**
   * Normalizes the make signed url options by allowing params to appear on
   * top level object with option to nest inside `params` property.
   * @param {Object} params
   * @param {Object} options
   */
  normalizeMakeSignedUrlOptions(params, options) {
    params = params || {};
    options = options || {};
    const query = options.query || params.query || {};
    const expiresAt = options.expiresAt || params.expiresAt;
    const purpose = options.purpose || params.purpose;
    const domain = options.domain;
    const protocol = options.protocol;
    const prefixUrl = options.prefixUrl || '';
    return { params, query, domain, protocol, prefixUrl, expiresAt, purpose };
  }
 
  /**
   * Validate the expires at time.
   * @param {Object} options
   */
  validateOptions(options) {
    if (options.expiresAt && !(options.expiresAt instanceof Date && !isNaN(options.expiresAt))) {
      throw new Error('UrlSigner requires a expiresAt as Date type');
    }
    if (options.purpose && !(typeof options.purpose === 'string')) {
      throw new Error('UrlSigner requires a purpose as string type');
    }
  }
 
  /**
   * Suffix the query string to the URL
   * @param {string} url
   * @param {Object} queryParams
   * @returns
   */
  suffixQueryString(url, queryParams) {
    Eif (queryParams) {
      const encoded = qs.stringify(queryParams);
      url = encoded ? `${url}?${encodeUrl(encoded)}` : url;
    }
    return url;
  }
}
 
module.exports = UrlSigner;