@sockethub/crypto 1.0.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
package/dist/index.js ADDED
@@ -0,0 +1,466 @@
1
+ import { createRequire } from "node:module";
2
+ var __create = Object.create;
3
+ var __getProtoOf = Object.getPrototypeOf;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __toESM = (mod, isNodeMode, target) => {
8
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
9
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
10
+ for (let key of __getOwnPropNames(mod))
11
+ if (!__hasOwnProp.call(to, key))
12
+ __defProp(to, key, {
13
+ get: () => mod[key],
14
+ enumerable: true
15
+ });
16
+ return to;
17
+ };
18
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
19
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
20
+
21
+ // ../../node_modules/object-hash/index.js
22
+ var require_object_hash = __commonJS((exports, module) => {
23
+ var crypto = __require("crypto");
24
+ exports = module.exports = objectHash;
25
+ function objectHash(object, options) {
26
+ options = applyDefaults(object, options);
27
+ return hash(object, options);
28
+ }
29
+ exports.sha1 = function(object) {
30
+ return objectHash(object);
31
+ };
32
+ exports.keys = function(object) {
33
+ return objectHash(object, { excludeValues: true, algorithm: "sha1", encoding: "hex" });
34
+ };
35
+ exports.MD5 = function(object) {
36
+ return objectHash(object, { algorithm: "md5", encoding: "hex" });
37
+ };
38
+ exports.keysMD5 = function(object) {
39
+ return objectHash(object, { algorithm: "md5", encoding: "hex", excludeValues: true });
40
+ };
41
+ var hashes = crypto.getHashes ? crypto.getHashes().slice() : ["sha1", "md5"];
42
+ hashes.push("passthrough");
43
+ var encodings = ["buffer", "hex", "binary", "base64"];
44
+ function applyDefaults(object, sourceOptions) {
45
+ sourceOptions = sourceOptions || {};
46
+ var options = {};
47
+ options.algorithm = sourceOptions.algorithm || "sha1";
48
+ options.encoding = sourceOptions.encoding || "hex";
49
+ options.excludeValues = sourceOptions.excludeValues ? true : false;
50
+ options.algorithm = options.algorithm.toLowerCase();
51
+ options.encoding = options.encoding.toLowerCase();
52
+ options.ignoreUnknown = sourceOptions.ignoreUnknown !== true ? false : true;
53
+ options.respectType = sourceOptions.respectType === false ? false : true;
54
+ options.respectFunctionNames = sourceOptions.respectFunctionNames === false ? false : true;
55
+ options.respectFunctionProperties = sourceOptions.respectFunctionProperties === false ? false : true;
56
+ options.unorderedArrays = sourceOptions.unorderedArrays !== true ? false : true;
57
+ options.unorderedSets = sourceOptions.unorderedSets === false ? false : true;
58
+ options.unorderedObjects = sourceOptions.unorderedObjects === false ? false : true;
59
+ options.replacer = sourceOptions.replacer || undefined;
60
+ options.excludeKeys = sourceOptions.excludeKeys || undefined;
61
+ if (typeof object === "undefined") {
62
+ throw new Error("Object argument required.");
63
+ }
64
+ for (var i = 0;i < hashes.length; ++i) {
65
+ if (hashes[i].toLowerCase() === options.algorithm.toLowerCase()) {
66
+ options.algorithm = hashes[i];
67
+ }
68
+ }
69
+ if (hashes.indexOf(options.algorithm) === -1) {
70
+ throw new Error('Algorithm "' + options.algorithm + '" not supported. ' + "supported values: " + hashes.join(", "));
71
+ }
72
+ if (encodings.indexOf(options.encoding) === -1 && options.algorithm !== "passthrough") {
73
+ throw new Error('Encoding "' + options.encoding + '" not supported. ' + "supported values: " + encodings.join(", "));
74
+ }
75
+ return options;
76
+ }
77
+ function isNativeFunction(f) {
78
+ if (typeof f !== "function") {
79
+ return false;
80
+ }
81
+ var exp = /^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i;
82
+ return exp.exec(Function.prototype.toString.call(f)) != null;
83
+ }
84
+ function hash(object, options) {
85
+ var hashingStream;
86
+ if (options.algorithm !== "passthrough") {
87
+ hashingStream = crypto.createHash(options.algorithm);
88
+ } else {
89
+ hashingStream = new PassThrough;
90
+ }
91
+ if (typeof hashingStream.write === "undefined") {
92
+ hashingStream.write = hashingStream.update;
93
+ hashingStream.end = hashingStream.update;
94
+ }
95
+ var hasher = typeHasher(options, hashingStream);
96
+ hasher.dispatch(object);
97
+ if (!hashingStream.update) {
98
+ hashingStream.end("");
99
+ }
100
+ if (hashingStream.digest) {
101
+ return hashingStream.digest(options.encoding === "buffer" ? undefined : options.encoding);
102
+ }
103
+ var buf = hashingStream.read();
104
+ if (options.encoding === "buffer") {
105
+ return buf;
106
+ }
107
+ return buf.toString(options.encoding);
108
+ }
109
+ exports.writeToStream = function(object, options, stream) {
110
+ if (typeof stream === "undefined") {
111
+ stream = options;
112
+ options = {};
113
+ }
114
+ options = applyDefaults(object, options);
115
+ return typeHasher(options, stream).dispatch(object);
116
+ };
117
+ function typeHasher(options, writeTo, context) {
118
+ context = context || [];
119
+ var write = function(str) {
120
+ if (writeTo.update) {
121
+ return writeTo.update(str, "utf8");
122
+ } else {
123
+ return writeTo.write(str, "utf8");
124
+ }
125
+ };
126
+ return {
127
+ dispatch: function(value) {
128
+ if (options.replacer) {
129
+ value = options.replacer(value);
130
+ }
131
+ var type = typeof value;
132
+ if (value === null) {
133
+ type = "null";
134
+ }
135
+ return this["_" + type](value);
136
+ },
137
+ _object: function(object) {
138
+ var pattern = /\[object (.*)\]/i;
139
+ var objString = Object.prototype.toString.call(object);
140
+ var objType = pattern.exec(objString);
141
+ if (!objType) {
142
+ objType = "unknown:[" + objString + "]";
143
+ } else {
144
+ objType = objType[1];
145
+ }
146
+ objType = objType.toLowerCase();
147
+ var objectNumber = null;
148
+ if ((objectNumber = context.indexOf(object)) >= 0) {
149
+ return this.dispatch("[CIRCULAR:" + objectNumber + "]");
150
+ } else {
151
+ context.push(object);
152
+ }
153
+ if (typeof Buffer !== "undefined" && Buffer.isBuffer && Buffer.isBuffer(object)) {
154
+ write("buffer:");
155
+ return write(object);
156
+ }
157
+ if (objType !== "object" && objType !== "function" && objType !== "asyncfunction") {
158
+ if (this["_" + objType]) {
159
+ this["_" + objType](object);
160
+ } else if (options.ignoreUnknown) {
161
+ return write("[" + objType + "]");
162
+ } else {
163
+ throw new Error('Unknown object type "' + objType + '"');
164
+ }
165
+ } else {
166
+ var keys = Object.keys(object);
167
+ if (options.unorderedObjects) {
168
+ keys = keys.sort();
169
+ }
170
+ if (options.respectType !== false && !isNativeFunction(object)) {
171
+ keys.splice(0, 0, "prototype", "__proto__", "constructor");
172
+ }
173
+ if (options.excludeKeys) {
174
+ keys = keys.filter(function(key) {
175
+ return !options.excludeKeys(key);
176
+ });
177
+ }
178
+ write("object:" + keys.length + ":");
179
+ var self = this;
180
+ return keys.forEach(function(key) {
181
+ self.dispatch(key);
182
+ write(":");
183
+ if (!options.excludeValues) {
184
+ self.dispatch(object[key]);
185
+ }
186
+ write(",");
187
+ });
188
+ }
189
+ },
190
+ _array: function(arr, unordered) {
191
+ unordered = typeof unordered !== "undefined" ? unordered : options.unorderedArrays !== false;
192
+ var self = this;
193
+ write("array:" + arr.length + ":");
194
+ if (!unordered || arr.length <= 1) {
195
+ return arr.forEach(function(entry) {
196
+ return self.dispatch(entry);
197
+ });
198
+ }
199
+ var contextAdditions = [];
200
+ var entries = arr.map(function(entry) {
201
+ var strm = new PassThrough;
202
+ var localContext = context.slice();
203
+ var hasher = typeHasher(options, strm, localContext);
204
+ hasher.dispatch(entry);
205
+ contextAdditions = contextAdditions.concat(localContext.slice(context.length));
206
+ return strm.read().toString();
207
+ });
208
+ context = context.concat(contextAdditions);
209
+ entries.sort();
210
+ return this._array(entries, false);
211
+ },
212
+ _date: function(date) {
213
+ return write("date:" + date.toJSON());
214
+ },
215
+ _symbol: function(sym) {
216
+ return write("symbol:" + sym.toString());
217
+ },
218
+ _error: function(err) {
219
+ return write("error:" + err.toString());
220
+ },
221
+ _boolean: function(bool) {
222
+ return write("bool:" + bool.toString());
223
+ },
224
+ _string: function(string) {
225
+ write("string:" + string.length + ":");
226
+ write(string.toString());
227
+ },
228
+ _function: function(fn) {
229
+ write("fn:");
230
+ if (isNativeFunction(fn)) {
231
+ this.dispatch("[native]");
232
+ } else {
233
+ this.dispatch(fn.toString());
234
+ }
235
+ if (options.respectFunctionNames !== false) {
236
+ this.dispatch("function-name:" + String(fn.name));
237
+ }
238
+ if (options.respectFunctionProperties) {
239
+ this._object(fn);
240
+ }
241
+ },
242
+ _number: function(number) {
243
+ return write("number:" + number.toString());
244
+ },
245
+ _xml: function(xml) {
246
+ return write("xml:" + xml.toString());
247
+ },
248
+ _null: function() {
249
+ return write("Null");
250
+ },
251
+ _undefined: function() {
252
+ return write("Undefined");
253
+ },
254
+ _regexp: function(regex) {
255
+ return write("regex:" + regex.toString());
256
+ },
257
+ _uint8array: function(arr) {
258
+ write("uint8array:");
259
+ return this.dispatch(Array.prototype.slice.call(arr));
260
+ },
261
+ _uint8clampedarray: function(arr) {
262
+ write("uint8clampedarray:");
263
+ return this.dispatch(Array.prototype.slice.call(arr));
264
+ },
265
+ _int8array: function(arr) {
266
+ write("int8array:");
267
+ return this.dispatch(Array.prototype.slice.call(arr));
268
+ },
269
+ _uint16array: function(arr) {
270
+ write("uint16array:");
271
+ return this.dispatch(Array.prototype.slice.call(arr));
272
+ },
273
+ _int16array: function(arr) {
274
+ write("int16array:");
275
+ return this.dispatch(Array.prototype.slice.call(arr));
276
+ },
277
+ _uint32array: function(arr) {
278
+ write("uint32array:");
279
+ return this.dispatch(Array.prototype.slice.call(arr));
280
+ },
281
+ _int32array: function(arr) {
282
+ write("int32array:");
283
+ return this.dispatch(Array.prototype.slice.call(arr));
284
+ },
285
+ _float32array: function(arr) {
286
+ write("float32array:");
287
+ return this.dispatch(Array.prototype.slice.call(arr));
288
+ },
289
+ _float64array: function(arr) {
290
+ write("float64array:");
291
+ return this.dispatch(Array.prototype.slice.call(arr));
292
+ },
293
+ _arraybuffer: function(arr) {
294
+ write("arraybuffer:");
295
+ return this.dispatch(new Uint8Array(arr));
296
+ },
297
+ _url: function(url) {
298
+ return write("url:" + url.toString(), "utf8");
299
+ },
300
+ _map: function(map) {
301
+ write("map:");
302
+ var arr = Array.from(map);
303
+ return this._array(arr, options.unorderedSets !== false);
304
+ },
305
+ _set: function(set) {
306
+ write("set:");
307
+ var arr = Array.from(set);
308
+ return this._array(arr, options.unorderedSets !== false);
309
+ },
310
+ _file: function(file) {
311
+ write("file:");
312
+ return this.dispatch([file.name, file.size, file.type, file.lastModfied]);
313
+ },
314
+ _blob: function() {
315
+ if (options.ignoreUnknown) {
316
+ return write("[blob]");
317
+ }
318
+ throw Error(`Hashing Blob objects is currently not supported
319
+ ` + `(see https://github.com/puleos/object-hash/issues/26)
320
+ ` + `Use "options.replacer" or "options.ignoreUnknown"
321
+ `);
322
+ },
323
+ _domwindow: function() {
324
+ return write("domwindow");
325
+ },
326
+ _bigint: function(number) {
327
+ return write("bigint:" + number.toString());
328
+ },
329
+ _process: function() {
330
+ return write("process");
331
+ },
332
+ _timer: function() {
333
+ return write("timer");
334
+ },
335
+ _pipe: function() {
336
+ return write("pipe");
337
+ },
338
+ _tcp: function() {
339
+ return write("tcp");
340
+ },
341
+ _udp: function() {
342
+ return write("udp");
343
+ },
344
+ _tty: function() {
345
+ return write("tty");
346
+ },
347
+ _statwatcher: function() {
348
+ return write("statwatcher");
349
+ },
350
+ _securecontext: function() {
351
+ return write("securecontext");
352
+ },
353
+ _connection: function() {
354
+ return write("connection");
355
+ },
356
+ _zlib: function() {
357
+ return write("zlib");
358
+ },
359
+ _context: function() {
360
+ return write("context");
361
+ },
362
+ _nodescript: function() {
363
+ return write("nodescript");
364
+ },
365
+ _httpparser: function() {
366
+ return write("httpparser");
367
+ },
368
+ _dataview: function() {
369
+ return write("dataview");
370
+ },
371
+ _signal: function() {
372
+ return write("signal");
373
+ },
374
+ _fsevent: function() {
375
+ return write("fsevent");
376
+ },
377
+ _tlswrap: function() {
378
+ return write("tlswrap");
379
+ }
380
+ };
381
+ }
382
+ function PassThrough() {
383
+ return {
384
+ buf: "",
385
+ write: function(b) {
386
+ this.buf += b;
387
+ },
388
+ end: function(b) {
389
+ this.buf += b;
390
+ },
391
+ read: function() {
392
+ return this.buf;
393
+ }
394
+ };
395
+ }
396
+ });
397
+
398
+ // src/index.ts
399
+ var import_object_hash = __toESM(require_object_hash(), 1);
400
+ import {
401
+ createCipheriv,
402
+ createDecipheriv,
403
+ createHash,
404
+ randomBytes
405
+ } from "node:crypto";
406
+ var ALGORITHM = "aes-256-cbc";
407
+ var IV_LENGTH = 16;
408
+ function getPlatformId(platform, actor, _crypto = crypto) {
409
+ return actor ? _crypto.hash(platform + actor) : _crypto.hash(platform);
410
+ }
411
+
412
+ class Crypto {
413
+ randomBytes;
414
+ constructor() {
415
+ this.createRandomBytes();
416
+ }
417
+ createRandomBytes() {
418
+ this.randomBytes = randomBytes;
419
+ }
420
+ encrypt(json, secret) {
421
+ Crypto.ensureSecret(secret);
422
+ const iv = this.randomBytes(IV_LENGTH);
423
+ const cipher = createCipheriv(ALGORITHM, Buffer.from(secret), iv);
424
+ let encrypted = cipher.update(JSON.stringify(json));
425
+ encrypted = Buffer.concat([encrypted, cipher.final()]);
426
+ return `${iv.toString("hex")}:${encrypted.toString("hex")}`;
427
+ }
428
+ decrypt(text, secret) {
429
+ Crypto.ensureSecret(secret);
430
+ const parts = text.split(":");
431
+ const iv = Buffer.from(parts.shift(), "hex");
432
+ const encryptedText = Buffer.from(parts.join(":"), "hex");
433
+ const decipher = createDecipheriv(ALGORITHM, Buffer.from(secret), iv);
434
+ let decrypted = decipher.update(encryptedText);
435
+ decrypted = Buffer.concat([decrypted, decipher.final()]);
436
+ return JSON.parse(decrypted.toString());
437
+ }
438
+ hash(text) {
439
+ const SHASum = createHash("sha1");
440
+ SHASum.update(text);
441
+ return SHASum.digest("hex").substring(0, 7);
442
+ }
443
+ objectHash(object) {
444
+ return import_object_hash.default(object);
445
+ }
446
+ randToken(len) {
447
+ if (len > 32) {
448
+ throw new Error(`crypto.randToken supports a length param of up to 32, ${len} given`);
449
+ }
450
+ const buf = this.randomBytes(len);
451
+ return buf.toString("hex").substring(0, len);
452
+ }
453
+ static ensureSecret(secret) {
454
+ if (secret.length !== 32) {
455
+ throw new Error(`secret must be a 32 char string, length: ${secret.length}`);
456
+ }
457
+ }
458
+ }
459
+ var crypto = new Crypto;
460
+ export {
461
+ getPlatformId,
462
+ crypto,
463
+ Crypto
464
+ };
465
+
466
+ //# debugId=2BD4490536E49C1E64756E2164756E21
@@ -0,0 +1,11 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../node_modules/object-hash/index.js", "../src/index.ts"],
4
+ "sourcesContent": [
5
+ "'use strict';\n\nvar crypto = require('crypto');\n\n/**\n * Exported function\n *\n * Options:\n *\n * - `algorithm` hash algo to be used by this instance: *'sha1', 'md5'\n * - `excludeValues` {true|*false} hash object keys, values ignored\n * - `encoding` hash encoding, supports 'buffer', '*hex', 'binary', 'base64'\n * - `ignoreUnknown` {true|*false} ignore unknown object types\n * - `replacer` optional function that replaces values before hashing\n * - `respectFunctionProperties` {*true|false} consider function properties when hashing\n * - `respectFunctionNames` {*true|false} consider 'name' property of functions for hashing\n * - `respectType` {*true|false} Respect special properties (prototype, constructor)\n * when hashing to distinguish between types\n * - `unorderedArrays` {true|*false} Sort all arrays before hashing\n * - `unorderedSets` {*true|false} Sort `Set` and `Map` instances before hashing\n * * = default\n *\n * @param {object} object value to hash\n * @param {object} options hashing options\n * @return {string} hash value\n * @api public\n */\nexports = module.exports = objectHash;\n\nfunction objectHash(object, options){\n options = applyDefaults(object, options);\n\n return hash(object, options);\n}\n\n/**\n * Exported sugar methods\n *\n * @param {object} object value to hash\n * @return {string} hash value\n * @api public\n */\nexports.sha1 = function(object){\n return objectHash(object);\n};\nexports.keys = function(object){\n return objectHash(object, {excludeValues: true, algorithm: 'sha1', encoding: 'hex'});\n};\nexports.MD5 = function(object){\n return objectHash(object, {algorithm: 'md5', encoding: 'hex'});\n};\nexports.keysMD5 = function(object){\n return objectHash(object, {algorithm: 'md5', encoding: 'hex', excludeValues: true});\n};\n\n// Internals\nvar hashes = crypto.getHashes ? crypto.getHashes().slice() : ['sha1', 'md5'];\nhashes.push('passthrough');\nvar encodings = ['buffer', 'hex', 'binary', 'base64'];\n\nfunction applyDefaults(object, sourceOptions){\n sourceOptions = sourceOptions || {};\n\n // create a copy rather than mutating\n var options = {};\n options.algorithm = sourceOptions.algorithm || 'sha1';\n options.encoding = sourceOptions.encoding || 'hex';\n options.excludeValues = sourceOptions.excludeValues ? true : false;\n options.algorithm = options.algorithm.toLowerCase();\n options.encoding = options.encoding.toLowerCase();\n options.ignoreUnknown = sourceOptions.ignoreUnknown !== true ? false : true; // default to false\n options.respectType = sourceOptions.respectType === false ? false : true; // default to true\n options.respectFunctionNames = sourceOptions.respectFunctionNames === false ? false : true;\n options.respectFunctionProperties = sourceOptions.respectFunctionProperties === false ? false : true;\n options.unorderedArrays = sourceOptions.unorderedArrays !== true ? false : true; // default to false\n options.unorderedSets = sourceOptions.unorderedSets === false ? false : true; // default to false\n options.unorderedObjects = sourceOptions.unorderedObjects === false ? false : true; // default to true\n options.replacer = sourceOptions.replacer || undefined;\n options.excludeKeys = sourceOptions.excludeKeys || undefined;\n\n if(typeof object === 'undefined') {\n throw new Error('Object argument required.');\n }\n\n // if there is a case-insensitive match in the hashes list, accept it\n // (i.e. SHA256 for sha256)\n for (var i = 0; i < hashes.length; ++i) {\n if (hashes[i].toLowerCase() === options.algorithm.toLowerCase()) {\n options.algorithm = hashes[i];\n }\n }\n\n if(hashes.indexOf(options.algorithm) === -1){\n throw new Error('Algorithm \"' + options.algorithm + '\" not supported. ' +\n 'supported values: ' + hashes.join(', '));\n }\n\n if(encodings.indexOf(options.encoding) === -1 &&\n options.algorithm !== 'passthrough'){\n throw new Error('Encoding \"' + options.encoding + '\" not supported. ' +\n 'supported values: ' + encodings.join(', '));\n }\n\n return options;\n}\n\n/** Check if the given function is a native function */\nfunction isNativeFunction(f) {\n if ((typeof f) !== 'function') {\n return false;\n }\n var exp = /^function\\s+\\w*\\s*\\(\\s*\\)\\s*{\\s+\\[native code\\]\\s+}$/i;\n return exp.exec(Function.prototype.toString.call(f)) != null;\n}\n\nfunction hash(object, options) {\n var hashingStream;\n\n if (options.algorithm !== 'passthrough') {\n hashingStream = crypto.createHash(options.algorithm);\n } else {\n hashingStream = new PassThrough();\n }\n\n if (typeof hashingStream.write === 'undefined') {\n hashingStream.write = hashingStream.update;\n hashingStream.end = hashingStream.update;\n }\n\n var hasher = typeHasher(options, hashingStream);\n hasher.dispatch(object);\n if (!hashingStream.update) {\n hashingStream.end('');\n }\n\n if (hashingStream.digest) {\n return hashingStream.digest(options.encoding === 'buffer' ? undefined : options.encoding);\n }\n\n var buf = hashingStream.read();\n if (options.encoding === 'buffer') {\n return buf;\n }\n\n return buf.toString(options.encoding);\n}\n\n/**\n * Expose streaming API\n *\n * @param {object} object Value to serialize\n * @param {object} options Options, as for hash()\n * @param {object} stream A stream to write the serializiation to\n * @api public\n */\nexports.writeToStream = function(object, options, stream) {\n if (typeof stream === 'undefined') {\n stream = options;\n options = {};\n }\n\n options = applyDefaults(object, options);\n\n return typeHasher(options, stream).dispatch(object);\n};\n\nfunction typeHasher(options, writeTo, context){\n context = context || [];\n var write = function(str) {\n if (writeTo.update) {\n return writeTo.update(str, 'utf8');\n } else {\n return writeTo.write(str, 'utf8');\n }\n };\n\n return {\n dispatch: function(value){\n if (options.replacer) {\n value = options.replacer(value);\n }\n\n var type = typeof value;\n if (value === null) {\n type = 'null';\n }\n\n //console.log(\"[DEBUG] Dispatch: \", value, \"->\", type, \" -> \", \"_\" + type);\n\n return this['_' + type](value);\n },\n _object: function(object) {\n var pattern = (/\\[object (.*)\\]/i);\n var objString = Object.prototype.toString.call(object);\n var objType = pattern.exec(objString);\n if (!objType) { // object type did not match [object ...]\n objType = 'unknown:[' + objString + ']';\n } else {\n objType = objType[1]; // take only the class name\n }\n\n objType = objType.toLowerCase();\n\n var objectNumber = null;\n\n if ((objectNumber = context.indexOf(object)) >= 0) {\n return this.dispatch('[CIRCULAR:' + objectNumber + ']');\n } else {\n context.push(object);\n }\n\n if (typeof Buffer !== 'undefined' && Buffer.isBuffer && Buffer.isBuffer(object)) {\n write('buffer:');\n return write(object);\n }\n\n if(objType !== 'object' && objType !== 'function' && objType !== 'asyncfunction') {\n if(this['_' + objType]) {\n this['_' + objType](object);\n } else if (options.ignoreUnknown) {\n return write('[' + objType + ']');\n } else {\n throw new Error('Unknown object type \"' + objType + '\"');\n }\n }else{\n var keys = Object.keys(object);\n if (options.unorderedObjects) {\n keys = keys.sort();\n }\n // Make sure to incorporate special properties, so\n // Types with different prototypes will produce\n // a different hash and objects derived from\n // different functions (`new Foo`, `new Bar`) will\n // produce different hashes.\n // We never do this for native functions since some\n // seem to break because of that.\n if (options.respectType !== false && !isNativeFunction(object)) {\n keys.splice(0, 0, 'prototype', '__proto__', 'constructor');\n }\n\n if (options.excludeKeys) {\n keys = keys.filter(function(key) { return !options.excludeKeys(key); });\n }\n\n write('object:' + keys.length + ':');\n var self = this;\n return keys.forEach(function(key){\n self.dispatch(key);\n write(':');\n if(!options.excludeValues) {\n self.dispatch(object[key]);\n }\n write(',');\n });\n }\n },\n _array: function(arr, unordered){\n unordered = typeof unordered !== 'undefined' ? unordered :\n options.unorderedArrays !== false; // default to options.unorderedArrays\n\n var self = this;\n write('array:' + arr.length + ':');\n if (!unordered || arr.length <= 1) {\n return arr.forEach(function(entry) {\n return self.dispatch(entry);\n });\n }\n\n // the unordered case is a little more complicated:\n // since there is no canonical ordering on objects,\n // i.e. {a:1} < {a:2} and {a:1} > {a:2} are both false,\n // we first serialize each entry using a PassThrough stream\n // before sorting.\n // also: we can’t use the same context array for all entries\n // since the order of hashing should *not* matter. instead,\n // we keep track of the additions to a copy of the context array\n // and add all of them to the global context array when we’re done\n var contextAdditions = [];\n var entries = arr.map(function(entry) {\n var strm = new PassThrough();\n var localContext = context.slice(); // make copy\n var hasher = typeHasher(options, strm, localContext);\n hasher.dispatch(entry);\n // take only what was added to localContext and append it to contextAdditions\n contextAdditions = contextAdditions.concat(localContext.slice(context.length));\n return strm.read().toString();\n });\n context = context.concat(contextAdditions);\n entries.sort();\n return this._array(entries, false);\n },\n _date: function(date){\n return write('date:' + date.toJSON());\n },\n _symbol: function(sym){\n return write('symbol:' + sym.toString());\n },\n _error: function(err){\n return write('error:' + err.toString());\n },\n _boolean: function(bool){\n return write('bool:' + bool.toString());\n },\n _string: function(string){\n write('string:' + string.length + ':');\n write(string.toString());\n },\n _function: function(fn){\n write('fn:');\n if (isNativeFunction(fn)) {\n this.dispatch('[native]');\n } else {\n this.dispatch(fn.toString());\n }\n\n if (options.respectFunctionNames !== false) {\n // Make sure we can still distinguish native functions\n // by their name, otherwise String and Function will\n // have the same hash\n this.dispatch(\"function-name:\" + String(fn.name));\n }\n\n if (options.respectFunctionProperties) {\n this._object(fn);\n }\n },\n _number: function(number){\n return write('number:' + number.toString());\n },\n _xml: function(xml){\n return write('xml:' + xml.toString());\n },\n _null: function() {\n return write('Null');\n },\n _undefined: function() {\n return write('Undefined');\n },\n _regexp: function(regex){\n return write('regex:' + regex.toString());\n },\n _uint8array: function(arr){\n write('uint8array:');\n return this.dispatch(Array.prototype.slice.call(arr));\n },\n _uint8clampedarray: function(arr){\n write('uint8clampedarray:');\n return this.dispatch(Array.prototype.slice.call(arr));\n },\n _int8array: function(arr){\n write('int8array:');\n return this.dispatch(Array.prototype.slice.call(arr));\n },\n _uint16array: function(arr){\n write('uint16array:');\n return this.dispatch(Array.prototype.slice.call(arr));\n },\n _int16array: function(arr){\n write('int16array:');\n return this.dispatch(Array.prototype.slice.call(arr));\n },\n _uint32array: function(arr){\n write('uint32array:');\n return this.dispatch(Array.prototype.slice.call(arr));\n },\n _int32array: function(arr){\n write('int32array:');\n return this.dispatch(Array.prototype.slice.call(arr));\n },\n _float32array: function(arr){\n write('float32array:');\n return this.dispatch(Array.prototype.slice.call(arr));\n },\n _float64array: function(arr){\n write('float64array:');\n return this.dispatch(Array.prototype.slice.call(arr));\n },\n _arraybuffer: function(arr){\n write('arraybuffer:');\n return this.dispatch(new Uint8Array(arr));\n },\n _url: function(url) {\n return write('url:' + url.toString(), 'utf8');\n },\n _map: function(map) {\n write('map:');\n var arr = Array.from(map);\n return this._array(arr, options.unorderedSets !== false);\n },\n _set: function(set) {\n write('set:');\n var arr = Array.from(set);\n return this._array(arr, options.unorderedSets !== false);\n },\n _file: function(file) {\n write('file:');\n return this.dispatch([file.name, file.size, file.type, file.lastModfied]);\n },\n _blob: function() {\n if (options.ignoreUnknown) {\n return write('[blob]');\n }\n\n throw Error('Hashing Blob objects is currently not supported\\n' +\n '(see https://github.com/puleos/object-hash/issues/26)\\n' +\n 'Use \"options.replacer\" or \"options.ignoreUnknown\"\\n');\n },\n _domwindow: function() { return write('domwindow'); },\n _bigint: function(number){\n return write('bigint:' + number.toString());\n },\n /* Node.js standard native objects */\n _process: function() { return write('process'); },\n _timer: function() { return write('timer'); },\n _pipe: function() { return write('pipe'); },\n _tcp: function() { return write('tcp'); },\n _udp: function() { return write('udp'); },\n _tty: function() { return write('tty'); },\n _statwatcher: function() { return write('statwatcher'); },\n _securecontext: function() { return write('securecontext'); },\n _connection: function() { return write('connection'); },\n _zlib: function() { return write('zlib'); },\n _context: function() { return write('context'); },\n _nodescript: function() { return write('nodescript'); },\n _httpparser: function() { return write('httpparser'); },\n _dataview: function() { return write('dataview'); },\n _signal: function() { return write('signal'); },\n _fsevent: function() { return write('fsevent'); },\n _tlswrap: function() { return write('tlswrap'); },\n };\n}\n\n// Mini-implementation of stream.PassThrough\n// We are far from having need for the full implementation, and we can\n// make assumptions like \"many writes, then only one final read\"\n// and we can ignore encoding specifics\nfunction PassThrough() {\n return {\n buf: '',\n\n write: function(b) {\n this.buf += b;\n },\n\n end: function(b) {\n this.buf += b;\n },\n\n read: function() {\n return this.buf;\n }\n };\n}\n",
6
+ "import {\n createCipheriv,\n createDecipheriv,\n createHash,\n randomBytes,\n} from \"node:crypto\";\nimport type { ActivityStream } from \"@sockethub/schemas\";\nimport hash from \"object-hash\";\n\nconst ALGORITHM = \"aes-256-cbc\";\nconst IV_LENGTH = 16; // For AES, this is always 16\n\nexport function getPlatformId(\n platform: string,\n actor?: string,\n _crypto = crypto,\n): string {\n return actor ? _crypto.hash(platform + actor) : _crypto.hash(platform);\n}\n\nexport class Crypto {\n randomBytes: typeof randomBytes;\n\n constructor() {\n this.createRandomBytes();\n }\n\n createRandomBytes() {\n this.randomBytes = randomBytes;\n }\n\n encrypt(json: ActivityStream, secret: string): string {\n Crypto.ensureSecret(secret);\n const iv = this.randomBytes(IV_LENGTH);\n const cipher = createCipheriv(ALGORITHM, Buffer.from(secret), iv);\n let encrypted = cipher.update(JSON.stringify(json));\n\n encrypted = Buffer.concat([encrypted, cipher.final()]);\n return `${iv.toString(\"hex\")}:${encrypted.toString(\"hex\")}`;\n }\n\n decrypt(text: string, secret: string): ActivityStream {\n Crypto.ensureSecret(secret);\n const parts = text.split(\":\");\n const iv = Buffer.from(parts.shift(), \"hex\");\n const encryptedText = Buffer.from(parts.join(\":\"), \"hex\");\n const decipher = createDecipheriv(ALGORITHM, Buffer.from(secret), iv);\n let decrypted = decipher.update(encryptedText);\n decrypted = Buffer.concat([decrypted, decipher.final()]);\n return JSON.parse(decrypted.toString());\n }\n\n hash(text: string): string {\n const SHASum = createHash(\"sha1\");\n SHASum.update(text);\n return SHASum.digest(\"hex\").substring(0, 7);\n }\n\n objectHash(object: object): string {\n return hash(object);\n }\n\n randToken(len: number): string {\n if (len > 32) {\n throw new Error(\n `crypto.randToken supports a length param of up to 32, ${len} given`,\n );\n }\n const buf = this.randomBytes(len);\n return buf.toString(\"hex\").substring(0, len);\n }\n\n private static ensureSecret(secret: string) {\n if (secret.length !== 32) {\n throw new Error(\n `secret must be a 32 char string, length: ${secret.length}`,\n );\n }\n }\n}\n\nexport const crypto = new Crypto();\n"
7
+ ],
8
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;EAEA,IAAI;AAAA,EAyBJ,UAAU,OAAO,UAAU;AAAA,EAE3B,SAAS,UAAU,CAAC,QAAQ,SAAQ;AAAA,IAClC,UAAU,cAAc,QAAQ,OAAO;AAAA,IAEvC,OAAO,KAAK,QAAQ,O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G,EAAE;AAAA,IACpE,IAAI,YAAY,SAAS,OAAO,aAAa;AAAA,IAC7C,YAAY,OAAO,OAAO,CAAC,WAAW,SAAS,MAAM,CAAC,CAAC;AAAA,IACvD,OAAO,KAAK,MAAM,UAAU,SAAS,CAAC;AAAA;AAAA,EAG1C,IAAI,CAAC,MAAsB;AAAA,IACvB,MAAM,SAAS,WAAW,MAAM;AAAA,IAChC,OAAO,OAAO,IAAI;AAAA,IAClB,OAAO,OAAO,OAAO,KAAK,EAAE,UAAU,GAAG,CAAC;AAAA;AAAA,EAG9C,UAAU,CAAC,QAAwB;AAAA,IAC/B,OAAO,2BAAK,MAAM;AAAA;AAAA,EAGtB,SAAS,CAAC,KAAqB;AAAA,IAC3B,IAAI,MAAM,IAAI;AAAA,MACV,MAAM,IAAI,MACN,yDAAyD,WAC7D;AAAA,IACJ;AAAA,IACA,MAAM,MAAM,KAAK,YAAY,GAAG;AAAA,IAChC,OAAO,IAAI,SAAS,KAAK,EAAE,UAAU,GAAG,GAAG;AAAA;AAAA,SAGhC,YAAY,CAAC,QAAgB;AAAA,IACxC,IAAI,OAAO,WAAW,IAAI;AAAA,MACtB,MAAM,IAAI,MACN,4CAA4C,OAAO,QACvD;AAAA,IACJ;AAAA;AAER;AAEO,IAAM,SAAS,IAAI;",
9
+ "debugId": "2BD4490536E49C1E64756E2164756E21",
10
+ "names": []
11
+ }
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@sockethub/crypto",
3
+ "description": "Crypto functions and helpers for Sockethub",
4
+ "version": "1.0.0-alpha.10",
5
+ "type": "module",
6
+ "private": false,
7
+ "author": "Nick Jennings <nick@silverbucket.net>",
8
+ "license": "MIT",
9
+ "publishConfig": {
10
+ "access": "public"
11
+ },
12
+ "main": "dist/index.js",
13
+ "exports": {
14
+ ".": {
15
+ "bun": "./src/index.ts",
16
+ "import": "./dist/index.js",
17
+ "default": "./dist/index.js"
18
+ }
19
+ },
20
+ "files": [
21
+ "src/",
22
+ "dist/"
23
+ ],
24
+ "engines": {
25
+ "bun": ">=1.2"
26
+ },
27
+ "keywords": [
28
+ "sockethub",
29
+ "messaging",
30
+ "redis",
31
+ "data lyer",
32
+ "rpc",
33
+ "data store"
34
+ ],
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/sockethub/sockethub.git",
38
+ "directory": "packages/data-layer"
39
+ },
40
+ "homepage": "https://github.com/sockethub/sockethub/tree/master/packages/data-layer",
41
+ "scripts": {
42
+ "build": "bun build src/index.ts --outdir dist --target node --format esm --sourcemap=external",
43
+ "clean": "rm -rf dist"
44
+ },
45
+ "dependencies": {
46
+ "@sockethub/schemas": "^3.0.0-alpha.10",
47
+ "object-hash": "^3.0.0"
48
+ },
49
+ "devDependencies": {
50
+ "@types/bun": "latest",
51
+ "@types/debug": "^4.1.12",
52
+ "@types/object-hash": "^3.0.6",
53
+ "@types/sinon": "^17.0.4",
54
+ "sinon": "^17.0.2"
55
+ },
56
+ "gitHead": "8e1abf116b2a6b57d33c6e1a4af9143870517bae"
57
+ }
@@ -0,0 +1,86 @@
1
+ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
2
+ import * as sinon from "sinon";
3
+
4
+ import { Crypto, getPlatformId } from "./index";
5
+
6
+ const secret = "a test secret.. that is 16 x 2..";
7
+ const data = { foo: "bar" };
8
+ const encryptedData =
9
+ "00000000000000000000000000000000:0543ec94d863fbf4b7a19b48e69d9317";
10
+
11
+ describe("crypto", () => {
12
+ let crypto;
13
+ beforeEach(() => {
14
+ class TestCrypto extends Crypto {
15
+ createRandomBytes() {
16
+ this.randomBytes = () => Buffer.alloc(16);
17
+ }
18
+ }
19
+ crypto = new TestCrypto();
20
+ });
21
+
22
+ it("encrypts", () => {
23
+ expect(crypto.encrypt(data, secret)).toEqual(encryptedData);
24
+ });
25
+
26
+ it("decrypts", () => {
27
+ expect(crypto.decrypt(encryptedData, secret)).toEqual(data);
28
+ });
29
+
30
+ it("hashes", () => {
31
+ expect(crypto.hash("foobar")).toEqual("8843d7f");
32
+ });
33
+
34
+ it("randTokens 8", () => {
35
+ const token = crypto.randToken(8);
36
+ expect(token.length).toEqual(8);
37
+ });
38
+
39
+ it("randTokens 16", () => {
40
+ const token = crypto.randToken(16);
41
+ expect(token.length).toEqual(16);
42
+ });
43
+
44
+ it("randTokens 32", () => {
45
+ const token = crypto.randToken(32);
46
+ expect(token.length).toEqual(32);
47
+ });
48
+
49
+ it("randTokens 33+ will fail", () => {
50
+ expect(() => {
51
+ crypto.randToken(33);
52
+ }).toThrow();
53
+ });
54
+ });
55
+
56
+ describe("getPlatformId", () => {
57
+ let cryptoHashStub: any;
58
+ let crypto;
59
+
60
+ beforeEach(() => {
61
+ cryptoHashStub = sinon.mock();
62
+ class TestCrypto extends Crypto {
63
+ createRandomBytes() {
64
+ this.randomBytes = () => Buffer.alloc(16);
65
+ }
66
+ }
67
+ crypto = new TestCrypto();
68
+ cryptoHashStub = sinon.stub(crypto, "hash");
69
+ cryptoHashStub.returnsArg(0);
70
+ });
71
+
72
+ afterEach(() => {
73
+ cryptoHashStub.restore();
74
+ });
75
+
76
+ it("generates platform hash", () => {
77
+ expect(getPlatformId("foo", undefined, crypto)).toEqual("foo");
78
+ sinon.assert.calledOnce(cryptoHashStub);
79
+ sinon.assert.calledWith(cryptoHashStub, "foo");
80
+ });
81
+ it("generates platform + actor hash", () => {
82
+ expect(getPlatformId("foo", "bar", crypto)).toEqual("foobar");
83
+ sinon.assert.calledOnce(cryptoHashStub);
84
+ sinon.assert.calledWith(cryptoHashStub, "foobar");
85
+ });
86
+ });
package/src/index.ts ADDED
@@ -0,0 +1,82 @@
1
+ import {
2
+ createCipheriv,
3
+ createDecipheriv,
4
+ createHash,
5
+ randomBytes,
6
+ } from "node:crypto";
7
+ import type { ActivityStream } from "@sockethub/schemas";
8
+ import hash from "object-hash";
9
+
10
+ const ALGORITHM = "aes-256-cbc";
11
+ const IV_LENGTH = 16; // For AES, this is always 16
12
+
13
+ export function getPlatformId(
14
+ platform: string,
15
+ actor?: string,
16
+ _crypto = crypto,
17
+ ): string {
18
+ return actor ? _crypto.hash(platform + actor) : _crypto.hash(platform);
19
+ }
20
+
21
+ export class Crypto {
22
+ randomBytes: typeof randomBytes;
23
+
24
+ constructor() {
25
+ this.createRandomBytes();
26
+ }
27
+
28
+ createRandomBytes() {
29
+ this.randomBytes = randomBytes;
30
+ }
31
+
32
+ encrypt(json: ActivityStream, secret: string): string {
33
+ Crypto.ensureSecret(secret);
34
+ const iv = this.randomBytes(IV_LENGTH);
35
+ const cipher = createCipheriv(ALGORITHM, Buffer.from(secret), iv);
36
+ let encrypted = cipher.update(JSON.stringify(json));
37
+
38
+ encrypted = Buffer.concat([encrypted, cipher.final()]);
39
+ return `${iv.toString("hex")}:${encrypted.toString("hex")}`;
40
+ }
41
+
42
+ decrypt(text: string, secret: string): ActivityStream {
43
+ Crypto.ensureSecret(secret);
44
+ const parts = text.split(":");
45
+ const iv = Buffer.from(parts.shift(), "hex");
46
+ const encryptedText = Buffer.from(parts.join(":"), "hex");
47
+ const decipher = createDecipheriv(ALGORITHM, Buffer.from(secret), iv);
48
+ let decrypted = decipher.update(encryptedText);
49
+ decrypted = Buffer.concat([decrypted, decipher.final()]);
50
+ return JSON.parse(decrypted.toString());
51
+ }
52
+
53
+ hash(text: string): string {
54
+ const SHASum = createHash("sha1");
55
+ SHASum.update(text);
56
+ return SHASum.digest("hex").substring(0, 7);
57
+ }
58
+
59
+ objectHash(object: object): string {
60
+ return hash(object);
61
+ }
62
+
63
+ randToken(len: number): string {
64
+ if (len > 32) {
65
+ throw new Error(
66
+ `crypto.randToken supports a length param of up to 32, ${len} given`,
67
+ );
68
+ }
69
+ const buf = this.randomBytes(len);
70
+ return buf.toString("hex").substring(0, len);
71
+ }
72
+
73
+ private static ensureSecret(secret: string) {
74
+ if (secret.length !== 32) {
75
+ throw new Error(
76
+ `secret must be a 32 char string, length: ${secret.length}`,
77
+ );
78
+ }
79
+ }
80
+ }
81
+
82
+ export const crypto = new Crypto();