Cleanup and linting on all *.js

This commit is contained in:
Tankred Hase 2016-02-03 14:26:23 +07:00
parent 4d325ca65c
commit 00ea3918c5
6 changed files with 106 additions and 70 deletions

View File

@ -105,14 +105,14 @@ module.exports = function(grunt) {
}
},
jshint: {
src: ['src/**/*.js'],
src: ['src/*.js'], // add more over time ... goal should be 100% coverage
build: ['Gruntfile.js', '*.json'],
options: {
jshintrc: '.jshintrc'
}
},
jscs: {
src: ['src/**/*.js'],
src: ['src/*.js'], // add more over time ... goal should be 100% coverage
build: ['Gruntfile.js'],
options: {
config: ".jscsrc",
@ -246,7 +246,7 @@ module.exports = function(grunt) {
grunt.registerTask('documentation', ['jsdoc']);
// Test/Dev tasks
grunt.registerTask('test', ['jshint:build', 'jscs:build', 'copy:zlib', 'mochaTest']);
grunt.registerTask('test', ['jshint', 'jscs', 'copy:zlib', 'mochaTest']);
grunt.registerTask('coverage', ['copy:zlib', 'mocha_istanbul:coverage']);
grunt.registerTask('saucelabs', ['default', 'copy:browsertest', 'connect', 'saucelabs-mocha']);
};

View File

@ -78,7 +78,9 @@ CleartextMessage.prototype.sign = function(privateKeys) {
signaturePacket.hashAlgorithm = config.prefer_hash_algorithm;
var signingKeyPacket = privateKeys[i].getSigningKeyPacket();
signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm;
if (!signingKeyPacket.isDecrypted) throw new Error('Private key is not decrypted.');
if (!signingKeyPacket.isDecrypted) {
throw new Error('Private key is not decrypted.');
}
signaturePacket.sign(signingKeyPacket, literalDataPacket);
packetlist.push(signaturePacket);
}
@ -167,11 +169,11 @@ function readArmored(armoredText) {
*/
function verifyHeaders(headers, packetlist) {
var checkHashAlgos = function(hashAlgos) {
function check(algo) {
return packetlist[i].hashAlgorithm === algo;
}
for (var i = 0; i < packetlist.length; i++) {
if (packetlist[i].tag === enums.packet.signature &&
!hashAlgos.some(function(algo) {
return packetlist[i].hashAlgorithm === algo;
})) {
if (packetlist[i].tag === enums.packet.signature && !hashAlgos.some(check)) {
return false;
}
}
@ -179,8 +181,8 @@ function verifyHeaders(headers, packetlist) {
};
var oneHeader = null;
var hashAlgos = [];
for (var i = 0; i < headers.length; i++) {
oneHeader = headers[i].match(/Hash: (.+)/); // get header value
headers.forEach(function(header) {
oneHeader = header.match(/Hash: (.+)/); // get header value
if (oneHeader) {
oneHeader = oneHeader[1].replace(/\s/g, ''); // remove whitespace
oneHeader = oneHeader.split(',');
@ -196,7 +198,7 @@ function verifyHeaders(headers, packetlist) {
} else {
throw new Error('Only "Hash" header allowed in cleartext signed message');
}
}
});
if (!hashAlgos.length && !checkHashAlgos([enums.hash.md5])) {
throw new Error('If no "Hash" header in cleartext signed message, then only MD5 signatures allowed');
} else if (!checkHashAlgos(hashAlgos)) {

View File

@ -301,19 +301,26 @@ module.exports = {
/** Asserts validity and converts from string/integer to integer. */
write: function(type, e) {
if (typeof e == 'number') {
if (typeof e === 'number') {
e = this.read(type, e);
}
if (type[e] !== undefined) {
return type[e];
} else throw new Error('Invalid enum value.');
} else {
throw new Error('Invalid enum value.');
}
},
/** Converts from an integer to string. */
read: function(type, e) {
for (var i in type)
if (type[i] == e) return i;
for (var i in type) {
if (type[i] === parseInt(e)) {
return i;
}
}
throw new Error('Invalid enum value.');
}
};

View File

@ -70,13 +70,17 @@ Key.prototype.packetlist2structure = function(packetlist) {
case enums.packet.userid:
case enums.packet.userAttribute:
user = new User(packetlist[i]);
if (!this.users) this.users = [];
if (!this.users) {
this.users = [];
}
this.users.push(user);
break;
case enums.packet.publicSubkey:
case enums.packet.secretSubkey:
user = null;
if (!this.subKeys) this.subKeys = [];
if (!this.subKeys) {
this.subKeys = [];
}
subKey = new SubKey(packetlist[i]);
this.subKeys.push(subKey);
break;
@ -91,24 +95,34 @@ Key.prototype.packetlist2structure = function(packetlist) {
continue;
}
if (packetlist[i].issuerKeyId.equals(primaryKeyId)) {
if (!user.selfCertifications) user.selfCertifications = [];
if (!user.selfCertifications) {
user.selfCertifications = [];
}
user.selfCertifications.push(packetlist[i]);
} else {
if (!user.otherCertifications) user.otherCertifications = [];
if (!user.otherCertifications) {
user.otherCertifications = [];
}
user.otherCertifications.push(packetlist[i]);
}
break;
case enums.signature.cert_revocation:
if (user) {
if (!user.revocationCertifications) user.revocationCertifications = [];
if (!user.revocationCertifications) {
user.revocationCertifications = [];
}
user.revocationCertifications.push(packetlist[i]);
} else {
if (!this.directSignatures) this.directSignatures = [];
if (!this.directSignatures) {
this.directSignatures = [];
}
this.directSignatures.push(packetlist[i]);
}
break;
case enums.signature.key:
if (!this.directSignatures) this.directSignatures = [];
if (!this.directSignatures) {
this.directSignatures = [];
}
this.directSignatures.push(packetlist[i]);
break;
case enums.signature.subkey_binding:
@ -228,7 +242,7 @@ Key.prototype.getUserIds = function() {
* @return {Boolean}
*/
Key.prototype.isPublic = function() {
return this.primaryKey.tag == enums.packet.publicKey;
return this.primaryKey.tag === enums.packet.publicKey;
};
/**
@ -236,7 +250,7 @@ Key.prototype.isPublic = function() {
* @return {Boolean}
*/
Key.prototype.isPrivate = function() {
return this.primaryKey.tag == enums.packet.secretKey;
return this.primaryKey.tag === enums.packet.secretKey;
};
/**
@ -321,9 +335,9 @@ function isValidEncryptionKeyPacket(keyPacket, signature) {
}
function isValidSigningKeyPacket(keyPacket, signature) {
return (keyPacket.algorithm == enums.read(enums.publicKey, enums.publicKey.dsa) ||
keyPacket.algorithm == enums.read(enums.publicKey, enums.publicKey.rsa_sign) ||
keyPacket.algorithm == enums.read(enums.publicKey, enums.publicKey.rsa_encrypt_sign)) &&
return (keyPacket.algorithm === enums.read(enums.publicKey, enums.publicKey.dsa) ||
keyPacket.algorithm === enums.read(enums.publicKey, enums.publicKey.rsa_sign) ||
keyPacket.algorithm === enums.read(enums.publicKey, enums.publicKey.rsa_encrypt_sign)) &&
(!signature.keyFlags ||
(signature.keyFlags[0] & enums.keyFlags.sign_data) !== 0);
}
@ -361,7 +375,9 @@ Key.prototype.decrypt = function(passphrase) {
var keys = this.getAllKeyPackets();
for (var i = 0; i < keys.length; i++) {
var success = keys[i].decrypt(passphrase);
if (!success) return false;
if (!success) {
return false;
}
}
} else {
throw new Error("Nothing to decrypt in a public key");
@ -383,7 +399,9 @@ Key.prototype.decryptKeyPacket = function(keyIds, passphrase) {
for (var j = 0; j < keyIds.length; j++) {
if (keyId.equals(keyIds[j])) {
var success = keys[i].decrypt(passphrase);
if (!success) return false;
if (!success) {
return false;
}
}
}
}
@ -406,7 +424,7 @@ Key.prototype.verifyPrimaryKey = function() {
return enums.keyStatus.revoked;
}
// check V3 expiration time
if (this.primaryKey.version == 3 && this.primaryKey.expirationTimeV3 !== 0 &&
if (this.primaryKey.version === 3 && this.primaryKey.expirationTimeV3 !== 0 &&
Date.now() > (this.primaryKey.created.getTime() + this.primaryKey.expirationTimeV3*24*3600*1000)) {
return enums.keyStatus.expired;
}
@ -427,7 +445,7 @@ Key.prototype.verifyPrimaryKey = function() {
return enums.keyStatus.invalid;
}
// check V4 expiration time
if (this.primaryKey.version == 4 && primaryUser.selfCertificate.keyNeverExpires === false &&
if (this.primaryKey.version === 4 && primaryUser.selfCertificate.keyNeverExpires === false &&
Date.now() > (this.primaryKey.created.getTime() + primaryUser.selfCertificate.keyExpirationTime*1000)) {
return enums.keyStatus.expired;
}
@ -439,10 +457,10 @@ Key.prototype.verifyPrimaryKey = function() {
* @return {Date|null}
*/
Key.prototype.getExpirationTime = function() {
if (this.primaryKey.version == 3) {
if (this.primaryKey.version === 3) {
return getExpirationTime(this.primaryKey);
}
if (this.primaryKey.version == 4) {
if (this.primaryKey.version === 4) {
var primaryUser = this.getPrimaryUser();
if (!primaryUser) {
return null;
@ -454,11 +472,11 @@ Key.prototype.getExpirationTime = function() {
function getExpirationTime(keyPacket, selfCertificate) {
// check V3 expiration time
if (keyPacket.version == 3 && keyPacket.expirationTimeV3 !== 0) {
if (keyPacket.version === 3 && keyPacket.expirationTimeV3 !== 0) {
return new Date(keyPacket.created.getTime() + keyPacket.expirationTimeV3*24*3600*1000);
}
// check V4 expiration time
if (keyPacket.version == 4 && selfCertificate.keyNeverExpires === false) {
if (keyPacket.version === 4 && selfCertificate.keyNeverExpires === false) {
return new Date(keyPacket.created.getTime() + selfCertificate.keyExpirationTime*1000);
}
return null;
@ -495,9 +513,9 @@ Key.prototype.getPrimaryUser = function() {
}
});
// return first valid
for (var i = 0; i < primUser.length; i++) {
if (primUser[i].user.isValidSelfCertificate(this.primaryKey, primUser[i].selfCertificate)) {
return primUser[i];
for (var k = 0; k < primUser.length; k++) {
if (primUser[k].user.isValidSelfCertificate(this.primaryKey, primUser[k].selfCertificate)) {
return primUser[k];
}
}
return null;
@ -612,8 +630,8 @@ function User(userPacket) {
if (!(this instanceof User)) {
return new User(userPacket);
}
this.userId = userPacket.tag == enums.packet.userid ? userPacket : null;
this.userAttribute = userPacket.tag == enums.packet.userAttribute ? userPacket : null;
this.userId = userPacket.tag === enums.packet.userid ? userPacket : null;
this.userAttribute = userPacket.tag === enums.packet.userAttribute ? userPacket : null;
this.selfCertifications = null;
this.otherCertifications = null;
this.revocationCertifications = null;
@ -642,11 +660,11 @@ User.prototype.isRevoked = function(certificate, primaryKey) {
if (this.revocationCertifications) {
var that = this;
return this.revocationCertifications.some(function(revCert) {
return revCert.issuerKeyId.equals(certificate.issuerKeyId) &&
!revCert.isExpired() &&
(revCert.verified ||
revCert.verify(primaryKey, {userid: that.userId || that.userAttribute, key: primaryKey}));
});
return revCert.issuerKeyId.equals(certificate.issuerKeyId) &&
!revCert.isExpired() &&
(revCert.verified ||
revCert.verify(primaryKey, {userid: that.userId || that.userAttribute, key: primaryKey}));
});
} else {
return false;
}
@ -773,7 +791,7 @@ SubKey.prototype.toPacketlist = function() {
* @return {Boolean}
*/
SubKey.prototype.isValidEncryptionKey = function(primaryKey) {
return this.verify(primaryKey) == enums.keyStatus.valid &&
return this.verify(primaryKey) === enums.keyStatus.valid &&
isValidEncryptionKeyPacket(this.subKey, this.bindingSignature);
};
@ -783,7 +801,7 @@ SubKey.prototype.isValidEncryptionKey = function(primaryKey) {
* @return {Boolean}
*/
SubKey.prototype.isValidSigningKey = function(primaryKey) {
return this.verify(primaryKey) == enums.keyStatus.valid &&
return this.verify(primaryKey) === enums.keyStatus.valid &&
isValidSigningKeyPacket(this.subKey, this.bindingSignature);
};
@ -800,7 +818,7 @@ SubKey.prototype.verify = function(primaryKey) {
return enums.keyStatus.revoked;
}
// check V3 expiration time
if (this.subKey.version == 3 && this.subKey.expirationTimeV3 !== 0 &&
if (this.subKey.version === 3 && this.subKey.expirationTimeV3 !== 0 &&
Date.now() > (this.subKey.created.getTime() + this.subKey.expirationTimeV3*24*3600*1000)) {
return enums.keyStatus.expired;
}
@ -816,7 +834,7 @@ SubKey.prototype.verify = function(primaryKey) {
return enums.keyStatus.invalid;
}
// check V4 expiration time
if (this.subKey.version == 4 &&
if (this.subKey.version === 4 &&
this.bindingSignature.keyNeverExpires === false &&
Date.now() > (this.subKey.created.getTime() + this.bindingSignature.keyExpirationTime*1000)) {
return enums.keyStatus.expired;
@ -874,7 +892,7 @@ function readArmored(armoredText) {
result.keys = [];
try {
var input = armor.decode(armoredText);
if (!(input.type == enums.armor.public_key || input.type == enums.armor.private_key)) {
if (!(input.type === enums.armor.public_key || input.type === enums.armor.private_key)) {
throw new Error('Armored text not of type key');
}
var packetlist = new packet.List();
@ -1026,8 +1044,8 @@ function generate(options) {
*/
function getPreferredSymAlgo(keys) {
var prioMap = {};
for (var i = 0; i < keys.length; i++) {
var primaryUser = keys[i].getPrimaryUser();
keys.forEach(function(key) {
var primaryUser = key.getPrimaryUser();
if (!primaryUser || !primaryUser.selfCertificate.preferredSymmetricAlgorithms) {
return config.encryption_cipher;
}
@ -1036,7 +1054,7 @@ function getPreferredSymAlgo(keys) {
entry.prio += 64 >> index;
entry.count++;
});
}
});
var prefAlgo = {prio: 0, algo: config.encryption_cipher};
for (var algo in prioMap) {
try {

View File

@ -87,7 +87,7 @@ Message.prototype.getSigningKeyIds = function() {
/**
* Decrypt the message
* @param {module:key~Key|String} privateKey private key with decrypted secret data, password or session key
* @param {String} sessionKeyAlgorithm if privateKey is a session key, this must be set to the session key algorithm (i.e. 'aes256').
* @param {String} sessionKeyAlgorithm if privateKey is a session key, this must be set to the session key algorithm (i.e. 'aes256').
* Do not set if privateKey is not a session key.
* @return {Array<module:message~Message>} new message with decrypted content
*/
@ -146,11 +146,13 @@ Message.prototype.decryptSessionKey = function(privateKey) {
return this;
}
var privateKeyPacket = privateKey.getKeyPacket(encryptionKeyIds);
if (!privateKeyPacket.isDecrypted) throw new Error('Private key is not decrypted.');
if (!privateKeyPacket.isDecrypted) {
throw new Error('Private key is not decrypted.');
}
var pkESKeyPacketlist = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey);
for (var i = 0; i < pkESKeyPacketlist.length; i++) {
if (pkESKeyPacketlist[i].publicKeyId.equals(privateKeyPacket.getKeyId())) {
keyPacket = pkESKeyPacketlist[i];
for (var j = 0; j < pkESKeyPacketlist.length; j++) {
if (pkESKeyPacketlist[j].publicKeyId.equals(privateKeyPacket.getKeyId())) {
keyPacket = pkESKeyPacketlist[j];
keyPacket.decrypt(privateKeyPacket);
break;
}
@ -244,10 +246,10 @@ function encryptSessionKey(sessionKey, symAlgo, keys, passwords) {
/** Convert to arrays if necessary */
if(keys && !Array.prototype.isPrototypeOf(keys)) {
keys = [keys]
keys = [keys];
}
if(passwords && !Array.prototype.isPrototypeOf(passwords)) {
passwords = [passwords]
passwords = [passwords];
}
var packetlist = new packet.List();
@ -278,7 +280,7 @@ function encryptSessionKey(sessionKey, symAlgo, keys, passwords) {
}
return new Message(packetlist);
};
}
/**
* Encrypt the message symmetrically using a passphrase.
@ -344,10 +346,12 @@ Message.prototype.sign = function(privateKeys) {
var packetlist = new packet.List();
var literalDataPacket = this.packets.findPacket(enums.packet.literal);
if (!literalDataPacket) throw new Error('No literal data packet to sign.');
if (!literalDataPacket) {
throw new Error('No literal data packet to sign.');
}
var literalFormat = enums.write(enums.literal, literalDataPacket.format);
var signatureType = literalFormat == enums.literal.binary ?
var signatureType = literalFormat === enums.literal.binary ?
enums.signature.binary : enums.signature.text;
var i, signingKeyPacket;
for (i = 0; i < privateKeys.length; i++) {
@ -374,7 +378,9 @@ Message.prototype.sign = function(privateKeys) {
signaturePacket.signatureType = signatureType;
signaturePacket.hashAlgorithm = config.prefer_hash_algorithm;
signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm;
if (!signingKeyPacket.isDecrypted) throw new Error('Private key is not decrypted.');
if (!signingKeyPacket.isDecrypted) {
throw new Error('Private key is not decrypted.');
}
signaturePacket.sign(signingKeyPacket, literalDataPacket);
packetlist.push(signaturePacket);
}
@ -391,7 +397,9 @@ Message.prototype.verify = function(keys) {
var result = [];
var msg = this.unwrapCompressed();
var literalDataList = msg.packets.filterByTag(enums.packet.literal);
if (literalDataList.length !== 1) throw new Error('Can only verify message with one literal data packet.');
if (literalDataList.length !== 1) {
throw new Error('Can only verify message with one literal data packet.');
}
var signatureList = msg.packets.filterByTag(enums.packet.signature);
for (var i = 0; i < signatureList.length; i++) {
var keyPacket = null;

View File

@ -37,6 +37,7 @@ var armor = require('./encoding/armor.js'),
enums = require('./enums.js'),
message = require('./message.js'),
cleartext = require('./cleartext.js'),
config = require('./config/config.js'),
key = require('./key.js'),
util = require('./util'),
AsyncProxy = require('./worker/async_proxy.js');
@ -55,7 +56,7 @@ var asyncProxy = null; // instance of the asyncproxy
function initWorker(path, options) {
if (options && options.worker || typeof window !== 'undefined' && window.Worker) {
options = options || {};
options.config = this.config;
options.config = config;
asyncProxy = new AsyncProxy(path, options);
return true;
} else {
@ -76,7 +77,7 @@ function getWorker() {
* @param {(Array<module:key~Key>|module:key~Key)} keys array of keys or single key, used to encrypt the message
* @param {String} data text/data message as native JavaScript string/binary string
* @param {(Array<String>|String)} passwords passwords for the message
* @param {Object} params parameter object with optional properties binary {Boolean},
* @param {Object} params parameter object with optional properties binary {Boolean},
* filename {String}, and packets {Boolean}
* @return {Promise<String> or Promise<Packetlist>} encrypted ASCII armored message, or Packetlist if params.packets is true
* @static
@ -87,14 +88,14 @@ function encryptMessage(keys, data, passwords, params) {
return asyncProxy.encryptMessage(keys, data, passwords, params);
}
var filename, binary, packets;
var filename, packets;
if(params) {
filename = params.filename;
packets = params.packets;
}
return execute(function() {
var msg, armored;
var msg;
if(data instanceof Uint8Array) {
msg = message.fromBinary(data, filename);
}
@ -110,7 +111,7 @@ function encryptMessage(keys, data, passwords, params) {
data: msg.packets.slice(dataIndex,msg.packets.length).write()
};
return obj;
}
}
else {
return armor.encode(enums.armor.message, msg.packets.write());
}