All files crx.js

100% Statements 80/80
100% Branches 22/22
100% Functions 17/17
100% Lines 80/80
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      1x 1x 1x 1x 1x 1x 1x 1x     18x 2x           16x   16x   16x   16x   16x   16x   16x         16x 56x     16x     1x                             4x 2x     2x 2x         2x 2x 2x   2x   2x   2x                     7x   7x   5x 5x   5x 5x   5x                         1x                                                       5x   5x 5x 1x     4x   4x                         2x                               4x   4x 4x 4x   4x 1x     3x                 3x 222x     3x 3x     3x                                         2x 2x 2x 2x   2x   2x   2x 2x 2x   2x 2x 2x   2x                           3x 3x 1x   2x           64x                       2x 1x     1x                     1x  
/* global require, process, Buffer, module */
'use strict';
 
var fs = require("fs");
var path = require("path");
var join = path.join;
var crypto = require("crypto");
var RSA = require("node-rsa");
var archiver = require("archiver");
var Promise = require("es6-promise").Promise;
var resolve = require("./resolver.js");
 
function ChromeExtension(attrs) {
  if ((this instanceof ChromeExtension) !== true) {
    return new ChromeExtension(attrs);
  }
 
  /*
   Defaults
   */
  this.appId = null;
 
  this.rootDirectory = '';
 
  this.publicKey = null;
 
  this.privateKey = null;
 
  this.codebase = null;
 
  this.path = null;
 
  this.src = '**';
 
  /*
  Copying attributes
   */
  for (var name in attrs) {
    this[name] = attrs[name];
  }
 
  this.loaded = false;
}
 
