Update appcache version.
[skeletonkey.git] / core.js
diff --git a/core.js b/core.js
index 171ede1edb7d2d6a998d7bcc435ecfcbc6abc2a0..3986dae01f959e41201b52d72c39b5e007b85926 100644 (file)
--- a/core.js
+++ b/core.js
  * DEALINGS IN THE SOFTWARE.
  */
 
+(function main() {
+  document.addEventListener('DOMContentLoaded', function() {
+    var controller = new SkeletonKey(document);
+  });
+})();
+
 /**
  * SkeletonKey is view controller for generating secure passwords.
  *
@@ -30,6 +36,14 @@ var SkeletonKey = SkeletonKey || function(doc) {
   this._username = doc.getElementById('username');
   this._password = doc.getElementById('password');
   this._generateButton = doc.getElementById('generate');
+
+  // If this is an extension, use defaults until the Chrome settings are loaded.
+  var win = null;
+  if (!this._isChromeExtension())
+    win = window;
+  this._options = new SkeletonKeyOptions(null, win);
+
+
   this._init();
 };
 
@@ -50,6 +64,26 @@ SkeletonKey.prototype.KEYSIZE = 256/32;
  */
 SkeletonKey.prototype._init = function() {
   this._generateButton.onclick = this._onGenerate.bind(this);
+
+  this._master.onkeyup = this._nextFieldInterceptor.bind(this);
+  this._sitekey.onkeyup = this._nextFieldInterceptor.bind(this);
+  this._username.onkeyup = this._nextFieldInterceptor.bind(this);
+
+  if (!this._isTouchDevice()) {
+    this._password.onmousedown = this._selectPassword.bind(this);
+    this._password.onmouseup = function(e) {
+      e.preventDefault();
+      e.stopPropagation();
+    };
+  }
+
+  if (this._isChromeExtension()) {
+    this._initChromeExtension();
+  } else {
+    // Chrome extensions will get the first field focused automatically, so only
+    // do it explicitly for hosted pages.
+    this._master.focus();
+  }
 };
 
 /**
@@ -59,8 +93,164 @@ SkeletonKey.prototype._init = function() {
  */
 SkeletonKey.prototype._onGenerate = function(e) {
   var salt = this._username.value + '@' + this._sitekey.value;
+
   // |key| is a WordArray of 32-bit words.
   var key = CryptoJS.PBKDF2(this._master.value, salt,
       {keySize: this.KEYSIZE, iterations: this.ITERATIONS});
-  console.log(key);
+
+  var hexString = key.toString();
+  hexString = this._capitalizeKey(hexString);
+
+  var maxLength = this._options.getMaximumPasswordLength();
+  if (hexString.length > maxLength)
+    hexString = hexString.substr(0, maxLength);
+
+  this._password.innerText = hexString;
+  this._selectPassword();
+};
+
+/**
+ * Takes a HEX string and returns a mixed-case string.
+ * @param {string} key
+ * @return string
+ * @private
+ */
+SkeletonKey.prototype._capitalizeKey = function(key) {
+  // |key| is too long for a decent password, so try and use the second half of
+  // it as the basis for capitalizing the key.
+  var capsSource = null;
+  var keyLength = key.length;
+  if (keyLength / 2 <= this._options.getMinimumPasswordLength()) {
+    capsSouce = key.substr(0, keyLength - this._options.getMinimumPasswordLength());
+  } else {
+    capsSource = key.substr(keyLength / 2);
+  }
+
+  if (!capsSource || capsSource.length < 1) {
+    return key;
+  }
+
+  key = key.substr(0, capsSource.length);
+  var capsSourceLength = capsSource.length;
+
+  var j = 0;
+  var newKey = "";
+  for (var i = 0; i < key.length; i++) {
+    var c = key.charCodeAt(i);
+    // If this is not a lowercase letter or there's no more source, skip.
+    if (c < 0x61 || c > 0x7A || j >= capsSourceLength) {
+      newKey += key[i];
+      continue;
+    }
+
+    var makeCap = capsSource.charCodeAt(j++) % 2;
+    if (makeCap)
+      newKey += String.fromCharCode(c - 0x20);
+    else
+      newKey += key[i];
+  }
+
+  return newKey;
+};
+
+/**
+ * Checks if the given key event is from the enter key and moves onto the next
+ * field or generates the password.
+ * @param {Event} e
+ * @private
+ */
+SkeletonKey.prototype._nextFieldInterceptor = function(e) {
+  if (e.keyCode != 0xD)
+    return;
+
+  if (this._master.value == "") {
+    this._master.focus();
+  } else if (this._sitekey.value == "") {
+    this._sitekey.focus();
+  } else if (this._username.value == "") {
+    this._username.focus();
+  } else {
+    this._generateButton.click();
+  }
 };
+
+/**
+ * Selects the contents of the generated password.
+ * @private
+ */
+SkeletonKey.prototype._selectPassword = function() {
+  this._generateButton.blur();
+
+  // Touch devices do not bring up the edit controls (for copy) for
+  // pre-selected text.
+  if (this._isTouchDevice())
+    return;
+
+  var range = document.createRange();
+  range.selectNode(this._password.firstChild);  // Select #text node.
+
+  var selection = window.getSelection();
+  selection.removeAllRanges();
+  selection.addRange(range);
+};
+
+/**
+ * Initalizes the Chrome extension pieces if running inside chrome.
+ * @private
+ */
+SkeletonKey.prototype._initChromeExtension = function() {
+  var query = {
+    "active": true,
+    "currentWindow": true
+  };
+  chrome.tabs.query(query, function (tabs) {
+    console.log(tabs);
+    if (tabs == null || tabs.length != 1)
+      return;
+
+    var url = tabs[0].url;
+    if (url == null || url == "")
+      return;
+
+    // Use a link to clevely parse the URL into the hostname.
+    var parser = document.createElement("a");
+    parser.href = url;
+    var hostname = parser.hostname.split(".");
+
+    // Filter out common subdomains and TLDs to keep the siteky short and
+    // memorable.
+    ["www", "login", "account", "accounts"].forEach(function(subdomain) {
+      if (hostname[0] == subdomain) {
+        hostname.shift();
+        return;
+      }
+    });
+
+    ["com", "net", "org", "edu", "info"].forEach(function(tld) {
+      if (hostname[hostname.length - 1] == tld) {
+        hostname.pop();
+        return;
+      }
+    });
+
+    this._sitekey.value = hostname.join(".");
+  }.bind(this));
+};
+
+/**
+ * Checks if SkeletonKey is running as a Chrome extension.
+ * @returns {bool}
+ * @private
+ */
+SkeletonKey.prototype._isChromeExtension = function() {
+  return typeof chrome !== 'undefined' && typeof chrome.tabs !== 'undefined';
+};
+
+/**
+ * Checks if SkeletonKey is running on a touch device.
+ * @returns {bool}
+ * @private
+ */
+SkeletonKey.prototype._isTouchDevice = function() {
+  return typeof document.createTouch === 'function';
+}