UNPKG

14.2 kBJavaScriptView Raw
1'use strict';
2
3var crypto = require('crypto');
4
5/**
6 * Exported function
7 *
8 * Options:
9 *
10 * - `algorithm` hash algo to be used by this instance: *'sha1', 'md5'
11 * - `excludeValues` {true|*false} hash object keys, values ignored
12 * - `encoding` hash encoding, supports 'buffer', '*hex', 'binary', 'base64'
13 * - `ignoreUnknown` {true|*false} ignore unknown object types
14 * - `replacer` optional function that replaces values before hashing
15 * - `respectFunctionProperties` {*true|false} consider function properties when hashing
16 * - `respectFunctionNames` {*true|false} consider 'name' property of functions for hashing
17 * - `respectType` {*true|false} Respect special properties (prototype, constructor)
18 * when hashing to distinguish between types
19 * - `unorderedArrays` {true|*false} Sort all arrays before hashing
20 * - `unorderedSets` {*true|false} Sort `Set` and `Map` instances before hashing
21 * * = default
22 *
23 * @param {object} object value to hash
24 * @param {object} options hashing options
25 * @return {string} hash value
26 * @api public
27 */
28exports = module.exports = objectHash;
29
30function objectHash(object, options){
31 options = applyDefaults(object, options);
32
33 return hash(object, options);
34}
35
36/**
37 * Exported sugar methods
38 *
39 * @param {object} object value to hash
40 * @return {string} hash value
41 * @api public
42 */
43exports.sha1 = function(object){
44 return objectHash(object);
45};
46exports.keys = function(object){
47 return objectHash(object, {excludeValues: true, algorithm: 'sha1', encoding: 'hex'});
48};
49exports.MD5 = function(object){
50 return objectHash(object, {algorithm: 'md5', encoding: 'hex'});
51};
52exports.keysMD5 = function(object){
53 return objectHash(object, {algorithm: 'md5', encoding: 'hex', excludeValues: true});
54};
55
56// Internals
57var hashes = crypto.getHashes ? crypto.getHashes().slice() : ['sha1', 'md5'];
58hashes.push('passthrough');
59var encodings = ['buffer', 'hex', 'binary', 'base64'];
60
61function applyDefaults(object, options){
62 options = options || {};
63 options.algorithm = options.algorithm || 'sha1';
64 options.encoding = options.encoding || 'hex';
65 options.excludeValues = options.excludeValues ? true : false;
66 options.algorithm = options.algorithm.toLowerCase();
67 options.encoding = options.encoding.toLowerCase();
68 options.ignoreUnknown = options.ignoreUnknown !== true ? false : true; // default to false
69 options.respectType = options.respectType === false ? false : true; // default to true
70 options.respectFunctionNames = options.respectFunctionNames === false ? false : true;
71 options.respectFunctionProperties = options.respectFunctionProperties === false ? false : true;
72 options.unorderedArrays = options.unorderedArrays !== true ? false : true; // default to false
73 options.unorderedSets = options.unorderedSets === false ? false : true; // default to false
74 options.replacer = options.replacer || undefined;
75
76 if(typeof object === 'undefined') {
77 throw new Error('Object argument required.');
78 }
79
80 // if there is a case-insensitive match in the hashes list, accept it
81 // (i.e. SHA256 for sha256)
82 for (var i = 0; i < hashes.length; ++i) {
83 if (hashes[i].toLowerCase() === options.algorithm.toLowerCase()) {
84 options.algorithm = hashes[i];
85 }
86 }
87
88 if(hashes.indexOf(options.algorithm) === -1){
89 throw new Error('Algorithm "' + options.algorithm + '" not supported. ' +
90 'supported values: ' + hashes.join(', '));
91 }
92
93 if(encodings.indexOf(options.encoding) === -1 &&
94 options.algorithm !== 'passthrough'){
95 throw new Error('Encoding "' + options.encoding + '" not supported. ' +
96 'supported values: ' + encodings.join(', '));
97 }
98
99 return options;
100}
101
102/** Check if the given function is a native function */
103function isNativeFunction(f) {
104 if ((typeof f) !== 'function') {
105 return false;
106 }
107 var exp = /^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i;
108 return exp.exec(Function.prototype.toString.call(f)) != null;
109}
110
111function hash(object, options) {
112 var hashingStream;
113
114 if (options.algorithm !== 'passthrough') {
115 hashingStream = crypto.createHash(options.algorithm);
116 } else {
117 hashingStream = new PassThrough();
118 }
119
120 if (typeof hashingStream.write === 'undefined') {
121 hashingStream.write = hashingStream.update;
122 hashingStream.end = hashingStream.update;
123 }
124
125 var hasher = typeHasher(options, hashingStream);
126 hasher.dispatch(object);
127 if (!hashingStream.update)
128 hashingStream.end('')
129
130 if (hashingStream.digest) {
131 return hashingStream.digest(options.encoding === 'buffer' ? undefined : options.encoding);
132 }
133
134 var buf = hashingStream.read();
135 if (options.encoding === 'buffer') {
136 return buf;
137 }
138
139 return buf.toString(options.encoding);
140}
141
142/**
143 * Expose streaming API
144 *
145 * @param {object} object Value to serialize
146 * @param {object} options Options, as for hash()
147 * @param {object} stream A stream to write the serializiation to
148 * @api public
149 */
150exports.writeToStream = function(object, options, stream) {
151 if (typeof stream === 'undefined') {
152 stream = options;
153 options = {};
154 }
155
156 options = applyDefaults(object, options);
157
158 return typeHasher(options, stream).dispatch(object);
159};
160
161function typeHasher(options, writeTo, context){
162 context = context || [];
163 var write = function(str) {
164 if (writeTo.update)
165 return writeTo.update(str, 'utf8');
166 else
167 return writeTo.write(str, 'utf8');
168 }
169
170 return {
171 dispatch: function(value){
172 if (options.replacer) {
173 value = options.replacer(value);
174 }
175
176 var type = typeof value;
177 if (value === null) {
178 type = 'null';
179 }
180
181 //console.log("[DEBUG] Dispatch: ", value, "->", type, " -> ", "_" + type);
182
183 return this['_' + type](value);
184 },
185 _object: function(object) {
186 var pattern = (/\[object (.*)\]/i);
187 var objString = Object.prototype.toString.call(object);
188 var objType = pattern.exec(objString);
189 if (!objType) { // object type did not match [object ...]
190 objType = 'unknown:[' + objString + ']';
191 } else {
192 objType = objType[1]; // take only the class name
193 }
194
195 objType = objType.toLowerCase();
196
197 var objectNumber = null;
198
199 if ((objectNumber = context.indexOf(object)) >= 0) {
200 return this.dispatch('[CIRCULAR:' + objectNumber + ']');
201 } else {
202 context.push(object);
203 }
204
205 if (typeof Buffer !== 'undefined' && Buffer.isBuffer && Buffer.isBuffer(object)) {
206 write('buffer:');
207 return write(object);
208 }
209
210 if(objType !== 'object' && objType !== 'function') {
211 if(this['_' + objType]) {
212 this['_' + objType](object);
213 } else if (options.ignoreUnknown) {
214 return write('[' + objType + ']');
215 } else {
216 throw new Error('Unknown object type "' + objType + '"');
217 }
218 }else{
219 var keys = Object.keys(object).sort();
220 // Make sure to incorporate special properties, so
221 // Types with different prototypes will produce
222 // a different hash and objects derived from
223 // different functions (`new Foo`, `new Bar`) will
224 // produce different hashes.
225 // We never do this for native functions since some
226 // seem to break because of that.
227 if (options.respectType !== false && !isNativeFunction(object)) {
228 keys.splice(0, 0, 'prototype', '__proto__', 'constructor');
229 }
230
231 write('object:' + keys.length + ':');
232 var self = this;
233 return keys.forEach(function(key){
234 self.dispatch(key);
235 write(':');
236 if(!options.excludeValues) {
237 self.dispatch(object[key]);
238 }
239 write(',');
240 });
241 }
242 },
243 _array: function(arr, unordered){
244 unordered = typeof unordered !== 'undefined' ? unordered :
245 options.unorderedArrays !== false; // default to options.unorderedArrays
246
247 var self = this;
248 write('array:' + arr.length + ':');
249 if (!unordered || arr.length <= 1) {
250 return arr.forEach(function(entry) {
251 return self.dispatch(entry);
252 });
253 }
254
255 // the unordered case is a little more complicated:
256 // since there is no canonical ordering on objects,
257 // i.e. {a:1} < {a:2} and {a:1} > {a:2} are both false,
258 // we first serialize each entry using a PassThrough stream
259 // before sorting.
260 // also: we can’t use the same context array for all entries
261 // since the order of hashing should *not* matter. instead,
262 // we keep track of the additions to a copy of the context array
263 // and add all of them to the global context array when we’re done
264 var contextAdditions = [];
265 var entries = arr.map(function(entry) {
266 var strm = new PassThrough();
267 var localContext = context.slice(); // make copy
268 var hasher = typeHasher(options, strm, localContext);
269 hasher.dispatch(entry);
270 // take only what was added to localContext and append it to contextAdditions
271 contextAdditions = contextAdditions.concat(localContext.slice(context.length));
272 return strm.read().toString();
273 });
274 context = context.concat(contextAdditions);
275 entries.sort();
276 return this._array(entries, false);
277 },
278 _date: function(date){
279 return write('date:' + date.toJSON());
280 },
281 _symbol: function(sym){
282 return write('symbol:' + sym.toString());
283 },
284 _error: function(err){
285 return write('error:' + err.toString());
286 },
287 _boolean: function(bool){
288 return write('bool:' + bool.toString());
289 },
290 _string: function(string){
291 write('string:' + string.length + ':');
292 write(string);
293 },
294 _function: function(fn){
295 write('fn:');
296 if (isNativeFunction(fn)) {
297 this.dispatch('[native]');
298 } else {
299 this.dispatch(fn.toString());
300 }
301
302 if (options.respectFunctionNames !== false) {
303 // Make sure we can still distinguish native functions
304 // by their name, otherwise String and Function will
305 // have the same hash
306 this.dispatch("function-name:" + String(fn.name));
307 }
308
309 if (options.respectFunctionProperties) {
310 this._object(fn);
311 }
312 },
313 _number: function(number){
314 return write('number:' + number.toString());
315 },
316 _xml: function(xml){
317 return write('xml:' + xml.toString());
318 },
319 _null: function() {
320 return write('Null');
321 },
322 _undefined: function() {
323 return write('Undefined');
324 },
325 _regexp: function(regex){
326 return write('regex:' + regex.toString());
327 },
328 _uint8array: function(arr){
329 write('uint8array:');
330 return this.dispatch(Array.prototype.slice.call(arr));
331 },
332 _uint8clampedarray: function(arr){
333 write('uint8clampedarray:');
334 return this.dispatch(Array.prototype.slice.call(arr));
335 },
336 _int8array: function(arr){
337 write('uint8array:');
338 return this.dispatch(Array.prototype.slice.call(arr));
339 },
340 _uint16array: function(arr){
341 write('uint16array:');
342 return this.dispatch(Array.prototype.slice.call(arr));
343 },
344 _int16array: function(arr){
345 write('uint16array:');
346 return this.dispatch(Array.prototype.slice.call(arr));
347 },
348 _uint32array: function(arr){
349 write('uint32array:');
350 return this.dispatch(Array.prototype.slice.call(arr));
351 },
352 _int32array: function(arr){
353 write('uint32array:');
354 return this.dispatch(Array.prototype.slice.call(arr));
355 },
356 _float32array: function(arr){
357 write('float32array:');
358 return this.dispatch(Array.prototype.slice.call(arr));
359 },
360 _float64array: function(arr){
361 write('float64array:');
362 return this.dispatch(Array.prototype.slice.call(arr));
363 },
364 _arraybuffer: function(arr){
365 write('arraybuffer:');
366 return this.dispatch(new Uint8Array(arr));
367 },
368 _url: function(url) {
369 return write('url:' + url.toString(), 'utf8');
370 },
371 _map: function(map) {
372 write('map:');
373 var arr = Array.from(map);
374 return this._array(arr, options.unorderedSets !== false);
375 },
376 _set: function(set) {
377 write('set:');
378 var arr = Array.from(set);
379 return this._array(arr, options.unorderedSets !== false);
380 },
381 _blob: function() {
382 if (options.ignoreUnknown) {
383 return write('[blob]');
384 }
385
386 throw Error('Hashing Blob objects is currently not supported\n' +
387 '(see https://github.com/puleos/object-hash/issues/26)\n' +
388 'Use "options.replacer" or "options.ignoreUnknown"\n');
389 },
390 _domwindow: function() { return write('domwindow'); },
391 /* Node.js standard native objects */
392 _process: function() { return write('process'); },
393 _timer: function() { return write('timer'); },
394 _pipe: function() { return write('pipe'); },
395 _tcp: function() { return write('tcp'); },
396 _udp: function() { return write('udp'); },
397 _tty: function() { return write('tty'); },
398 _statwatcher: function() { return write('statwatcher'); },
399 _securecontext: function() { return write('securecontext'); },
400 _connection: function() { return write('connection'); },
401 _zlib: function() { return write('zlib'); },
402 _context: function() { return write('context'); },
403 _nodescript: function() { return write('nodescript'); },
404 _httpparser: function() { return write('httpparser'); },
405 _dataview: function() { return write('dataview'); },
406 _signal: function() { return write('signal'); },
407 _fsevent: function() { return write('fsevent'); },
408 _tlswrap: function() { return write('tlswrap'); }
409 };
410}
411
412// Mini-implementation of stream.PassThrough
413// We are far from having need for the full implementation, and we can
414// make assumtions like "many writes, then only one final read"
415// and we can ignore encoding specifics
416function PassThrough() {
417 return {
418 buf: '',
419
420 write: function(b) {
421 this.buf += b;
422 },
423
424 end: function(b) {
425 this.buf += b;
426 },
427
428 read: function() {
429 return this.buf;
430 }
431 };
432}