ChromeExtension.prototype = {
 
  /**
   * Packs the content of the extension in a crx file.
   *
   * @param {Buffer=} contentsBuffer
   * @returns {Promise}
   * @example
   *
   * crx.pack().then(function(crxContent){
   *  // do something with the crxContent binary data
   * });
   *
   */
  pack: function (contentsBuffer) {
    if (!this.loaded) {
      return this.load().then(this.pack.bind(this, contentsBuffer));
    }
 
    var selfie = this;
    var packP = [
      this.generatePublicKey(),
      contentsBuffer || selfie.loadContents()
    ];
 
    return Promise.all(packP).then(function(outputs){
      var publicKey = outputs[0];
      var contents = outputs[1];
 
      selfie.publicKey = publicKey;
 
      var signature = selfie.generateSignature(contents);
 
      return selfie.generatePackage(signature, publicKey, contents);
    });
  },
 
  /**
   * Loads extension manifest and copies its content to a workable path.
   *
   * @param {string=} path
   * @returns {Promise}
   */
  load: function (path) {
    var selfie = this;
 
    return resolve(path || selfie.rootDirectory)
      .then(function(metadata){
        selfie.path = metadata.path;
        selfie.src = metadata.src;
 
        selfie.manifest = require(join(selfie.path, "manifest.json"));
        selfie.loaded = true;
 
        return selfie;
      });
  },
 
  /**
   * Writes data into the extension workable directory.
   *
   * @deprecated
   * @param {string} path
   * @param {*} data
   * @returns {Promise}
   */
  writeFile: function (path, data) {
    var absPath = join(this.path, path);
 
    /* istanbul ignore next */
    return new Promise(function(resolve, reject){
      fs.writeFile(absPath, data, function (err) {
        if (err) {
          return reject(err);
        }
 
        resolve();
      });
    });
  },
 
  /**
   * Generates a public key.
   *
   * BC BREAK `this.publicKey` is not stored anymore (since 1.0.0)
   * BC BREAK callback parameter has been removed in favor to the promise interface.
   *
   * @returns {Promise} Resolves to {Buffer} containing the public key
   * @example
   *
   * crx.generatePublicKey(function(publicKey){
   *   // do something with publicKey
   * });
   */
  generatePublicKey: function () {
    var privateKey = this.privateKey;
 
    return new Promise(function(resolve, reject){
      if (!privateKey) {
        return reject('Impossible to generate a public key: privateKey option has not been defined or is empty.');
      }
 
      var key = new RSA(privateKey);
 
      resolve(key.exportKey('pkcs8-public-der'));
    });
  },
 
  /**
   * Generates a SHA1 package signature.
   *
   * BC BREAK `this.signature` is not stored anymore (since 1.0.0)
   *
   * @param {Buffer} contents
   * @returns {Buffer}
   */
  generateSignature: function (contents) {
    return new Buffer(
      crypto
        .createSign("sha1")
        .update(contents)
        .sign(this.privateKey),
      "binary"
    );
  },
 
  /**
   *
   * BC BREAK `this.contents` is not stored anymore (since 1.0.0)
   *
   * @returns {Promise}
   */
  loadContents: function () {
    var selfie = this;
 
    return new Promise(function(resolve, reject){
      var archive = archiver('zip');
      var contents = new Buffer('');
 
      if (!selfie.loaded) {
	      throw new Error('crx.load needs to be called first in order to prepare the workspace.');
      }
 
      archive.on('error', reject);
 
      /*
        TODO: Remove in v4.
        It will be better to resolve an archive object
        rather than fitting everything in memory.
 
        @see https://github.com/oncletom/crx/issues/61
      */
      archive.on('data', function (buf) {
        contents = Buffer.concat([contents, buf]);
      });
 
      archive.on('finish', function () {
        resolve(contents);
      });
 
      archive
        .glob(selfie.src, {
          cwd: selfie.path,
          matchBase: true,
          ignore: ['*.pem', '.git', '*.crx']
        })
        .finalize();
    });
  },
 
  /**
   * Generates and returns a signed package from extension content.
   *
   * BC BREAK `this.package` is not stored anymore (since 1.0.0)
   *
   * @param {Buffer} signature
   * @param {Buffer} publicKey
   * @param {Buffer} contents
   * @returns {Buffer}
   */
  generatePackage: function (signature, publicKey, contents) {
    var keyLength = publicKey.length;
    var sigLength = signature.length;
    var zipLength = contents.length;
    var length = 16 + keyLength + sigLength + zipLength;
 
    var crx = new Buffer(length);
 
    crx.write("Cr24" + new Array(13).join("\x00"), "binary");
 
    crx[4] = 2;
    crx.writeUInt32LE(keyLength, 8);
    crx.writeUInt32LE(sigLength, 12);
 
    publicKey.copy(crx, 16);
    signature.copy(crx, 16 + keyLength);
    contents.copy(crx, 16 + keyLength + sigLength);
 
    return crx;
  },
 
  /**
   * Generates an appId from the publicKey.
   * Public key has to be set for this to work, otherwise an error is thrown.
   *
   * BC BREAK `this.appId` is not stored anymore (since 1.0.0)
   * BC BREAK introduced `publicKey` parameter as it is not stored any more since 2.0.0
   *
   * @param {Buffer|string} [publicKey] the public key to use to generate the app ID
   * @returns {string}
   */
  generateAppId: function (publicKey) {
    publicKey = publicKey || this.publicKey;
    if (typeof publicKey !== 'string' && !(publicKey instanceof Buffer)) {
      throw new Error('Public key is neither set, nor given');
    }
    return crypto
      .createHash("sha256")
      .update(publicKey)
      .digest("hex")
      .slice(0, 32)
      .replace(/./g, function (x) {
        return (parseInt(x, 16) + 10).toString(26);
      });
  },
 
  /**
   * Generates an updateXML file from the extension content.
   *
   * BC BREAK `this.updateXML` is not stored anymore (since 1.0.0)
   *
   * @returns {Buffer}
   */
  generateUpdateXML: function () {
    if (!this.codebase) {
      throw new Error("No URL provided for update.xml.");
    }
 
    return new Buffer(
      "<?xml version='1.0' encoding='UTF-8'?>\n" +
      "<gupdate xmlns='http://www.google.com/update2/response' protocol='2.0'>\n" +
      "  <app appid='" + (this.appId || this.generateAppId()) + "'>\n" +
      "    <updatecheck codebase='" + this.codebase + "' version='" + this.manifest.version + "' />\n" +
      "  </app>\n" +
      "</gupdate>"
    );
  }
};
 
module.exports = ChromeExtension;