All files / src adapter.ts

96.87% Statements 31/32
81.25% Branches 13/16
100% Functions 7/7
100% Lines 28/28

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 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 1782x 2x 2x             2x                                           2x             1x 1x                         70x   24x                                 70x   6x                   2x                   13x                   19x 19x         19x       19x   19x                     52x   52x   52x 52x       52x 1x     51x     51x         51x                                                     24x      
import { timingSafeEqual } from "crypto";
import { binaryLikeToBuffer } from "./buffer";
import { decode, encode } from "./digest";
import type {
  HashingOptions,
  InstanceOptions,
  VerificationOptions
} from "./options";
 
export const instanceDefaults: Required<InstanceOptions> = {
  pepper: "",
  algorithmSeparatorChar: "$",
  encoding: "safe-base64",
  includeAlgorithm: true
};
 
export interface HashingAdapter {
  readonly name: string;
  hash(options: HashingOptions): Promise<string>;
  verify(options: VerificationOptions): Promise<boolean>;
}
 
export type AdapterClass = new (options: InstanceOptions) => HashingAdapter;
 
/**
 *
 *
 * @export
 * @class AlgorithmsMismatchError
 * @extends {Error}
 */
export class AlgorithmsMismatchError extends Error {
  /**
   * Creates an instance of AlgorithmsMismatchError.
   * @param {string} expected
   * @param {string} encoded
   * @memberof AlgorithmsMismatchError
   */
  constructor(public expected: string, public encoded: string) {
    super(
      `Verifier expected hash to be created with algorithm: ${expected}. Got: ${encoded}`
    );
  }
}
 
/**
 *
 *
 * @param {HashingOptions} options
 * @return {Buffer} {Buffer}
 */
function createSalt(options: HashingOptions): Buffer | undefined {
  if (!options.pepper && !options.salt) return;
 
  return Buffer.concat([
    binaryLikeToBuffer(options.pepper ?? ""),
    binaryLikeToBuffer(options.salt ?? "")
  ]);
}
 
/**
 *
 *
 * @param {string} algorithmName
 * @param {string|Function} encoding
 * @return {*}
 */
function resolveEncoding(
  algorithmName: string,
  encoding: Required<InstanceOptions>["encoding"]
) {
  if (typeof encoding === "string") return encoding;
 
  return encoding(algorithmName);
}
 
/**
 *
 *
 * @export
 * @abstract
 * @class BaseHashingAdapter
 */
export abstract class BaseHashingAdapter implements HashingAdapter {
  protected readonly _options: InstanceOptions;
  abstract readonly name: string;
 
  /**
   * Creates an instance of BaseHashingAdapter.
   * @param {InstanceOptions} [options={}]
   * @memberof BaseHashingAdapter
   */
  constructor(options: InstanceOptions = {}) {
    this._options = options;
  }
 
  /**
   *
   *
   * @param {HashingOptions} options
   * @memberof BaseHashingAdapter
   */
  async hash(options: HashingOptions): Promise<string> {
    const mergedOptions = { ...instanceDefaults, ...this._options, ...options };
    const hashBuffer = await this._hash(
      binaryLikeToBuffer(mergedOptions.password),
      createSalt(mergedOptions)
    );
 
    const hash = encode(
      resolveEncoding(this.name, mergedOptions.encoding),
      hashBuffer
    );
    Iif (!mergedOptions.includeAlgorithm) return hash;
 
    return this.name + mergedOptions.algorithmSeparatorChar + hash;
  }
 
  /**
   *
   *
   * @param {VerificationOptions} options
   * @return {Promise<boolean>}  {Promise<boolean>}
   * @memberof BaseHashingAdapter
   */
  async verify(options: VerificationOptions): Promise<boolean> {
    const mergedOptions = { ...instanceDefaults, ...this._options, ...options };
 
    let hashString = mergedOptions.hash;
 
    if (mergedOptions.includeAlgorithm) {
      const [algorithm, ...hashParts] = hashString.split(
        mergedOptions.algorithmSeparatorChar
      );
 
      if (algorithm !== this.name) {
        throw new AlgorithmsMismatchError(this.name, algorithm);
      }
 
      hashString = hashParts.join(mergedOptions.algorithmSeparatorChar);
    }
 
    const hashBuffer = decode(
      resolveEncoding(this.name, mergedOptions.encoding),
      hashString
    );
 
    return await this._verify(
      binaryLikeToBuffer(mergedOptions.password),
      createSalt(mergedOptions),
      hashBuffer
    );
  }
 
  protected abstract _hash(
    password: Buffer,
    salt: Buffer | undefined
  ): Promise<Buffer>;
 
  /**
   *
   *
   * @protected
   * @param {Buffer} password
   * @param {Buffer=} salt
   * @param {Buffer} hash
   * @return {Promise<boolean>}  {Promise<boolean>}
   * @memberof BaseHashingAdapter
   */
  protected async _verify(
    password: Buffer,
    salt: Buffer | undefined,
    hash: Buffer
  ): Promise<boolean> {
    return timingSafeEqual(await this._hash(password, salt), hash);
  }
}