DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Mercurial (39c1aeb25240)

VCS Links

Line Code
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 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

var EXPORTED_SYMBOLS = ["CreditCard"];

// The list of known and supported credit card network ids ("types")
// This list mirrors the networks from dom/payments/BasicCardPayment.cpp
// and is defined by https://www.w3.org/Payments/card-network-ids
const SUPPORTED_NETWORKS = Object.freeze([
  "amex",
  "cartebancaire",
  "diners",
  "discover",
  "jcb",
  "mastercard",
  "mir",
  "unionpay",
  "visa",
]);

class CreditCard {
  /**
   * A CreditCard object represents a credit card, with
   * number, name, expiration, network, and CCV.
   * The number is the only required information when creating
   * an object, all other members are optional. The number
   * is validated during construction and will throw if invalid.
   *
   * @param {string} name, optional
   * @param {string} number
   * @param {string} expirationString, optional
   * @param {string|number} expirationMonth, optional
   * @param {string|number} expirationYear, optional
   * @param {string} network, optional
   * @param {string|number} ccv, optional
   * @param {string} encryptedNumber, optional
   * @throws if number is an invalid credit card number
   */
  constructor({
    name,
    number,
    expirationString,
    expirationMonth,
    expirationYear,
    network,
    ccv,
    encryptedNumber,
  }) {
    this._name = name;
    this._unmodifiedNumber = number;
    this._encryptedNumber = encryptedNumber;
    this._ccv = ccv;
    this.number = number;
    let { month, year } = CreditCard.normalizeExpiration({
      expirationString,
      expirationMonth,
      expirationYear,
    });
    this._expirationMonth = month;
    this._expirationYear = year;
    this.network = network;
  }

  set name(value) {
    this._name = value;
  }

  set expirationMonth(value) {
    if (typeof value == "undefined") {
      this._expirationMonth = undefined;
      return;
    }
    this._expirationMonth = CreditCard.normalizeExpirationMonth(value);
  }

  get expirationMonth() {
    return this._expirationMonth;
  }

  set expirationYear(value) {
    if (typeof value == "undefined") {
      this._expirationYear = undefined;
      return;
    }
    this._expirationYear = CreditCard.normalizeExpirationYear(value);
  }

  get expirationYear() {
    return this._expirationYear;
  }

  set expirationString(value) {
    let { month, year } = CreditCard.parseExpirationString(value);
    this.expirationMonth = month;
    this.expirationYear = year;
  }

  set ccv(value) {
    this._ccv = value;
  }

  get number() {
    return this._number;
  }

  /**
   * Sets the number member of a CreditCard object. If the number
   * is not valid according to the Luhn algorithm then the member
   * will get set to the empty string before throwing an exception.
   *
   * @param {string} value
   * @throws if the value is an invalid credit card number
   */
  set number(value) {
    if (value) {
      let normalizedNumber = value.replace(/[-\s]/g, "");
      // Based on the information on wiki[1], the shortest valid length should be
      // 12 digits (Maestro).
      // [1] https://en.wikipedia.org/wiki/Payment_card_number
      normalizedNumber = normalizedNumber.match(/^\d{12,}$/)
        ? normalizedNumber
        : "";
      this._number = normalizedNumber;
    } else {
      this._number = "";
    }

    if (value && !this.isValidNumber()) {
      this._number = "";
      throw new Error("Invalid credit card number");
    }
  }

  get network() {
    return this._network;
  }

  set network(value) {
    this._network = value || undefined;
  }

  // Implements the Luhn checksum algorithm as described at
  // http://wikipedia.org/wiki/Luhn_algorithm
  // Number digit lengths vary with network, but should fall within 12-19 range. [2]
  // More details at https://en.wikipedia.org/wiki/Payment_card_number
  isValidNumber() {
    if (!this._number) {
      return false;
    }

    // Remove dashes and whitespace
    let number = this._number.replace(/[\-\s]/g, "");

    let len = number.length;
    if (len < 12 || len > 19) {
      return false;
    }

    if (!/^\d+$/.test(number)) {
      return false;
    }

    let total = 0;
    for (let i = 0; i < len; i++) {
      let ch = parseInt(number[len - i - 1], 10);
      if (i % 2 == 1) {
        // Double it, add digits together if > 10
        ch *= 2;
        if (ch > 9) {
          ch -= 9;
        }
      }
      total += ch;
    }
    return total % 10 == 0;
  }

