@pageproof/sdk-pr 330.0.1620336044578 → 331.0.1620600296845
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/lib/adapters/ICryptoAdapter.d.ts +5 -5
- package/lib/adapters/ICryptoAdapter.js +1 -1
- package/lib/adapters/SchedulerCryptoAdapter.d.ts +10 -10
- package/lib/adapters/SchedulerCryptoAdapter.js +1 -1
- package/lib/adapters/SyncCryptoAdapter.d.ts +8 -8
- package/lib/adapters/SyncCryptoAdapter.js +1 -1
- package/lib/api/Comments.js +1 -1
- package/lib/api/Files.js +1 -1
- package/lib/api/ProofsAssetsExtractedText.js +1 -1
- package/lib/core/KeyPairs.d.ts +11 -0
- package/lib/core/KeyPairs.js +1 -0
- package/lib/core/PageProof.d.ts +2 -0
- package/lib/core/PageProof.js +1 -1
- package/lib/crypto/decryptBytes.js +1 -1
- package/lib/crypto/decryptComment.d.ts +2 -2
- package/lib/crypto/decryptComment.js +1 -1
- package/lib/crypto/decryptData.js +1 -1
- package/lib/crypto/decryptFileBlock.d.ts +1 -1
- package/lib/crypto/decryptFileBlock.js +1 -1
- package/lib/crypto/decryptImage.d.ts +2 -2
- package/lib/crypto/decryptImage.js +1 -1
- package/lib/crypto/envelopes.d.ts +2 -2
- package/lib/crypto/envelopes.js +1 -1
- package/lib/pageproof.js +1 -1
- package/lib/sync-crypto-adapter.js +1 -1
- package/lib/worker-crypto-adapter.js +1 -1
- package/lib/worker.cffdaf8a.js +2 -0
- package/package.json +1 -1
- package/lib/worker.33813125.js +0 -2
|
@@ -5,7 +5,7 @@ declare class ICryptoAdapter {
|
|
|
5
5
|
* @abstract
|
|
6
6
|
* @param {string} data$ The encrypted (and encoded) data
|
|
7
7
|
* @param {string} envelope$ The envelope containing the key
|
|
8
|
-
* @param {string}
|
|
8
|
+
* @param {string[]} privateKeyPEMs The user's private keys used to decrypt the envelope
|
|
9
9
|
* @param {string[]} before Any pre-processing to do on the encrypted data
|
|
10
10
|
* @param {string[]} after Any post-processing to do on the newly-decrypted data
|
|
11
11
|
* @returns {Promise<string>} The decrypted (and encoded) data
|
|
@@ -15,7 +15,7 @@ declare class ICryptoAdapter {
|
|
|
15
15
|
* @abstract
|
|
16
16
|
* @param {string} comment$ The encrypted comment
|
|
17
17
|
* @param {string} envelope The comment envelope containing the key
|
|
18
|
-
* @param {string}
|
|
18
|
+
* @param {string[]} privateKeyPEMs The user's private keys used to decrypt the envelope
|
|
19
19
|
* @returns {Promise<string>} The original, raw comment text
|
|
20
20
|
*/
|
|
21
21
|
decryptComment(): Promise<string>;
|
|
@@ -31,14 +31,14 @@ declare class ICryptoAdapter {
|
|
|
31
31
|
/**
|
|
32
32
|
* @abstract
|
|
33
33
|
* @param {string} data$ The encrypted file block (and envelope)
|
|
34
|
-
* @param {string}
|
|
34
|
+
* @param {string[]} privateKeyPEMs The user's private keys used to decrypt the embedded envelope
|
|
35
35
|
* @returns {Promise<string>} A base64 representation of the original block
|
|
36
36
|
*/
|
|
37
37
|
decryptFileBlock(): Promise<string>;
|
|
38
38
|
/**
|
|
39
39
|
* @abstract
|
|
40
40
|
* @param {string} data$ The encrypted image (and envelope)
|
|
41
|
-
* @param {string}
|
|
41
|
+
* @param {string[]} privateKeyPEMs The user's private keys used to decrypt the embedded envelope
|
|
42
42
|
* @returns {Promise<string>} A base64 representation of the original image
|
|
43
43
|
*/
|
|
44
44
|
decryptImage(): Promise<string>;
|
|
@@ -73,7 +73,7 @@ declare class ICryptoAdapter {
|
|
|
73
73
|
/**
|
|
74
74
|
* @abstract
|
|
75
75
|
* @param {string} envelope The full envelope to unseal
|
|
76
|
-
* @param {string}
|
|
76
|
+
* @param {string[]} privateKeyPEMs The user's private keys (in PEM format), used to decrypt the envelope
|
|
77
77
|
* @returns {Promise<string>} The secret within the envelope
|
|
78
78
|
*/
|
|
79
79
|
envelopeUnseal(): Promise<string>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.__esModule=true;var _class,_temp;function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function notImplementedStub(name){return new Error(name+" is not implemented on ICryptoAdapter.")}var ICryptoAdapter=(_temp=_class=function(){function ICryptoAdapter(){_classCallCheck(this,ICryptoAdapter)}ICryptoAdapter.prototype.decryptBytes=function decryptBytes(){throw notImplementedStub("decryptBytes(comment$: string, envelope$: string,
|
|
1
|
+
"use strict";exports.__esModule=true;var _class,_temp;function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function notImplementedStub(name){return new Error(name+" is not implemented on ICryptoAdapter.")}var ICryptoAdapter=(_temp=_class=function(){function ICryptoAdapter(){_classCallCheck(this,ICryptoAdapter)}ICryptoAdapter.prototype.decryptBytes=function decryptBytes(){throw notImplementedStub("decryptBytes(comment$: string, envelope$: string, privateKeyPEMs: string[], before: string[], after: string[]): Promise<string>")};ICryptoAdapter.prototype.decryptComment=function decryptComment(){throw notImplementedStub("decryptComment(comment$: string, envelope: string, privateKeyPEMs: string[]): Promise<string>")};ICryptoAdapter.prototype.decryptData=function decryptData(){throw notImplementedStub("decryptData(version: number, data$: string, envelope$: string, privateKeyPEM: string): Promise<string>")};ICryptoAdapter.prototype.decryptFileBlock=function decryptFileBlock(){throw notImplementedStub("decryptFileBlock(data$: string, privateKeyPEMs: string[]): Promise<string>")};ICryptoAdapter.prototype.decryptImage=function decryptImage(){throw notImplementedStub("decryptImage(data$: string, privateKeyPEMs: string[]): Promise<string>")};ICryptoAdapter.prototype.decryptPrivateKey=function decryptPrivateKey(){throw notImplementedStub("decryptPrivateKey(privateKey$: string, password: string): Promise<string>")};ICryptoAdapter.prototype.encryptFileBlock=function encryptFileBlock(){throw notImplementedStub("encryptFileBlock(keyIV: {key: string, iv: string}, fileBlockBase64: string): Promise<string>")};ICryptoAdapter.prototype.encryptPrivateKey=function encryptPrivateKey(){throw notImplementedStub("encryptPrivateKey(privateKeyPEM: string, password: string): Promise<string>")};ICryptoAdapter.prototype.envelopeSeal=function envelopeSeal(){throw notImplementedStub("envelopeSeal(secret: string, publicKeyPEMs: Array<string>): Promise<string>")};ICryptoAdapter.prototype.envelopeUnseal=function envelopeUnseal(){throw notImplementedStub("envelopeUnseal(envelope: string, privateKeyPEMs: string[]): Promise<string>")};ICryptoAdapter.prototype.generateAuthorizationHeaders=function generateAuthorizationHeaders(){throw notImplementedStub("generateAuthorizationHeaders(method: string, path: string, session: Session): Promise<Object<string, string>>")};ICryptoAdapter.prototype.generateKeyIV=function generateKeyIV(){throw notImplementedStub("generateKeyIV(): Promise<{KeyIV}>")};ICryptoAdapter.prototype.generateKeyPair=function generateKeyPair(){throw notImplementedStub("generateKeyPair(): Promise<{KeyPair}>")};ICryptoAdapter.prototype.generatePasswordHash=function generatePasswordHash(){throw notImplementedStub("generatePasswordHash(password: string): Promise<string>")};ICryptoAdapter.prototype.generateWrappedSymmetricKey=function generateWrappedSymmetricKey(){throw notImplementedStub("generateWrappedSymmetricKey(serverPublicKeyPEM: string): Promise<WrappedSymmetricKey>")};ICryptoAdapter.prototype.decryptManagedPrivateKey=function decryptManagedPrivateKey(){throw notImplementedStub("decryptManagedPrivateKey(privateKey$: string, keyBase64: string): Promise<string>")};ICryptoAdapter.prototype.encryptComment=function encryptComment(){throw notImplementedStub("encryptComment(comment: string, publicKeyPEMs: Array<string>): Promise<EncryptedComment>")};return ICryptoAdapter}(),_class.__adapter__="ICryptoAdapter",_temp);exports.default=ICryptoAdapter;
|
|
@@ -5,19 +5,19 @@ declare class SchedulerCryptoAdapter extends ICryptoAdapter {
|
|
|
5
5
|
/**
|
|
6
6
|
* @param {string} data$ The encrypted (and encoded) data
|
|
7
7
|
* @param {string} envelope$ The envelope containing the key
|
|
8
|
-
* @param {string}
|
|
8
|
+
* @param {string[]} privateKeyPEMs The user's private keys used to decrypt the envelope
|
|
9
9
|
* @param {string[]} before Any pre-processing to do on the encrypted data
|
|
10
10
|
* @param {string[]} after Any post-processing to do on the newly-decrypted data
|
|
11
11
|
* @returns {Promise<string>} The decrypted (and encoded) data
|
|
12
12
|
*/
|
|
13
|
-
decryptBytes(comment$: any, envelope$: string,
|
|
13
|
+
decryptBytes(comment$: any, envelope$: string, privateKeyPEMs: string[], before: string[], after: string[]): Promise<string>;
|
|
14
14
|
/**
|
|
15
15
|
* @param {string} comment$ The encrypted comment
|
|
16
16
|
* @param {string} envelope The comment envelope containing the key
|
|
17
|
-
* @param {string}
|
|
17
|
+
* @param {string[]} privateKeyPEMs The user's private keys used to decrypt the envelope
|
|
18
18
|
* @returns {Promise<string>} The original, raw comment text
|
|
19
19
|
*/
|
|
20
|
-
decryptComment(comment$: string, envelope: string,
|
|
20
|
+
decryptComment(comment$: string, envelope: string, privateKeyPEMs: string[]): Promise<string>;
|
|
21
21
|
/**
|
|
22
22
|
* @abstract
|
|
23
23
|
* @param {number} version The encryption version number
|
|
@@ -29,16 +29,16 @@ declare class SchedulerCryptoAdapter extends ICryptoAdapter {
|
|
|
29
29
|
decryptData(version: number, data$: string, envelope$: string, privateKeyPEM: string): Promise<string>;
|
|
30
30
|
/**
|
|
31
31
|
* @param {string} data$ The encrypted file block (and envelope)
|
|
32
|
-
* @param {string}
|
|
32
|
+
* @param {string[]} privateKeyPEMs The user's private keys used to decrypt the embedded envelope
|
|
33
33
|
* @returns {Promise<string>} A base64 representation of the original block
|
|
34
34
|
*/
|
|
35
|
-
decryptFileBlock(data$: string,
|
|
35
|
+
decryptFileBlock(data$: string, privateKeyPEMs: string[]): Promise<string>;
|
|
36
36
|
/**
|
|
37
37
|
* @param {string} data$ The encrypted image (and envelope)
|
|
38
|
-
* @param {string}
|
|
38
|
+
* @param {string[]} privateKeyPEMs The user's private keys used to decrypt the embedded envelope
|
|
39
39
|
* @returns {Promise<string>} A base64 representation of the original image
|
|
40
40
|
*/
|
|
41
|
-
decryptImage(data$: string,
|
|
41
|
+
decryptImage(data$: string, privateKeyPEMs: string[]): Promise<string>;
|
|
42
42
|
/**
|
|
43
43
|
* @param {string} privateKey$ The user's encrypted private key
|
|
44
44
|
* @param {string} password The user's original password, used to decrypt the private key
|
|
@@ -69,10 +69,10 @@ declare class SchedulerCryptoAdapter extends ICryptoAdapter {
|
|
|
69
69
|
envelopeSeal(secret: string, publicKeyPEMs: string[]): Promise<string>;
|
|
70
70
|
/**
|
|
71
71
|
* @param {string} envelope The full envelope to unseal
|
|
72
|
-
* @param {string}
|
|
72
|
+
* @param {string[]} privateKeyPEMs The user's private keys (in PEM format), used to decrypt the envelope
|
|
73
73
|
* @returns {Promise<string>} The secret within the envelope
|
|
74
74
|
*/
|
|
75
|
-
envelopeUnseal(envelope: string,
|
|
75
|
+
envelopeUnseal(envelope: string, privateKeyPEMs: string[]): Promise<string>;
|
|
76
76
|
/**
|
|
77
77
|
* @param {string} method The request method/verb (eg. GET, POST)
|
|
78
78
|
* @param {string} path The endpoint (pathname)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.__esModule=true;var _Scheduler=require("../util/Scheduler");var _Scheduler2=_interopRequireDefault(_Scheduler);var _ICryptoAdapter2=require("./ICryptoAdapter");var _ICryptoAdapter3=_interopRequireDefault(_ICryptoAdapter2);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&(typeof call==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+typeof superClass)}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var SchedulerCryptoAdapter=function(_ICryptoAdapter){_inherits(SchedulerCryptoAdapter,_ICryptoAdapter);function SchedulerCryptoAdapter(options){_classCallCheck(this,SchedulerCryptoAdapter);var _this=_possibleConstructorReturn(this,_ICryptoAdapter.call(this));_this.scheduler=new _Scheduler2.default(options);return _this}SchedulerCryptoAdapter.prototype.decryptBytes=function decryptBytes(comment$,envelope$,
|
|
1
|
+
"use strict";exports.__esModule=true;var _Scheduler=require("../util/Scheduler");var _Scheduler2=_interopRequireDefault(_Scheduler);var _ICryptoAdapter2=require("./ICryptoAdapter");var _ICryptoAdapter3=_interopRequireDefault(_ICryptoAdapter2);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&(typeof call==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+typeof superClass)}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var SchedulerCryptoAdapter=function(_ICryptoAdapter){_inherits(SchedulerCryptoAdapter,_ICryptoAdapter);function SchedulerCryptoAdapter(options){_classCallCheck(this,SchedulerCryptoAdapter);var _this=_possibleConstructorReturn(this,_ICryptoAdapter.call(this));_this.scheduler=new _Scheduler2.default(options);return _this}SchedulerCryptoAdapter.prototype.decryptBytes=function decryptBytes(comment$,envelope$,privateKeyPEMs,before,after){return this.scheduler.send({type:"decryptBytes",args:[comment$,envelope$,privateKeyPEMs,before,after]})};SchedulerCryptoAdapter.prototype.decryptComment=function decryptComment(comment$,envelope,privateKeyPEMs){return this.scheduler.send({type:"decryptComment",args:[comment$,envelope,privateKeyPEMs]})};SchedulerCryptoAdapter.prototype.decryptData=function decryptData(version,data$,envelope$,privateKeyPEM){return this.scheduler.send({type:"decryptData",args:[version,data$,envelope$,privateKeyPEM]})};SchedulerCryptoAdapter.prototype.decryptFileBlock=function decryptFileBlock(data$,privateKeyPEMs){return this.scheduler.send({type:"decryptFileBlock",args:[data$,privateKeyPEMs]})};SchedulerCryptoAdapter.prototype.decryptImage=function decryptImage(data$,privateKeyPEMs){return this.scheduler.send({type:"decryptImage",args:[data$,privateKeyPEMs]})};SchedulerCryptoAdapter.prototype.decryptPrivateKey=function decryptPrivateKey(privateKey$,password){return this.scheduler.send({type:"decryptPrivateKey",args:[privateKey$,password]})};SchedulerCryptoAdapter.prototype.encryptFileBlock=function encryptFileBlock(keyIV,fileBlock,decodeBlock){return this.scheduler.send({type:"encryptFileBlock",args:[keyIV,fileBlock,decodeBlock]})};SchedulerCryptoAdapter.prototype.encryptPrivateKey=function encryptPrivateKey(privateKeyPEM,password){return this.scheduler.send({type:"encryptPrivateKey",args:[privateKeyPEM,password]})};SchedulerCryptoAdapter.prototype.envelopeSeal=function envelopeSeal(secret,publicKeyPEMs){return this.scheduler.send({type:"envelopeSeal",args:[secret,publicKeyPEMs]})};SchedulerCryptoAdapter.prototype.envelopeUnseal=function envelopeUnseal(envelope,privateKeyPEMs){return this.scheduler.send({type:"envelopeUnseal",args:[envelope,privateKeyPEMs]})};SchedulerCryptoAdapter.prototype.generateAuthorizationHeaders=function generateAuthorizationHeaders(method,path,session){return this.scheduler.send({type:"generateAuthorizationHeaders",args:[method,path,session]})};SchedulerCryptoAdapter.prototype.generateKeyIV=function generateKeyIV(){return this.scheduler.send({type:"generateKeyIV"})};SchedulerCryptoAdapter.prototype.generateKeyPair=function generateKeyPair(){return this.scheduler.send({type:"generateKeyPair"})};SchedulerCryptoAdapter.prototype.generatePasswordHash=function generatePasswordHash(password){return this.scheduler.send({type:"generatePasswordHash",args:[password]})};SchedulerCryptoAdapter.prototype.generateWrappedSymmetricKey=function generateWrappedSymmetricKey(serverPublicKeyPEM){return this.scheduler.send({type:"generateWrappedSymmetricKey",args:[serverPublicKeyPEM]})};SchedulerCryptoAdapter.prototype.decryptManagedPrivateKey=function decryptManagedPrivateKey(privateKey$,keyBase64){return this.scheduler.send({type:"decryptManagedPrivateKey",args:[privateKey$,keyBase64]})};SchedulerCryptoAdapter.prototype.encryptComment=function encryptComment(comment,publicKeyPEMs){return this.scheduler.send({type:"encryptComment",args:[comment,publicKeyPEMs]})};return SchedulerCryptoAdapter}(_ICryptoAdapter3.default);exports.default=SchedulerCryptoAdapter;
|
|
@@ -3,19 +3,19 @@ declare class SyncCryptoAdapter extends ICryptoAdapter {
|
|
|
3
3
|
/**
|
|
4
4
|
* @param {string} data$ The encrypted (and encoded) data
|
|
5
5
|
* @param {string} envelope$ The envelope containing the key
|
|
6
|
-
* @param {string}
|
|
6
|
+
* @param {string[]} privateKeyPEMs The user's private keys used to decrypt the envelope
|
|
7
7
|
* @param {string[]} before Any pre-processing to do on the encrypted data
|
|
8
8
|
* @param {string[]} after Any post-processing to do on the newly-decrypted data
|
|
9
9
|
* @returns {Promise<string>} The decrypted (and encoded) data
|
|
10
10
|
*/
|
|
11
|
-
decryptBytes(comment$: any, envelope$: string,
|
|
11
|
+
decryptBytes(comment$: any, envelope$: string, privateKeyPEMs: string[], before: string[], after: string[]): Promise<string>;
|
|
12
12
|
/**
|
|
13
13
|
* @param {string} comment$ The encrypted comment
|
|
14
14
|
* @param {string} envelope The comment envelope containing the key
|
|
15
|
-
* @param {string}
|
|
15
|
+
* @param {string[]} privateKeyPEMs The user's private keys used to decrypt the envelope
|
|
16
16
|
* @returns {Promise<string>} The original, raw comment text
|
|
17
17
|
*/
|
|
18
|
-
decryptComment(comment$: string, envelope: string,
|
|
18
|
+
decryptComment(comment$: string, envelope: string, privateKeyPEMs: string[]): Promise<string>;
|
|
19
19
|
/**
|
|
20
20
|
* @param {number} version The encryption version number
|
|
21
21
|
* @param {string} data$ The encrypted data
|
|
@@ -26,10 +26,10 @@ declare class SyncCryptoAdapter extends ICryptoAdapter {
|
|
|
26
26
|
decryptData(version: number, data$: string, envelope$: string, privateKeyPEM: string): Promise<string>;
|
|
27
27
|
/**
|
|
28
28
|
* @param {string} data$ The encrypted image (and envelope)
|
|
29
|
-
* @param {string}
|
|
29
|
+
* @param {string[]} privateKeyPEMs The user's private keys used to decrypt the embedded envelope
|
|
30
30
|
* @returns {Promise<string>} A base64 representation of the original image
|
|
31
31
|
*/
|
|
32
|
-
decryptImage(data$: string,
|
|
32
|
+
decryptImage(data$: string, privateKeyPEMs: string[]): Promise<string>;
|
|
33
33
|
/**
|
|
34
34
|
* @param {string} privateKey$ The user's encrypted private key
|
|
35
35
|
* @param {string} password The user's original password, used to decrypt the private key
|
|
@@ -60,10 +60,10 @@ declare class SyncCryptoAdapter extends ICryptoAdapter {
|
|
|
60
60
|
envelopeSeal(secret: string, publicKeyPEMs: string[]): Promise<string>;
|
|
61
61
|
/**
|
|
62
62
|
* @param {string} envelope The full envelope to unseal
|
|
63
|
-
* @param {string}
|
|
63
|
+
* @param {string[]} privateKeyPEMs The user's private keys (in PEM format), used to decrypt the envelope
|
|
64
64
|
* @returns {Promise<string>} The secret within the envelope
|
|
65
65
|
*/
|
|
66
|
-
envelopeUnseal(envelope: string,
|
|
66
|
+
envelopeUnseal(envelope: string, privateKeyPEMs: string[]): Promise<string>;
|
|
67
67
|
/**
|
|
68
68
|
* @param {string} method The request method/verb (eg. GET, POST)
|
|
69
69
|
* @param {string} path The endpoint (pathname)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.__esModule=true;var _ICryptoAdapter2=require("./ICryptoAdapter");var _ICryptoAdapter3=_interopRequireDefault(_ICryptoAdapter2);var _crypto=require("../crypto");var crypto=_interopRequireWildcard(_crypto);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&(typeof call==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+typeof superClass)}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var SyncCryptoAdapter=function(_ICryptoAdapter){_inherits(SyncCryptoAdapter,_ICryptoAdapter);function SyncCryptoAdapter(){_classCallCheck(this,SyncCryptoAdapter);return _possibleConstructorReturn(this,_ICryptoAdapter.apply(this,arguments))}SyncCryptoAdapter.prototype.decryptBytes=function decryptBytes(comment$,envelope$,
|
|
1
|
+
"use strict";exports.__esModule=true;var _ICryptoAdapter2=require("./ICryptoAdapter");var _ICryptoAdapter3=_interopRequireDefault(_ICryptoAdapter2);var _crypto=require("../crypto");var crypto=_interopRequireWildcard(_crypto);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&(typeof call==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+typeof superClass)}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var SyncCryptoAdapter=function(_ICryptoAdapter){_inherits(SyncCryptoAdapter,_ICryptoAdapter);function SyncCryptoAdapter(){_classCallCheck(this,SyncCryptoAdapter);return _possibleConstructorReturn(this,_ICryptoAdapter.apply(this,arguments))}SyncCryptoAdapter.prototype.decryptBytes=function decryptBytes(comment$,envelope$,privateKeyPEMs,before,after){return crypto.decryptBytes(comment$,envelope$,privateKeyPEMs,before,after)};SyncCryptoAdapter.prototype.decryptComment=function decryptComment(comment$,envelope,privateKeyPEMs){return crypto.decryptComment(comment$,envelope,privateKeyPEMs)};SyncCryptoAdapter.prototype.decryptData=function decryptData(version,data$,envelope$,privateKeyPEM){return crypto.decryptData(version,data$,envelope$,privateKeyPEM)};SyncCryptoAdapter.prototype.decryptImage=function decryptImage(data$,privateKeyPEMs){return crypto.decryptImage(data$,privateKeyPEMs)};SyncCryptoAdapter.prototype.decryptPrivateKey=function decryptPrivateKey(privateKey$,password){return crypto.decryptPrivateKey(privateKey$,password)};SyncCryptoAdapter.prototype.encryptFileBlock=function encryptFileBlock(keyIV,fileBlock,decodeBlock){return crypto.encryptFileBlock(keyIV,fileBlock,decodeBlock)};SyncCryptoAdapter.prototype.encryptPrivateKey=function encryptPrivateKey(privateKeyPEM,password){return crypto.encryptPrivateKey(privateKeyPEM,password)};SyncCryptoAdapter.prototype.envelopeSeal=function envelopeSeal(secret,publicKeyPEMs){return crypto.envelopeSeal(secret,publicKeyPEMs)};SyncCryptoAdapter.prototype.envelopeUnseal=function envelopeUnseal(envelope,privateKeyPEMs){return crypto.envelopeUnseal(envelope,privateKeyPEMs)};SyncCryptoAdapter.prototype.generateAuthorizationHeaders=function generateAuthorizationHeaders(method,path,session){return crypto.generateAuthorizationHeaders(method,path,session)};SyncCryptoAdapter.prototype.generateKeyIV=function generateKeyIV(){return crypto.generateKeyIV()};SyncCryptoAdapter.prototype.generateKeyPair=function generateKeyPair(){return crypto.generateKeyPair()};SyncCryptoAdapter.prototype.generatePasswordHash=function generatePasswordHash(password){return crypto.generatePasswordHash(password)};SyncCryptoAdapter.prototype.generateWrappedSymmetricKey=function generateWrappedSymmetricKey(serverPublicKeyPEM){return crypto.generateWrappedSymmetricKey(serverPublicKeyPEM)};SyncCryptoAdapter.prototype.decryptManagedPrivateKey=function decryptManagedPrivateKey(privateKey$,keyBase64){return crypto.decryptManagedPrivateKey(privateKey$,keyBase64)};SyncCryptoAdapter.prototype.encryptComment=function encryptComment(comment,publicKeyPEMs){return crypto.encryptComment(comment,publicKeyPEMs)};return SyncCryptoAdapter}(_ICryptoAdapter3.default);exports.default=SyncCryptoAdapter;
|
package/lib/api/Comments.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.__esModule=true;var _API2=require("./API");var _API3=_interopRequireDefault(_API2);var _Comment=require("../models/Comment");var _Comment2=_interopRequireDefault(_Comment);var _CommentState=require("../enum/CommentState");var _CommentState2=_interopRequireDefault(_CommentState);var _constants=require("../util/constants");var _sort=require("../util/sort");var _v=require("../util/comments/v2");var _extractMentions=require("../util/comments/extractMentions");var _extractMentions2=_interopRequireDefault(_extractMentions);var _parseComment=require("../util/comments/parseComment");var _parseComment2=_interopRequireDefault(_parseComment);var _creationToken=require("../util/creationToken");var _throttle=require("../util/throttle");var _throttle2=_interopRequireDefault(_throttle);var _getCommentState=require("../util/comments/getCommentState");var _getCommentState2=_interopRequireDefault(_getCommentState);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&(typeof call==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+typeof superClass)}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}function getCommentDataFromPages(pages){var comments=[];Object.keys(pages).forEach(function(pageNumber){pages[pageNumber].Comments.forEach(function(commentData){comments.push(commentData)})});return comments}var _sortPages=(0,_sort.sortObjectsByKey)("pageNumber");var _sortCreatedDateDESC=(0,_sort.sortObjectsByKey)("createdDate",true);var _sortCreatedDateASC=(0,_sort.sortObjectsByKey)("createdDate",false);var sortComments=(0,_sort.combineSort)(_sortPages,_sortCreatedDateDESC);var sortReplies=(0,_sort.combineSort)(_sortPages,_sortCreatedDateASC);function mapComments(commentsData){var comments=[];var replies=[];commentsData.forEach(function(commentData){var entity=(new _Comment2.default).fromComment(commentData);if(entity.parentCommentId){replies.push(entity)}else{comments.push(entity)}});comments.sort(sortComments);var commentIds=comments.map(function(c){return c.id});var sortByParentCommentIndex=(0,_sort.sortObjectsBy)(function(r){return commentIds.indexOf(r.parentCommentId)},true);replies.sort((0,_sort.combineSort)(sortReplies,sortByParentCommentIndex));return comments.concat(replies)}var Comments=function(_API){_inherits(Comments,_API);function Comments(){_classCallCheck(this,Comments);return _possibleConstructorReturn(this,_API.apply(this,arguments))}Comments.prototype._mark=function _mark(commentId,state,value){if(Object.keys(_CommentState2.default).map(function(key){return _CommentState2.default[key]}).indexOf(state)===-1){throw new Error('Cannot mark comment state "'+state+'".')}var TODO=_CommentState2.default.TODO,DONE=_CommentState2.default.DONE,UNMARKED=_CommentState2.default.UNMARKED;var data={commentId:commentId};switch(state){case UNMARKED:{data.change=0;data.done=0;break}case TODO:{data.change=value?1:0;data.done=0;break}case DONE:{data.done=value?1:0;break}}return this.client.request("comments.state.update",data).then(function(response){return(0,_getCommentState2.default)(response.data)})};Comments.prototype._markAll=function _markAll(proofId,commentIds,state,value){if(Object.keys(_CommentState2.default).map(function(key){return _CommentState2.default[key]}).indexOf(state)===-1){throw new Error('Cannot mark comment state "'+state+'".')}var TODO=_CommentState2.default.TODO,DONE=_CommentState2.default.DONE,UNMARKED=_CommentState2.default.UNMARKED;var data={proofId:proofId,commentIds:commentIds};switch(state){case UNMARKED:{data.change=0;data.done=0;break}case TODO:{data.change=value?1:0;data.done=0;break}case DONE:{data.done=value?1:0;break}}return this.client.request("comments.state.multiple-update",data).then(function(response){return response.data.map(function(comment){return{commentId:comment.CommentId,commentState:(0,_getCommentState2.default)(comment)}})})};Comments.prototype.mark=function mark(commentId,state){return this._mark(commentId,state,true)};Comments.prototype.unmark=function unmark(commentId,state){return this._mark(commentId,state,false)};Comments.prototype.markAll=function markAll(proofId,commentIds,state){return this._markAll(proofId,commentIds,state,true)};Comments.prototype.unmarkAll=function unmarkAll(proofId,commentIds,state){return this._markAll(proofId,commentIds,state,false)};Comments.prototype.delete=function _delete(commentId){return this.client.request("comments.delete",{commentId:commentId})};Comments.prototype.load=function load(_options){var _this2=this;var options=typeof _options==="string"?{proofId:_options}:_options;var proofId=options.proofId,_options$pageNumber=options.pageNumber,pageNumber=_options$pageNumber===undefined?null:_options$pageNumber,_options$sinceDate=options.sinceDate,sinceDate=_options$sinceDate===undefined?null:_options$sinceDate,_options$async=options.async,async=_options$async===undefined?false:_options$async,_options$decrypt=options.decrypt,decrypt=_options$decrypt===undefined?true:_options$decrypt,onDecryptComment=options.onDecryptComment,onDecryptComments=options.onDecryptComments,_options$onDecryptCom=options.onDecryptCommentsThrottleMs,onDecryptCommentsThrottleMs=_options$onDecryptCom===undefined?1e3:_options$onDecryptCom,onDecryptError=options.onDecryptError;var sinceDateISO=sinceDate?sinceDate.toISOString().match(_constants.ISO_REGEX)[0]:_constants.DEFAULT_ISO_DATE;var payload={proofId:proofId,page:pageNumber,timestamp:sinceDateISO};return this.client.request(pageNumber!==null?"comments.load-page":"comments.load-all",payload).then(function(response){var comments=mapComments(response.data.Pages?getCommentDataFromPages(response.data.Pages):response.data);var wait=Promise.resolve();if(decrypt){var scheduled=[];var pendingBatch=[];var scheduleOnDecryptComments=onDecryptComments?(0,_throttle2.default)(function(){if(pendingBatch.length){onDecryptComments(pendingBatch);pendingBatch=[]}},onDecryptCommentsThrottleMs):function(){};var cached=Promise.all(comments.map(function(comment){return _this2.client.cache.auto(_constants.COMMENT_CACHE_PREFIX+comment.comment$,function(resolve){scheduled.push({comment:comment,resolve:resolve})}).then(function(rawComment){if(rawComment){comment.fromRawComment(rawComment)}return comment})}));wait=wait.then(function(){return cached});wait=wait.then(function(){var decrypted=scheduled.map(function(_ref){var comment=_ref.comment,resolve=_ref.resolve;return _this2.client.crypto().decryptComment(comment.comment$,comment.envelope,_this2.client.
|
|
1
|
+
"use strict";exports.__esModule=true;var _API2=require("./API");var _API3=_interopRequireDefault(_API2);var _Comment=require("../models/Comment");var _Comment2=_interopRequireDefault(_Comment);var _CommentState=require("../enum/CommentState");var _CommentState2=_interopRequireDefault(_CommentState);var _constants=require("../util/constants");var _sort=require("../util/sort");var _v=require("../util/comments/v2");var _extractMentions=require("../util/comments/extractMentions");var _extractMentions2=_interopRequireDefault(_extractMentions);var _parseComment=require("../util/comments/parseComment");var _parseComment2=_interopRequireDefault(_parseComment);var _creationToken=require("../util/creationToken");var _throttle=require("../util/throttle");var _throttle2=_interopRequireDefault(_throttle);var _getCommentState=require("../util/comments/getCommentState");var _getCommentState2=_interopRequireDefault(_getCommentState);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&(typeof call==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+typeof superClass)}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}function getCommentDataFromPages(pages){var comments=[];Object.keys(pages).forEach(function(pageNumber){pages[pageNumber].Comments.forEach(function(commentData){comments.push(commentData)})});return comments}var _sortPages=(0,_sort.sortObjectsByKey)("pageNumber");var _sortCreatedDateDESC=(0,_sort.sortObjectsByKey)("createdDate",true);var _sortCreatedDateASC=(0,_sort.sortObjectsByKey)("createdDate",false);var sortComments=(0,_sort.combineSort)(_sortPages,_sortCreatedDateDESC);var sortReplies=(0,_sort.combineSort)(_sortPages,_sortCreatedDateASC);function mapComments(commentsData){var comments=[];var replies=[];commentsData.forEach(function(commentData){var entity=(new _Comment2.default).fromComment(commentData);if(entity.parentCommentId){replies.push(entity)}else{comments.push(entity)}});comments.sort(sortComments);var commentIds=comments.map(function(c){return c.id});var sortByParentCommentIndex=(0,_sort.sortObjectsBy)(function(r){return commentIds.indexOf(r.parentCommentId)},true);replies.sort((0,_sort.combineSort)(sortReplies,sortByParentCommentIndex));return comments.concat(replies)}var Comments=function(_API){_inherits(Comments,_API);function Comments(){_classCallCheck(this,Comments);return _possibleConstructorReturn(this,_API.apply(this,arguments))}Comments.prototype._mark=function _mark(commentId,state,value){if(Object.keys(_CommentState2.default).map(function(key){return _CommentState2.default[key]}).indexOf(state)===-1){throw new Error('Cannot mark comment state "'+state+'".')}var TODO=_CommentState2.default.TODO,DONE=_CommentState2.default.DONE,UNMARKED=_CommentState2.default.UNMARKED;var data={commentId:commentId};switch(state){case UNMARKED:{data.change=0;data.done=0;break}case TODO:{data.change=value?1:0;data.done=0;break}case DONE:{data.done=value?1:0;break}}return this.client.request("comments.state.update",data).then(function(response){return(0,_getCommentState2.default)(response.data)})};Comments.prototype._markAll=function _markAll(proofId,commentIds,state,value){if(Object.keys(_CommentState2.default).map(function(key){return _CommentState2.default[key]}).indexOf(state)===-1){throw new Error('Cannot mark comment state "'+state+'".')}var TODO=_CommentState2.default.TODO,DONE=_CommentState2.default.DONE,UNMARKED=_CommentState2.default.UNMARKED;var data={proofId:proofId,commentIds:commentIds};switch(state){case UNMARKED:{data.change=0;data.done=0;break}case TODO:{data.change=value?1:0;data.done=0;break}case DONE:{data.done=value?1:0;break}}return this.client.request("comments.state.multiple-update",data).then(function(response){return response.data.map(function(comment){return{commentId:comment.CommentId,commentState:(0,_getCommentState2.default)(comment)}})})};Comments.prototype.mark=function mark(commentId,state){return this._mark(commentId,state,true)};Comments.prototype.unmark=function unmark(commentId,state){return this._mark(commentId,state,false)};Comments.prototype.markAll=function markAll(proofId,commentIds,state){return this._markAll(proofId,commentIds,state,true)};Comments.prototype.unmarkAll=function unmarkAll(proofId,commentIds,state){return this._markAll(proofId,commentIds,state,false)};Comments.prototype.delete=function _delete(commentId){return this.client.request("comments.delete",{commentId:commentId})};Comments.prototype.load=function load(_options){var _this2=this;var options=typeof _options==="string"?{proofId:_options}:_options;var proofId=options.proofId,_options$pageNumber=options.pageNumber,pageNumber=_options$pageNumber===undefined?null:_options$pageNumber,_options$sinceDate=options.sinceDate,sinceDate=_options$sinceDate===undefined?null:_options$sinceDate,_options$async=options.async,async=_options$async===undefined?false:_options$async,_options$decrypt=options.decrypt,decrypt=_options$decrypt===undefined?true:_options$decrypt,onDecryptComment=options.onDecryptComment,onDecryptComments=options.onDecryptComments,_options$onDecryptCom=options.onDecryptCommentsThrottleMs,onDecryptCommentsThrottleMs=_options$onDecryptCom===undefined?1e3:_options$onDecryptCom,onDecryptError=options.onDecryptError;var sinceDateISO=sinceDate?sinceDate.toISOString().match(_constants.ISO_REGEX)[0]:_constants.DEFAULT_ISO_DATE;var payload={proofId:proofId,page:pageNumber,timestamp:sinceDateISO};return this.client.request(pageNumber!==null?"comments.load-page":"comments.load-all",payload).then(function(response){var comments=mapComments(response.data.Pages?getCommentDataFromPages(response.data.Pages):response.data);var wait=Promise.resolve();if(decrypt){var scheduled=[];var pendingBatch=[];var scheduleOnDecryptComments=onDecryptComments?(0,_throttle2.default)(function(){if(pendingBatch.length){onDecryptComments(pendingBatch);pendingBatch=[]}},onDecryptCommentsThrottleMs):function(){};var cached=Promise.all(comments.map(function(comment){return _this2.client.cache.auto(_constants.COMMENT_CACHE_PREFIX+comment.comment$,function(resolve){scheduled.push({comment:comment,resolve:resolve})}).then(function(rawComment){if(rawComment){comment.fromRawComment(rawComment)}return comment})}));wait=wait.then(function(){return cached});wait=wait.then(function(){var decrypted=scheduled.map(function(_ref){var comment=_ref.comment,resolve=_ref.resolve;return _this2.client.crypto().decryptComment(comment.comment$,comment.envelope,_this2.client.keyPairs.getPrivateKeyPEMs()).then(function(rawComment){comment.fromRawComment(rawComment);resolve(rawComment);if(onDecryptComment){onDecryptComment(comment)}pendingBatch.push(comment);scheduleOnDecryptComments()}).catch(function(err){if(onDecryptError){onDecryptError(err,comment)}if(!async){return Promise.reject(err)}return undefined})});if(!async){return Promise.all(decrypted)}return null})}return wait.then(function(){return comments})})};Comments.prototype.create=function create(_ref2){var _this3=this;var raw=_ref2.raw,tokens=_ref2.tokens,proofId=_ref2.proofId,_ref2$pageNumber=_ref2.pageNumber,pageNumber=_ref2$pageNumber===undefined?1:_ref2$pageNumber,pin=_ref2.pin,mediaTime=_ref2.mediaTime,mediaDuration=_ref2.mediaDuration,parentCommentId=_ref2.parentCommentId,metadata=_ref2.metadata,state=_ref2.state,retryCreationToken=_ref2.creationToken;var mentions=[];var serialized=raw||(0,_v.serialize)(tokens);{var parsed=tokens||(0,_parseComment2.default)(raw);mentions.push.apply(mentions,(0,_extractMentions2.default)(parsed))}var creationToken=retryCreationToken||(0,_creationToken.generateCreationToken)();return this.client.crypto().encryptComment(serialized,this.client.keyPairs.getPublicKeyPEMs()).then(function(_ref3){var envelope=_ref3.envelope,comment$=_ref3.comment$;return{proofId:proofId,page:parentCommentId?undefined:pageNumber,envelope:envelope,encryptedComment:comment$,xy:JSON.stringify({x:pin&&typeof pin.x==="number"?pin.x:null,y:pin&&typeof pin.y==="number"?pin.y:null,x2:pin&&typeof pin.x2==="number"?pin.x2:null,y2:pin&&typeof pin.y2==="number"?pin.y2:null,time:typeof mediaTime==="number"?mediaTime:null,duration:typeof mediaDuration==="number"?mediaDuration:null}),boxFillImage:pin.fill?pin.fill.image:undefined,boxFillType:pin.fill?pin.fill.type:undefined,parent:parentCommentId||undefined,mentions:mentions,metadata:metadata?JSON.stringify(metadata):"{}",creationToken:creationToken,change:state===_CommentState2.default.TODO?"1":undefined,done:state===_CommentState2.default.DONE?"1":undefined}}).then(function(requestData){return _this3.client.request("comments.create",requestData).then(function(response){return(new _Comment2.default).fromComment(response.data).fromRawComment(serialized)})}).catch(function(err){if(err){err.creationToken=creationToken}return Promise.reject(err)})};return Comments}(_API3.default);exports.default=Comments;
|
package/lib/api/Files.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.__esModule=true;var _API2=require("./API");var _API3=_interopRequireDefault(_API2);var _File=require("../models/File");var _File2=_interopRequireDefault(_File);var _FileStatus=require("../enum/FileStatus");var _FileStatus2=_interopRequireDefault(_FileStatus);var _ImportProvider=require("../enum/ImportProvider");var _ImportProvider2=_interopRequireDefault(_ImportProvider);var _streamBlocks=require("../util/streamBlocks");var _streamBlocks2=_interopRequireDefault(_streamBlocks);var _bluffer=require("../bluffer");var _bluffer2=_interopRequireDefault(_bluffer);var _getContentLength=require("../util/getContentLength");var _getContentLength2=_interopRequireDefault(_getContentLength);var _constants=require("../util/constants");var _throttle=require("../util/throttle");var _throttle2=_interopRequireDefault(_throttle);var _concurrent=require("../util/concurrent");var _concurrent2=_interopRequireDefault(_concurrent);var _sleep=require("../util/sleep");var _sleep2=_interopRequireDefault(_sleep);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _objectWithoutProperties(obj,keys){var target={};for(var i in obj){if(keys.indexOf(i)>=0)continue;if(!Object.prototype.hasOwnProperty.call(obj,i))continue;target[i]=obj[i]}return target}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&(typeof call==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+typeof superClass)}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}function parseFilename(filename){var extensionIndex=filename.lastIndexOf(".");var name=filename.substring(0,extensionIndex);var extension=filename.substring(extensionIndex+1);return{name:name,extension:extension}}function containPercentage(percent,left,right){var total=1-(left+right);return total*percent+left}var Files=function(_API){_inherits(Files,_API);function Files(){_classCallCheck(this,Files);return _possibleConstructorReturn(this,_API.apply(this,arguments))}Files.prototype.generateToken=function generateToken(assignedTo,assignedType){if(assignedTo&&!assignedType){return Promise.reject(Error('The "assignedType" option is required when specifying the "assignedTo" option.'))}if(!assignedTo&&assignedType){return Promise.reject(Error('The "assignedTo" option is required when specifying the "assignedType" option.'))}return this.client.request("files.legacy.generate-token",{relatedId:assignedTo,fileType:assignedType}).then(function(response){return response.data.Token})};Files.prototype.setCanDownload=function setCanDownload(fileId,canDownload){return this.client.request("files.can-download.update",{fileId:fileId,downloadOriginal:canDownload?1:0})};Files.prototype._waitFileProcessed=function _waitFileProcessed(id){var _this2=this;return new Promise(function(resolve,reject){var checkTimeout=null;var timeoutTimeout=null;var check=function check(){_this2.details(id).then(function(file){checkTimeout=null;switch(file.status){case _FileStatus2.default.OK:{resolve(file);break}case _FileStatus2.default.ERROR:{reject(new Error("File "+id+" encountered a processing error: "+file.message));break}default:{checkTimeout=setTimeout(check,5e3);break}}if(!checkTimeout||file.status===_FileStatus2.default.RIPPING){clearTimeout(timeoutTimeout)}}).catch(reject)};check();timeoutTimeout=setTimeout(function(){clearTimeout(checkTimeout);reject(new Error("File did not finish processing within specified duration."))},3e4)})};Files.prototype._createWebsiteFile=function _createWebsiteFile(url){var _this3=this;return this._generateKeyIVEnvelope().then(function(_ref){var envelope=_ref.envelope;return _this3.client.request("files.import.web",{url:url,envelope:envelope})}).then(function(response){return response.data})};Files.prototype._importFileFromUrl=function _importFileFromUrl(_ref2){var _this4=this;var name=_ref2.name,url=_ref2.url,provider=_ref2.provider,auth=_ref2.auth,download=_ref2.download;var endpoint=provider;if(provider===_ImportProvider2.default.NONE){endpoint="generic"}var _parseFilename=parseFilename(name),filename=_parseFilename.name,extension=_parseFilename.extension;return this._generateKeyIVEnvelope().then(function(_ref3){var envelope=_ref3.envelope;return _this4.client.request("files.import."+endpoint,{extn:extension,filename:filename,url:url,envelope:envelope,accessToken:auth,storeOriginal:download})}).then(function(response){return response.data})};Files.prototype.import=function _import(_ref4){var _this5=this;var name=_ref4.name,url=_ref4.url,_ref4$provider=_ref4.provider,provider=_ref4$provider===undefined?_ImportProvider2.default.NONE:_ref4$provider,auth=_ref4.auth,_ref4$download=_ref4.download,download=_ref4$download===undefined?false:_ref4$download,_ref4$process=_ref4.process,process=_ref4$process===undefined?false:_ref4$process;var providerSupported=Object.keys(_ImportProvider2.default).some(function(key){return _ImportProvider2.default[key]===provider});if(!providerSupported){return Promise.reject(new Error('Unsupported provider "'+provider+'"'))}return(provider===_ImportProvider2.default.WEBSITE?this._createWebsiteFile(url):this._importFileFromUrl({name:name,url:url,provider:provider,auth:auth,download:download})).then(function(token){if(process){return _this5._waitFileProcessed(token)}else{var file=new _File2.default;file.id=token;return file}})};Files.prototype.email=function email(){return this.client.request("files.create-email").then(function(response){return response.data})};Files.prototype._generateKeyIVEnvelope=function _generateKeyIVEnvelope(){var _this6=this;return this.client.crypto().generateKeyIV().then(function(keyIV){return Promise.all([keyIV,_this6.client.crypto().envelopeSeal(keyIV.keyIV,[_this6.client.session.serverPublicKeyPEM,_this6.client.session.publicKeyPEM])])}).then(function(_ref5){var keyIV=_ref5[0],envelope=_ref5[1];return{keyIV:keyIV,envelope:envelope}})};Files.prototype.upload=function upload(){return this.upload__v2.apply(this,arguments)};Files.prototype.upload__v2=function upload__v2(files){var _this7=this;var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var _options$concurrent=options.concurrent,concurrency=_options$concurrent===undefined?6:_options$concurrent,opts=_objectWithoutProperties(options,["concurrent"]);var scheduleChunk=(0,_concurrent2.default)(concurrency);var scheduleDone=(0,_concurrent2.default)(1);var doneFiles=[];var multipleFiles=Array.isArray(files);var filesList=multipleFiles?files:[files];var done=function done(result){doneFiles.push(result);return scheduleDone(function(){if(doneFiles.length){var _doneFiles=doneFiles.slice();doneFiles.length=0;return _this7.client.request("files.v2.upload-complete",{files:_doneFiles})}return null})};return this.client.request("files.v2.generate-credentials",{supports:{providers:["abs","custom"]},files:filesList.map(function(file){var name=void 0;var extension=void 0;if(file.extension){var _ref6=[file.name,file.extension];name=_ref6[0];extension=_ref6[1]}else{var parsed=parseFilename(file.name);var _ref7=[parsed.name,parsed.extension];name=_ref7[0];extension=_ref7[1]}var size=(0,_getContentLength2.default)(file.contents);var chunks=Math.ceil(size/_constants.BYTES_PER_BLOCK);if(file.onProgress){file.onProgress(0)}return{name:name,extension:extension,chunks:chunks,size:size,hash:null,adobeExportData:file.adobeExportData?JSON.stringify(file.adobeExportData):null,assignedTo:file.assignedTo,assignedType:file.assignedType,canDownload:typeof file.download!=="undefined"?!!file.download:true}})}).then(function(response){return Promise.all(filesList.map(function(file,index){var definition=response.data[index];if(file.onProgress){file.onProgress(1)}var entity=new _File2.default;entity.id=definition.FileId;if(file.onFileDetails){file.onFileDetails(entity)}return _this7._upload__v2(file,definition,opts,scheduleChunk,done).then(function(){return entity})}))}).then(function(results){return multipleFiles?results:results[0]})};Files.prototype._upload__v2=function _upload__v2(file,definition,options,schedule,done){var _this8=this;return this._generateKeyIVEnvelope().then(function(_ref8){var keyIV=_ref8.keyIV,envelope=_ref8.envelope;return new Promise(function(resolve,reject){var fileId=definition.FileId,uploadCredentials=definition.UploadCredentials;var bluffer=new _bluffer2.default;var complete=false;var index=0;var blocks=(0,_streamBlocks2.default)(file.contents,function(b){return bluffer.readBase64(b)});var tasks=[];var count=Math.ceil((0,_getContentLength2.default)(file.contents)/_constants.BYTES_PER_BLOCK);var percent=new Array(count);var lastPercent=1;var onUploadProgress=function onUploadProgress(){};var onProgress=file.onProgress;if(onProgress){onUploadProgress=function onUploadProgress(blockIndex,progress){percent[blockIndex]=Math.max(progress,percent[blockIndex]||0);var totalPercent=containPercentage(percent.reduce(function(a,b){return a+(b||0)},0)/count/100,.01,.01)*100;if(typeof options.progressDecimalPlaces!=="undefined"){totalPercent=+totalPercent.toFixed(options.progressDecimalPlaces)}if(lastPercent!==totalPercent){onProgress(totalPercent);lastPercent=totalPercent}}}function handle(block,blockIndex){var task=encryptAndUpload(block,blockIndex);tasks.push(task);return task}var abs=function abs(block,blockIndex){return _this8.client.rawRequest({method:"PUT",host:uploadCredentials.url,path:"/"+fileId+"/"+blockIndex,query:uploadCredentials.sas,body:block,headers:{"x-ms-blob-type":"BlockBlob"}},{onUploadProgress:onUploadProgress.bind(null,blockIndex)})};var custom=function custom(block,blockIndex){var values={"file.id":fileId,"chunk.index":blockIndex};var interpolate=function interpolate(str){var map=arguments.length>1&&arguments[1]!==undefined?arguments[1]:function(a){return a};return str.replace(/\{([\w\.]+)\}/g,function(_,key){return map(values[key])})};var interpolatedHeaders={};Object.keys(uploadCredentials.headers).forEach(function(name){var value=interpolate(uploadCredentials.headers[name]);interpolatedHeaders[interpolate(name)]=value});return _this8.client.rawRequest({method:uploadCredentials.method,host:interpolate(uploadCredentials.host),path:interpolate(uploadCredentials.path,encodeURIComponent),query:interpolate(uploadCredentials.query,encodeURIComponent),body:block,headers:interpolatedHeaders},{onUploadProgress:onUploadProgress.bind(null,blockIndex)})};var uploadData={abs:abs,custom:custom}[uploadCredentials.type];var encryptAndUpload=function encryptAndUpload(block,blockIndex){return _this8.client.crypto().encryptFileBlock(keyIV,block,true).then(function(block$_){return bluffer.createBase64(block$_)}).then(function(block$){var retries=0;var chunkRetryLimit=typeof options.chunkRetryLimit!=="undefined"?options.chunkRetryLimit:3;function attemptUploadData(){return uploadData(block$,blockIndex).then(function(response){if([200,201].indexOf(response.status)===-1){if(retries<chunkRetryLimit){retries++;if(options.chunkRetryDelay){return(0,_sleep2.default)(options.chunkRetryDelay).then(attemptUploadData)}return attemptUploadData()}else{var err=new Error("Failed to upload block #"+blockIndex+" (retried "+retries+" times).");reject(err);complete=true;throw err}}return response})}return attemptUploadData()})};var finish=function finish(){return done({fileId:fileId,envelope:envelope}).then(function(){if(onProgress)onProgress(100)})};function next(){if(complete){return}schedule(function(){return blocks().then(function(data){if(data){next();return handle(data,index++)}else if(!complete){complete=true;var final=Promise.all(tasks).then(finish);resolve(final)}})})}next();if(file.async!==false){resolve()}})})};Files.prototype.upload__legacy=function upload__legacy(_ref9){var _this9=this;var name=_ref9.name,contents=_ref9.contents,adobeExportData=_ref9.adobeExportData,assignedTo=_ref9.assignedTo,assignedType=_ref9.assignedType,_ref9$download=_ref9.download,download=_ref9$download===undefined?false:_ref9$download,_ref9$async=_ref9.async,async=_ref9$async===undefined?true:_ref9$async,onProgress=_ref9.onProgress,onError=_ref9.onError;return this.generateToken(assignedTo,assignedType).then(function(token){return Promise.all([token,_this9._generateKeyIVEnvelope()])}).then(function(_ref10){var token=_ref10[0],_ref10$=_ref10[1],keyIV=_ref10$.keyIV,envelope=_ref10$.envelope;var process=_this9._upload__legacy({name:name,contents:contents,adobeExportData:adobeExportData,download:download,token:token,keyIV:keyIV,envelope:envelope,onProgress:onProgress,onError:onError});if(async){process=Promise.resolve()}return process.then(function(){return token})}).then(function(token){var file=new _File2.default;file.id=token;return file})};Files.prototype._upload__legacy=function _upload__legacy(_ref11){var _this10=this;var name=_ref11.name,contents=_ref11.contents,adobeExportData=_ref11.adobeExportData,download=_ref11.download,token=_ref11.token,keyIV=_ref11.keyIV,envelope=_ref11.envelope,onProgress=_ref11.onProgress;return new Promise(function(resolve){var concurrent=4;var _parseFilename2=parseFilename(name),filename=_parseFilename2.name,extension=_parseFilename2.extension;var blocks=(0,_streamBlocks2.default)(contents);var chain=Promise.resolve();var index=0;var end=false;var count=Math.ceil((0,_getContentLength2.default)(contents)/_constants.BYTES_PER_BLOCK);var percent=new Array(count);var onUploadProgress=function onUploadProgress(){};if(onProgress){onUploadProgress=function onUploadProgress(blockIndex,progress){percent[blockIndex]=Math.max(progress,percent[blockIndex]||0);onProgress(percent.reduce(function(a,b){return a+(b||0)},0)/count*.99)}}var process=function process(block,blockIndex){return _this10.client.crypto().encryptFileBlock(keyIV,block).then(function(block$){return _this10.client.request("files.legacy.upload-block",{block:blockIndex,part:1,token:token,data:block$},{onUploadProgress:onUploadProgress.bind(null,blockIndex)})})};function next(){blocks().then(function(block){if(end)return;if(block===null){end=true;resolve(chain.then(complete))}else{var handle=process(block,index++);chain=chain.then(function(){return handle});handle.then(next)}})}var complete=function complete(){return _this10.client.request("files.legacy.upload-complete",{block:0,blockCount:index,part:0,token:token,extn:extension,pages:1,filename:filename,storeoriginal:download?1:0,adobeExportData:adobeExportData?JSON.stringify(adobeExportData):null,envelope:envelope}).then(function(){return onProgress&&onProgress(100)})};while(concurrent--){next()}})};Files.prototype.download=function download(_options){var _this11=this;var options=typeof _options==="string"?{fileId:_options}:_options;var fileId=options.fileId,onFileDetails=options.onFileDetails;return this.details(fileId).then(function(file){if(!file.downloadable){throw new Error("File "+fileId+" is not downloadable.")}if(file.status!==_FileStatus2.default.OK){throw new Error("File "+fileId+" cannot be download. The file may still be uploading, processing or has errored.")}if(!file.blocks){throw new Error("File "+fileId+" is empty.")}if(onFileDetails){onFileDetails(file)}return _this11._downloadFile(file,options)})};Files.prototype._downloadFile=function _downloadFile(file,options){var _this12=this;return new Promise(function(resolve){var concurrent=4;var bluffer=new _bluffer2.default;var count=file.blocks;var blocks=new Array(count);var chain=Promise.resolve();var onData=options.onData||function onData(block,index){blocks[index]=block};var onDownloadProgress=function onDownloadProgress(){};if(options.onProgress){var percent=new Array(count);onDownloadProgress=function onDownloadProgress(blockIndex,progress){percent[blockIndex]=Math.max(progress,percent[blockIndex]||0);options.onProgress(percent.reduce(function(a,b){return a+(b||0)},0)/count*.99)}}var process=function process(blockIndex){return _this12.client.request("files.download-block",{proofId:file.assignedTo,fileId:file.id,block:blockIndex+1,s:options.silent?1:undefined},{onDownloadProgress:onDownloadProgress.bind(null,blockIndex)}).then(function(response){return _this12.client.crypto().decryptFileBlock(response.data,_this12.client.session.privateKeyPEM).then(function(blockBase64){return bluffer.createBase64(blockBase64)})})};var index=0;var end=false;function next(){if(end)return;if(index<blocks.length){var blockIndex=index++;var block=process(blockIndex);chain=chain.then(function(){return block.then(function(data){return onData(data,blockIndex,count)})});block.then(next)}else{end=true;resolve(chain.then(complete))}}var complete=function complete(){if(options.onProgress){options.onProgress(100)}if(!options.onData){return bluffer.combine.apply(bluffer,blocks)}return null};while(concurrent--){next()}})};Files.prototype.details=function details(fileId){return this.client.request("files.details",{fileId:fileId}).then(function(response){return(new _File2.default).fromFile(response.data)})};Files.prototype.thumbnail=function thumbnail(fileId){var _this13=this;return this.client.cache.auto(_constants.THUMBNAIL_CACHE_PREFIX+fileId,function(){return _this13._thumbnail(fileId)})};Files.prototype._thumbnail=function _thumbnail(fileId){var _this14=this;return this.client.request("files.thumbnail",{fileId:fileId}).then(function(response){return _this14.client.crypto().decryptImage(response.data,_this14.client.session.privateKeyPEM)}).then(function(imageBase64){var bluffer=new _bluffer2.default;return bluffer.createBase64(imageBase64)})};Files.prototype.thumbnails=function thumbnails(fileIds,_ref12){var _this15=this;var _ref12$async=_ref12.async,async=_ref12$async===undefined?false:_ref12$async,onLoadThumbnail=_ref12.onLoadThumbnail,onLoadThumbnails=_ref12.onLoadThumbnails,_ref12$onLoadThumbnai=_ref12.onLoadThumbnailsThrottleMs,onLoadThumbnailsThrottleMs=_ref12$onLoadThumbnai===undefined?1e3:_ref12$onLoadThumbnai,onLoadError=_ref12.onLoadError;var scheduled=[];var pendingBatch={};var scheduleOnLoadThumbnails=onLoadThumbnails?(0,_throttle2.default)(function(){if(Object.keys(pendingBatch).length){onLoadThumbnails(pendingBatch);pendingBatch={}}},onLoadThumbnailsThrottleMs):function(){};return Promise.all(fileIds.map(function(fileId){return _this15.client.cache.auto(_constants.THUMBNAIL_CACHE_PREFIX+fileId,function(resolve){scheduled.push({fileId:fileId,resolve:resolve})}).then(function(thumbnail){var _ref13;return thumbnail&&(_ref13={},_ref13[fileId]=thumbnail,_ref13)})})).then(function(entries){var more=Promise.all(scheduled.map(function(_ref14){var fileId=_ref14.fileId,resolve=_ref14.resolve;return _this15._thumbnail(fileId).then(function(thumbnail){var _ref15;resolve(thumbnail);if(onLoadThumbnail){var _onLoadThumbnail;onLoadThumbnail((_onLoadThumbnail={},_onLoadThumbnail[fileId]=thumbnail,_onLoadThumbnail))}pendingBatch[fileId]=thumbnail;scheduleOnLoadThumbnails();return _ref15={},_ref15[fileId]=thumbnail,_ref15}).catch(function(err){if(onLoadError){onLoadError(err,fileId)}if(!async){return Promise.reject(err)}return{}})}));if(async){return entries}else{return more.then(function(moreEntries){return[].concat(entries,moreEntries)})}}).then(function(entries){return Object.assign.apply(Object,[{}].concat(entries))})};return Files}(_API3.default);exports.default=Files;
|
|
1
|
+
"use strict";exports.__esModule=true;var _API2=require("./API");var _API3=_interopRequireDefault(_API2);var _File=require("../models/File");var _File2=_interopRequireDefault(_File);var _FileStatus=require("../enum/FileStatus");var _FileStatus2=_interopRequireDefault(_FileStatus);var _ImportProvider=require("../enum/ImportProvider");var _ImportProvider2=_interopRequireDefault(_ImportProvider);var _streamBlocks=require("../util/streamBlocks");var _streamBlocks2=_interopRequireDefault(_streamBlocks);var _bluffer=require("../bluffer");var _bluffer2=_interopRequireDefault(_bluffer);var _getContentLength=require("../util/getContentLength");var _getContentLength2=_interopRequireDefault(_getContentLength);var _constants=require("../util/constants");var _throttle=require("../util/throttle");var _throttle2=_interopRequireDefault(_throttle);var _concurrent=require("../util/concurrent");var _concurrent2=_interopRequireDefault(_concurrent);var _sleep=require("../util/sleep");var _sleep2=_interopRequireDefault(_sleep);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _objectWithoutProperties(obj,keys){var target={};for(var i in obj){if(keys.indexOf(i)>=0)continue;if(!Object.prototype.hasOwnProperty.call(obj,i))continue;target[i]=obj[i]}return target}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&(typeof call==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+typeof superClass)}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}function parseFilename(filename){var extensionIndex=filename.lastIndexOf(".");var name=filename.substring(0,extensionIndex);var extension=filename.substring(extensionIndex+1);return{name:name,extension:extension}}function containPercentage(percent,left,right){var total=1-(left+right);return total*percent+left}var Files=function(_API){_inherits(Files,_API);function Files(){_classCallCheck(this,Files);return _possibleConstructorReturn(this,_API.apply(this,arguments))}Files.prototype.generateToken=function generateToken(assignedTo,assignedType){if(assignedTo&&!assignedType){return Promise.reject(Error('The "assignedType" option is required when specifying the "assignedTo" option.'))}if(!assignedTo&&assignedType){return Promise.reject(Error('The "assignedTo" option is required when specifying the "assignedType" option.'))}return this.client.request("files.legacy.generate-token",{relatedId:assignedTo,fileType:assignedType}).then(function(response){return response.data.Token})};Files.prototype.setCanDownload=function setCanDownload(fileId,canDownload){return this.client.request("files.can-download.update",{fileId:fileId,downloadOriginal:canDownload?1:0})};Files.prototype._waitFileProcessed=function _waitFileProcessed(id){var _this2=this;return new Promise(function(resolve,reject){var checkTimeout=null;var timeoutTimeout=null;var check=function check(){_this2.details(id).then(function(file){checkTimeout=null;switch(file.status){case _FileStatus2.default.OK:{resolve(file);break}case _FileStatus2.default.ERROR:{reject(new Error("File "+id+" encountered a processing error: "+file.message));break}default:{checkTimeout=setTimeout(check,5e3);break}}if(!checkTimeout||file.status===_FileStatus2.default.RIPPING){clearTimeout(timeoutTimeout)}}).catch(reject)};check();timeoutTimeout=setTimeout(function(){clearTimeout(checkTimeout);reject(new Error("File did not finish processing within specified duration."))},3e4)})};Files.prototype._createWebsiteFile=function _createWebsiteFile(url){var _this3=this;return this._generateKeyIVEnvelope().then(function(_ref){var envelope=_ref.envelope;return _this3.client.request("files.import.web",{url:url,envelope:envelope})}).then(function(response){return response.data})};Files.prototype._importFileFromUrl=function _importFileFromUrl(_ref2){var _this4=this;var name=_ref2.name,url=_ref2.url,provider=_ref2.provider,auth=_ref2.auth,download=_ref2.download;var endpoint=provider;if(provider===_ImportProvider2.default.NONE){endpoint="generic"}var _parseFilename=parseFilename(name),filename=_parseFilename.name,extension=_parseFilename.extension;return this._generateKeyIVEnvelope().then(function(_ref3){var envelope=_ref3.envelope;return _this4.client.request("files.import."+endpoint,{extn:extension,filename:filename,url:url,envelope:envelope,accessToken:auth,storeOriginal:download})}).then(function(response){return response.data})};Files.prototype.import=function _import(_ref4){var _this5=this;var name=_ref4.name,url=_ref4.url,_ref4$provider=_ref4.provider,provider=_ref4$provider===undefined?_ImportProvider2.default.NONE:_ref4$provider,auth=_ref4.auth,_ref4$download=_ref4.download,download=_ref4$download===undefined?false:_ref4$download,_ref4$process=_ref4.process,process=_ref4$process===undefined?false:_ref4$process;var providerSupported=Object.keys(_ImportProvider2.default).some(function(key){return _ImportProvider2.default[key]===provider});if(!providerSupported){return Promise.reject(new Error('Unsupported provider "'+provider+'"'))}return(provider===_ImportProvider2.default.WEBSITE?this._createWebsiteFile(url):this._importFileFromUrl({name:name,url:url,provider:provider,auth:auth,download:download})).then(function(token){if(process){return _this5._waitFileProcessed(token)}else{var file=new _File2.default;file.id=token;return file}})};Files.prototype.email=function email(){return this.client.request("files.create-email").then(function(response){return response.data})};Files.prototype._generateKeyIVEnvelope=function _generateKeyIVEnvelope(){var _this6=this;return this.client.crypto().generateKeyIV().then(function(keyIV){return Promise.all([keyIV,_this6.client.crypto().envelopeSeal(keyIV.keyIV,[_this6.client.session.serverPublicKeyPEM,_this6.client.session.publicKeyPEM])])}).then(function(_ref5){var keyIV=_ref5[0],envelope=_ref5[1];return{keyIV:keyIV,envelope:envelope}})};Files.prototype.upload=function upload(){return this.upload__v2.apply(this,arguments)};Files.prototype.upload__v2=function upload__v2(files){var _this7=this;var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var _options$concurrent=options.concurrent,concurrency=_options$concurrent===undefined?6:_options$concurrent,opts=_objectWithoutProperties(options,["concurrent"]);var scheduleChunk=(0,_concurrent2.default)(concurrency);var scheduleDone=(0,_concurrent2.default)(1);var doneFiles=[];var multipleFiles=Array.isArray(files);var filesList=multipleFiles?files:[files];var done=function done(result){doneFiles.push(result);return scheduleDone(function(){if(doneFiles.length){var _doneFiles=doneFiles.slice();doneFiles.length=0;return _this7.client.request("files.v2.upload-complete",{files:_doneFiles})}return null})};return this.client.request("files.v2.generate-credentials",{supports:{providers:["abs","custom"]},files:filesList.map(function(file){var name=void 0;var extension=void 0;if(file.extension){var _ref6=[file.name,file.extension];name=_ref6[0];extension=_ref6[1]}else{var parsed=parseFilename(file.name);var _ref7=[parsed.name,parsed.extension];name=_ref7[0];extension=_ref7[1]}var size=(0,_getContentLength2.default)(file.contents);var chunks=Math.ceil(size/_constants.BYTES_PER_BLOCK);if(file.onProgress){file.onProgress(0)}return{name:name,extension:extension,chunks:chunks,size:size,hash:null,adobeExportData:file.adobeExportData?JSON.stringify(file.adobeExportData):null,assignedTo:file.assignedTo,assignedType:file.assignedType,canDownload:typeof file.download!=="undefined"?!!file.download:true}})}).then(function(response){return Promise.all(filesList.map(function(file,index){var definition=response.data[index];if(file.onProgress){file.onProgress(1)}var entity=new _File2.default;entity.id=definition.FileId;if(file.onFileDetails){file.onFileDetails(entity)}return _this7._upload__v2(file,definition,opts,scheduleChunk,done).then(function(){return entity})}))}).then(function(results){return multipleFiles?results:results[0]})};Files.prototype._upload__v2=function _upload__v2(file,definition,options,schedule,done){var _this8=this;return this._generateKeyIVEnvelope().then(function(_ref8){var keyIV=_ref8.keyIV,envelope=_ref8.envelope;return new Promise(function(resolve,reject){var fileId=definition.FileId,uploadCredentials=definition.UploadCredentials;var bluffer=new _bluffer2.default;var complete=false;var index=0;var blocks=(0,_streamBlocks2.default)(file.contents,function(b){return bluffer.readBase64(b)});var tasks=[];var count=Math.ceil((0,_getContentLength2.default)(file.contents)/_constants.BYTES_PER_BLOCK);var percent=new Array(count);var lastPercent=1;var onUploadProgress=function onUploadProgress(){};var onProgress=file.onProgress;if(onProgress){onUploadProgress=function onUploadProgress(blockIndex,progress){percent[blockIndex]=Math.max(progress,percent[blockIndex]||0);var totalPercent=containPercentage(percent.reduce(function(a,b){return a+(b||0)},0)/count/100,.01,.01)*100;if(typeof options.progressDecimalPlaces!=="undefined"){totalPercent=+totalPercent.toFixed(options.progressDecimalPlaces)}if(lastPercent!==totalPercent){onProgress(totalPercent);lastPercent=totalPercent}}}function handle(block,blockIndex){var task=encryptAndUpload(block,blockIndex);tasks.push(task);return task}var abs=function abs(block,blockIndex){return _this8.client.rawRequest({method:"PUT",host:uploadCredentials.url,path:"/"+fileId+"/"+blockIndex,query:uploadCredentials.sas,body:block,headers:{"x-ms-blob-type":"BlockBlob"}},{onUploadProgress:onUploadProgress.bind(null,blockIndex)})};var custom=function custom(block,blockIndex){var values={"file.id":fileId,"chunk.index":blockIndex};var interpolate=function interpolate(str){var map=arguments.length>1&&arguments[1]!==undefined?arguments[1]:function(a){return a};return str.replace(/\{([\w\.]+)\}/g,function(_,key){return map(values[key])})};var interpolatedHeaders={};Object.keys(uploadCredentials.headers).forEach(function(name){var value=interpolate(uploadCredentials.headers[name]);interpolatedHeaders[interpolate(name)]=value});return _this8.client.rawRequest({method:uploadCredentials.method,host:interpolate(uploadCredentials.host),path:interpolate(uploadCredentials.path,encodeURIComponent),query:interpolate(uploadCredentials.query,encodeURIComponent),body:block,headers:interpolatedHeaders},{onUploadProgress:onUploadProgress.bind(null,blockIndex)})};var uploadData={abs:abs,custom:custom}[uploadCredentials.type];var encryptAndUpload=function encryptAndUpload(block,blockIndex){return _this8.client.crypto().encryptFileBlock(keyIV,block,true).then(function(block$_){return bluffer.createBase64(block$_)}).then(function(block$){var retries=0;var chunkRetryLimit=typeof options.chunkRetryLimit!=="undefined"?options.chunkRetryLimit:3;function attemptUploadData(){return uploadData(block$,blockIndex).then(function(response){if([200,201].indexOf(response.status)===-1){if(retries<chunkRetryLimit){retries++;if(options.chunkRetryDelay){return(0,_sleep2.default)(options.chunkRetryDelay).then(attemptUploadData)}return attemptUploadData()}else{var err=new Error("Failed to upload block #"+blockIndex+" (retried "+retries+" times).");reject(err);complete=true;throw err}}return response})}return attemptUploadData()})};var finish=function finish(){return done({fileId:fileId,envelope:envelope}).then(function(){if(onProgress)onProgress(100)})};function next(){if(complete){return}schedule(function(){return blocks().then(function(data){if(data){next();return handle(data,index++)}else if(!complete){complete=true;var final=Promise.all(tasks).then(finish);resolve(final)}})})}next();if(file.async!==false){resolve()}})})};Files.prototype.upload__legacy=function upload__legacy(_ref9){var _this9=this;var name=_ref9.name,contents=_ref9.contents,adobeExportData=_ref9.adobeExportData,assignedTo=_ref9.assignedTo,assignedType=_ref9.assignedType,_ref9$download=_ref9.download,download=_ref9$download===undefined?false:_ref9$download,_ref9$async=_ref9.async,async=_ref9$async===undefined?true:_ref9$async,onProgress=_ref9.onProgress,onError=_ref9.onError;return this.generateToken(assignedTo,assignedType).then(function(token){return Promise.all([token,_this9._generateKeyIVEnvelope()])}).then(function(_ref10){var token=_ref10[0],_ref10$=_ref10[1],keyIV=_ref10$.keyIV,envelope=_ref10$.envelope;var process=_this9._upload__legacy({name:name,contents:contents,adobeExportData:adobeExportData,download:download,token:token,keyIV:keyIV,envelope:envelope,onProgress:onProgress,onError:onError});if(async){process=Promise.resolve()}return process.then(function(){return token})}).then(function(token){var file=new _File2.default;file.id=token;return file})};Files.prototype._upload__legacy=function _upload__legacy(_ref11){var _this10=this;var name=_ref11.name,contents=_ref11.contents,adobeExportData=_ref11.adobeExportData,download=_ref11.download,token=_ref11.token,keyIV=_ref11.keyIV,envelope=_ref11.envelope,onProgress=_ref11.onProgress;return new Promise(function(resolve){var concurrent=4;var _parseFilename2=parseFilename(name),filename=_parseFilename2.name,extension=_parseFilename2.extension;var blocks=(0,_streamBlocks2.default)(contents);var chain=Promise.resolve();var index=0;var end=false;var count=Math.ceil((0,_getContentLength2.default)(contents)/_constants.BYTES_PER_BLOCK);var percent=new Array(count);var onUploadProgress=function onUploadProgress(){};if(onProgress){onUploadProgress=function onUploadProgress(blockIndex,progress){percent[blockIndex]=Math.max(progress,percent[blockIndex]||0);onProgress(percent.reduce(function(a,b){return a+(b||0)},0)/count*.99)}}var process=function process(block,blockIndex){return _this10.client.crypto().encryptFileBlock(keyIV,block).then(function(block$){return _this10.client.request("files.legacy.upload-block",{block:blockIndex,part:1,token:token,data:block$},{onUploadProgress:onUploadProgress.bind(null,blockIndex)})})};function next(){blocks().then(function(block){if(end)return;if(block===null){end=true;resolve(chain.then(complete))}else{var handle=process(block,index++);chain=chain.then(function(){return handle});handle.then(next)}})}var complete=function complete(){return _this10.client.request("files.legacy.upload-complete",{block:0,blockCount:index,part:0,token:token,extn:extension,pages:1,filename:filename,storeoriginal:download?1:0,adobeExportData:adobeExportData?JSON.stringify(adobeExportData):null,envelope:envelope}).then(function(){return onProgress&&onProgress(100)})};while(concurrent--){next()}})};Files.prototype.download=function download(_options){var _this11=this;var options=typeof _options==="string"?{fileId:_options}:_options;var fileId=options.fileId,onFileDetails=options.onFileDetails;return this.details(fileId).then(function(file){if(!file.downloadable){throw new Error("File "+fileId+" is not downloadable.")}if(file.status!==_FileStatus2.default.OK){throw new Error("File "+fileId+" cannot be download. The file may still be uploading, processing or has errored.")}if(!file.blocks){throw new Error("File "+fileId+" is empty.")}if(onFileDetails){onFileDetails(file)}return _this11._downloadFile(file,options)})};Files.prototype._downloadFile=function _downloadFile(file,options){var _this12=this;return new Promise(function(resolve){var concurrent=4;var bluffer=new _bluffer2.default;var count=file.blocks;var blocks=new Array(count);var chain=Promise.resolve();var onData=options.onData||function onData(block,index){blocks[index]=block};var onDownloadProgress=function onDownloadProgress(){};if(options.onProgress){var percent=new Array(count);onDownloadProgress=function onDownloadProgress(blockIndex,progress){percent[blockIndex]=Math.max(progress,percent[blockIndex]||0);options.onProgress(percent.reduce(function(a,b){return a+(b||0)},0)/count*.99)}}var process=function process(blockIndex){return _this12.client.request("files.download-block",{proofId:file.assignedTo,fileId:file.id,block:blockIndex+1,s:options.silent?1:undefined},{onDownloadProgress:onDownloadProgress.bind(null,blockIndex)}).then(function(response){return _this12.client.crypto().decryptFileBlock(response.data,_this12.client.keyPairs.getPrivateKeyPEMs()).then(function(blockBase64){return bluffer.createBase64(blockBase64)})})};var index=0;var end=false;function next(){if(end)return;if(index<blocks.length){var blockIndex=index++;var block=process(blockIndex);chain=chain.then(function(){return block.then(function(data){return onData(data,blockIndex,count)})});block.then(next)}else{end=true;resolve(chain.then(complete))}}var complete=function complete(){if(options.onProgress){options.onProgress(100)}if(!options.onData){return bluffer.combine.apply(bluffer,blocks)}return null};while(concurrent--){next()}})};Files.prototype.details=function details(fileId){return this.client.request("files.details",{fileId:fileId}).then(function(response){return(new _File2.default).fromFile(response.data)})};Files.prototype.thumbnail=function thumbnail(fileId){var _this13=this;return this.client.cache.auto(_constants.THUMBNAIL_CACHE_PREFIX+fileId,function(){return _this13._thumbnail(fileId)})};Files.prototype._thumbnail=function _thumbnail(fileId){var _this14=this;return this.client.request("files.thumbnail",{fileId:fileId}).then(function(response){return _this14.client.crypto().decryptImage(response.data,_this14.client.keyPairs.getPrivateKeyPEMs())}).then(function(imageBase64){var bluffer=new _bluffer2.default;return bluffer.createBase64(imageBase64)})};Files.prototype.thumbnails=function thumbnails(fileIds,_ref12){var _this15=this;var _ref12$async=_ref12.async,async=_ref12$async===undefined?false:_ref12$async,onLoadThumbnail=_ref12.onLoadThumbnail,onLoadThumbnails=_ref12.onLoadThumbnails,_ref12$onLoadThumbnai=_ref12.onLoadThumbnailsThrottleMs,onLoadThumbnailsThrottleMs=_ref12$onLoadThumbnai===undefined?1e3:_ref12$onLoadThumbnai,onLoadError=_ref12.onLoadError;var scheduled=[];var pendingBatch={};var scheduleOnLoadThumbnails=onLoadThumbnails?(0,_throttle2.default)(function(){if(Object.keys(pendingBatch).length){onLoadThumbnails(pendingBatch);pendingBatch={}}},onLoadThumbnailsThrottleMs):function(){};return Promise.all(fileIds.map(function(fileId){return _this15.client.cache.auto(_constants.THUMBNAIL_CACHE_PREFIX+fileId,function(resolve){scheduled.push({fileId:fileId,resolve:resolve})}).then(function(thumbnail){var _ref13;return thumbnail&&(_ref13={},_ref13[fileId]=thumbnail,_ref13)})})).then(function(entries){var more=Promise.all(scheduled.map(function(_ref14){var fileId=_ref14.fileId,resolve=_ref14.resolve;return _this15._thumbnail(fileId).then(function(thumbnail){var _ref15;resolve(thumbnail);if(onLoadThumbnail){var _onLoadThumbnail;onLoadThumbnail((_onLoadThumbnail={},_onLoadThumbnail[fileId]=thumbnail,_onLoadThumbnail))}pendingBatch[fileId]=thumbnail;scheduleOnLoadThumbnails();return _ref15={},_ref15[fileId]=thumbnail,_ref15}).catch(function(err){if(onLoadError){onLoadError(err,fileId)}if(!async){return Promise.reject(err)}return{}})}));if(async){return entries}else{return more.then(function(moreEntries){return[].concat(entries,moreEntries)})}}).then(function(entries){return Object.assign.apply(Object,[{}].concat(entries))})};return Files}(_API3.default);exports.default=Files;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.__esModule=true;var _API2=require("./API");var _API3=_interopRequireDefault(_API2);var _whatwgURL=require("../util/whatwgURL");var _whatwgURL2=_interopRequireDefault(_whatwgURL);var _bluffer=require("../bluffer");var _bluffer2=_interopRequireDefault(_bluffer);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&(typeof call==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+typeof superClass)}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var ProofsAssetsExtractedText=function(_API){_inherits(ProofsAssetsExtractedText,_API);function ProofsAssetsExtractedText(){_classCallCheck(this,ProofsAssetsExtractedText);return _possibleConstructorReturn(this,_API.apply(this,arguments))}ProofsAssetsExtractedText.prototype.resources=function resources(proofId){return this.client.request("proofs.assets.extracted-text",{proofId:proofId}).then(function(response){return response.data.result}).catch(function(err){if(err&&err.response&&err.response.code===400)return;throw err})};ProofsAssetsExtractedText.prototype.download=function download(resources,pageNumber){var _this2=this;var matchingPages=resources.pages.filter(function(page){return page.number===pageNumber});if(!matchingPages||!matchingPages.length){return Promise.reject(new Error("Page does not contain any text."))}var envelope=resources.envelope;var url=new _whatwgURL2.default(matchingPages[0].chunks[0].url);var bluffer=new _bluffer2.default;return this.client.rawRequest({method:"GET",url:url},{bluffer:true}).then(function(response){return response.body}).then(function(buffer){return bluffer.readBase64(buffer)}).then(function(buffer){return _this2.client.crypto().decryptBytes(buffer,envelope,_this2.client.
|
|
1
|
+
"use strict";exports.__esModule=true;var _API2=require("./API");var _API3=_interopRequireDefault(_API2);var _whatwgURL=require("../util/whatwgURL");var _whatwgURL2=_interopRequireDefault(_whatwgURL);var _bluffer=require("../bluffer");var _bluffer2=_interopRequireDefault(_bluffer);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&(typeof call==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+typeof superClass)}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var ProofsAssetsExtractedText=function(_API){_inherits(ProofsAssetsExtractedText,_API);function ProofsAssetsExtractedText(){_classCallCheck(this,ProofsAssetsExtractedText);return _possibleConstructorReturn(this,_API.apply(this,arguments))}ProofsAssetsExtractedText.prototype.resources=function resources(proofId){return this.client.request("proofs.assets.extracted-text",{proofId:proofId}).then(function(response){return response.data.result}).catch(function(err){if(err&&err.response&&err.response.code===400)return;throw err})};ProofsAssetsExtractedText.prototype.download=function download(resources,pageNumber){var _this2=this;var matchingPages=resources.pages.filter(function(page){return page.number===pageNumber});if(!matchingPages||!matchingPages.length){return Promise.reject(new Error("Page does not contain any text."))}var envelope=resources.envelope;var url=new _whatwgURL2.default(matchingPages[0].chunks[0].url);var bluffer=new _bluffer2.default;return this.client.rawRequest({method:"GET",url:url},{bluffer:true}).then(function(response){return response.body}).then(function(buffer){return bluffer.readBase64(buffer)}).then(function(buffer){return _this2.client.crypto().decryptBytes(buffer,envelope,_this2.client.keyPairs.getPrivateKeyPEMs(),[],["unzip"])}).then(function(base64){return bluffer.createBase64(base64)}).then(function(buffer){return bluffer.readArrayBuffer(buffer)}).then(function(ab){return _this2.client.protobuf().ExtractedText(ab)})};return ProofsAssetsExtractedText}(_API3.default);exports.default=ProofsAssetsExtractedText;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export default class KeyPairs {
|
|
2
|
+
constructor(client: any);
|
|
3
|
+
/** @private */
|
|
4
|
+
client: any;
|
|
5
|
+
/** @private */
|
|
6
|
+
keyPairs: any[];
|
|
7
|
+
addKeyPair(keyPair: any): () => void;
|
|
8
|
+
removeKeyPair(keyPair: any): void;
|
|
9
|
+
getPrivateKeyPEMs(): any[];
|
|
10
|
+
getPublicKeyPEMs(): any[];
|
|
11
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";exports.__esModule=true;function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var KeyPairs=function(){function KeyPairs(client){_classCallCheck(this,KeyPairs);this.keyPairs=[];this.client=client}KeyPairs.prototype.addKeyPair=function addKeyPair(keyPair){var _this=this;this.keyPairs.push(keyPair);return function(){return _this.removeKeyPair(keyPair)}};KeyPairs.prototype.removeKeyPair=function removeKeyPair(keyPair){this.keyPairs.splice(this.keyPairs.indexOf(keyPair),1)};KeyPairs.prototype.getPrivateKeyPEMs=function getPrivateKeyPEMs(){return[this.client.session.privateKeyPEM].concat(this.keyPairs.map(function(keyPair){return keyPair.privateKeyPEM})).filter(Boolean)};KeyPairs.prototype.getPublicKeyPEMs=function getPublicKeyPEMs(){return[this.client.session.serverPublicKeyPEM,this.client.session.publicKeyPEM].concat(this.keyPairs.map(function(keyPair){return keyPair.publicKeyPEM})).filter(Boolean)};return KeyPairs}();exports.default=KeyPairs;
|
package/lib/core/PageProof.d.ts
CHANGED
package/lib/core/PageProof.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.__esModule=true;var _AdapterRepository=require("./AdapterRepository");var _AdapterRepository2=_interopRequireDefault(_AdapterRepository);var _Cache=require("./Cache");var _Cache2=_interopRequireDefault(_Cache);var _Request=require("../network/Request");var _Request2=_interopRequireDefault(_Request);var _Response=require("../network/Response");var _Response2=_interopRequireDefault(_Response);var _Accounts=require("../api/Accounts");var _Accounts2=_interopRequireDefault(_Accounts);var _Dashboard=require("../api/Dashboard");var _Dashboard2=_interopRequireDefault(_Dashboard);var _Users=require("../api/Users");var _Users2=_interopRequireDefault(_Users);var _Proofs=require("../api/Proofs");var _Proofs2=_interopRequireDefault(_Proofs);var _Briefs=require("../api/Briefs");var _Briefs2=_interopRequireDefault(_Briefs);var _Files=require("../api/Files");var _Files2=_interopRequireDefault(_Files);var _Admin=require("../api/admin/Admin");var _Admin2=_interopRequireDefault(_Admin);var _Workflows=require("../api/Workflows");var _Workflows2=_interopRequireDefault(_Workflows);var _Preferences=require("../api/Preferences");var _Preferences2=_interopRequireDefault(_Preferences);var _Comments=require("../api/Comments");var _Comments2=_interopRequireDefault(_Comments);var _Profile=require("../api/Profile");var _Profile2=_interopRequireDefault(_Profile);var _Sessions=require("../api/Sessions");var _Sessions2=_interopRequireDefault(_Sessions);var _Encryption=require("../api/Encryption");var _Encryption2=_interopRequireDefault(_Encryption);var _Live=require("../api/Live");var _Live2=_interopRequireDefault(_Live);var _Brian=require("../api/brian/Brian");var _Brian2=_interopRequireDefault(_Brian);var _Session=require("../models/Session");var _Session2=_interopRequireDefault(_Session);var _EventEmitter=require("../events/EventEmitter");var _EventEmitter2=_interopRequireDefault(_EventEmitter);var _ResponseStatus=require("../enum/ResponseStatus");var _ResponseStatus2=_interopRequireDefault(_ResponseStatus);var _sleep=require("../util/sleep");var _sleep2=_interopRequireDefault(_sleep);var _constants=require("../util/constants");var _getTimezone=require("../util/getTimezone");var _getTimezone2=_interopRequireDefault(_getTimezone);var _Reports=require("../api/Reports");var _Reports2=_interopRequireDefault(_Reports);var _Teams=require("../api/Teams");var _Teams2=_interopRequireDefault(_Teams);var _Printing=require("../api/Printing");var _Printing2=_interopRequireDefault(_Printing);var _FreeTrial=require("../api/FreeTrial");var _FreeTrial2=_interopRequireDefault(_FreeTrial);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var debug=require("debug")("PageProof");var PageProof=function(){function PageProof(){var _ref=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{},_ref$options=_ref.options,options=_ref$options===undefined?{}:_ref$options,_ref$adapters=_ref.adapters,adapters=_ref$adapters===undefined?[]:_ref$adapters;_classCallCheck(this,PageProof);this.options=options;this.events=new _EventEmitter2.default;this.adapters=new _AdapterRepository2.default(adapters);this.cache=new _Cache2.default(this);this.accounts=new _Accounts2.default(this);this.comments=new _Comments2.default(this);this.dashboard=new _Dashboard2.default(this);this.files=new _Files2.default(this);this.profile=new _Profile2.default(this);this.proofs=new _Proofs2.default(this);this.briefs=new _Briefs2.default(this);this.users=new _Users2.default(this);this.workflows=new _Workflows2.default(this);this.preferences=new _Preferences2.default(this);this.sessions=new _Sessions2.default(this);this.encryption=new _Encryption2.default(this);this.live=new _Live2.default(this);this.reports=new _Reports2.default(this);this.teams=new _Teams2.default(this);this.printing=new _Printing2.default(this);this.freeTrial=new _FreeTrial2.default(this);this.__admin=new _Admin2.default(this);this._hijackAdmin();this._init();this._registerCoreHooks();this._enhance()}PageProof.prototype._init=function _init(){var requestAdapter=this.adapters.getRequestAdapter();if(!this.options.endpoint){this.options.endpoint=requestAdapter.options.endpoint}if(!this.options.applicationId){this.options.applicationId=requestAdapter.options.applicationId}if(!this.options.subscriptionKey){this.options.subscriptionKey=requestAdapter.options.key||this.options.key}if(this.options.subscriptionKey&&!this.options.applicationId){throw new Error("You must provide an applicationId.")}};PageProof.prototype._hijackAdmin=function _hijackAdmin(){var _this=this;var adminKeys=Object.getOwnPropertyNames(this.__admin);adminKeys.forEach(function(adminKey){return _this.admin[adminKey]=_this.__admin[adminKey]})};PageProof.prototype._registerCoreHooks=function _registerCoreHooks(){this.on("error.throttled",function(event){var ms=event.data.response.data.timeout;debug("Sleeping "+ms+"ms until rate limit resets");return(0,_sleep2.default)(ms)})};PageProof.prototype._enhance=function _enhance(){var _this2=this;var adapters=this.adapters.getEnhancementAdapters();adapters.forEach(function(adapter){return adapter.onClientReady(_this2)})};PageProof.prototype.setSession=function setSession(session){if(session&&!(session instanceof _Session2.default)){this.session=(new _Session2.default).fromJSON(session)}else{this.session=session||null}return this.session};PageProof.prototype.rawRequest=function rawRequest(_ref2,options){var method=_ref2.method,url=_ref2.url,host=_ref2.host,path=_ref2.path,query=_ref2.query,body=_ref2.body,headers=_ref2.headers;var adapter=this.adapters.getRequestAdapter();if(url){host=url.origin;path=url.pathname;query=url.search}return adapter.send({host:host,method:method,path:path,query:query,body:body,headers:headers,credentials:false},options)};PageProof.prototype.getRequestLocalEncodedMetadata=function getRequestLocalEncodedMetadata(){return[(0,_getTimezone2.default)()].map(function(value){return value!==null&&value!==undefined?encodeURIComponent(value):"#"}).join(":")};PageProof.prototype.request=function request(name,params,options){var _this3=this;var request=new _Request2.default(this.options.endpoint,name,params);var adapter=this.adapters.getRequestAdapter();var start=Promise.resolve();if(!request.endpoint.anonymous){if(!this.session){return Promise.reject(new Error("Cannot make call to endpoint ("+name+") when unauthorized."))}var crypto=this.adapters.getCryptoAdapter();start=crypto.generateAuthorizationHeaders(request.getMethod(),request.getPath(),this.session).then(function(headers){return request.addHeaders(headers)})}if(this.options.applicationId){request.addHeader(_constants.DEVICE_ID_HEADER,this.options.applicationId)}if(this.options.subscriptionKey){request.addHeader(_constants.SUBSCRIPTION_KEY_HEADER,this.options.subscriptionKey)}var localEncodedMetadata=this.getRequestLocalEncodedMetadata();if(localEncodedMetadata){request.addHeader(_constants.LOCAL_ENCODED_METADATA_HEADER,localEncodedMetadata)}var meta={request:request};return start.then(function(){var data=request.build();return _this3.events.emit("experimental.request.before",meta,true).then(function(){return data})}).then(function(data){return adapter.send(data,options)}).then(_Response2.default.parse).then(function(response){meta.response=response;_this3.events.emit("experimental.request.after",meta);if(response.code===_ResponseStatus2.default.ERROR_THROTTLED){var handlers=_this3.events.emit("error.throttled",meta);if(handlers.some(Boolean)){return Promise.all(handlers).then(function(){_this3.events.emit("experimental.request.retry",meta);return _this3.request(name,params,options)})}}if(response.code===_ResponseStatus2.default.ERROR_UNAUTHORISED){var sessionToken=_this3.session?_this3.session.token:null;return _this3.events.emit("error.unauthorized",meta,true).then(function(){if(_this3.session&&_this3.session.token!==sessionToken){return _this3.request(name,params,options)}return response})}if(response.deprecated){var message="The "+name+" API has been deprecated. "+(response.deprecated||"");_this3.events.emit("error.deprecated",{name:name,message:message})}return response}).then(function(response){try{if(response.error){_this3.events.emit("error.response",meta);var err=new Error(response.message+" ["+name+"]");err.response=response;err.request=request;return Promise.reject(err)}else{_this3.events.emit("experimental.request.resolve",meta);return Promise.resolve(response)}}finally{_this3.events.emit("experimental.request.finally",meta)}})};PageProof.prototype.admin=function admin(){if(!this.session){return Promise.reject(new Error("You must be logged in to use the Admin API."))}if(!this.session.user.isAdmin){return Promise.reject(new Error("The current user must be an administrator of a team or enterprise account."))}if(!this._admin){this._admin=Promise.resolve(this.__admin)}return this._admin};PageProof.prototype.brian=function brian(){if(!this.session||this.session.userId!==_constants.BRIAN_USER_ID){return Promise.reject(new Error("You do not have permission to use this API."))}if(!this._brian){this._brian=Promise.resolve(new _Brian2.default(this))}return this._brian};PageProof.prototype.crypto=function crypto(){return this.adapters.getCryptoAdapter()};PageProof.prototype.protobuf=function protobuf(){return this.adapters.getProtobufAdapter()};PageProof.prototype.on=function on(event,handler){return this.events.on(event,handler)};return PageProof}();exports.default=PageProof;
|
|
1
|
+
"use strict";exports.__esModule=true;var _AdapterRepository=require("./AdapterRepository");var _AdapterRepository2=_interopRequireDefault(_AdapterRepository);var _Cache=require("./Cache");var _Cache2=_interopRequireDefault(_Cache);var _Request=require("../network/Request");var _Request2=_interopRequireDefault(_Request);var _Response=require("../network/Response");var _Response2=_interopRequireDefault(_Response);var _Accounts=require("../api/Accounts");var _Accounts2=_interopRequireDefault(_Accounts);var _Dashboard=require("../api/Dashboard");var _Dashboard2=_interopRequireDefault(_Dashboard);var _Users=require("../api/Users");var _Users2=_interopRequireDefault(_Users);var _Proofs=require("../api/Proofs");var _Proofs2=_interopRequireDefault(_Proofs);var _Briefs=require("../api/Briefs");var _Briefs2=_interopRequireDefault(_Briefs);var _Files=require("../api/Files");var _Files2=_interopRequireDefault(_Files);var _Admin=require("../api/admin/Admin");var _Admin2=_interopRequireDefault(_Admin);var _Workflows=require("../api/Workflows");var _Workflows2=_interopRequireDefault(_Workflows);var _Preferences=require("../api/Preferences");var _Preferences2=_interopRequireDefault(_Preferences);var _Comments=require("../api/Comments");var _Comments2=_interopRequireDefault(_Comments);var _Profile=require("../api/Profile");var _Profile2=_interopRequireDefault(_Profile);var _Sessions=require("../api/Sessions");var _Sessions2=_interopRequireDefault(_Sessions);var _Encryption=require("../api/Encryption");var _Encryption2=_interopRequireDefault(_Encryption);var _Live=require("../api/Live");var _Live2=_interopRequireDefault(_Live);var _Brian=require("../api/brian/Brian");var _Brian2=_interopRequireDefault(_Brian);var _Session=require("../models/Session");var _Session2=_interopRequireDefault(_Session);var _EventEmitter=require("../events/EventEmitter");var _EventEmitter2=_interopRequireDefault(_EventEmitter);var _ResponseStatus=require("../enum/ResponseStatus");var _ResponseStatus2=_interopRequireDefault(_ResponseStatus);var _sleep=require("../util/sleep");var _sleep2=_interopRequireDefault(_sleep);var _constants=require("../util/constants");var _getTimezone=require("../util/getTimezone");var _getTimezone2=_interopRequireDefault(_getTimezone);var _Reports=require("../api/Reports");var _Reports2=_interopRequireDefault(_Reports);var _Teams=require("../api/Teams");var _Teams2=_interopRequireDefault(_Teams);var _Printing=require("../api/Printing");var _Printing2=_interopRequireDefault(_Printing);var _FreeTrial=require("../api/FreeTrial");var _FreeTrial2=_interopRequireDefault(_FreeTrial);var _KeyPairs=require("./KeyPairs");var _KeyPairs2=_interopRequireDefault(_KeyPairs);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var debug=require("debug")("PageProof");var PageProof=function(){function PageProof(){var _ref=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{},_ref$options=_ref.options,options=_ref$options===undefined?{}:_ref$options,_ref$adapters=_ref.adapters,adapters=_ref$adapters===undefined?[]:_ref$adapters;_classCallCheck(this,PageProof);this.options=options;this.events=new _EventEmitter2.default;this.adapters=new _AdapterRepository2.default(adapters);this.cache=new _Cache2.default(this);this.keyPairs=new _KeyPairs2.default(this);this.accounts=new _Accounts2.default(this);this.comments=new _Comments2.default(this);this.dashboard=new _Dashboard2.default(this);this.files=new _Files2.default(this);this.profile=new _Profile2.default(this);this.proofs=new _Proofs2.default(this);this.briefs=new _Briefs2.default(this);this.users=new _Users2.default(this);this.workflows=new _Workflows2.default(this);this.preferences=new _Preferences2.default(this);this.sessions=new _Sessions2.default(this);this.encryption=new _Encryption2.default(this);this.live=new _Live2.default(this);this.reports=new _Reports2.default(this);this.teams=new _Teams2.default(this);this.printing=new _Printing2.default(this);this.freeTrial=new _FreeTrial2.default(this);this.__admin=new _Admin2.default(this);this._hijackAdmin();this._init();this._registerCoreHooks();this._enhance()}PageProof.prototype._init=function _init(){var requestAdapter=this.adapters.getRequestAdapter();if(!this.options.endpoint){this.options.endpoint=requestAdapter.options.endpoint}if(!this.options.applicationId){this.options.applicationId=requestAdapter.options.applicationId}if(!this.options.subscriptionKey){this.options.subscriptionKey=requestAdapter.options.key||this.options.key}if(this.options.subscriptionKey&&!this.options.applicationId){throw new Error("You must provide an applicationId.")}};PageProof.prototype._hijackAdmin=function _hijackAdmin(){var _this=this;var adminKeys=Object.getOwnPropertyNames(this.__admin);adminKeys.forEach(function(adminKey){return _this.admin[adminKey]=_this.__admin[adminKey]})};PageProof.prototype._registerCoreHooks=function _registerCoreHooks(){this.on("error.throttled",function(event){var ms=event.data.response.data.timeout;debug("Sleeping "+ms+"ms until rate limit resets");return(0,_sleep2.default)(ms)})};PageProof.prototype._enhance=function _enhance(){var _this2=this;var adapters=this.adapters.getEnhancementAdapters();adapters.forEach(function(adapter){return adapter.onClientReady(_this2)})};PageProof.prototype.setSession=function setSession(session){if(session&&!(session instanceof _Session2.default)){this.session=(new _Session2.default).fromJSON(session)}else{this.session=session||null}return this.session};PageProof.prototype.rawRequest=function rawRequest(_ref2,options){var method=_ref2.method,url=_ref2.url,host=_ref2.host,path=_ref2.path,query=_ref2.query,body=_ref2.body,headers=_ref2.headers;var adapter=this.adapters.getRequestAdapter();if(url){host=url.origin;path=url.pathname;query=url.search}return adapter.send({host:host,method:method,path:path,query:query,body:body,headers:headers,credentials:false},options)};PageProof.prototype.getRequestLocalEncodedMetadata=function getRequestLocalEncodedMetadata(){return[(0,_getTimezone2.default)()].map(function(value){return value!==null&&value!==undefined?encodeURIComponent(value):"#"}).join(":")};PageProof.prototype.request=function request(name,params,options){var _this3=this;var request=new _Request2.default(this.options.endpoint,name,params);var adapter=this.adapters.getRequestAdapter();var start=Promise.resolve();if(!request.endpoint.anonymous){if(!this.session){return Promise.reject(new Error("Cannot make call to endpoint ("+name+") when unauthorized."))}var crypto=this.adapters.getCryptoAdapter();start=crypto.generateAuthorizationHeaders(request.getMethod(),request.getPath(),this.session).then(function(headers){return request.addHeaders(headers)})}if(this.options.applicationId){request.addHeader(_constants.DEVICE_ID_HEADER,this.options.applicationId)}if(this.options.subscriptionKey){request.addHeader(_constants.SUBSCRIPTION_KEY_HEADER,this.options.subscriptionKey)}var localEncodedMetadata=this.getRequestLocalEncodedMetadata();if(localEncodedMetadata){request.addHeader(_constants.LOCAL_ENCODED_METADATA_HEADER,localEncodedMetadata)}var meta={request:request};return start.then(function(){var data=request.build();return _this3.events.emit("experimental.request.before",meta,true).then(function(){return data})}).then(function(data){return adapter.send(data,options)}).then(_Response2.default.parse).then(function(response){meta.response=response;_this3.events.emit("experimental.request.after",meta);if(response.code===_ResponseStatus2.default.ERROR_THROTTLED){var handlers=_this3.events.emit("error.throttled",meta);if(handlers.some(Boolean)){return Promise.all(handlers).then(function(){_this3.events.emit("experimental.request.retry",meta);return _this3.request(name,params,options)})}}if(response.code===_ResponseStatus2.default.ERROR_UNAUTHORISED){var sessionToken=_this3.session?_this3.session.token:null;return _this3.events.emit("error.unauthorized",meta,true).then(function(){if(_this3.session&&_this3.session.token!==sessionToken){return _this3.request(name,params,options)}return response})}if(response.deprecated){var message="The "+name+" API has been deprecated. "+(response.deprecated||"");_this3.events.emit("error.deprecated",{name:name,message:message})}return response}).then(function(response){try{if(response.error){_this3.events.emit("error.response",meta);var err=new Error(response.message+" ["+name+"]");err.response=response;err.request=request;return Promise.reject(err)}else{_this3.events.emit("experimental.request.resolve",meta);return Promise.resolve(response)}}finally{_this3.events.emit("experimental.request.finally",meta)}})};PageProof.prototype.admin=function admin(){if(!this.session){return Promise.reject(new Error("You must be logged in to use the Admin API."))}if(!this.session.user.isAdmin){return Promise.reject(new Error("The current user must be an administrator of a team or enterprise account."))}if(!this._admin){this._admin=Promise.resolve(this.__admin)}return this._admin};PageProof.prototype.brian=function brian(){if(!this.session||this.session.userId!==_constants.BRIAN_USER_ID){return Promise.reject(new Error("You do not have permission to use this API."))}if(!this._brian){this._brian=Promise.resolve(new _Brian2.default(this))}return this._brian};PageProof.prototype.crypto=function crypto(){return this.adapters.getCryptoAdapter()};PageProof.prototype.protobuf=function protobuf(){return this.adapters.getProtobufAdapter()};PageProof.prototype.on=function on(event,handler){return this.events.on(event,handler)};return PageProof}();exports.default=PageProof;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.__esModule=true;exports.default=decryptBytes;var _nodeForge=require("node-forge");var forge=_interopRequireWildcard(_nodeForge);var _pako=require("pako");var _pako2=_interopRequireDefault(_pako);var _byteStringBufferToArrayBuffer=require("./util/byteStringBufferToArrayBuffer");var _byteStringBufferToArrayBuffer2=_interopRequireDefault(_byteStringBufferToArrayBuffer);var _envelopes=require("./envelopes");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function decryptBytes(data$,envelope$,privateKeyPEM,before,after){var data=void 0;function transform(name){try{switch(name){case"unzip":{data=_pako2.default.ungzip(data).buffer;break}case"zip":{data=_pako2.default.gzip(data).buffer;break}default:{throw new Error('Unknown transform "'+name+'".')}}}catch(err){throw new Error(err)}}return(0,_envelopes.envelopeUnseal)(envelope$,privateKeyPEM).then(function(keyIV){data=(0,_byteStringBufferToArrayBuffer2.default)(forge.util.createBuffer(forge.util.decode64(data$)));if(before&&before.length){before.forEach(transform)}var key=forge.util.hexToBytes(keyIV.key);var iv=forge.util.hexToBytes(keyIV.iv);var decipher=forge.cipher.createDecipher("AES-CBC",key);decipher.start({iv:iv});decipher.update(forge.util.createBuffer(data));if(!decipher.finish()){throw new Error("Failed to decrypt bytes.")}data=(0,_byteStringBufferToArrayBuffer2.default)(decipher.output);if(after&&after.length){after.forEach(transform)}return forge.util.encode64(forge.util.createBuffer(data).bytes())})}
|
|
1
|
+
"use strict";exports.__esModule=true;exports.default=decryptBytes;var _nodeForge=require("node-forge");var forge=_interopRequireWildcard(_nodeForge);var _pako=require("pako");var _pako2=_interopRequireDefault(_pako);var _byteStringBufferToArrayBuffer=require("./util/byteStringBufferToArrayBuffer");var _byteStringBufferToArrayBuffer2=_interopRequireDefault(_byteStringBufferToArrayBuffer);var _envelopes=require("./envelopes");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function decryptBytes(data$,envelope$,privateKeyPEM,before,after){var data=void 0;function transform(name){try{switch(name){case"unzip":{data=_pako2.default.ungzip(data).buffer;break}case"zip":{data=_pako2.default.gzip(data).buffer;break}default:{throw new Error('Unknown transform "'+name+'".')}}}catch(err){throw new Error(err)}}return(0,_envelopes.envelopeUnseal)(envelope$,[privateKeyPEM]).then(function(keyIV){data=(0,_byteStringBufferToArrayBuffer2.default)(forge.util.createBuffer(forge.util.decode64(data$)));if(before&&before.length){before.forEach(transform)}var key=forge.util.hexToBytes(keyIV.key);var iv=forge.util.hexToBytes(keyIV.iv);var decipher=forge.cipher.createDecipher("AES-CBC",key);decipher.start({iv:iv});decipher.update(forge.util.createBuffer(data));if(!decipher.finish()){throw new Error("Failed to decrypt bytes.")}data=(0,_byteStringBufferToArrayBuffer2.default)(decipher.output);if(after&&after.length){after.forEach(transform)}return forge.util.encode64(forge.util.createBuffer(data).bytes())})}
|
|
@@ -3,7 +3,7 @@ export default decryptComment;
|
|
|
3
3
|
* @private
|
|
4
4
|
* @param {string} comment$ The encrypted comment
|
|
5
5
|
* @param {string} envelope The comment envelope
|
|
6
|
-
* @param {string}
|
|
6
|
+
* @param {string[]} privateKeyPEMs The user's private key (in PEM format)
|
|
7
7
|
* @returns {Promise<string>}
|
|
8
8
|
*/
|
|
9
|
-
declare function decryptComment(comment$: string, envelope: string,
|
|
9
|
+
declare function decryptComment(comment$: string, envelope: string, privateKeyPEMs: string[]): Promise<string>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.__esModule=true;var _aes=require("crypto-js/aes");var _encUtf=require("crypto-js/enc-utf8");var _encUtf2=_interopRequireDefault(_encUtf);var _envelopes=require("./envelopes");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function decryptComment(comment$,envelope,
|
|
1
|
+
"use strict";exports.__esModule=true;var _aes=require("crypto-js/aes");var _encUtf=require("crypto-js/enc-utf8");var _encUtf2=_interopRequireDefault(_encUtf);var _envelopes=require("./envelopes");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function decryptComment(comment$,envelope,privateKeyPEMs){return(0,_envelopes.envelopeUnseal)(envelope,privateKeyPEMs).then(function(_ref){var key=_ref.key,iv=_ref.iv;var raw=(0,_aes.decrypt)(comment$,key,{iv:iv}).toString(_encUtf2.default);if(!raw){throw new Error("Unable to decrypt comment.")}return raw})}exports.default=decryptComment;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.__esModule=true;var _nodeForge=require("node-forge");var forge=_interopRequireWildcard(_nodeForge);var _envelopes=require("./envelopes");function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function decryptData(version,data$,envelope$,privateKeyPEM){switch(version){case 1:{return(0,_envelopes.envelopeUnseal)(envelope$,privateKeyPEM).then(function(keyIV){var key=forge.util.hexToBytes(keyIV.key);var iv=forge.util.hexToBytes(keyIV.iv);var data=forge.util.createBuffer(forge.util.decode64(data$));var decipher=forge.cipher.createDecipher("AES-CBC",key);decipher.start({iv:iv});decipher.update(data);decipher.finish();var output=decipher.output.toString();if(!output){throw new Error("Unable to decrypt data.")}return forge.util.decode64(output)})}default:{return Promise.reject(new Error("Unsupported encryption version - a newer version of the SDK is required to decrypt this data."))}}}exports.default=decryptData;
|
|
1
|
+
"use strict";exports.__esModule=true;var _nodeForge=require("node-forge");var forge=_interopRequireWildcard(_nodeForge);var _envelopes=require("./envelopes");function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function decryptData(version,data$,envelope$,privateKeyPEM){switch(version){case 1:{return(0,_envelopes.envelopeUnseal)(envelope$,[privateKeyPEM]).then(function(keyIV){var key=forge.util.hexToBytes(keyIV.key);var iv=forge.util.hexToBytes(keyIV.iv);var data=forge.util.createBuffer(forge.util.decode64(data$));var decipher=forge.cipher.createDecipher("AES-CBC",key);decipher.start({iv:iv});decipher.update(data);decipher.finish();var output=decipher.output.toString();if(!output){throw new Error("Unable to decrypt data.")}return forge.util.decode64(output)})}default:{return Promise.reject(new Error("Unsupported encryption version - a newer version of the SDK is required to decrypt this data."))}}}exports.default=decryptData;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.__esModule=true;var _nodeForge=require("node-forge");var forge=_interopRequireWildcard(_nodeForge);var _decryptImage=require("./decryptImage");var _decryptImage2=_interopRequireDefault(_decryptImage);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function decryptFileBlock(data$,
|
|
1
|
+
"use strict";exports.__esModule=true;var _nodeForge=require("node-forge");var forge=_interopRequireWildcard(_nodeForge);var _decryptImage=require("./decryptImage");var _decryptImage2=_interopRequireDefault(_decryptImage);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function decryptFileBlock(data$,privateKeyPEMs){return(0,_decryptImage2.default)(data$,privateKeyPEMs).then(function(doubleBase64){return forge.util.decode64(doubleBase64)})}exports.default=decryptFileBlock;
|
|
@@ -2,7 +2,7 @@ export default decryptImage;
|
|
|
2
2
|
/**
|
|
3
3
|
* @private
|
|
4
4
|
* @param {string} data$ The encrypted image data (containing the envelope and base64 encoded image)
|
|
5
|
-
* @param {string}
|
|
5
|
+
* @param {string[]} privateKeyPEMs The user's private keys (in PEM format)
|
|
6
6
|
* @returns {Promise<string>}
|
|
7
7
|
*/
|
|
8
|
-
declare function decryptImage(data$: string,
|
|
8
|
+
declare function decryptImage(data$: string, privateKeyPEMs: string[]): Promise<string>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.__esModule=true;var _nodeForge=require("node-forge");var forge=_interopRequireWildcard(_nodeForge);var _envelopes=require("./envelopes");function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}var ENVELOPE_DATA_SEPARATOR="-";function decryptImage(data$,
|
|
1
|
+
"use strict";exports.__esModule=true;var _nodeForge=require("node-forge");var forge=_interopRequireWildcard(_nodeForge);var _envelopes=require("./envelopes");function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}var ENVELOPE_DATA_SEPARATOR="-";function decryptImage(data$,privateKeyPEMs){var _data$$split=data$.split(ENVELOPE_DATA_SEPARATOR),envelope=_data$$split[0],dataBase64=_data$$split[1];return(0,_envelopes.envelopeUnseal)(envelope,privateKeyPEMs).then(function(keyIV){var key=forge.util.hexToBytes(keyIV.key);var iv=forge.util.hexToBytes(keyIV.iv);var data=forge.util.createBuffer(forge.util.decode64(dataBase64));var decipher=forge.cipher.createDecipher("AES-CBC",key);decipher.start({iv:iv});decipher.update(data);decipher.finish();var output=decipher.output.toString();if(!output){throw new Error("Unable to decrypt image.")}return output})}exports.default=decryptImage;
|
|
@@ -8,10 +8,10 @@ export function envelopeSeal(secret: string, publicKeyPEMs: string[]): Promise<s
|
|
|
8
8
|
/**
|
|
9
9
|
* @private
|
|
10
10
|
* @param {string} envelope The envelope holding the secret
|
|
11
|
-
* @param {string}
|
|
11
|
+
* @param {string[]} privateKeyPEMs The private keys used to unseal the secret
|
|
12
12
|
* @returns {Promise<{key: string, iv: string}>}
|
|
13
13
|
*/
|
|
14
|
-
export function envelopeUnseal(envelope: string,
|
|
14
|
+
export function envelopeUnseal(envelope: string, privateKeyPEMs: string[]): Promise<{
|
|
15
15
|
key: string;
|
|
16
16
|
iv: string;
|
|
17
17
|
}>;
|
package/lib/crypto/envelopes.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.__esModule=true;exports.envelopeUnseal=exports.envelopeSeal=undefined;var _nodeForge=require("node-forge");var forge=_interopRequireWildcard(_nodeForge);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}var ENVELOPE_VERSION="0001";var ENVELOPE_ALGORITHM="RSAES-PKCS1-V1_5";var ENVELOPE_KEY_SEPARATOR="|";function attemptEnvelopeUnseal(recipient,
|
|
1
|
+
"use strict";exports.__esModule=true;exports.envelopeUnseal=exports.envelopeSeal=undefined;var _nodeForge=require("node-forge");var forge=_interopRequireWildcard(_nodeForge);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}var ENVELOPE_VERSION="0001";var ENVELOPE_ALGORITHM="RSAES-PKCS1-V1_5";var ENVELOPE_KEY_SEPARATOR="|";function attemptEnvelopeUnseal(recipient,privateKeys){try{var encrypted=forge.util.decode64(recipient);for(var i=0;i<privateKeys.length;i++){try{var privateKey=privateKeys[i];var decrypted=privateKey.decrypt(encrypted,ENVELOPE_ALGORITHM);if(decrypted){return decrypted}}catch(err){}}}catch(err){}return null}function envelopeSeal(secret,publicKeyPEMs){return new Promise(function(resolve){var recipients=[];publicKeyPEMs.forEach(function(pem){var publicKey=forge.pki.publicKeyFromPem(pem);var encrypted=publicKey.encrypt(secret,ENVELOPE_ALGORITHM);recipients.push(forge.util.encode64(encrypted))});resolve(ENVELOPE_VERSION+ENVELOPE_KEY_SEPARATOR+recipients.join(ENVELOPE_KEY_SEPARATOR))})}function envelopeUnseal(envelope,privateKeyPEMs){return new Promise(function(resolve,reject){var privateKeys=privateKeyPEMs.map(function(privateKeyPEM){return forge.pki.privateKeyFromPem(privateKeyPEM)});var recipients=envelope.split(ENVELOPE_KEY_SEPARATOR);for(var index=0;index<recipients.length;index+=1){var result=attemptEnvelopeUnseal(recipients[index],privateKeys);if(result!==null){var _result$split=result.split(ENVELOPE_KEY_SEPARATOR),key=_result$split[0],iv=_result$split[1];resolve({key:key,iv:iv});return}}reject(new Error("Unable to unseal envelope. The provided private key(s) were "+("unable to decrypt any of the "+recipients.length+" envelopes(s).")))})}exports.envelopeSeal=envelopeSeal;exports.envelopeUnseal=envelopeUnseal;
|