/*
Copyright 2005 Collin Jackson

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of Stanford University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

/**
 * Hashed Password
 * Combination of page URI and plaintext password.
 * Treated as a string, it is the hashed password.
 */

function SPH_HashedPassword(password, uri) {
  var realm = this._getRealm(uri);      
  var hashedPassword = this._getHashedPassword(password, realm);
  this.toString = function() { return hashedPassword; }
}

SPH_HashedPassword.prototype = {

  /**
   * Extract the hashing salt from the URI where the password field resides
   */
  _getRealm: function(uri) {
     // Obtain the salt using the site name

     // Read the host name out of the URL
     var domainRegex = /^https?:\/\/([^\/]+)\/.*$/;
     var domain = uri.replace(domainRegex, "$1");

     // TODO: Deal with edge cases like .co.uk, e.g.
     // var realmRegex = /([^\/.]+\.[^\/.]+(\.(uk)|(fr)|(jp))?)$/;
     // var realmMatches = domain.match(realmRegex);  

     return domain; 
  },

  /**
   * Determine the hashed password from the salt and the master password
   */
  _getHashedPassword: function(password, realm) {
    var hash = b64_hmac_md5(password, realm);
    var size = password.length + SPH_kPasswordPrefix.length;
    var nonalphanumeric = password.match(/\W/) != null;
    var result = this._applyConstraints(hash, size, nonalphanumeric);
    return result;
  },

  /**
   * Fiddle with the password a bit after hashing it so that it will get through
   * most website filters. We require one upper and lower case, one digit, and
   * we look at the user's password to determine if there should be at least one 
   * alphanumeric or not.
   */
  _applyConstraints: function(hash, size, nonalphanumeric) {
    var result = hash.substring(0, size);
    var extras = hash.substring(size).split('');

    // Some utility functions to keep things tidy
    function prepend(what) { result = what + result.substring(0, result.length - 1); }
    function rotate(arr, amount) { while(amount--) arr.push(arr.shift()) }
    function nextExtra() { return extras.length ? extras.shift().charCodeAt(0) : 0; }
    function between(min, interval, offset) { return min + offset % interval; }
    function nextBetween(base, interval) { 
      return String.fromCharCode(between(base.charCodeAt(0), interval, nextExtra()));
    }

    // Perform replacements
    if (!result.match(/[A-Z]/)) prepend(nextBetween('A', 26));
    if (!result.match(/[a-z]/)) prepend(nextBetween('a', 26));
    if (!result.match(/[0-9]/)) prepend(nextBetween('0', 10));
    if (!result.match(/[\W]/) && nonalphanumeric) prepend('+');
    if (result.match(/[\W]/) && !nonalphanumeric) {
      while(result.replace(/[\W]/, "")) prepend(nextBetween('A', 26));
    }

    // Rotate the result to make it harder to guess the inserted characters
    result = result.split('');
    rotate(result, nextExtra());
    return result.join('');
  }
}