  /**
   * Returns true if the card number is valid and the
   * expiration date has not passed. Otherwise false.
   *
   * @returns {boolean}
   */
  isValid() {
    if (!this.isValidNumber()) {
      return false;
    }

    let currentDate = new Date();
    let currentYear = currentDate.getFullYear();
    if (this._expirationYear > currentYear) {
      return true;
    }

    // getMonth is 0-based, so add 1 because credit cards are 1-based
    let currentMonth = currentDate.getMonth() + 1;
    return (
      this._expirationYear == currentYear &&
      this._expirationMonth >= currentMonth
    );
  }

  get maskedNumber() {
    return CreditCard.getMaskedNumber(this._number);
  }

  get longMaskedNumber() {
    return CreditCard.getLongMaskedNumber(this._number);
  }

  /**
   * Get credit card display label. It should display masked numbers and the
   * cardholder's name, separated by a comma.
   */
  static getLabel({ number, name }) {
    let parts = [];

    if (number) {
      parts.push(CreditCard.getMaskedNumber(number));
    }
    if (name) {
      parts.push(name);
    }
    return parts.join(", ");
  }

  static normalizeExpirationMonth(month) {
    month = parseInt(month, 10);
    if (isNaN(month) || month < 1 || month > 12) {
      return undefined;
    }
    return month;
  }

  static normalizeExpirationYear(year) {
    year = parseInt(year, 10);
    if (isNaN(year) || year < 0) {
      return undefined;
    }
    if (year < 100) {
      year += 2000;
    }
    return year;
  }

  static parseExpirationString(expirationString) {
    let rules = [
      {
        regex: "(\\d{4})[-/](\\d{1,2})",
        yearIndex: 1,
        monthIndex: 2,
      },
      {
        regex: "(\\d{1,2})[-/](\\d{4})",
        yearIndex: 2,
        monthIndex: 1,
      },
      {
        regex: "(\\d{1,2})[-/](\\d{1,2})",
      },
      {
        regex: "(\\d{2})(\\d{2})",
      },
    ];

    for (let rule of rules) {
      let result = new RegExp(`(?:^|\\D)${rule.regex}(?!\\d)`).exec(
        expirationString
      );
      if (!result) {
        continue;
      }

      let year, month;

      if (!rule.yearIndex || !rule.monthIndex) {
        month = parseInt(result[1], 10);
        if (month > 12) {
          year = parseInt(result[1], 10);
          month = parseInt(result[2], 10);
        } else {
          year = parseInt(result[2], 10);
        }
      } else {
        year = parseInt(result[rule.yearIndex], 10);
        month = parseInt(result[rule.monthIndex], 10);
      }

      if (month < 1 || month > 12 || (year >= 100 && year < 2000)) {
        continue;
      }

      return { month, year };
    }
    return { month: undefined, year: undefined };
  }

  static normalizeExpiration({
    expirationString,
    expirationMonth,
    expirationYear,
  }) {
    // Only prefer the string version if missing one or both parsed formats.
    let parsedExpiration = {};
    if (expirationString && (!expirationMonth || !expirationYear)) {
      parsedExpiration = CreditCard.parseExpirationString(expirationString);
    }
    return {
      month: CreditCard.normalizeExpirationMonth(
        parsedExpiration.month || expirationMonth
      ),
      year: CreditCard.normalizeExpirationYear(
        parsedExpiration.year || expirationYear
      ),
    };
  }

  static formatMaskedNumber(maskedNumber) {
    return {
      affix: "****",
      label: maskedNumber.replace(/^\**/, ""),
    };
  }

  static getMaskedNumber(number) {
    return "*".repeat(4) + " " + number.substr(-4);
  }

  static getLongMaskedNumber(number) {
    return "*".repeat(number.length - 4) + number.substr(-4);
  }

  /*
   * Validates the number according to the Luhn algorithm. This
   * method does not throw an exception if the number is invalid.
   */
  static isValidNumber(number) {
    try {
      new CreditCard({ number });
    } catch (ex) {
      return false;
    }
    return true;
  }

  static isValidNetwork(network) {
    return SUPPORTED_NETWORKS.includes(network);
  }
}
CreditCard.SUPPORTED_NETWORKS = SUPPORTED_NETWORKS;